ppchatocrv3.py 26 KB

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