pipeline_v4.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. from typing import Any, Dict, Optional
  15. import re
  16. import cv2
  17. import json
  18. import base64
  19. import numpy as np
  20. import copy
  21. from .pipeline_base import PP_ChatOCR_Pipeline
  22. from .result import VisualInfoResult
  23. from ...common.reader import ReadImage
  24. from ...common.batch_sampler import ImageBatchSampler
  25. from ....utils import logging
  26. from ...utils.pp_option import PaddlePredictorOption
  27. from ..layout_parsing.result import LayoutParsingResult
  28. class PP_ChatOCRv4_Pipeline(PP_ChatOCR_Pipeline):
  29. """PP-ChatOCRv4 Pipeline"""
  30. entities = ["PP-ChatOCRv4-doc"]
  31. def __init__(
  32. self,
  33. config: Dict,
  34. device: str = None,
  35. pp_option: PaddlePredictorOption = None,
  36. use_hpip: bool = False,
  37. hpi_params: Optional[Dict[str, Any]] = None,
  38. ) -> None:
  39. """Initializes the pp-chatocrv3-doc pipeline.
  40. Args:
  41. config (Dict): Configuration dictionary containing various settings.
  42. device (str, optional): Device to run the predictions on. Defaults to None.
  43. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  44. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  45. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  46. use_layout_parsing (bool, optional): Whether to use layout parsing. Defaults to True.
  47. """
  48. super().__init__(
  49. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  50. )
  51. self.pipeline_name = config["pipeline_name"]
  52. self.inintial_predictor(config)
  53. self.batch_sampler = ImageBatchSampler(batch_size=1)
  54. self.img_reader = ReadImage(format="BGR")
  55. self.table_structure_len_max = 500
  56. def inintial_predictor(self, config: dict) -> None:
  57. """
  58. Initializes the predictor with the given configuration.
  59. Args:
  60. config (dict): The configuration dictionary containing the necessary
  61. parameters for initializing the predictor.
  62. Returns:
  63. None
  64. """
  65. layout_parsing_config = config["SubPipelines"]["LayoutParser"]
  66. self.layout_parsing_pipeline = self.create_pipeline(layout_parsing_config)
  67. from .. import create_chat_bot
  68. chat_bot_config = config["SubModules"]["LLM_Chat"]
  69. self.chat_bot = create_chat_bot(chat_bot_config)
  70. from .. import create_retriever
  71. retriever_config = config["SubModules"]["LLM_Retriever"]
  72. self.retriever = create_retriever(retriever_config)
  73. from .. import create_prompt_engeering
  74. text_pe_config = config["SubModules"]["PromptEngneering"]["KIE_CommonText"]
  75. self.text_pe = create_prompt_engeering(text_pe_config)
  76. table_pe_config = config["SubModules"]["PromptEngneering"]["KIE_Table"]
  77. self.table_pe = create_prompt_engeering(table_pe_config)
  78. self.use_mllm_predict = False
  79. if "use_mllm_predict" in config:
  80. self.use_mllm_predict = config["use_mllm_predict"]
  81. if self.use_mllm_predict:
  82. mllm_chat_bot_config = config["SubModules"]["MLLM_Chat"]
  83. self.mllm_chat_bot = create_chat_bot(mllm_chat_bot_config)
  84. ensemble_pe_config = config["SubModules"]["PromptEngneering"]["Ensemble"]
  85. self.ensemble_pe = create_prompt_engeering(ensemble_pe_config)
  86. return
  87. def decode_visual_result(
  88. self, layout_parsing_result: LayoutParsingResult
  89. ) -> VisualInfoResult:
  90. """
  91. Decodes the visual result from the layout parsing result.
  92. Args:
  93. layout_parsing_result (LayoutParsingResult): The result of layout parsing.
  94. Returns:
  95. VisualInfoResult: The decoded visual information.
  96. """
  97. text_paragraphs_ocr_res = layout_parsing_result["text_paragraphs_ocr_res"]
  98. seal_res_list = layout_parsing_result["seal_res_list"]
  99. normal_text_dict = {}
  100. for seal_res in seal_res_list:
  101. for text in seal_res["rec_text"]:
  102. layout_type = "印章"
  103. if layout_type not in normal_text_dict:
  104. normal_text_dict[layout_type] = f"{text}"
  105. else:
  106. normal_text_dict[layout_type] += f"\n {text}"
  107. for text in text_paragraphs_ocr_res["rec_text"]:
  108. layout_type = "words in text block"
  109. if layout_type not in normal_text_dict:
  110. normal_text_dict[layout_type] = text
  111. else:
  112. normal_text_dict[layout_type] += f"\n {text}"
  113. table_res_list = layout_parsing_result["table_res_list"]
  114. table_text_list = []
  115. table_html_list = []
  116. table_nei_text_list = []
  117. for table_res in table_res_list:
  118. table_html_list.append(table_res["pred_html"])
  119. single_table_text = " ".join(table_res["table_ocr_pred"]["rec_text"])
  120. table_text_list.append(single_table_text)
  121. table_nei_text_list.append(table_res["neighbor_text"])
  122. visual_info = {}
  123. visual_info["normal_text_dict"] = normal_text_dict
  124. visual_info["table_text_list"] = table_text_list
  125. visual_info["table_html_list"] = table_html_list
  126. visual_info["table_nei_text_list"] = table_nei_text_list
  127. return VisualInfoResult(visual_info)
  128. # Function to perform visual prediction on input images
  129. def visual_predict(
  130. self,
  131. input: str | list[str] | np.ndarray | list[np.ndarray],
  132. use_doc_orientation_classify: bool = False, # Whether to use document orientation classification
  133. use_doc_unwarping: bool = False, # Whether to use document unwarping
  134. use_general_ocr: bool = True, # Whether to use general OCR
  135. use_seal_recognition: bool = True, # Whether to use seal recognition
  136. use_table_recognition: bool = True, # Whether to use table recognition
  137. **kwargs,
  138. ) -> dict:
  139. """
  140. This function takes an input image or a list of images and performs various visual
  141. prediction tasks such as document orientation classification, document unwarping,
  142. general OCR, seal recognition, and table recognition based on the provided flags.
  143. Args:
  144. input (str | list[str] | np.ndarray | list[np.ndarray]): Input image path, list of image paths,
  145. numpy array of an image, or list of numpy arrays.
  146. use_doc_orientation_classify (bool): Flag to use document orientation classification.
  147. use_doc_unwarping (bool): Flag to use document unwarping.
  148. use_general_ocr (bool): Flag to use general OCR.
  149. use_seal_recognition (bool): Flag to use seal recognition.
  150. use_table_recognition (bool): Flag to use table recognition.
  151. **kwargs: Additional keyword arguments.
  152. Returns:
  153. dict: A dictionary containing the layout parsing result and visual information.
  154. """
  155. for layout_parsing_result in self.layout_parsing_pipeline.predict(
  156. input,
  157. use_doc_orientation_classify=use_doc_orientation_classify,
  158. use_doc_unwarping=use_doc_unwarping,
  159. use_general_ocr=use_general_ocr,
  160. use_seal_recognition=use_seal_recognition,
  161. use_table_recognition=use_table_recognition,
  162. ):
  163. visual_info = self.decode_visual_result(layout_parsing_result)
  164. visual_predict_res = {
  165. "layout_parsing_result": layout_parsing_result,
  166. "visual_info": visual_info,
  167. }
  168. yield visual_predict_res
  169. def save_visual_info_list(
  170. self, visual_info: VisualInfoResult, save_path: str
  171. ) -> None:
  172. """
  173. Save the visual info list to the specified file path.
  174. Args:
  175. visual_info (VisualInfoResult): The visual info result, which can be a single object or a list of objects.
  176. save_path (str): The file path to save the visual info list.
  177. Returns:
  178. None
  179. """
  180. if not isinstance(visual_info, list):
  181. visual_info_list = [visual_info]
  182. else:
  183. visual_info_list = visual_info
  184. with open(save_path, "w") as fout:
  185. fout.write(json.dumps(visual_info_list, ensure_ascii=False) + "\n")
  186. return
  187. def load_visual_info_list(self, data_path: str) -> list[VisualInfoResult]:
  188. """
  189. Loads visual info list from a JSON file.
  190. Args:
  191. data_path (str): The path to the JSON file containing visual info.
  192. Returns:
  193. list[VisualInfoResult]: A list of VisualInfoResult objects parsed from the JSON file.
  194. """
  195. with open(data_path, "r") as fin:
  196. data = fin.readline()
  197. visual_info_list = json.loads(data)
  198. return visual_info_list
  199. def merge_visual_info_list(
  200. self, visual_info_list: list[VisualInfoResult]
  201. ) -> tuple[list, list, list, list]:
  202. """
  203. Merge visual info lists.
  204. Args:
  205. visual_info_list (list[VisualInfoResult]): A list of visual info results.
  206. Returns:
  207. tuple[list, list, list, list]: A tuple containing four lists, one for normal text dicts,
  208. one for table text lists, one for table HTML lists.
  209. one for table neighbor texts.
  210. """
  211. all_normal_text_list = []
  212. all_table_text_list = []
  213. all_table_html_list = []
  214. all_table_nei_text_list = []
  215. for single_visual_info in visual_info_list:
  216. normal_text_dict = single_visual_info["normal_text_dict"]
  217. for key in normal_text_dict:
  218. normal_text_dict[key] = normal_text_dict[key].replace("\n", "")
  219. table_text_list = single_visual_info["table_text_list"]
  220. table_html_list = single_visual_info["table_html_list"]
  221. table_nei_text_list = single_visual_info["table_nei_text_list"]
  222. all_normal_text_list.append(normal_text_dict)
  223. all_table_text_list.extend(table_text_list)
  224. all_table_html_list.extend(table_html_list)
  225. all_table_nei_text_list.extend(table_nei_text_list)
  226. return (
  227. all_normal_text_list,
  228. all_table_text_list,
  229. all_table_html_list,
  230. all_table_nei_text_list,
  231. )
  232. def build_vector(
  233. self,
  234. visual_info: VisualInfoResult,
  235. min_characters: int = 3500,
  236. llm_request_interval: float = 1.0,
  237. ) -> dict:
  238. """
  239. Build a vector representation from visual information.
  240. Args:
  241. visual_info (VisualInfoResult): The visual information input, can be a single instance or a list of instances.
  242. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  243. llm_request_interval (float): The interval between LLM requests, defaults to 1.0.
  244. Returns:
  245. dict: A dictionary containing the vector info and a flag indicating if the text is too short.
  246. """
  247. if not isinstance(visual_info, list):
  248. visual_info_list = [visual_info]
  249. else:
  250. visual_info_list = visual_info
  251. all_visual_info = self.merge_visual_info_list(visual_info_list)
  252. (
  253. all_normal_text_list,
  254. all_table_text_list,
  255. all_table_html_list,
  256. all_table_nei_text_list,
  257. ) = all_visual_info
  258. vector_info = {}
  259. all_items = []
  260. for i, normal_text_dict in enumerate(all_normal_text_list):
  261. for type, text in normal_text_dict.items():
  262. all_items += [f"{type}:{text}\n"]
  263. for table_html, table_text, table_nei_text in zip(
  264. all_table_html_list, all_table_text_list, all_table_nei_text_list
  265. ):
  266. if len(table_html) > min_characters - self.table_structure_len_max:
  267. all_items += [f"table:{table_text}\t{table_nei_text}"]
  268. all_text_str = "".join(all_items)
  269. if len(all_text_str) > min_characters:
  270. vector_info["flag_too_short_text"] = False
  271. vector_info["vector"] = self.retriever.generate_vector_database(all_items)
  272. else:
  273. vector_info["flag_too_short_text"] = True
  274. vector_info["vector"] = all_items
  275. return vector_info
  276. def save_vector(self, vector_info: dict, save_path: str) -> None:
  277. if "flag_too_short_text" not in vector_info or "vector" not in vector_info:
  278. logging.error("Invalid vector info.")
  279. return
  280. save_vector_info = {}
  281. save_vector_info["flag_too_short_text"] = vector_info["flag_too_short_text"]
  282. if not vector_info["flag_too_short_text"]:
  283. save_vector_info["vector"] = self.retriever.encode_vector_store_to_bytes(
  284. vector_info["vector"]
  285. )
  286. else:
  287. save_vector_info["vector"] = vector_info["vector"]
  288. with open(save_path, "w") as fout:
  289. fout.write(json.dumps(save_vector_info, ensure_ascii=False) + "\n")
  290. return
  291. def load_vector(self, data_path: str) -> dict:
  292. vector_info = None
  293. with open(data_path, "r") as fin:
  294. data = fin.readline()
  295. vector_info = json.loads(data)
  296. if "flag_too_short_text" not in vector_info or "vector" not in vector_info:
  297. logging.error("Invalid vector info.")
  298. return
  299. if not vector_info["flag_too_short_text"]:
  300. vector_info["vector"] = self.retriever.decode_vector_store_from_bytes(
  301. vector_info["vector"]
  302. )
  303. return vector_info
  304. def format_key(self, key_list: str | list[str]) -> list[str]:
  305. """
  306. Formats the key list.
  307. Args:
  308. key_list (str|list[str]): A string or a list of strings representing the keys.
  309. Returns:
  310. list[str]: A list of formatted keys.
  311. """
  312. if key_list == "":
  313. return []
  314. if isinstance(key_list, list):
  315. key_list = [key.replace("\xa0", " ") for key in key_list]
  316. return key_list
  317. if isinstance(key_list, str):
  318. key_list = re.sub(r"[\t\n\r\f\v]", "", key_list)
  319. key_list = key_list.replace(",", ",").split(",")
  320. return key_list
  321. return []
  322. def mllm_pred(
  323. self,
  324. input: str | np.ndarray,
  325. key_list,
  326. **kwargs,
  327. ) -> dict:
  328. key_list = self.format_key(key_list)
  329. if len(key_list) == 0:
  330. return {"mllm_res": "Error:输入的key_list无效!"}
  331. if isinstance(input, list):
  332. logging.error("Input is a list, but it's not supported here.")
  333. return {"mllm_res": "Error:Input is a list, but it's not supported here!"}
  334. image_array_list = self.img_reader([input])
  335. if (
  336. isinstance(input, str)
  337. and input.endswith(".pdf")
  338. and len(image_array_list) > 1
  339. ):
  340. logging.error("The input with PDF should have only one page.")
  341. return {"mllm_res": "Error:The input with PDF should have only one page!"}
  342. for image_array in image_array_list:
  343. assert len(image_array.shape) == 3
  344. image_string = cv2.imencode(".jpg", image_array)[1].tostring()
  345. image_base64 = base64.b64encode(image_string).decode("utf-8")
  346. result = {}
  347. for key in key_list:
  348. prompt = (
  349. str(key)
  350. + "\n请用图片中完整出现的内容回答,可以是单词、短语或句子,针对问题回答尽可能详细和完整,并保持格式、单位、符号和标点都与图片中的文字内容完全一致。"
  351. )
  352. mllm_chat_bot_result = self.mllm_chat_bot.generate_chat_results(
  353. prompt=prompt, image=image_base64
  354. )
  355. if mllm_chat_bot_result is None:
  356. return {"mllm_res": "大模型调用失败"}
  357. result[key] = mllm_chat_bot_result
  358. return {"mllm_res": result}
  359. def generate_and_merge_chat_results(
  360. self, prompt: str, key_list: list, final_results: dict, failed_results: list
  361. ) -> None:
  362. """
  363. Generate and merge chat results into the final results dictionary.
  364. Args:
  365. prompt (str): The input prompt for the chat bot.
  366. key_list (list): A list of keys to track which results to merge.
  367. final_results (dict): The dictionary to store the final merged results.
  368. failed_results (list): A list of failed results to avoid merging.
  369. Returns:
  370. None
  371. """
  372. llm_result = self.chat_bot.generate_chat_results(prompt)
  373. if llm_result is None:
  374. logging.error(
  375. "chat bot error: \n [prompt:]\n %s\n [result:] %s\n"
  376. % (prompt, self.chat_bot.ERROR_MASSAGE)
  377. )
  378. return
  379. llm_result = self.chat_bot.fix_llm_result_format(llm_result)
  380. for key, value in llm_result.items():
  381. if value not in failed_results and key in key_list:
  382. key_list.remove(key)
  383. final_results[key] = value
  384. return
  385. def get_related_normal_text(
  386. self,
  387. use_vector_retrieval: bool,
  388. vector_info: dict,
  389. key_list: list[str],
  390. all_normal_text_list: list,
  391. min_characters: int,
  392. ) -> str:
  393. """
  394. Retrieve related normal text based on vector retrieval or all normal text list.
  395. Args:
  396. use_vector_retrieval (bool): Whether to use vector retrieval.
  397. vector_info (dict): Dictionary containing vector information.
  398. key_list (list[str]): List of keys to generate question keys.
  399. all_normal_text_list (list): List of normal text.
  400. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  401. Returns:
  402. str: Related normal text.
  403. """
  404. if use_vector_retrieval and vector_info is not None:
  405. question_key_list = [f"{key}" for key in key_list]
  406. vector = vector_info["vector"]
  407. if not vector_info["flag_too_short_text"]:
  408. related_text = self.retriever.similarity_retrieval(
  409. question_key_list, vector, topk=5, min_characters=min_characters
  410. )
  411. else:
  412. if len(vector) > 0:
  413. related_text = "".join(vector)
  414. else:
  415. related_text = ""
  416. else:
  417. all_items = []
  418. for i, normal_text_dict in enumerate(all_normal_text_list):
  419. for type, text in normal_text_dict.items():
  420. all_items += [f"{type}:{text}\n"]
  421. related_text = "".join(all_items)
  422. if len(related_text) > min_characters:
  423. logging.warning(
  424. "The input text content is too long, the large language model may truncate it."
  425. )
  426. return related_text
  427. def ensemble_ocr_llm_mllm(
  428. self, key_list: list[str], ocr_llm_predict_dict: dict, mllm_predict_dict: dict
  429. ) -> dict:
  430. """
  431. Ensemble OCR_LLM and LMM predictions based on given key list.
  432. Args:
  433. key_list (list[str]): List of keys to retrieve predictions.
  434. ocr_llm_predict_dict (dict): Dictionary containing OCR LLM predictions.
  435. mllm_predict_dict (dict): Dictionary containing mLLM predictions.
  436. Returns:
  437. dict: A dictionary with final predictions.
  438. """
  439. final_predict_dict = {}
  440. for key in key_list:
  441. predict = ""
  442. ocr_llm_predict = ""
  443. mllm_predict = ""
  444. if key in ocr_llm_predict_dict:
  445. ocr_llm_predict = ocr_llm_predict_dict[key]
  446. if key in mllm_predict_dict:
  447. mllm_predict = mllm_predict_dict[key]
  448. if ocr_llm_predict != "" and mllm_predict != "":
  449. prompt = self.ensemble_pe.generate_prompt(
  450. key, ocr_llm_predict, mllm_predict
  451. )
  452. llm_result = self.chat_bot.generate_chat_results(prompt)
  453. if llm_result is not None:
  454. llm_result = self.chat_bot.fix_llm_result_format(llm_result)
  455. if key in llm_result:
  456. tmp = llm_result[key]
  457. if "B" in tmp:
  458. predict = mllm_predict
  459. else:
  460. predict = ocr_llm_predict
  461. else:
  462. predict = ocr_llm_predict
  463. elif key in ocr_llm_predict_dict:
  464. predict = ocr_llm_predict_dict[key]
  465. elif key in mllm_predict_dict:
  466. predict = mllm_predict_dict[key]
  467. if predict != "":
  468. final_predict_dict[key] = predict
  469. return final_predict_dict
  470. def chat(
  471. self,
  472. key_list: str | list[str],
  473. visual_info: VisualInfoResult,
  474. use_vector_retrieval: bool = True,
  475. vector_info: dict = None,
  476. min_characters: int = 3500,
  477. text_task_description: str = None,
  478. text_output_format: str = None,
  479. text_rules_str: str = None,
  480. text_few_shot_demo_text_content: str = None,
  481. text_few_shot_demo_key_value_list: str = None,
  482. table_task_description: str = None,
  483. table_output_format: str = None,
  484. table_rules_str: str = None,
  485. table_few_shot_demo_text_content: str = None,
  486. table_few_shot_demo_key_value_list: str = None,
  487. mllm_predict_dict: dict = None,
  488. mllm_integration_strategy: str = "integration",
  489. ) -> dict:
  490. """
  491. Generates chat results based on the provided key list and visual information.
  492. Args:
  493. key_list (str | list[str]): A single key or a list of keys to extract information.
  494. visual_info (VisualInfoResult): The visual information result.
  495. use_vector_retrieval (bool): Whether to use vector retrieval.
  496. vector_info (dict): The vector information for retrieval.
  497. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  498. text_task_description (str): The description of the text task.
  499. text_output_format (str): The output format for text results.
  500. text_rules_str (str): The rules for generating text results.
  501. text_few_shot_demo_text_content (str): The text content for few-shot demos.
  502. text_few_shot_demo_key_value_list (str): The key-value list for few-shot demos.
  503. table_task_description (str): The description of the table task.
  504. table_output_format (str): The output format for table results.
  505. table_rules_str (str): The rules for generating table results.
  506. table_few_shot_demo_text_content (str): The text content for table few-shot demos.
  507. table_few_shot_demo_key_value_list (str): The key-value list for table few-shot demos.
  508. mllm_predict_dict (dict): The dictionary of mLLM predicts.
  509. mllm_integration_strategy(str): The integration strategy of mLLM and LLM, defaults to "integration", options are "integration", "llm_only" and "mllm_only".
  510. Returns:
  511. dict: A dictionary containing the chat results.
  512. """
  513. key_list = self.format_key(key_list)
  514. key_list_ori = key_list.copy()
  515. if len(key_list) == 0:
  516. return {"chat_res": "Error:输入的key_list无效!"}
  517. if not isinstance(visual_info, list):
  518. visual_info_list = [visual_info]
  519. else:
  520. visual_info_list = visual_info
  521. all_visual_info = self.merge_visual_info_list(visual_info_list)
  522. (
  523. all_normal_text_list,
  524. all_table_text_list,
  525. all_table_html_list,
  526. all_table_nei_text_list,
  527. ) = all_visual_info
  528. final_results = {}
  529. failed_results = ["大模型调用失败", "未知", "未找到关键信息", "None", ""]
  530. if len(key_list) > 0:
  531. related_text = self.get_related_normal_text(
  532. use_vector_retrieval,
  533. vector_info,
  534. key_list,
  535. all_normal_text_list,
  536. min_characters,
  537. )
  538. if len(related_text) > 0:
  539. prompt = self.text_pe.generate_prompt(
  540. related_text,
  541. key_list,
  542. task_description=text_task_description,
  543. output_format=text_output_format,
  544. rules_str=text_rules_str,
  545. few_shot_demo_text_content=text_few_shot_demo_text_content,
  546. few_shot_demo_key_value_list=text_few_shot_demo_key_value_list,
  547. )
  548. self.generate_and_merge_chat_results(
  549. prompt, key_list, final_results, failed_results
  550. )
  551. if len(key_list) > 0:
  552. for table_html, table_text, table_nei_text in zip(
  553. all_table_html_list, all_table_text_list, all_table_nei_text_list
  554. ):
  555. if len(table_html) <= min_characters - self.table_structure_len_max:
  556. for table_info in [table_html]:
  557. if len(key_list) > 0:
  558. if len(table_nei_text) > 0:
  559. table_info = (
  560. table_info + "\n 表格周围文字:" + table_nei_text
  561. )
  562. prompt = self.table_pe.generate_prompt(
  563. table_info,
  564. key_list,
  565. task_description=table_task_description,
  566. output_format=table_output_format,
  567. rules_str=table_rules_str,
  568. few_shot_demo_text_content=table_few_shot_demo_text_content,
  569. few_shot_demo_key_value_list=table_few_shot_demo_key_value_list,
  570. )
  571. self.generate_and_merge_chat_results(
  572. prompt, key_list, final_results, failed_results
  573. )
  574. if self.use_mllm_predict and mllm_predict_dict != "llm_only":
  575. if mllm_integration_strategy == "integration":
  576. final_predict_dict = self.ensemble_ocr_llm_mllm(
  577. key_list_ori, final_results, mllm_predict_dict
  578. )
  579. elif mllm_integration_strategy == "mllm_only":
  580. final_predict_dict = mllm_predict_dict
  581. else:
  582. return {
  583. "chat_res": f"Error:Unsupported mllm_integration_strategy {mllm_integration_strategy}, only support 'integration', 'llm_only' and 'mllm_only'!"
  584. }
  585. else:
  586. final_predict_dict = final_results
  587. return {"chat_res": final_predict_dict}
  588. def predict(self, *args, **kwargs) -> None:
  589. logging.error(
  590. "PP-ChatOCRv4-doc Pipeline do not support to call `predict()` directly! Please invoke `visual_predict`, `build_vector`, `chat` sequentially to obtain the result."
  591. )
  592. return