ppchatocrv3.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import re
  16. import json
  17. import numpy as np
  18. from .utils import *
  19. from copy import deepcopy
  20. from ...components import *
  21. from ..ocr import OCRPipeline
  22. from ....utils import logging
  23. from ...results import *
  24. from ...components.llm import ErnieBot
  25. from ...utils.io import ImageReader, PDFReader
  26. from ..table_recognition import _TableRecPipeline
  27. from ...components.llm import create_llm_api, ErnieBot
  28. from ....utils.file_interface import read_yaml_file
  29. from ..table_recognition.utils import convert_4point2rect, get_ori_coordinate_for_table
  30. PROMPT_FILE = os.path.join(os.path.dirname(__file__), "ch_prompt.yaml")
  31. class PPChatOCRPipeline(_TableRecPipeline):
  32. """PP-ChatOCRv3 Pileline"""
  33. entities = "PP-ChatOCRv3-doc"
  34. def __init__(
  35. self,
  36. layout_model,
  37. text_det_model,
  38. text_rec_model,
  39. table_model,
  40. doc_image_ori_cls_model=None,
  41. doc_image_unwarp_model=None,
  42. seal_text_det_model=None,
  43. llm_name="ernie-3.5",
  44. llm_params={},
  45. task_prompt_yaml=None,
  46. user_prompt_yaml=None,
  47. layout_batch_size=1,
  48. text_det_batch_size=1,
  49. text_rec_batch_size=1,
  50. table_batch_size=1,
  51. doc_image_ori_cls_batch_size=1,
  52. doc_image_unwarp_batch_size=1,
  53. seal_text_det_batch_size=1,
  54. recovery=True,
  55. device=None,
  56. predictor_kwargs=None,
  57. _build_models=True,
  58. ):
  59. super().__init__(device, predictor_kwargs)
  60. if _build_models:
  61. self._build_predictor(
  62. layout_model=layout_model,
  63. text_det_model=text_det_model,
  64. text_rec_model=text_rec_model,
  65. table_model=table_model,
  66. doc_image_ori_cls_model=doc_image_ori_cls_model,
  67. doc_image_unwarp_model=doc_image_unwarp_model,
  68. seal_text_det_model=seal_text_det_model,
  69. llm_name=llm_name,
  70. llm_params=llm_params,
  71. )
  72. self.set_predictor(
  73. layout_batch_size=layout_batch_size,
  74. text_det_batch_size=text_det_batch_size,
  75. text_rec_batch_size=text_rec_batch_size,
  76. table_batch_size=table_batch_size,
  77. doc_image_ori_cls_batch_size=doc_image_ori_cls_batch_size,
  78. doc_image_unwarp_batch_size=doc_image_unwarp_batch_size,
  79. seal_text_det_batch_size=seal_text_det_batch_size,
  80. )
  81. # get base prompt from yaml info
  82. if task_prompt_yaml:
  83. self.task_prompt_dict = read_yaml_file(task_prompt_yaml)
  84. else:
  85. self.task_prompt_dict = read_yaml_file(
  86. PROMPT_FILE
  87. ) # get user prompt from yaml info
  88. if user_prompt_yaml:
  89. self.user_prompt_dict = read_yaml_file(user_prompt_yaml)
  90. else:
  91. self.user_prompt_dict = None
  92. self.recovery = recovery
  93. self.visual_info = None
  94. self.vector = None
  95. self.visual_flag = False
  96. def _build_predictor(
  97. self,
  98. layout_model,
  99. text_det_model,
  100. text_rec_model,
  101. table_model,
  102. llm_name,
  103. llm_params,
  104. seal_text_det_model=None,
  105. doc_image_ori_cls_model=None,
  106. doc_image_unwarp_model=None,
  107. ):
  108. super()._build_predictor(
  109. layout_model, text_det_model, text_rec_model, table_model
  110. )
  111. if seal_text_det_model:
  112. self.curve_pipeline = self._create(
  113. pipeline=OCRPipeline,
  114. text_det_model=seal_text_det_model,
  115. text_rec_model=text_rec_model,
  116. )
  117. else:
  118. self.curve_pipeline = None
  119. if doc_image_ori_cls_model:
  120. self.doc_image_ori_cls_predictor = self._create(doc_image_ori_cls_model)
  121. else:
  122. self.doc_image_ori_cls_predictor = None
  123. if doc_image_unwarp_model:
  124. self.doc_image_unwarp_predictor = self._create(doc_image_unwarp_model)
  125. else:
  126. self.doc_image_unwarp_predictor = None
  127. self.img_reader = ReadImage(format="RGB")
  128. self.llm_api = create_llm_api(
  129. llm_name,
  130. llm_params,
  131. )
  132. self.cropper = CropByBoxes()
  133. def set_predictor(
  134. self,
  135. layout_batch_size=None,
  136. text_det_batch_size=None,
  137. text_rec_batch_size=None,
  138. table_batch_size=None,
  139. doc_image_ori_cls_batch_size=None,
  140. doc_image_unwarp_batch_size=None,
  141. seal_text_det_batch_size=None,
  142. device=None,
  143. ):
  144. if text_det_batch_size and text_det_batch_size > 1:
  145. logging.warning(
  146. f"text det model only support batch_size=1 now,the setting of text_det_batch_size={text_det_batch_size} will not using! "
  147. )
  148. if layout_batch_size:
  149. self.layout_predictor.set_predictor(batch_size=layout_batch_size)
  150. if text_rec_batch_size:
  151. self.ocr_pipeline.text_rec_model.set_predictor(
  152. batch_size=text_rec_batch_size
  153. )
  154. if table_batch_size:
  155. self.table_predictor.set_predictor(batch_size=table_batch_size)
  156. if self.curve_pipeline and seal_text_det_batch_size:
  157. self.curve_pipeline.text_det_model.set_predictor(
  158. batch_size=seal_text_det_batch_size
  159. )
  160. if self.doc_image_ori_cls_predictor and doc_image_ori_cls_batch_size:
  161. self.doc_image_ori_cls_predictor.set_predictor(
  162. batch_size=doc_image_ori_cls_batch_size
  163. )
  164. if self.doc_image_unwarp_predictor and doc_image_unwarp_batch_size:
  165. self.doc_image_unwarp_predictor.set_predictor(
  166. batch_size=doc_image_unwarp_batch_size
  167. )
  168. if device:
  169. if self.curve_pipeline:
  170. self.curve_pipeline.set_predictor(device=device)
  171. if self.doc_image_ori_cls_predictor:
  172. self.doc_image_ori_cls_predictor.set_predictor(device=device)
  173. if self.doc_image_unwarp_predictor:
  174. self.doc_image_unwarp_predictor.set_predictor(device=device)
  175. self.layout_predictor.set_predictor(device=device)
  176. self.ocr_pipeline.set_predictor(device=device)
  177. def predict(self, *args, **kwargs):
  178. logging.error(
  179. "PP-ChatOCRv3-doc Pipeline do not support to call `predict()` directly! Please call `visual_predict(input)` firstly to get visual prediction of `input` and call `chat(key_list)` to get the result of query specified by `key_list`."
  180. )
  181. return
  182. def visual_predict(
  183. self,
  184. input,
  185. use_doc_image_ori_cls_model=True,
  186. use_doc_image_unwarp_model=True,
  187. use_seal_text_det_model=True,
  188. recovery=True,
  189. **kwargs,
  190. ):
  191. self.set_predictor(**kwargs)
  192. visual_info = {"ocr_text": [], "table_html": [], "table_text": []}
  193. # get all visual result
  194. visual_result = list(
  195. self.get_visual_result(
  196. input,
  197. use_doc_image_ori_cls_model=use_doc_image_ori_cls_model,
  198. use_doc_image_unwarp_model=use_doc_image_unwarp_model,
  199. use_seal_text_det_model=use_seal_text_det_model,
  200. recovery=recovery,
  201. )
  202. )
  203. # decode visual result to get table_html, table_text, ocr_text
  204. ocr_text, table_text, table_html = self.decode_visual_result(visual_result)
  205. visual_info["ocr_text"] = ocr_text
  206. visual_info["table_html"] = table_html
  207. visual_info["table_text"] = table_text
  208. visual_info = VisualInfoResult(visual_info)
  209. # for local user save visual info in self
  210. self.visual_info = visual_info
  211. self.visual_flag = True
  212. return visual_result, visual_info
  213. def get_visual_result(
  214. self,
  215. inputs,
  216. use_doc_image_ori_cls_model=True,
  217. use_doc_image_unwarp_model=True,
  218. use_seal_text_det_model=True,
  219. recovery=True,
  220. ):
  221. # get oricls and unwarp results
  222. img_info_list = list(self.img_reader(inputs))[0]
  223. oricls_results = []
  224. if self.doc_image_ori_cls_predictor and use_doc_image_ori_cls_model:
  225. oricls_results = get_oriclas_results(
  226. img_info_list, self.doc_image_ori_cls_predictor
  227. )
  228. unwarp_results = []
  229. if self.doc_image_unwarp_predictor and use_doc_image_unwarp_model:
  230. unwarp_results = get_unwarp_results(
  231. img_info_list, self.doc_image_unwarp_predictor
  232. )
  233. img_list = [img_info["img"] for img_info in img_info_list]
  234. for idx, (img_info, layout_pred) in enumerate(
  235. zip(img_info_list, self.layout_predictor(img_list))
  236. ):
  237. single_img_res = {
  238. "input_path": "",
  239. "layout_result": DetResult({}),
  240. "ocr_result": OCRResult({}),
  241. "table_ocr_result": [],
  242. "table_result": StructureTableResult([]),
  243. "structure_result": [],
  244. "oricls_result": TopkResult({}),
  245. "unwarp_result": DocTrResult({}),
  246. "curve_result": [],
  247. }
  248. # update oricls and unwarp results
  249. if oricls_results:
  250. single_img_res["oricls_result"] = oricls_results[idx]
  251. if unwarp_results:
  252. single_img_res["unwarp_result"] = unwarp_results[idx]
  253. # update layout result
  254. single_img_res["input_path"] = layout_pred["input_path"]
  255. single_img_res["layout_result"] = layout_pred
  256. single_img = img_info["img"]
  257. table_subs = []
  258. curve_subs = []
  259. structure_res = []
  260. ocr_res_with_layout = []
  261. if len(layout_pred["boxes"]) > 0:
  262. subs_of_img = list(self._crop_by_boxes(layout_pred))
  263. # get cropped images
  264. for sub in subs_of_img:
  265. box = sub["box"]
  266. xmin, ymin, xmax, ymax = [int(i) for i in box]
  267. mask_flag = True
  268. if sub["label"].lower() == "table":
  269. table_subs.append(sub)
  270. elif sub["label"].lower() == "seal":
  271. curve_subs.append(sub)
  272. else:
  273. if self.recovery and recovery:
  274. # TODO: Why use the entire image?
  275. wht_im = (
  276. np.ones(single_img.shape, dtype=single_img.dtype) * 255
  277. )
  278. wht_im[ymin:ymax, xmin:xmax, :] = sub["img"]
  279. sub_ocr_res = get_ocr_res(self.ocr_pipeline, wht_im)
  280. else:
  281. sub_ocr_res = get_ocr_res(self.ocr_pipeline, sub)
  282. sub_ocr_res["dt_polys"] = get_ori_coordinate_for_table(
  283. xmin, ymin, sub_ocr_res["dt_polys"]
  284. )
  285. layout_label = sub["label"].lower()
  286. if sub_ocr_res and sub["label"].lower() in [
  287. "image",
  288. "figure",
  289. "img",
  290. "fig",
  291. ]:
  292. mask_flag = False
  293. else:
  294. ocr_res_with_layout.append(sub_ocr_res)
  295. structure_res.append(
  296. {
  297. "layout_bbox": box,
  298. f"{layout_label}": "\n".join(
  299. sub_ocr_res["rec_text"]
  300. ),
  301. }
  302. )
  303. if mask_flag:
  304. single_img[ymin:ymax, xmin:xmax, :] = 255
  305. curve_pipeline = self.ocr_pipeline
  306. if self.curve_pipeline and use_seal_text_det_model:
  307. curve_pipeline = self.curve_pipeline
  308. all_curve_res = get_ocr_res(curve_pipeline, curve_subs)
  309. single_img_res["curve_result"] = all_curve_res
  310. if isinstance(all_curve_res, dict):
  311. all_curve_res = [all_curve_res]
  312. for sub, curve_res in zip(curve_subs, all_curve_res):
  313. structure_res.append(
  314. {
  315. "layout_bbox": sub["box"],
  316. "印章": "".join(curve_res["rec_text"]),
  317. }
  318. )
  319. ocr_res = get_ocr_res(self.ocr_pipeline, single_img)
  320. ocr_res["input_path"] = layout_pred["input_path"]
  321. all_table_res, _ = self.get_table_result(table_subs)
  322. for idx, single_dt_poly in enumerate(ocr_res["dt_polys"]):
  323. structure_res.append(
  324. {
  325. "layout_bbox": convert_4point2rect(single_dt_poly),
  326. "words in text block": ocr_res["rec_text"][idx],
  327. }
  328. )
  329. # update ocr result
  330. for layout_ocr_res in ocr_res_with_layout:
  331. ocr_res["dt_polys"].extend(layout_ocr_res["dt_polys"])
  332. ocr_res["rec_text"].extend(layout_ocr_res["rec_text"])
  333. ocr_res["input_path"] = single_img_res["input_path"]
  334. all_table_ocr_res = []
  335. # get table text from html
  336. structure_res_table, all_table_ocr_res = get_table_text_from_html(
  337. all_table_res
  338. )
  339. structure_res.extend(structure_res_table)
  340. # sort the layout result by the left top point of the box
  341. structure_res = sorted_layout_boxes(structure_res, w=single_img.shape[1])
  342. structure_res = [LayoutStructureResult(item) for item in structure_res]
  343. single_img_res["table_result"] = all_table_res
  344. single_img_res["ocr_result"] = ocr_res
  345. single_img_res["table_ocr_result"] = all_table_ocr_res
  346. single_img_res["structure_result"] = structure_res
  347. yield VisualResult(single_img_res)
  348. def decode_visual_result(self, visual_result):
  349. ocr_text = []
  350. table_text_list = []
  351. table_html = []
  352. for single_img_pred in visual_result:
  353. layout_res = single_img_pred["structure_result"]
  354. layout_res_copy = deepcopy(layout_res)
  355. # layout_res is [{"layout_bbox": [x1, y1, x2, y2], "layout": "single","words in text block":"xxx"}, {"layout_bbox": [x1, y1, x2, y2], "layout": "double","印章":"xxx"}
  356. ocr_res = {}
  357. for block in layout_res_copy:
  358. block.pop("layout_bbox")
  359. block.pop("layout")
  360. for layout_type, text in block.items():
  361. if text == "":
  362. continue
  363. # Table results are used separately
  364. if layout_type == "table":
  365. continue
  366. if layout_type not in ocr_res:
  367. ocr_res[layout_type] = text
  368. else:
  369. ocr_res[layout_type] += f"\n {text}"
  370. single_table_text = " ".join(single_img_pred["table_ocr_result"])
  371. for table_pred in single_img_pred["table_result"]:
  372. html = table_pred["html"]
  373. table_html.append(html)
  374. if ocr_res:
  375. ocr_text.append(ocr_res)
  376. table_text_list.append(single_table_text)
  377. return ocr_text, table_text_list, table_html
  378. def build_vector(
  379. self,
  380. llm_name=None,
  381. llm_params={},
  382. visual_info=None,
  383. min_characters=3500,
  384. llm_request_interval=1.0,
  385. ):
  386. """get vector for ocr"""
  387. if isinstance(self.llm_api, ErnieBot):
  388. get_vector_flag = True
  389. else:
  390. logging.warning("Do not use ErnieBot, will not get vector text.")
  391. get_vector_flag = False
  392. if not any([visual_info, self.visual_info]):
  393. return VectorResult({"vector": None})
  394. ocr_text = visual_info["ocr_text"]
  395. html_list = visual_info["table_html"]
  396. table_text_list = visual_info["table_text"]
  397. # add table text to ocr text
  398. for html, table_text_rec in zip(html_list, table_text_list):
  399. if len(html) > 3000:
  400. ocr_text.append({"table": table_text_rec})
  401. ocr_all_result = "".join(["\n".join(e.values()) for e in ocr_text])
  402. if len(ocr_all_result) > min_characters and get_vector_flag:
  403. if visual_info and llm_name:
  404. # for serving or local
  405. llm_api = create_llm_api(llm_name, llm_params)
  406. text_result = llm_api.get_vector(ocr_text, llm_request_interval)
  407. else:
  408. # for local
  409. text_result = self.llm_api.get_vector(ocr_text, llm_request_interval)
  410. else:
  411. text_result = str(ocr_text)
  412. self.visual_flag = False
  413. return VectorResult({"vector": text_result})
  414. def retrieval(
  415. self,
  416. key_list,
  417. vector,
  418. llm_name=None,
  419. llm_params={},
  420. llm_request_interval=0.1,
  421. ):
  422. assert "vector" in vector
  423. key_list = format_key(key_list)
  424. # for serving
  425. if llm_name:
  426. _vector = vector["vector"]
  427. llm_api = create_llm_api(llm_name, llm_params)
  428. retrieval = llm_api.caculate_similar(
  429. vector=_vector,
  430. key_list=key_list,
  431. llm_params=llm_params,
  432. sleep_time=llm_request_interval,
  433. )
  434. else:
  435. _vector = vector["vector"]
  436. retrieval = self.llm_api.caculate_similar(
  437. vector=_vector, key_list=key_list, sleep_time=llm_request_interval
  438. )
  439. return RetrievalResult({"retrieval": retrieval})
  440. def chat(
  441. self,
  442. key_list,
  443. vector=None,
  444. visual_info=None,
  445. retrieval_result=None,
  446. user_task_description="",
  447. rules="",
  448. few_shot="",
  449. save_prompt=False,
  450. llm_name=None,
  451. llm_params={},
  452. ):
  453. """
  454. chat with key
  455. """
  456. if not any([vector, visual_info, retrieval_result]):
  457. return ChatResult(
  458. {"chat_res": "请先完成图像解析再开始再对话", "prompt": ""}
  459. )
  460. key_list = format_key(key_list)
  461. # first get from table, then get from text in table, last get from all ocr
  462. ocr_text = visual_info["ocr_text"]
  463. html_list = visual_info["table_html"]
  464. table_text_list = visual_info["table_text"]
  465. prompt_res = {"ocr_prompt": "str", "table_prompt": [], "html_prompt": []}
  466. final_results = {}
  467. failed_results = ["大模型调用失败", "未知", "未找到关键信息", "None", ""]
  468. if html_list:
  469. prompt_list = self.get_prompt_for_table(
  470. html_list, key_list, rules, few_shot
  471. )
  472. prompt_res["html_prompt"] = prompt_list
  473. for prompt, table_text in zip(prompt_list, table_text_list):
  474. logging.debug(prompt)
  475. res = self.get_llm_result(prompt)
  476. # TODO: why use one html but the whole table_text in next step
  477. if list(res.values())[0] in failed_results:
  478. logging.debug(
  479. "table html sequence is too much longer, using ocr directly!"
  480. )
  481. prompt = self.get_prompt_for_ocr(
  482. table_text, key_list, rules, few_shot, user_task_description
  483. )
  484. logging.debug(prompt)
  485. prompt_res["table_prompt"].append(prompt)
  486. res = self.get_llm_result(prompt)
  487. for key, value in res.items():
  488. if value not in failed_results and key in key_list:
  489. key_list.remove(key)
  490. final_results[key] = value
  491. if len(key_list) > 0:
  492. logging.debug("get result from ocr")
  493. if retrieval_result:
  494. ocr_text = retrieval_result.get("retrieval")
  495. elif vector:
  496. # for serving
  497. if llm_name:
  498. ocr_text = self.retrieval(
  499. key_list=key_list,
  500. vector=vector,
  501. llm_name=llm_name,
  502. llm_params=llm_params,
  503. )["retrieval"]
  504. # for local
  505. else:
  506. ocr_text = self.retrieval(key_list=key_list, vector=vector)[
  507. "retrieval"
  508. ]
  509. prompt = self.get_prompt_for_ocr(
  510. ocr_text,
  511. key_list,
  512. rules,
  513. few_shot,
  514. user_task_description,
  515. )
  516. logging.debug(prompt)
  517. prompt_res["ocr_prompt"] = prompt
  518. res = self.get_llm_result(prompt)
  519. if res:
  520. final_results.update(res)
  521. if not res and not final_results:
  522. final_results = self.llm_api.ERROR_MASSAGE
  523. if save_prompt:
  524. return ChatResult({"chat_res": final_results, "prompt": prompt_res})
  525. else:
  526. return ChatResult({"chat_res": final_results, "prompt": ""})
  527. def get_llm_result(self, prompt):
  528. """get llm result and decode to dict"""
  529. llm_result = self.llm_api.pred(prompt)
  530. # when the llm pred failed, return None
  531. if not llm_result:
  532. return None
  533. if "json" in llm_result or "```" in llm_result:
  534. llm_result = (
  535. llm_result.replace("```", "").replace("json", "").replace("/n", "")
  536. )
  537. llm_result = llm_result.replace("[", "").replace("]", "")
  538. try:
  539. llm_result = json.loads(llm_result)
  540. llm_result_final = {}
  541. for key in llm_result:
  542. value = llm_result[key]
  543. if isinstance(value, list):
  544. if len(value) > 0:
  545. llm_result_final[key] = value[0]
  546. else:
  547. llm_result_final[key] = value
  548. return llm_result_final
  549. except:
  550. results = (
  551. llm_result.replace("\n", "")
  552. .replace(" ", "")
  553. .replace("{", "")
  554. .replace("}", "")
  555. )
  556. if not results.endswith('"'):
  557. results = results + '"'
  558. pattern = r'"(.*?)": "([^"]*)"'
  559. matches = re.findall(pattern, str(results))
  560. llm_result = {k: v for k, v in matches}
  561. return llm_result
  562. def get_prompt_for_table(self, table_result, key_list, rules="", few_shot=""):
  563. """get prompt for table"""
  564. prompt_key_information = []
  565. merge_table = ""
  566. for idx, result in enumerate(table_result):
  567. if len(merge_table + result) < 2000:
  568. merge_table += result
  569. if len(merge_table + result) > 2000 or idx == len(table_result) - 1:
  570. single_prompt = self.get_kie_prompt(
  571. merge_table,
  572. key_list,
  573. rules_str=rules,
  574. few_shot_demo_str=few_shot,
  575. prompt_type="table",
  576. )
  577. prompt_key_information.append(single_prompt)
  578. merge_table = ""
  579. return prompt_key_information
  580. def get_prompt_for_ocr(
  581. self,
  582. ocr_result,
  583. key_list,
  584. rules="",
  585. few_shot="",
  586. user_task_description="",
  587. ):
  588. """get prompt for ocr"""
  589. prompt_key_information = self.get_kie_prompt(
  590. ocr_result, key_list, user_task_description, rules, few_shot
  591. )
  592. return prompt_key_information
  593. def get_kie_prompt(
  594. self,
  595. text_result,
  596. key_list,
  597. user_task_description="",
  598. rules_str="",
  599. few_shot_demo_str="",
  600. prompt_type="common",
  601. ):
  602. """get_kie_prompt"""
  603. if prompt_type == "table":
  604. task_description = self.task_prompt_dict["kie_table_prompt"][
  605. "task_description"
  606. ]
  607. else:
  608. task_description = self.task_prompt_dict["kie_common_prompt"][
  609. "task_description"
  610. ]
  611. output_format = self.task_prompt_dict["kie_common_prompt"]["output_format"]
  612. if len(user_task_description) > 0:
  613. task_description = user_task_description
  614. task_description = task_description + output_format
  615. few_shot_demo_key_value = ""
  616. if self.user_prompt_dict:
  617. logging.info("======= common use custom ========")
  618. task_description = self.user_prompt_dict["task_description"]
  619. rules_str = self.user_prompt_dict["rules_str"]
  620. few_shot_demo_str = self.user_prompt_dict["few_shot_demo_str"]
  621. few_shot_demo_key_value = self.user_prompt_dict["few_shot_demo_key_value"]
  622. prompt = f"""{task_description}{rules_str}{few_shot_demo_str}{few_shot_demo_key_value}"""
  623. if prompt_type == "table":
  624. prompt += f"""\n结合上面,下面正式开始:\
  625. 表格内容:```{text_result}```\
  626. 关键词列表:[{key_list}]。""".replace(
  627. " ", ""
  628. )
  629. else:
  630. prompt += f"""\n结合上面的例子,下面正式开始:\
  631. OCR文字:```{text_result}```\
  632. 关键词列表:[{key_list}]。""".replace(
  633. " ", ""
  634. )
  635. return prompt