pipeline_v3.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 json
  17. import numpy as np
  18. import copy
  19. from .pipeline_base import PP_ChatOCR_Pipeline
  20. from .result import VisualInfoResult
  21. from ...common.reader import ReadImage
  22. from ...common.batch_sampler import ImageBatchSampler
  23. from ....utils import logging
  24. from ...utils.pp_option import PaddlePredictorOption
  25. from ..layout_parsing.result import LayoutParsingResult
  26. class PP_ChatOCRv3_Pipeline(PP_ChatOCR_Pipeline):
  27. """PP-ChatOCR Pipeline"""
  28. entities = ["PP-ChatOCRv3-doc"]
  29. def __init__(
  30. self,
  31. config: Dict,
  32. device: str = None,
  33. pp_option: PaddlePredictorOption = None,
  34. use_hpip: bool = False,
  35. hpi_params: Optional[Dict[str, Any]] = None,
  36. ) -> None:
  37. """Initializes the pp-chatocrv3-doc pipeline.
  38. Args:
  39. config (Dict): Configuration dictionary containing various settings.
  40. device (str, optional): Device to run the predictions on. Defaults to None.
  41. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  42. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  43. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  44. use_layout_parsing (bool, optional): Whether to use layout parsing. Defaults to True.
  45. """
  46. super().__init__(
  47. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  48. )
  49. self.pipeline_name = config["pipeline_name"]
  50. self.inintial_predictor(config)
  51. self.batch_sampler = ImageBatchSampler(batch_size=1)
  52. self.img_reader = ReadImage(format="BGR")
  53. self.table_structure_len_max = 500
  54. def inintial_predictor(self, config: dict) -> None:
  55. """
  56. Initializes the predictor with the given configuration.
  57. Args:
  58. config (dict): The configuration dictionary containing the necessary
  59. parameters for initializing the predictor.
  60. Returns:
  61. None
  62. """
  63. layout_parsing_config = config["SubPipelines"]["LayoutParser"]
  64. self.layout_parsing_pipeline = self.create_pipeline(layout_parsing_config)
  65. from .. import create_chat_bot
  66. chat_bot_config = config["SubModules"]["LLM_Chat"]
  67. self.chat_bot = create_chat_bot(chat_bot_config)
  68. from .. import create_retriever
  69. retriever_config = config["SubModules"]["LLM_Retriever"]
  70. self.retriever = create_retriever(retriever_config)
  71. from .. import create_prompt_engeering
  72. text_pe_config = config["SubModules"]["PromptEngneering"]["KIE_CommonText"]
  73. self.text_pe = create_prompt_engeering(text_pe_config)
  74. table_pe_config = config["SubModules"]["PromptEngneering"]["KIE_Table"]
  75. self.table_pe = create_prompt_engeering(table_pe_config)
  76. return
  77. def decode_visual_result(
  78. self, layout_parsing_result: LayoutParsingResult
  79. ) -> VisualInfoResult:
  80. """
  81. Decodes the visual result from the layout parsing result.
  82. Args:
  83. layout_parsing_result (LayoutParsingResult): The result of layout parsing.
  84. Returns:
  85. VisualInfoResult: The decoded visual information.
  86. """
  87. text_paragraphs_ocr_res = layout_parsing_result["text_paragraphs_ocr_res"]
  88. seal_res_list = layout_parsing_result["seal_res_list"]
  89. normal_text_dict = {}
  90. for seal_res in seal_res_list:
  91. for text in seal_res["rec_text"]:
  92. layout_type = "印章"
  93. if layout_type not in normal_text_dict:
  94. normal_text_dict[layout_type] = f"{text}"
  95. else:
  96. normal_text_dict[layout_type] += f"\n {text}"
  97. for text in text_paragraphs_ocr_res["rec_text"]:
  98. layout_type = "words in text block"
  99. if layout_type not in normal_text_dict:
  100. normal_text_dict[layout_type] = text
  101. else:
  102. normal_text_dict[layout_type] += f"\n {text}"
  103. table_res_list = layout_parsing_result["table_res_list"]
  104. table_text_list = []
  105. table_html_list = []
  106. for table_res in table_res_list:
  107. table_html_list.append(table_res["pred_html"])
  108. single_table_text = " ".join(table_res["table_ocr_pred"]["rec_text"])
  109. table_text_list.append(single_table_text)
  110. visual_info = {}
  111. visual_info["normal_text_dict"] = normal_text_dict
  112. visual_info["table_text_list"] = table_text_list
  113. visual_info["table_html_list"] = table_html_list
  114. return VisualInfoResult(visual_info)
  115. # Function to perform visual prediction on input images
  116. def visual_predict(
  117. self,
  118. input: str | list[str] | np.ndarray | list[np.ndarray],
  119. use_doc_orientation_classify: bool = False, # Whether to use document orientation classification
  120. use_doc_unwarping: bool = False, # Whether to use document unwarping
  121. use_general_ocr: bool = True, # Whether to use general OCR
  122. use_seal_recognition: bool = True, # Whether to use seal recognition
  123. use_table_recognition: bool = True, # Whether to use table recognition
  124. **kwargs,
  125. ) -> dict:
  126. """
  127. This function takes an input image or a list of images and performs various visual
  128. prediction tasks such as document orientation classification, document unwarping,
  129. general OCR, seal recognition, and table recognition based on the provided flags.
  130. Args:
  131. input (str | list[str] | np.ndarray | list[np.ndarray]): Input image path, list of image paths,
  132. numpy array of an image, or list of numpy arrays.
  133. use_doc_orientation_classify (bool): Flag to use document orientation classification.
  134. use_doc_unwarping (bool): Flag to use document unwarping.
  135. use_general_ocr (bool): Flag to use general OCR.
  136. use_seal_recognition (bool): Flag to use seal recognition.
  137. use_table_recognition (bool): Flag to use table recognition.
  138. **kwargs: Additional keyword arguments.
  139. Returns:
  140. dict: A dictionary containing the layout parsing result and visual information.
  141. """
  142. for layout_parsing_result in self.layout_parsing_pipeline.predict(
  143. input,
  144. use_doc_orientation_classify=use_doc_orientation_classify,
  145. use_doc_unwarping=use_doc_unwarping,
  146. use_general_ocr=use_general_ocr,
  147. use_seal_recognition=use_seal_recognition,
  148. use_table_recognition=use_table_recognition,
  149. ):
  150. visual_info = self.decode_visual_result(layout_parsing_result)
  151. visual_predict_res = {
  152. "layout_parsing_result": layout_parsing_result,
  153. "visual_info": visual_info,
  154. }
  155. yield visual_predict_res
  156. def save_visual_info_list(
  157. self, visual_info: VisualInfoResult, save_path: str
  158. ) -> None:
  159. """
  160. Save the visual info list to the specified file path.
  161. Args:
  162. visual_info (VisualInfoResult): The visual info result, which can be a single object or a list of objects.
  163. save_path (str): The file path to save the visual info list.
  164. Returns:
  165. None
  166. """
  167. if not isinstance(visual_info, list):
  168. visual_info_list = [visual_info]
  169. else:
  170. visual_info_list = visual_info
  171. with open(save_path, "w") as fout:
  172. fout.write(json.dumps(visual_info_list, ensure_ascii=False) + "\n")
  173. return
  174. def load_visual_info_list(self, data_path: str) -> list[VisualInfoResult]:
  175. """
  176. Loads visual info list from a JSON file.
  177. Args:
  178. data_path (str): The path to the JSON file containing visual info.
  179. Returns:
  180. list[VisualInfoResult]: A list of VisualInfoResult objects parsed from the JSON file.
  181. """
  182. with open(data_path, "r") as fin:
  183. data = fin.readline()
  184. visual_info_list = json.loads(data)
  185. return visual_info_list
  186. def merge_visual_info_list(
  187. self, visual_info_list: list[VisualInfoResult]
  188. ) -> tuple[list, list, list]:
  189. """
  190. Merge visual info lists.
  191. Args:
  192. visual_info_list (list[VisualInfoResult]): A list of visual info results.
  193. Returns:
  194. tuple[list, list, list]: A tuple containing four lists, one for normal text dicts,
  195. one for table text lists, one for table HTML lists.
  196. """
  197. all_normal_text_list = []
  198. all_table_text_list = []
  199. all_table_html_list = []
  200. for single_visual_info in visual_info_list:
  201. normal_text_dict = single_visual_info["normal_text_dict"]
  202. for key in normal_text_dict:
  203. normal_text_dict[key] = normal_text_dict[key].replace("\n", "")
  204. table_text_list = single_visual_info["table_text_list"]
  205. table_html_list = single_visual_info["table_html_list"]
  206. all_normal_text_list.append(normal_text_dict)
  207. all_table_text_list.extend(table_text_list)
  208. all_table_html_list.extend(table_html_list)
  209. return (all_normal_text_list, all_table_text_list, all_table_html_list)
  210. def build_vector(
  211. self,
  212. visual_info: VisualInfoResult,
  213. min_characters: int = 3500,
  214. llm_request_interval: float = 1.0,
  215. ) -> dict:
  216. """
  217. Build a vector representation from visual information.
  218. Args:
  219. visual_info (VisualInfoResult): The visual information input, can be a single instance or a list of instances.
  220. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  221. llm_request_interval (float): The interval between LLM requests, defaults to 1.0.
  222. Returns:
  223. dict: A dictionary containing the vector info and a flag indicating if the text is too short.
  224. """
  225. if not isinstance(visual_info, list):
  226. visual_info_list = [visual_info]
  227. else:
  228. visual_info_list = visual_info
  229. all_visual_info = self.merge_visual_info_list(visual_info_list)
  230. (
  231. all_normal_text_list,
  232. all_table_text_list,
  233. all_table_html_list,
  234. ) = all_visual_info
  235. vector_info = {}
  236. all_items = []
  237. for i, normal_text_dict in enumerate(all_normal_text_list):
  238. for type, text in normal_text_dict.items():
  239. all_items += [f"{type}:{text}\n"]
  240. for table_html, table_text in zip(all_table_html_list, all_table_text_list):
  241. if len(table_html) > min_characters - self.table_structure_len_max:
  242. all_items += [f"table:{table_text}"]
  243. all_text_str = "".join(all_items)
  244. if len(all_text_str) > min_characters:
  245. vector_info["flag_too_short_text"] = False
  246. vector_info["vector"] = self.retriever.generate_vector_database(all_items)
  247. else:
  248. vector_info["flag_too_short_text"] = True
  249. vector_info["vector"] = all_items
  250. return vector_info
  251. def save_vector(self, vector_info: dict, save_path: str) -> None:
  252. if "flag_too_short_text" not in vector_info or "vector" not in vector_info:
  253. logging.error("Invalid vector info.")
  254. return
  255. save_vector_info = {}
  256. save_vector_info["flag_too_short_text"] = vector_info["flag_too_short_text"]
  257. if not vector_info["flag_too_short_text"]:
  258. save_vector_info["vector"] = self.retriever.encode_vector_store_to_bytes(
  259. vector_info["vector"]
  260. )
  261. else:
  262. save_vector_info["vector"] = vector_info["vector"]
  263. with open(save_path, "w") as fout:
  264. fout.write(json.dumps(save_vector_info, ensure_ascii=False) + "\n")
  265. return
  266. def load_vector(self, data_path: str) -> dict:
  267. vector_info = None
  268. with open(data_path, "r") as fin:
  269. data = fin.readline()
  270. vector_info = json.loads(data)
  271. if "flag_too_short_text" not in vector_info or "vector" not in vector_info:
  272. logging.error("Invalid vector info.")
  273. return {}
  274. if not vector_info["flag_too_short_text"]:
  275. vector_info["vector"] = self.retriever.decode_vector_store_from_bytes(
  276. vector_info["vector"]
  277. )
  278. return vector_info
  279. def format_key(self, key_list: str | list[str]) -> list[str]:
  280. """
  281. Formats the key list.
  282. Args:
  283. key_list (str|list[str]): A string or a list of strings representing the keys.
  284. Returns:
  285. list[str]: A list of formatted keys.
  286. """
  287. if key_list == "":
  288. return []
  289. if isinstance(key_list, list):
  290. return key_list
  291. if isinstance(key_list, str):
  292. key_list = re.sub(r"[\t\n\r\f\v]", "", key_list)
  293. key_list = key_list.replace(",", ",").split(",")
  294. return key_list
  295. return []
  296. def generate_and_merge_chat_results(
  297. self, prompt: str, key_list: list, final_results: dict, failed_results: list
  298. ) -> None:
  299. """
  300. Generate and merge chat results into the final results dictionary.
  301. Args:
  302. prompt (str): The input prompt for the chat bot.
  303. key_list (list): A list of keys to track which results to merge.
  304. final_results (dict): The dictionary to store the final merged results.
  305. failed_results (list): A list of failed results to avoid merging.
  306. Returns:
  307. None
  308. """
  309. llm_result = self.chat_bot.generate_chat_results(prompt)
  310. if llm_result is None:
  311. logging.error(
  312. "chat bot error: \n [prompt:]\n %s\n [result:] %s\n"
  313. % (prompt, self.chat_bot.ERROR_MASSAGE)
  314. )
  315. return
  316. llm_result = self.chat_bot.fix_llm_result_format(llm_result)
  317. for key, value in llm_result.items():
  318. if value not in failed_results and key in key_list:
  319. key_list.remove(key)
  320. final_results[key] = value
  321. return
  322. def get_related_normal_text(
  323. self,
  324. use_vector_retrieval: bool,
  325. vector_info: dict,
  326. key_list: list[str],
  327. all_normal_text_list: list,
  328. min_characters: int,
  329. ) -> str:
  330. """
  331. Retrieve related normal text based on vector retrieval or all normal text list.
  332. Args:
  333. use_vector_retrieval (bool): Whether to use vector retrieval.
  334. vector_info (dict): Dictionary containing vector information.
  335. key_list (list[str]): List of keys to generate question keys.
  336. all_normal_text_list (list): List of normal text.
  337. min_characters (int): Minimum number of characters required for the output.
  338. Returns:
  339. str: Related normal text.
  340. """
  341. if use_vector_retrieval and vector_info is not None:
  342. question_key_list = [f"{key}" for key in key_list]
  343. vector = vector_info["vector"]
  344. if not vector_info["flag_too_short_text"]:
  345. related_text = self.retriever.similarity_retrieval(
  346. question_key_list, vector
  347. )
  348. else:
  349. if len(vector) > 0:
  350. related_text = "".join(vector)
  351. else:
  352. related_text = ""
  353. else:
  354. all_items = []
  355. for i, normal_text_dict in enumerate(all_normal_text_list):
  356. for type, text in normal_text_dict.items():
  357. all_items += [f"{type}:{text}\n"]
  358. related_text = "".join(all_items)
  359. if len(related_text) > min_characters:
  360. logging.warning(
  361. "The input text content is too long, the large language model may truncate it."
  362. )
  363. return related_text
  364. def chat(
  365. self,
  366. key_list: str | list[str],
  367. visual_info: VisualInfoResult,
  368. use_vector_retrieval: bool = True,
  369. vector_info: dict = None,
  370. min_characters: int = 3500,
  371. text_task_description: str = None,
  372. text_output_format: str = None,
  373. text_rules_str: str = None,
  374. text_few_shot_demo_text_content: str = None,
  375. text_few_shot_demo_key_value_list: str = None,
  376. table_task_description: str = None,
  377. table_output_format: str = None,
  378. table_rules_str: str = None,
  379. table_few_shot_demo_text_content: str = None,
  380. table_few_shot_demo_key_value_list: str = None,
  381. ) -> dict:
  382. """
  383. Generates chat results based on the provided key list and visual information.
  384. Args:
  385. key_list (str | list[str]): A single key or a list of keys to extract information.
  386. visual_info (VisualInfoResult): The visual information result.
  387. use_vector_retrieval (bool): Whether to use vector retrieval.
  388. vector_info (dict): The vector information for retrieval.
  389. min_characters (int): The minimum number of characters required.
  390. text_task_description (str): The description of the text task.
  391. text_output_format (str): The output format for text results.
  392. text_rules_str (str): The rules for generating text results.
  393. text_few_shot_demo_text_content (str): The text content for few-shot demos.
  394. text_few_shot_demo_key_value_list (str): The key-value list for few-shot demos.
  395. table_task_description (str): The description of the table task.
  396. table_output_format (str): The output format for table results.
  397. table_rules_str (str): The rules for generating table results.
  398. table_few_shot_demo_text_content (str): The text content for table few-shot demos.
  399. table_few_shot_demo_key_value_list (str): The key-value list for table few-shot demos.
  400. Returns:
  401. dict: A dictionary containing the chat results.
  402. """
  403. key_list = self.format_key(key_list)
  404. key_list_ori = key_list.copy()
  405. if len(key_list) == 0:
  406. return {"chat_res": "Error:输入的key_list无效!"}
  407. if not isinstance(visual_info, list):
  408. visual_info_list = [visual_info]
  409. else:
  410. visual_info_list = visual_info
  411. all_visual_info = self.merge_visual_info_list(visual_info_list)
  412. (
  413. all_normal_text_list,
  414. all_table_text_list,
  415. all_table_html_list,
  416. ) = all_visual_info
  417. final_results = {}
  418. failed_results = ["大模型调用失败", "未知", "未找到关键信息", "None", ""]
  419. if len(key_list) > 0:
  420. for table_html, table_text in zip(all_table_html_list, all_table_text_list):
  421. if len(table_html) <= min_characters - self.table_structure_len_max:
  422. for table_info in [table_html]:
  423. if len(key_list) > 0:
  424. prompt = self.table_pe.generate_prompt(
  425. table_info,
  426. key_list,
  427. task_description=table_task_description,
  428. output_format=table_output_format,
  429. rules_str=table_rules_str,
  430. few_shot_demo_text_content=table_few_shot_demo_text_content,
  431. few_shot_demo_key_value_list=table_few_shot_demo_key_value_list,
  432. )
  433. self.generate_and_merge_chat_results(
  434. prompt, key_list, final_results, failed_results
  435. )
  436. if len(key_list) > 0:
  437. related_text = self.get_related_normal_text(
  438. use_vector_retrieval,
  439. vector_info,
  440. key_list,
  441. all_normal_text_list,
  442. min_characters,
  443. )
  444. if len(related_text) > 0:
  445. prompt = self.text_pe.generate_prompt(
  446. related_text,
  447. key_list,
  448. task_description=text_task_description,
  449. output_format=text_output_format,
  450. rules_str=text_rules_str,
  451. few_shot_demo_text_content=text_few_shot_demo_text_content,
  452. few_shot_demo_key_value_list=text_few_shot_demo_key_value_list,
  453. )
  454. self.generate_and_merge_chat_results(
  455. prompt, key_list, final_results, failed_results
  456. )
  457. return {"chat_res": final_results}
  458. def predict(self, *args, **kwargs) -> None:
  459. logging.error(
  460. "PP-ChatOCRv3-doc Pipeline do not support to call `predict()` directly! Please invoke `visual_predict`, `build_vector`, `chat` sequentially to obtain the result."
  461. )
  462. return