pipeline_v3.py 22 KB

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