pipeline_v4.py 41 KB

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