pipeline_v4.py 40 KB

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