ppchatocrv3.py 27 KB

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