ppchatocrv3.py 27 KB

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