ppchatocrv3.py 25 KB

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