pipeline_v4.py 38 KB

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