pipeline.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 ..base import BasePipeline
  15. from typing import Any, Dict, Optional
  16. # import numpy as np
  17. # import cv2
  18. from .result import VisualInfoResult
  19. import re
  20. ########## [TODO]后续需要更新路径
  21. from ...components.transforms import ReadImage
  22. import json
  23. class PP_ChatOCRv3_doc_Pipeline(BasePipeline):
  24. """PP-ChatOCRv3-doc Pipeline"""
  25. entities = "PP-ChatOCRv3-doc"
  26. def __init__(self,
  27. config,
  28. device=None,
  29. pp_option=None,
  30. use_hpip: bool = False,
  31. hpi_params: Optional[Dict[str, Any]] = None):
  32. super().__init__(device=device, pp_option=pp_option,
  33. use_hpip=use_hpip, hpi_params=hpi_params)
  34. self.inintial_predictor(config)
  35. self.img_reader = ReadImage(format="BGR")
  36. def inintial_predictor(self, config):
  37. # layout_parsing_config = config['SubPipelines']["LayoutParser"]
  38. # self.layout_parsing_pipeline = self.create_pipeline(layout_parsing_config)
  39. chat_bot_config = config['SubModules']['LLM_Chat']
  40. self.chat_bot = self.create_chat_bot(chat_bot_config)
  41. retriever_config = config['SubModules']['LLM_Retriever']
  42. self.retriever = self.create_retriever(retriever_config)
  43. text_pe_config = config['SubModules']['PromptEngneering']['KIE_CommonText']
  44. self.text_pe = self.create_prompt_engeering(text_pe_config)
  45. table_pe_config = config['SubModules']['PromptEngneering']['KIE_Table']
  46. self.table_pe = self.create_prompt_engeering(table_pe_config)
  47. return
  48. def decode_visual_result(self, layout_parsing_result):
  49. text_paragraphs_ocr_res = layout_parsing_result['text_paragraphs_ocr_res']
  50. seal_res_list = layout_parsing_result['seal_res_list']
  51. normal_text_dict = {}
  52. layout_type = "text"
  53. for text in text_paragraphs_ocr_res['rec_text']:
  54. if layout_type not in normal_text_dict:
  55. normal_text_dict[layout_type] = text
  56. else:
  57. normal_text_dict[layout_type] += f"\n {text}"
  58. layout_type = "seal"
  59. for seal_res in seal_res_list:
  60. for text in seal_res['rec_text']:
  61. if layout_type not in normal_text_dict:
  62. normal_text_dict[layout_type] = text
  63. else:
  64. normal_text_dict[layout_type] += f"\n {text}"
  65. table_res_list = layout_parsing_result['table_res_list']
  66. table_text_list = []
  67. table_html_list = []
  68. for table_res in table_res_list:
  69. table_html_list.append(table_res['pred_html'])
  70. single_table_text = " ".join(table_res["table_ocr_pred"]['rec_text'])
  71. table_text_list.append(single_table_text)
  72. visual_info = {}
  73. visual_info['normal_text_dict'] = normal_text_dict
  74. visual_info['table_text_list'] = table_text_list
  75. visual_info['table_html_list'] = table_html_list
  76. return VisualInfoResult(visual_info)
  77. def visual_predict(self, input,
  78. use_doc_orientation_classify=True,
  79. use_doc_unwarping=True,
  80. use_common_ocr=True,
  81. use_seal_recognition=True,
  82. use_table_recognition=True,
  83. **kwargs):
  84. if not isinstance(input, list):
  85. input_list = [input]
  86. else:
  87. input_list = input
  88. img_id = 1
  89. for input in input_list:
  90. if isinstance(input, str):
  91. image_array = next(self.img_reader(input))[0]['img']
  92. else:
  93. image_array = input
  94. assert len(image_array.shape) == 3
  95. layout_parsing_result = next(self.layout_parsing_pipeline.predict(
  96. image_array,
  97. use_doc_orientation_classify=use_doc_orientation_classify,
  98. use_doc_unwarping=use_doc_unwarping,
  99. use_common_ocr=use_common_ocr,
  100. use_seal_recognition=use_seal_recognition,
  101. use_table_recognition=use_table_recognition))
  102. visual_info = self.decode_visual_result(layout_parsing_result)
  103. visual_predict_res = {"layout_parsing_result":layout_parsing_result,
  104. "visual_info":visual_info}
  105. yield visual_predict_res
  106. def save_visual_info_list(self, visual_info, save_path):
  107. if not isinstance(visual_info, list):
  108. visual_info_list = [visual_info]
  109. else:
  110. visual_info_list = visual_info
  111. with open(save_path, "w") as fout:
  112. fout.write(json.dumps(visual_info_list, ensure_ascii=False) + "\n")
  113. return
  114. def load_visual_info_list(self, data_path):
  115. with open(data_path, "r") as fin:
  116. data = fin.readline()
  117. visual_info_list = json.loads(data)
  118. return visual_info_list
  119. def merge_visual_info_list(self, visual_info_list):
  120. all_normal_text_list = []
  121. all_table_text_list = []
  122. all_table_html_list = []
  123. for single_visual_info in visual_info_list:
  124. normal_text_dict = single_visual_info['normal_text_dict']
  125. table_text_list = single_visual_info['table_text_list']
  126. table_html_list = single_visual_info['table_html_list']
  127. all_normal_text_list.append(normal_text_dict)
  128. all_table_text_list.extend(table_text_list)
  129. all_table_html_list.extend(table_html_list)
  130. return all_normal_text_list, all_table_text_list, all_table_html_list
  131. def build_vector(self, visual_info,
  132. min_characters=3500,
  133. llm_request_interval=1.0):
  134. if not isinstance(visual_info, list):
  135. visual_info_list = [visual_info]
  136. else:
  137. visual_info_list = visual_info
  138. all_visual_info = self.merge_visual_info_list(visual_info_list)
  139. all_normal_text_list, all_table_text_list, all_table_html_list = all_visual_info
  140. all_normal_text_str = "".join(["\n".join(e.values()) for e in all_normal_text_list])
  141. vector_info = {}
  142. all_items = []
  143. for i, normal_text_dict in enumerate(all_normal_text_list):
  144. for type, text in normal_text_dict.items():
  145. all_items += [f"{type}:{text}"]
  146. if len(all_normal_text_str) > min_characters:
  147. vector_info['flag_too_short_text'] = False
  148. vector_info['vector'] = self.retriever.generate_vector_database(
  149. all_items)
  150. else:
  151. vector_info['flag_too_short_text'] = True
  152. vector_info['vector'] = all_items
  153. return vector_info
  154. def format_key(self, key_list):
  155. """format key"""
  156. if key_list == "":
  157. return []
  158. if isinstance(key_list, list):
  159. return key_list
  160. if isinstance(key_list, str):
  161. key_list = re.sub(r"[\t\n\r\f\v]", "", key_list)
  162. key_list = key_list.replace(",", ",").split(",")
  163. return key_list
  164. return []
  165. def fix_llm_result_format(self, llm_result):
  166. if not llm_result:
  167. return {}
  168. if "json" in llm_result or "```" in llm_result:
  169. llm_result = (
  170. llm_result.replace("```", "").replace("json", "").replace("/n", "")
  171. )
  172. llm_result = llm_result.replace("[", "").replace("]", "")
  173. try:
  174. llm_result = json.loads(llm_result)
  175. llm_result_final = {}
  176. for key in llm_result:
  177. value = llm_result[key]
  178. if isinstance(value, list):
  179. if len(value) > 0:
  180. llm_result_final[key] = value[0]
  181. else:
  182. llm_result_final[key] = value
  183. return llm_result_final
  184. except:
  185. results = (
  186. llm_result.replace("\n", "")
  187. .replace(" ", "")
  188. .replace("{", "")
  189. .replace("}", "")
  190. )
  191. if not results.endswith('"'):
  192. results = results + '"'
  193. pattern = r'"(.*?)": "([^"]*)"'
  194. matches = re.findall(pattern, str(results))
  195. if len(matches) > 0:
  196. llm_result = {k: v for k, v in matches}
  197. return llm_result
  198. else:
  199. return {}
  200. def generate_and_merge_chat_results(self, prompt, key_list,
  201. final_results, failed_results):
  202. llm_result = self.chat_bot.generate_chat_results(prompt)
  203. llm_result = self.fix_llm_result_format(llm_result)
  204. for key, value in llm_result.items():
  205. if value not in failed_results and key in key_list:
  206. key_list.remove(key)
  207. final_results[key] = value
  208. return
  209. def chat(self, visual_info,
  210. key_list,
  211. vector_info,
  212. text_task_description=None,
  213. text_output_format=None,
  214. text_rules_str=None,
  215. text_few_shot_demo_text_content=None,
  216. text_few_shot_demo_key_value_list=None,
  217. table_task_description=None,
  218. table_output_format=None,
  219. table_rules_str=None,
  220. table_few_shot_demo_text_content=None,
  221. table_few_shot_demo_key_value_list=None):
  222. key_list = self.format_key(key_list)
  223. if len(key_list) == 0:
  224. return {"chat_res": "输入的key_list无效!"}
  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. all_normal_text_list, all_table_text_list, all_table_html_list = all_visual_info
  231. final_results = {}
  232. failed_results = ["大模型调用失败", "未知", "未找到关键信息", "None", ""]
  233. for all_table_info in [all_table_html_list, all_table_text_list]:
  234. for table_info in all_table_info:
  235. if len(key_list) == 0:
  236. continue
  237. prompt = self.table_pe.generate_prompt(table_info,
  238. key_list,
  239. task_description=table_task_description,
  240. output_format=table_output_format,
  241. rules_str=table_rules_str,
  242. few_shot_demo_text_content=table_few_shot_demo_text_content,
  243. few_shot_demo_key_value_list=table_few_shot_demo_key_value_list)
  244. self.generate_and_merge_chat_results(prompt,
  245. key_list, final_results, failed_results)
  246. if len(key_list) > 0:
  247. question_key_list = [f"抽取关键信息:{key}" for key in key_list]
  248. vector = vector_info['vector']
  249. if not vector_info['flag_too_short_text']:
  250. related_text = self.retriever.similarity_retrieval(
  251. question_key_list, vector)
  252. else:
  253. related_text = " ".join(vector)
  254. prompt = self.text_pe.generate_prompt(related_text,
  255. key_list,
  256. task_description=text_task_description,
  257. output_format=text_output_format,
  258. rules_str=text_rules_str,
  259. few_shot_demo_text_content=text_few_shot_demo_text_content,
  260. few_shot_demo_key_value_list=text_few_shot_demo_key_value_list)
  261. self.generate_and_merge_chat_results(prompt,
  262. key_list, final_results, failed_results)
  263. return final_results
  264. def predict(self, *args, **kwargs):
  265. logging.error(
  266. "PP-ChatOCRv3-doc Pipeline do not support to call `predict()` directly! Please invoke `visual_predict`, `build_vector`, `chat` sequentially to obtain the result."
  267. )
  268. return