ppchatocrv3.py 27 KB

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