ppchatocrv3.py 27 KB

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