pipeline_v4.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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, Union, List, Tuple
  15. import os
  16. import re
  17. import cv2
  18. import copy
  19. import json
  20. import base64
  21. import numpy as np
  22. from .pipeline_base import PP_ChatOCR_Pipeline
  23. from ...common.reader import ReadImage
  24. from ...common.batch_sampler import ImageBatchSampler
  25. from ....utils import logging
  26. from ....utils.file_interface import custom_open
  27. from ...utils.pp_option import PaddlePredictorOption
  28. from ..layout_parsing.result import LayoutParsingResult
  29. from ..components.chat_server import BaseChat
  30. class PP_ChatOCRv4_Pipeline(PP_ChatOCR_Pipeline):
  31. """PP-ChatOCRv4 Pipeline"""
  32. entities = ["PP-ChatOCRv4-doc"]
  33. def __init__(
  34. self,
  35. config: Dict,
  36. device: str = None,
  37. pp_option: PaddlePredictorOption = None,
  38. use_hpip: bool = False,
  39. initial_predictor: bool = True,
  40. ) -> None:
  41. """Initializes the pp-chatocrv3-doc pipeline.
  42. Args:
  43. config (Dict): Configuration dictionary containing various settings.
  44. device (str, optional): Device to run the predictions on. Defaults to None.
  45. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  46. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  47. use_layout_parsing (bool, optional): Whether to use layout parsing. Defaults to True.
  48. initial_predictor (bool, optional): Whether to initialize the predictor. Defaults to True.
  49. """
  50. super().__init__(device=device, pp_option=pp_option, use_hpip=use_hpip)
  51. self.pipeline_name = config["pipeline_name"]
  52. self.config = config
  53. self.use_layout_parser = config.get("use_layout_parser", True)
  54. self.use_mllm_predict = config.get("use_mllm_predict", True)
  55. self.layout_parsing_pipeline = None
  56. self.chat_bot = None
  57. self.retriever = None
  58. self.mllm_chat_bot = None
  59. if initial_predictor:
  60. self.inintial_visual_predictor(config)
  61. self.inintial_chat_predictor(config)
  62. self.inintial_retriever_predictor(config)
  63. self.inintial_mllm_predictor(config)
  64. self.batch_sampler = ImageBatchSampler(batch_size=1)
  65. self.img_reader = ReadImage(format="BGR")
  66. self.table_structure_len_max = 500
  67. def inintial_visual_predictor(self, config: dict) -> None:
  68. """
  69. Initializes the visual predictor with the given configuration.
  70. Args:
  71. config (dict): The configuration dictionary containing the necessary
  72. parameters for initializing the predictor.
  73. Returns:
  74. None
  75. """
  76. self.use_layout_parser = config.get("use_layout_parser", True)
  77. if self.use_layout_parser:
  78. layout_parsing_config = config.get("SubPipelines", {}).get(
  79. "LayoutParser",
  80. {"pipeline_config_error": "config error for layout_parsing_pipeline!"},
  81. )
  82. self.layout_parsing_pipeline = self.create_pipeline(layout_parsing_config)
  83. return
  84. def inintial_retriever_predictor(self, config: dict) -> None:
  85. """
  86. Initializes the retriever predictor with the given configuration.
  87. Args:
  88. config (dict): The configuration dictionary containing the necessary
  89. parameters for initializing the predictor.
  90. Returns:
  91. None
  92. """
  93. from .. import create_retriever
  94. retriever_config = config.get("SubModules", {}).get(
  95. "LLM_Retriever",
  96. {"retriever_config_error": "config error for llm retriever!"},
  97. )
  98. self.retriever = create_retriever(retriever_config)
  99. def inintial_chat_predictor(self, config: dict) -> None:
  100. """
  101. Initializes the chat predictor with the given configuration.
  102. Args:
  103. config (dict): The configuration dictionary containing the necessary
  104. parameters for initializing the predictor.
  105. Returns:
  106. None
  107. """
  108. from .. import create_chat_bot
  109. chat_bot_config = config.get("SubModules", {}).get(
  110. "LLM_Chat",
  111. {"chat_bot_config_error": "config error for llm chat bot!"},
  112. )
  113. self.chat_bot = create_chat_bot(chat_bot_config)
  114. from .. import create_prompt_engineering
  115. text_pe_config = (
  116. config.get("SubModules", {})
  117. .get("PromptEngneering", {})
  118. .get(
  119. "KIE_CommonText",
  120. {"pe_config_error": "config error for text_pe!"},
  121. )
  122. )
  123. self.text_pe = create_prompt_engineering(text_pe_config)
  124. table_pe_config = (
  125. config.get("SubModules", {})
  126. .get("PromptEngneering", {})
  127. .get(
  128. "KIE_Table",
  129. {"pe_config_error": "config error for table_pe!"},
  130. )
  131. )
  132. self.table_pe = create_prompt_engineering(table_pe_config)
  133. return
  134. def inintial_mllm_predictor(self, config: dict) -> None:
  135. """
  136. Initializes the predictor with the given configuration.
  137. Args:
  138. config (dict): The configuration dictionary containing the necessary
  139. parameters for initializing the predictor.
  140. Returns:
  141. None
  142. """
  143. from .. import create_chat_bot, create_prompt_engineering
  144. self.use_mllm_predict = config.get("use_mllm_predict", True)
  145. if self.use_mllm_predict:
  146. mllm_chat_bot_config = config.get("SubModules", {}).get(
  147. "MLLM_Chat",
  148. {"mllm_chat_bot_config": "config error for mllm chat bot!"},
  149. )
  150. self.mllm_chat_bot = create_chat_bot(mllm_chat_bot_config)
  151. ensemble_pe_config = (
  152. config.get("SubModules", {})
  153. .get("PromptEngneering", {})
  154. .get(
  155. "Ensemble",
  156. {"pe_config_error": "config error for ensemble_pe!"},
  157. )
  158. )
  159. self.ensemble_pe = create_prompt_engineering(ensemble_pe_config)
  160. return
  161. def decode_visual_result(self, layout_parsing_result: LayoutParsingResult) -> dict:
  162. """
  163. Decodes the visual result from the layout parsing result.
  164. Args:
  165. layout_parsing_result (LayoutParsingResult): The result of layout parsing.
  166. Returns:
  167. dict: The decoded visual information.
  168. """
  169. normal_text_dict = {}
  170. parsing_res_list = layout_parsing_result["parsing_res_list"]
  171. for pno in range(len(parsing_res_list)):
  172. label = parsing_res_list[pno]["block_label"]
  173. content = parsing_res_list[pno]["block_content"]
  174. if label in ["table", "formula"]:
  175. continue
  176. if label not in normal_text_dict:
  177. normal_text_dict["words in " + label] = content
  178. else:
  179. normal_text_dict["words in " + label] += f"\n {content}"
  180. table_res_list = layout_parsing_result["table_res_list"]
  181. table_text_list = []
  182. table_html_list = []
  183. table_nei_text_list = []
  184. for table_res in table_res_list:
  185. table_html_list.append(table_res["pred_html"])
  186. single_table_text = " ".join(table_res["table_ocr_pred"]["rec_texts"])
  187. table_text_list.append(single_table_text)
  188. table_nei_text_list.append(table_res["neighbor_texts"])
  189. visual_info = {}
  190. visual_info["normal_text_dict"] = normal_text_dict
  191. visual_info["table_text_list"] = table_text_list
  192. visual_info["table_html_list"] = table_html_list
  193. visual_info["table_nei_text_list"] = table_nei_text_list
  194. return visual_info
  195. # Function to perform visual prediction on input images
  196. def visual_predict(
  197. self,
  198. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  199. use_doc_orientation_classify: Optional[bool] = None,
  200. use_doc_unwarping: Optional[bool] = None,
  201. use_general_ocr: Optional[bool] = None,
  202. use_seal_recognition: Optional[bool] = None,
  203. use_table_recognition: Optional[bool] = None,
  204. text_det_limit_side_len: Optional[int] = None,
  205. text_det_limit_type: Optional[str] = None,
  206. text_det_thresh: Optional[float] = None,
  207. text_det_box_thresh: Optional[float] = None,
  208. text_det_unclip_ratio: Optional[float] = None,
  209. text_rec_score_thresh: Optional[float] = None,
  210. seal_det_limit_side_len: Optional[int] = None,
  211. seal_det_limit_type: Optional[str] = None,
  212. seal_det_thresh: Optional[float] = None,
  213. seal_det_box_thresh: Optional[float] = None,
  214. seal_det_unclip_ratio: Optional[float] = None,
  215. seal_rec_score_thresh: Optional[float] = None,
  216. **kwargs,
  217. ) -> dict:
  218. """
  219. This function takes an input image or a list of images and performs various visual
  220. prediction tasks such as document orientation classification, document unwarping,
  221. general OCR, seal recognition, and table recognition based on the provided flags.
  222. Args:
  223. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): Input image path, list of image paths,
  224. numpy array of an image, or list of numpy arrays.
  225. use_doc_orientation_classify (bool): Flag to use document orientation classification.
  226. use_doc_unwarping (bool): Flag to use document unwarping.
  227. use_general_ocr (bool): Flag to use general OCR.
  228. use_seal_recognition (bool): Flag to use seal recognition.
  229. use_table_recognition (bool): Flag to use table recognition.
  230. **kwargs: Additional keyword arguments.
  231. Returns:
  232. dict: A dictionary containing the layout parsing result and visual information.
  233. """
  234. if self.use_layout_parser == False:
  235. logging.error("The models for layout parser are not initialized.")
  236. yield {"error": "The models for layout parser are not initialized."}
  237. if self.layout_parsing_pipeline is None:
  238. logging.warning(
  239. "The layout parsing pipeline is not initialized, will initialize it now."
  240. )
  241. self.inintial_visual_predictor(self.config)
  242. for layout_parsing_result in self.layout_parsing_pipeline.predict(
  243. input,
  244. use_doc_orientation_classify=use_doc_orientation_classify,
  245. use_doc_unwarping=use_doc_unwarping,
  246. use_general_ocr=use_general_ocr,
  247. use_seal_recognition=use_seal_recognition,
  248. use_table_recognition=use_table_recognition,
  249. text_det_limit_side_len=text_det_limit_side_len,
  250. text_det_limit_type=text_det_limit_type,
  251. text_det_thresh=text_det_thresh,
  252. text_det_box_thresh=text_det_box_thresh,
  253. text_det_unclip_ratio=text_det_unclip_ratio,
  254. text_rec_score_thresh=text_rec_score_thresh,
  255. seal_det_box_thresh=seal_det_box_thresh,
  256. seal_det_limit_side_len=seal_det_limit_side_len,
  257. seal_det_limit_type=seal_det_limit_type,
  258. seal_det_thresh=seal_det_thresh,
  259. seal_det_unclip_ratio=seal_det_unclip_ratio,
  260. seal_rec_score_thresh=seal_rec_score_thresh,
  261. ):
  262. visual_info = self.decode_visual_result(layout_parsing_result)
  263. visual_predict_res = {
  264. "layout_parsing_result": layout_parsing_result,
  265. "visual_info": visual_info,
  266. }
  267. yield visual_predict_res
  268. def save_visual_info_list(self, visual_info: dict, save_path: str) -> None:
  269. """
  270. Save the visual info list to the specified file path.
  271. Args:
  272. visual_info (dict): The visual info result, which can be a single object or a list of objects.
  273. save_path (str): The file path to save the visual info list.
  274. Returns:
  275. None
  276. """
  277. if not isinstance(visual_info, list):
  278. visual_info_list = [visual_info]
  279. else:
  280. visual_info_list = visual_info
  281. with open(save_path, "w") as fout:
  282. fout.write(json.dumps(visual_info_list, ensure_ascii=False) + "\n")
  283. return
  284. def load_visual_info_list(self, data_path: str) -> List[dict]:
  285. """
  286. Loads visual info list from a JSON file.
  287. Args:
  288. data_path (str): The path to the JSON file containing visual info.
  289. Returns:
  290. list[dict]: A list of dict objects parsed from the JSON file.
  291. """
  292. with open(data_path, "r") as fin:
  293. data = fin.readline()
  294. visual_info_list = json.loads(data)
  295. return visual_info_list
  296. def merge_visual_info_list(
  297. self, visual_info_list: List[dict]
  298. ) -> Tuple[list, list, list, list]:
  299. """
  300. Merge visual info lists.
  301. Args:
  302. visual_info_list (list[dict]): A list of visual info results.
  303. Returns:
  304. tuple[list, list, list, list]: A tuple containing four lists, one for normal text dicts,
  305. one for table text lists, one for table HTML lists.
  306. one for table neighbor texts.
  307. """
  308. all_normal_text_list = []
  309. all_table_text_list = []
  310. all_table_html_list = []
  311. all_table_nei_text_list = []
  312. for single_visual_info in visual_info_list:
  313. normal_text_dict = single_visual_info["normal_text_dict"]
  314. for key in normal_text_dict:
  315. normal_text_dict[key] = normal_text_dict[key].replace("\n", "")
  316. table_text_list = single_visual_info["table_text_list"]
  317. table_html_list = single_visual_info["table_html_list"]
  318. table_nei_text_list = single_visual_info["table_nei_text_list"]
  319. all_normal_text_list.append(normal_text_dict)
  320. all_table_text_list.extend(table_text_list)
  321. all_table_html_list.extend(table_html_list)
  322. all_table_nei_text_list.extend(table_nei_text_list)
  323. return (
  324. all_normal_text_list,
  325. all_table_text_list,
  326. all_table_html_list,
  327. all_table_nei_text_list,
  328. )
  329. def build_vector(
  330. self,
  331. visual_info: dict,
  332. min_characters: int = 3500,
  333. block_size: int = 300,
  334. flag_save_bytes_vector: bool = False,
  335. retriever_config: dict = None,
  336. ) -> dict:
  337. """
  338. Build a vector representation from visual information.
  339. Args:
  340. visual_info (dict): The visual information input, can be a single instance or a list of instances.
  341. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  342. block_size (int): The size of each chunk to split the text into.
  343. flag_save_bytes_vector (bool): Whether to save the vector as bytes, defaults to False.
  344. retriever_config (dict): The configuration for the retriever, defaults to None.
  345. Returns:
  346. dict: A dictionary containing the vector info and a flag indicating if the text is too short.
  347. """
  348. if not isinstance(visual_info, list):
  349. visual_info_list = [visual_info]
  350. else:
  351. visual_info_list = visual_info
  352. if retriever_config is not None:
  353. from .. import create_retriever
  354. retriever = create_retriever(retriever_config)
  355. else:
  356. if self.retriever is None:
  357. logging.warning(
  358. "The retriever is not initialized,will initialize it now."
  359. )
  360. self.inintial_retriever_predictor(self.config)
  361. retriever = self.retriever
  362. all_visual_info = self.merge_visual_info_list(visual_info_list)
  363. (
  364. all_normal_text_list,
  365. all_table_text_list,
  366. all_table_html_list,
  367. all_table_nei_text_list,
  368. ) = all_visual_info
  369. vector_info = {}
  370. all_items = []
  371. for i, normal_text_dict in enumerate(all_normal_text_list):
  372. for type, text in normal_text_dict.items():
  373. all_items += [f"{type}:{text}\n"]
  374. for table_html, table_text, table_nei_text in zip(
  375. all_table_html_list, all_table_text_list, all_table_nei_text_list
  376. ):
  377. if len(table_html) > min_characters - self.table_structure_len_max:
  378. all_items += [f"table:{table_text}\t{table_nei_text}"]
  379. all_text_str = "".join(all_items)
  380. vector_info["flag_save_bytes_vector"] = False
  381. if len(all_text_str) > min_characters:
  382. vector_info["flag_too_short_text"] = False
  383. vector_info["model_name"] = retriever.model_name
  384. vector_info["block_size"] = block_size
  385. vector_info["vector"] = retriever.generate_vector_database(
  386. all_items, block_size=block_size
  387. )
  388. if flag_save_bytes_vector:
  389. vector_info["vector"] = retriever.encode_vector_store_to_bytes(
  390. vector_info["vector"]
  391. )
  392. vector_info["flag_save_bytes_vector"] = True
  393. else:
  394. vector_info["flag_too_short_text"] = True
  395. vector_info["vector"] = all_items
  396. return vector_info
  397. def save_vector(self, vector_info: dict, save_path: str) -> None:
  398. directory = os.path.dirname(save_path)
  399. if not os.path.exists(directory):
  400. os.makedirs(directory)
  401. if self.retriever is None:
  402. logging.warning("The retriever is not initialized,will initialize it now.")
  403. self.inintial_retriever_predictor(self.config)
  404. vector_info_data = copy.deepcopy(vector_info)
  405. if (
  406. not vector_info["flag_too_short_text"]
  407. and not vector_info["flag_save_bytes_vector"]
  408. ):
  409. vector_info_data["vector"] = self.retriever.encode_vector_store_to_bytes(
  410. vector_info_data["vector"]
  411. )
  412. vector_info_data["flag_save_bytes_vector"] = True
  413. with custom_open(save_path, "w") as fout:
  414. fout.write(json.dumps(vector_info_data, ensure_ascii=False) + "\n")
  415. return
  416. def load_vector(self, data_path: str) -> dict:
  417. vector_info = None
  418. if self.retriever is None:
  419. logging.warning("The retriever is not initialized,will initialize it now.")
  420. self.inintial_retriever_predictor(self.config)
  421. with open(data_path, "r") as fin:
  422. data = fin.readline()
  423. vector_info = json.loads(data)
  424. if (
  425. "flag_too_short_text" not in vector_info
  426. or "flag_save_bytes_vector" not in vector_info
  427. or "vector" not in vector_info
  428. ):
  429. logging.error("Invalid vector info.")
  430. return {"error": "Invalid vector info when load vector!"}
  431. if vector_info["flag_save_bytes_vector"]:
  432. vector_info["vector"] = self.retriever.decode_vector_store_from_bytes(
  433. vector_info["vector"]
  434. )
  435. vector_info["flag_save_bytes_vector"] = False
  436. return vector_info
  437. def format_key(self, key_list: Union[str, List[str]]) -> List[str]:
  438. """
  439. Formats the key list.
  440. Args:
  441. key_list (str|list[str]): A string or a list of strings representing the keys.
  442. Returns:
  443. list[str]: A list of formatted keys.
  444. """
  445. if key_list == "":
  446. return []
  447. if isinstance(key_list, list):
  448. key_list = [key.replace("\xa0", " ") for key in key_list]
  449. return key_list
  450. if isinstance(key_list, str):
  451. key_list = re.sub(r"[\t\n\r\f\v]", "", key_list)
  452. key_list = key_list.replace(",", ",").split(",")
  453. return key_list
  454. return []
  455. def mllm_pred(
  456. self,
  457. input: Union[str, np.ndarray],
  458. key_list: Union[str, List[str]],
  459. mllm_chat_bot_config=None,
  460. ) -> dict:
  461. """
  462. Generates MLLM results based on the provided key list and input image.
  463. Args:
  464. input (Union[str, np.ndarray]): Input image path, or numpy array of an image.
  465. key_list (Union[str, list[str]]): A single key or a list of keys to extract information.
  466. chat_bot_config (dict): The parameters for LLM chatbot, including api_type, api_key... refer to config file for more details.
  467. Returns:
  468. dict: A dictionary containing the chat results.
  469. """
  470. if self.use_mllm_predict == False:
  471. logging.error("MLLM prediction is disabled.")
  472. return {"mllm_res": "Error:MLLM prediction is disabled!"}
  473. key_list = self.format_key(key_list)
  474. if len(key_list) == 0:
  475. return {"mllm_res": "Error:输入的key_list无效!"}
  476. if isinstance(input, list):
  477. logging.error("Input is a list, but it's not supported here.")
  478. return {"mllm_res": "Error:Input is a list, but it's not supported here!"}
  479. image_array_list = self.img_reader([input])
  480. if (
  481. isinstance(input, str)
  482. and input.endswith(".pdf")
  483. and len(image_array_list) > 1
  484. ):
  485. logging.error("The input with PDF should have only one page.")
  486. return {"mllm_res": "Error:The input with PDF should have only one page!"}
  487. if self.mllm_chat_bot is None:
  488. logging.warning(
  489. "The MLLM chat bot is not initialized,will initialize it now."
  490. )
  491. self.inintial_mllm_predictor(self.config)
  492. if mllm_chat_bot_config is not None:
  493. from .. import create_chat_bot
  494. mllm_chat_bot = create_chat_bot(mllm_chat_bot_config)
  495. else:
  496. mllm_chat_bot = self.mllm_chat_bot
  497. for image_array in image_array_list:
  498. assert len(image_array.shape) == 3
  499. image_string = cv2.imencode(".jpg", image_array)[1].tostring()
  500. image_base64 = base64.b64encode(image_string).decode("utf-8")
  501. result = {}
  502. for key in key_list:
  503. prompt = (
  504. str(key)
  505. + "\n请用图片中完整出现的内容回答,可以是单词、短语或句子,针对问题回答尽可能详细和完整,并保持格式、单位、符号和标点都与图片中的文字内容完全一致。"
  506. )
  507. mllm_chat_bot_result = mllm_chat_bot.generate_chat_results(
  508. prompt=prompt, image=image_base64
  509. )
  510. if mllm_chat_bot_result is None:
  511. return {"mllm_res": "大模型调用失败"}
  512. result[key] = mllm_chat_bot_result
  513. return {"mllm_res": result}
  514. def generate_and_merge_chat_results(
  515. self,
  516. chat_bot: BaseChat,
  517. prompt: str,
  518. key_list: list,
  519. final_results: dict,
  520. failed_results: list,
  521. ) -> None:
  522. """
  523. Generate and merge chat results into the final results dictionary.
  524. Args:
  525. prompt (str): The input prompt for the chat bot.
  526. key_list (list): A list of keys to track which results to merge.
  527. final_results (dict): The dictionary to store the final merged results.
  528. failed_results (list): A list of failed results to avoid merging.
  529. Returns:
  530. None
  531. """
  532. llm_result = chat_bot.generate_chat_results(prompt)
  533. if llm_result is None:
  534. logging.error(
  535. "chat bot error: \n [prompt:]\n %s\n [result:] %s\n"
  536. % (prompt, self.chat_bot.ERROR_MASSAGE)
  537. )
  538. return
  539. llm_result = self.chat_bot.fix_llm_result_format(llm_result)
  540. for key, value in llm_result.items():
  541. if value not in failed_results and key in key_list:
  542. key_list.remove(key)
  543. final_results[key] = value
  544. return
  545. def get_related_normal_text(
  546. self,
  547. retriever_config: dict,
  548. use_vector_retrieval: bool,
  549. vector_info: dict,
  550. key_list: List[str],
  551. all_normal_text_list: list,
  552. min_characters: int,
  553. ) -> str:
  554. """
  555. Retrieve related normal text based on vector retrieval or all normal text list.
  556. Args:
  557. retriever_config (dict): Configuration for the retriever.
  558. use_vector_retrieval (bool): Whether to use vector retrieval.
  559. vector_info (dict): Dictionary containing vector information.
  560. key_list (list[str]): List of keys to generate question keys.
  561. all_normal_text_list (list): List of normal text.
  562. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  563. Returns:
  564. str: Related normal text.
  565. """
  566. if use_vector_retrieval and vector_info is not None:
  567. if retriever_config is not None:
  568. from .. import create_retriever
  569. retriever = create_retriever(retriever_config)
  570. else:
  571. if self.retriever is None:
  572. logging.warning(
  573. "The retriever is not initialized,will initialize it now."
  574. )
  575. self.inintial_retriever_predictor(self.config)
  576. retriever = self.retriever
  577. question_key_list = [f"{key}" for key in key_list]
  578. vector = vector_info["vector"]
  579. if not vector_info["flag_too_short_text"]:
  580. assert (
  581. vector_info["model_name"] == retriever.model_name
  582. ), f"The vector model name ({vector_info['model_name']}) does not match the retriever model name ({retriever.model_name}). Please check your retriever config."
  583. if vector_info["flag_save_bytes_vector"]:
  584. vector = retriever.decode_vector_store_from_bytes(vector)
  585. related_text = retriever.similarity_retrieval(
  586. question_key_list, vector, topk=50, min_characters=min_characters
  587. )
  588. else:
  589. if len(vector) > 0:
  590. related_text = "".join(vector)
  591. else:
  592. related_text = ""
  593. else:
  594. all_items = []
  595. for i, normal_text_dict in enumerate(all_normal_text_list):
  596. for type, text in normal_text_dict.items():
  597. all_items += [f"{type}:{text}\n"]
  598. related_text = "".join(all_items)
  599. if len(related_text) > min_characters:
  600. logging.warning(
  601. "The input text content is too long, the large language model may truncate it."
  602. )
  603. return related_text
  604. def ensemble_ocr_llm_mllm(
  605. self, key_list: List[str], ocr_llm_predict_dict: dict, mllm_predict_dict: dict
  606. ) -> dict:
  607. """
  608. Ensemble OCR_LLM and LMM predictions based on given key list.
  609. Args:
  610. key_list (list[str]): List of keys to retrieve predictions.
  611. ocr_llm_predict_dict (dict): Dictionary containing OCR LLM predictions.
  612. mllm_predict_dict (dict): Dictionary containing mLLM predictions.
  613. Returns:
  614. dict: A dictionary with final predictions.
  615. """
  616. final_predict_dict = {}
  617. for key in key_list:
  618. predict = ""
  619. ocr_llm_predict = ""
  620. mllm_predict = ""
  621. if key in ocr_llm_predict_dict:
  622. ocr_llm_predict = ocr_llm_predict_dict[key]
  623. if key in mllm_predict_dict:
  624. mllm_predict = mllm_predict_dict[key]
  625. if ocr_llm_predict != "" and mllm_predict != "":
  626. prompt = self.ensemble_pe.generate_prompt(
  627. key, ocr_llm_predict, mllm_predict
  628. )
  629. llm_result = self.chat_bot.generate_chat_results(prompt)
  630. if llm_result is not None:
  631. llm_result = self.chat_bot.fix_llm_result_format(llm_result)
  632. if key in llm_result:
  633. tmp = llm_result[key]
  634. if "B" in tmp:
  635. predict = mllm_predict
  636. else:
  637. predict = ocr_llm_predict
  638. else:
  639. predict = ocr_llm_predict
  640. elif key in ocr_llm_predict_dict:
  641. predict = ocr_llm_predict_dict[key]
  642. elif key in mllm_predict_dict:
  643. predict = mllm_predict_dict[key]
  644. if predict != "":
  645. final_predict_dict[key] = predict
  646. return final_predict_dict
  647. def chat(
  648. self,
  649. key_list: Union[str, List[str]],
  650. visual_info: dict,
  651. use_vector_retrieval: bool = True,
  652. vector_info: dict = None,
  653. min_characters: int = 3500,
  654. text_task_description: str = None,
  655. text_output_format: str = None,
  656. text_rules_str: str = None,
  657. text_few_shot_demo_text_content: str = None,
  658. text_few_shot_demo_key_value_list: str = None,
  659. table_task_description: str = None,
  660. table_output_format: str = None,
  661. table_rules_str: str = None,
  662. table_few_shot_demo_text_content: str = None,
  663. table_few_shot_demo_key_value_list: str = None,
  664. mllm_predict_info: dict = None,
  665. mllm_integration_strategy: str = "integration",
  666. chat_bot_config: dict = None,
  667. retriever_config: dict = None,
  668. ) -> dict:
  669. """
  670. Generates chat results based on the provided key list and visual information.
  671. Args:
  672. key_list (Union[str, list[str]]): A single key or a list of keys to extract information.
  673. visual_info (dict): The visual information result.
  674. use_vector_retrieval (bool): Whether to use vector retrieval.
  675. vector_info (dict): The vector information for retrieval.
  676. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  677. text_task_description (str): The description of the text task.
  678. text_output_format (str): The output format for text results.
  679. text_rules_str (str): The rules for generating text results.
  680. text_few_shot_demo_text_content (str): The text content for few-shot demos.
  681. text_few_shot_demo_key_value_list (str): The key-value list for few-shot demos.
  682. table_task_description (str): The description of the table task.
  683. table_output_format (str): The output format for table results.
  684. table_rules_str (str): The rules for generating table results.
  685. table_few_shot_demo_text_content (str): The text content for table few-shot demos.
  686. table_few_shot_demo_key_value_list (str): The key-value list for table few-shot demos.
  687. mllm_predict_dict (dict): The dictionary of mLLM predicts.
  688. mllm_integration_strategy (str): The integration strategy of mLLM and LLM, defaults to "integration", options are "integration", "llm_only" and "mllm_only".
  689. chat_bot_config (dict): The parameters for LLM chatbot, including api_type, api_key... refer to config file for more details.
  690. retriever_config (dict): The parameters for LLM retriever, including api_type, api_key... refer to config file for more details.
  691. Returns:
  692. dict: A dictionary containing the chat results.
  693. """
  694. key_list = self.format_key(key_list)
  695. key_list_ori = key_list.copy()
  696. if len(key_list) == 0:
  697. return {"chat_res": "Error:输入的key_list无效!"}
  698. if not isinstance(visual_info, list):
  699. visual_info_list = [visual_info]
  700. else:
  701. visual_info_list = visual_info
  702. if self.chat_bot is None:
  703. logging.warning(
  704. "The LLM chat bot is not initialized,will initialize it now."
  705. )
  706. self.inintial_chat_predictor(self.config)
  707. if chat_bot_config is not None:
  708. from .. import create_chat_bot
  709. chat_bot = create_chat_bot(chat_bot_config)
  710. else:
  711. chat_bot = self.chat_bot
  712. all_visual_info = self.merge_visual_info_list(visual_info_list)
  713. (
  714. all_normal_text_list,
  715. all_table_text_list,
  716. all_table_html_list,
  717. all_table_nei_text_list,
  718. ) = all_visual_info
  719. final_results = {}
  720. failed_results = ["大模型调用失败", "未知", "未找到关键信息", "None", ""]
  721. if len(key_list) > 0:
  722. related_text = self.get_related_normal_text(
  723. retriever_config,
  724. use_vector_retrieval,
  725. vector_info,
  726. key_list,
  727. all_normal_text_list,
  728. min_characters,
  729. )
  730. if len(related_text) > 0:
  731. prompt = self.text_pe.generate_prompt(
  732. related_text,
  733. key_list,
  734. task_description=text_task_description,
  735. output_format=text_output_format,
  736. rules_str=text_rules_str,
  737. few_shot_demo_text_content=text_few_shot_demo_text_content,
  738. few_shot_demo_key_value_list=text_few_shot_demo_key_value_list,
  739. )
  740. self.generate_and_merge_chat_results(
  741. chat_bot, prompt, key_list, final_results, failed_results
  742. )
  743. if len(key_list) > 0:
  744. for table_html, table_text, table_nei_text in zip(
  745. all_table_html_list, all_table_text_list, all_table_nei_text_list
  746. ):
  747. if len(table_html) <= min_characters - self.table_structure_len_max:
  748. for table_info in [table_html]:
  749. if len(key_list) > 0:
  750. if len(table_nei_text) > 0:
  751. table_info = (
  752. table_info + "\n 表格周围文字:" + table_nei_text
  753. )
  754. prompt = self.table_pe.generate_prompt(
  755. table_info,
  756. key_list,
  757. task_description=table_task_description,
  758. output_format=table_output_format,
  759. rules_str=table_rules_str,
  760. few_shot_demo_text_content=table_few_shot_demo_text_content,
  761. few_shot_demo_key_value_list=table_few_shot_demo_key_value_list,
  762. )
  763. self.generate_and_merge_chat_results(
  764. chat_bot,
  765. prompt,
  766. key_list,
  767. final_results,
  768. failed_results,
  769. )
  770. if (
  771. self.use_mllm_predict
  772. and mllm_integration_strategy != "llm_only"
  773. and mllm_predict_info is not None
  774. ):
  775. if mllm_integration_strategy == "integration":
  776. final_predict_dict = self.ensemble_ocr_llm_mllm(
  777. key_list_ori, final_results, mllm_predict_info
  778. )
  779. elif mllm_integration_strategy == "mllm_only":
  780. final_predict_dict = mllm_predict_info
  781. else:
  782. return {
  783. "chat_res": f"Error:Unsupported mllm_integration_strategy {mllm_integration_strategy}, only support 'integration', 'llm_only' and 'mllm_only'!"
  784. }
  785. else:
  786. final_predict_dict = final_results
  787. return {"chat_res": final_predict_dict}
  788. def predict(self, *args, **kwargs) -> None:
  789. logging.error(
  790. "PP-ChatOCRv4-doc Pipeline do not support to call `predict()` directly! Please invoke `visual_predict`, `build_vector`, `chat` sequentially to obtain the result."
  791. )
  792. return