pipeline_v3.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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 copy
  15. import json
  16. import os
  17. import re
  18. from typing import Any, Dict, List, Optional, Tuple, Union
  19. import numpy as np
  20. from ....utils import logging
  21. from ....utils.deps import pipeline_requires_extra
  22. from ....utils.file_interface import custom_open
  23. from ...common.batch_sampler import ImageBatchSampler
  24. from ...common.reader import ReadImage
  25. from ...utils.hpi import HPIConfig
  26. from ...utils.pp_option import PaddlePredictorOption
  27. from ..components.chat_server import BaseChat
  28. from ..layout_parsing.result import LayoutParsingResult
  29. from .pipeline_base import PP_ChatOCR_Pipeline
  30. @pipeline_requires_extra("ie")
  31. class PP_ChatOCRv3_Pipeline(PP_ChatOCR_Pipeline):
  32. """PP-ChatOCR Pipeline"""
  33. entities = ["PP-ChatOCRv3-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.layout_parsing_pipeline = None
  62. self.chat_bot = None
  63. self.retriever = None
  64. if initial_predictor:
  65. self.inintial_visual_predictor(config)
  66. self.inintial_chat_predictor(config)
  67. self.inintial_retriever_predictor(config)
  68. self.batch_sampler = ImageBatchSampler(batch_size=1)
  69. self.img_reader = ReadImage(format="BGR")
  70. self.table_structure_len_max = 500
  71. def inintial_visual_predictor(self, config: dict) -> None:
  72. """
  73. Initializes the visual predictor with the given configuration.
  74. Args:
  75. config (dict): The configuration dictionary containing the necessary
  76. parameters for initializing the predictor.
  77. Returns:
  78. None
  79. """
  80. self.use_layout_parser = config.get("use_layout_parser", True)
  81. if self.use_layout_parser:
  82. layout_parsing_config = config.get("SubPipelines", {}).get(
  83. "LayoutParser",
  84. {"pipeline_config_error": "config error for layout_parsing_pipeline!"},
  85. )
  86. self.layout_parsing_pipeline = self.create_pipeline(layout_parsing_config)
  87. return
  88. def inintial_retriever_predictor(self, config: dict) -> None:
  89. """
  90. Initializes the retriever predictor with the given configuration.
  91. Args:
  92. config (dict): The configuration dictionary containing the necessary
  93. parameters for initializing the predictor.
  94. Returns:
  95. None
  96. """
  97. from .. import create_retriever
  98. retriever_config = config.get("SubModules", {}).get(
  99. "LLM_Retriever",
  100. {"retriever_config_error": "config error for llm retriever!"},
  101. )
  102. self.retriever = create_retriever(retriever_config)
  103. def inintial_chat_predictor(self, config: dict) -> None:
  104. """
  105. Initializes the chat predictor with the given configuration.
  106. Args:
  107. config (dict): The configuration dictionary containing the necessary
  108. parameters for initializing the predictor.
  109. Returns:
  110. None
  111. """
  112. from .. import create_chat_bot
  113. chat_bot_config = config.get("SubModules", {}).get(
  114. "LLM_Chat",
  115. {"chat_bot_config_error": "config error for llm chat bot!"},
  116. )
  117. self.chat_bot = create_chat_bot(chat_bot_config)
  118. from .. import create_prompt_engineering
  119. text_pe_config = (
  120. config.get("SubModules", {})
  121. .get("PromptEngneering", {})
  122. .get(
  123. "KIE_CommonText",
  124. {"pe_config_error": "config error for text_pe!"},
  125. )
  126. )
  127. self.text_pe = create_prompt_engineering(text_pe_config)
  128. table_pe_config = (
  129. config.get("SubModules", {})
  130. .get("PromptEngneering", {})
  131. .get(
  132. "KIE_Table",
  133. {"pe_config_error": "config error for table_pe!"},
  134. )
  135. )
  136. self.table_pe = create_prompt_engineering(table_pe_config)
  137. return
  138. def decode_visual_result(self, layout_parsing_result: LayoutParsingResult) -> dict:
  139. """
  140. Decodes the visual result from the layout parsing result.
  141. Args:
  142. layout_parsing_result (LayoutParsingResult): The result of layout parsing.
  143. Returns:
  144. dict: The decoded visual information.
  145. """
  146. normal_text_dict = {}
  147. parsing_res_list = layout_parsing_result["parsing_res_list"]
  148. for pno in range(len(parsing_res_list)):
  149. label = parsing_res_list[pno]["block_label"]
  150. content = parsing_res_list[pno]["block_content"]
  151. if label in ["table", "formula"]:
  152. continue
  153. key = f"words in {label}"
  154. if key not in normal_text_dict:
  155. normal_text_dict[key] = content
  156. else:
  157. normal_text_dict[key] += f"\n {content}"
  158. table_res_list = layout_parsing_result["table_res_list"]
  159. table_text_list = []
  160. table_html_list = []
  161. for table_res in table_res_list:
  162. table_html_list.append(table_res["pred_html"])
  163. single_table_text = " ".join(table_res["table_ocr_pred"]["rec_texts"])
  164. table_text_list.append(single_table_text)
  165. visual_info = {}
  166. visual_info["normal_text_dict"] = normal_text_dict
  167. visual_info["table_text_list"] = table_text_list
  168. visual_info["table_html_list"] = table_html_list
  169. return visual_info
  170. # Function to perform visual prediction on input images
  171. def visual_predict(
  172. self,
  173. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  174. use_doc_orientation_classify: Optional[bool] = None,
  175. use_doc_unwarping: Optional[bool] = None,
  176. use_seal_recognition: Optional[bool] = None,
  177. use_table_recognition: Optional[bool] = None,
  178. layout_threshold: Optional[Union[float, dict]] = None,
  179. layout_nms: Optional[bool] = None,
  180. layout_unclip_ratio: Optional[Union[float, Tuple[float, float], dict]] = None,
  181. layout_merge_bboxes_mode: Optional[str] = None,
  182. text_det_limit_side_len: Optional[int] = None,
  183. text_det_limit_type: Optional[str] = None,
  184. text_det_thresh: Optional[float] = None,
  185. text_det_box_thresh: Optional[float] = None,
  186. text_det_unclip_ratio: Optional[float] = None,
  187. text_rec_score_thresh: Optional[float] = None,
  188. seal_det_limit_side_len: Optional[int] = None,
  189. seal_det_limit_type: Optional[str] = None,
  190. seal_det_thresh: Optional[float] = None,
  191. seal_det_box_thresh: Optional[float] = None,
  192. seal_det_unclip_ratio: Optional[float] = None,
  193. seal_rec_score_thresh: Optional[float] = None,
  194. **kwargs,
  195. ) -> dict:
  196. """
  197. This function takes an input image or a list of images and performs various visual
  198. prediction tasks such as document orientation classification, document unwarping,
  199. general OCR, seal recognition, and table recognition based on the provided flags.
  200. Args:
  201. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): Input image path, list of image paths,
  202. numpy array of an image, or list of numpy arrays.
  203. use_doc_orientation_classify (bool): Flag to use document orientation classification.
  204. use_doc_unwarping (bool): Flag to use document unwarping.
  205. use_seal_recognition (bool): Flag to use seal recognition.
  206. use_table_recognition (bool): Flag to use table recognition.
  207. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  208. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  209. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  210. Defaults to None.
  211. If it's a single number, then both width and height are used.
  212. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  213. If it's None, then no unclipping will be performed.
  214. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  215. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  216. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  217. text_det_thresh (Optional[float]): Threshold for text detection.
  218. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  219. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  220. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  221. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  222. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  223. seal_det_thresh (Optional[float]): Threshold for seal detection.
  224. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  225. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  226. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  227. **kwargs: Additional keyword arguments.
  228. Returns:
  229. dict: A dictionary containing the layout parsing result and visual information.
  230. """
  231. if self.use_layout_parser == False:
  232. logging.error("The models for layout parser are not initialized.")
  233. yield {"error": "The models for layout parser are not initialized."}
  234. if self.layout_parsing_pipeline is None:
  235. logging.warning(
  236. "The layout parsing pipeline is not initialized, will initialize it now."
  237. )
  238. self.inintial_visual_predictor(self.config)
  239. for layout_parsing_result in self.layout_parsing_pipeline.predict(
  240. input,
  241. use_doc_orientation_classify=use_doc_orientation_classify,
  242. use_doc_unwarping=use_doc_unwarping,
  243. use_seal_recognition=use_seal_recognition,
  244. use_table_recognition=use_table_recognition,
  245. layout_threshold=layout_threshold,
  246. layout_nms=layout_nms,
  247. layout_unclip_ratio=layout_unclip_ratio,
  248. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  249. text_det_limit_side_len=text_det_limit_side_len,
  250. text_det_limit_type=text_det_limit_type,
  251. text_det_thresh=text_det_thresh,
  252. text_det_box_thresh=text_det_box_thresh,
  253. text_det_unclip_ratio=text_det_unclip_ratio,
  254. text_rec_score_thresh=text_rec_score_thresh,
  255. seal_det_box_thresh=seal_det_box_thresh,
  256. seal_det_limit_side_len=seal_det_limit_side_len,
  257. seal_det_limit_type=seal_det_limit_type,
  258. seal_det_thresh=seal_det_thresh,
  259. seal_det_unclip_ratio=seal_det_unclip_ratio,
  260. seal_rec_score_thresh=seal_rec_score_thresh,
  261. ):
  262. visual_info = self.decode_visual_result(layout_parsing_result)
  263. visual_predict_res = {
  264. "layout_parsing_result": layout_parsing_result,
  265. "visual_info": visual_info,
  266. }
  267. yield visual_predict_res
  268. def save_visual_info_list(self, visual_info: dict, save_path: str) -> None:
  269. """
  270. Save the visual info list to the specified file path.
  271. Args:
  272. visual_info (dict): The visual info result, which can be a single object or a list of objects.
  273. save_path (str): The file path to save the visual info list.
  274. Returns:
  275. None
  276. """
  277. if not isinstance(visual_info, list):
  278. visual_info_list = [visual_info]
  279. else:
  280. visual_info_list = visual_info
  281. directory = os.path.dirname(save_path)
  282. if not os.path.exists(directory):
  283. os.makedirs(directory)
  284. with custom_open(save_path, "w") as fout:
  285. fout.write(json.dumps(visual_info_list, ensure_ascii=False) + "\n")
  286. return
  287. def load_visual_info_list(self, data_path: str) -> List[dict]:
  288. """
  289. Loads visual info list from a JSON file.
  290. Args:
  291. data_path (str): The path to the JSON file containing visual info.
  292. Returns:
  293. list[dict]: A list of dict objects parsed from the JSON file.
  294. """
  295. with custom_open(data_path, "r") as fin:
  296. data = fin.readline()
  297. visual_info_list = json.loads(data)
  298. return visual_info_list
  299. def merge_visual_info_list(
  300. self, visual_info_list: List[dict]
  301. ) -> Tuple[list, list, list]:
  302. """
  303. Merge visual info lists.
  304. Args:
  305. visual_info_list (list[dict]): A list of visual info results.
  306. Returns:
  307. tuple[list, list, list]: A tuple containing four lists, one for normal text dicts,
  308. one for table text lists, one for table HTML lists.
  309. """
  310. all_normal_text_list = []
  311. all_table_text_list = []
  312. all_table_html_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. all_normal_text_list.append(normal_text_dict)
  320. all_table_text_list.extend(table_text_list)
  321. all_table_html_list.extend(table_html_list)
  322. return (all_normal_text_list, all_table_text_list, all_table_html_list)
  323. def build_vector(
  324. self,
  325. visual_info: dict,
  326. min_characters: int = 3500,
  327. block_size: int = 300,
  328. flag_save_bytes_vector: bool = False,
  329. retriever_config: dict = None,
  330. ) -> dict:
  331. """
  332. Build a vector representation from visual information.
  333. Args:
  334. visual_info (dict): The visual information input, can be a single instance or a list of instances.
  335. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  336. block_size (int): The size of each chunk to split the text into.
  337. flag_save_bytes_vector (bool): Whether to save the vector as bytes, defaults to False.
  338. retriever_config (dict): The configuration for the retriever, defaults to None.
  339. Returns:
  340. dict: A dictionary containing the vector info and a flag indicating if the text is too short.
  341. """
  342. if not isinstance(visual_info, list):
  343. visual_info_list = [visual_info]
  344. else:
  345. visual_info_list = visual_info
  346. if retriever_config is not None:
  347. from .. import create_retriever
  348. retriever = create_retriever(retriever_config)
  349. else:
  350. if self.retriever is None:
  351. logging.warning(
  352. "The retriever is not initialized,will initialize it now."
  353. )
  354. self.inintial_retriever_predictor(self.config)
  355. retriever = self.retriever
  356. all_visual_info = self.merge_visual_info_list(visual_info_list)
  357. (
  358. all_normal_text_list,
  359. all_table_text_list,
  360. all_table_html_list,
  361. ) = all_visual_info
  362. vector_info = {}
  363. all_items = []
  364. for i, normal_text_dict in enumerate(all_normal_text_list):
  365. for type, text in normal_text_dict.items():
  366. all_items += [f"{type}:{text}\n"]
  367. for table_html, table_text in zip(all_table_html_list, all_table_text_list):
  368. if len(table_html) > min_characters - self.table_structure_len_max:
  369. all_items += [f"table:{table_text}"]
  370. all_text_str = "".join(all_items)
  371. vector_info["flag_save_bytes_vector"] = False
  372. if len(all_text_str) > min_characters:
  373. vector_info["flag_too_short_text"] = False
  374. vector_info["model_name"] = retriever.model_name
  375. vector_info["block_size"] = block_size
  376. vector_info["vector"] = retriever.generate_vector_database(
  377. all_items, block_size=block_size
  378. )
  379. if flag_save_bytes_vector:
  380. vector_info["vector"] = retriever.encode_vector_store_to_bytes(
  381. vector_info["vector"]
  382. )
  383. vector_info["flag_save_bytes_vector"] = True
  384. else:
  385. vector_info["flag_too_short_text"] = True
  386. vector_info["vector"] = all_items
  387. return vector_info
  388. def save_vector(
  389. self, vector_info: dict, save_path: str, retriever_config: dict = None
  390. ) -> None:
  391. directory = os.path.dirname(save_path)
  392. if not os.path.exists(directory):
  393. os.makedirs(directory)
  394. if retriever_config is not None:
  395. from .. import create_retriever
  396. retriever = create_retriever(retriever_config)
  397. else:
  398. if self.retriever is None:
  399. logging.warning(
  400. "The retriever is not initialized,will initialize it now."
  401. )
  402. self.inintial_retriever_predictor(self.config)
  403. retriever = self.retriever
  404. vector_info_data = copy.deepcopy(vector_info)
  405. if (
  406. not vector_info["flag_too_short_text"]
  407. and not vector_info["flag_save_bytes_vector"]
  408. ):
  409. vector_info_data["vector"] = retriever.encode_vector_store_to_bytes(
  410. vector_info_data["vector"]
  411. )
  412. vector_info_data["flag_save_bytes_vector"] = True
  413. with custom_open(save_path, "w") as fout:
  414. fout.write(json.dumps(vector_info_data, ensure_ascii=False) + "\n")
  415. return
  416. def load_vector(self, data_path: str, retriever_config: dict = None) -> dict:
  417. vector_info = None
  418. if retriever_config is not None:
  419. from .. import create_retriever
  420. retriever = create_retriever(retriever_config)
  421. else:
  422. if self.retriever is None:
  423. logging.warning(
  424. "The retriever is not initialized,will initialize it now."
  425. )
  426. self.inintial_retriever_predictor(self.config)
  427. retriever = self.retriever
  428. with open(data_path, "r") as fin:
  429. data = fin.readline()
  430. vector_info = json.loads(data)
  431. if (
  432. "flag_too_short_text" not in vector_info
  433. or "flag_save_bytes_vector" not in vector_info
  434. or "vector" not in vector_info
  435. ):
  436. logging.error("Invalid vector info.")
  437. return {"error": "Invalid vector info when load vector!"}
  438. if vector_info["flag_save_bytes_vector"]:
  439. vector_info["vector"] = retriever.decode_vector_store_from_bytes(
  440. vector_info["vector"]
  441. )
  442. vector_info["flag_save_bytes_vector"] = False
  443. return vector_info
  444. def format_key(self, key_list: Union[str, List[str]]) -> List[str]:
  445. """
  446. Formats the key list.
  447. Args:
  448. key_list (str|list[str]): A string or a list of strings representing the keys.
  449. Returns:
  450. list[str]: A list of formatted keys.
  451. """
  452. if key_list == "":
  453. return []
  454. if isinstance(key_list, list):
  455. return key_list
  456. if isinstance(key_list, str):
  457. key_list = re.sub(r"[\t\n\r\f\v]", "", key_list)
  458. key_list = key_list.replace(",", ",").split(",")
  459. return key_list
  460. return []
  461. def generate_and_merge_chat_results(
  462. self,
  463. chat_bot: BaseChat,
  464. prompt: str,
  465. key_list: list,
  466. final_results: dict,
  467. failed_results: list,
  468. ) -> None:
  469. """
  470. Generate and merge chat results into the final results dictionary.
  471. Args:
  472. prompt (str): The input prompt for the chat bot.
  473. key_list (list): A list of keys to track which results to merge.
  474. final_results (dict): The dictionary to store the final merged results.
  475. failed_results (list): A list of failed results to avoid merging.
  476. Returns:
  477. None
  478. """
  479. llm_result = chat_bot.generate_chat_results(prompt)
  480. llm_result_content = llm_result["content"]
  481. llm_result_reasoning_content = llm_result["reasoning_content"]
  482. if llm_result_reasoning_content is not None:
  483. if "reasoning_content" not in final_results:
  484. final_results["reasoning_content"] = [llm_result_reasoning_content]
  485. else:
  486. final_results["reasoning_content"].append(llm_result_reasoning_content)
  487. if llm_result_content is None:
  488. logging.error(
  489. "chat bot error: \n [prompt:]\n %s\n [result:] %s\n"
  490. % (prompt, chat_bot.ERROR_MASSAGE)
  491. )
  492. return
  493. llm_result_content = chat_bot.fix_llm_result_format(llm_result_content)
  494. for key, value in llm_result_content.items():
  495. if value not in failed_results and key in key_list:
  496. key_list.remove(key)
  497. final_results[key] = value
  498. return
  499. def get_related_normal_text(
  500. self,
  501. retriever_config: dict,
  502. use_vector_retrieval: bool,
  503. vector_info: dict,
  504. key_list: List[str],
  505. all_normal_text_list: list,
  506. min_characters: int,
  507. ) -> str:
  508. """
  509. Retrieve related normal text based on vector retrieval or all normal text list.
  510. Args:
  511. retriever_config (dict): Configuration for the retriever.
  512. use_vector_retrieval (bool): Whether to use vector retrieval.
  513. vector_info (dict): Dictionary containing vector information.
  514. key_list (list[str]): List of keys to generate question keys.
  515. all_normal_text_list (list): List of normal text.
  516. min_characters (int): The minimum number of characters required for text processing, defaults to 3500.
  517. Returns:
  518. str: Related normal text.
  519. """
  520. if use_vector_retrieval and vector_info is not None:
  521. if retriever_config is not None:
  522. from .. import create_retriever
  523. retriever = create_retriever(retriever_config)
  524. else:
  525. if self.retriever is None:
  526. logging.warning(
  527. "The retriever is not initialized,will initialize it now."
  528. )
  529. self.inintial_retriever_predictor(self.config)
  530. retriever = self.retriever
  531. question_key_list = [f"{key}" for key in key_list]
  532. vector = vector_info["vector"]
  533. if not vector_info["flag_too_short_text"]:
  534. assert (
  535. vector_info["model_name"] == retriever.model_name
  536. ), f"The vector model name ({vector_info['model_name']}) does not match the retriever model name ({retriever.model_name}). Please check your retriever config."
  537. if vector_info["flag_save_bytes_vector"]:
  538. vector = retriever.decode_vector_store_from_bytes(vector)
  539. related_text = retriever.similarity_retrieval(
  540. question_key_list, vector, topk=50, min_characters=min_characters
  541. )
  542. else:
  543. if len(vector) > 0:
  544. related_text = "".join(vector)
  545. else:
  546. related_text = ""
  547. else:
  548. all_items = []
  549. for i, normal_text_dict in enumerate(all_normal_text_list):
  550. for type, text in normal_text_dict.items():
  551. all_items += [f"{type}:{text}\n"]
  552. related_text = "".join(all_items)
  553. if len(related_text) > min_characters:
  554. logging.warning(
  555. "The input text content is too long, the large language model may truncate it."
  556. )
  557. return related_text
  558. def chat(
  559. self,
  560. key_list: Union[str, List[str]],
  561. visual_info: List[dict],
  562. use_vector_retrieval: bool = True,
  563. vector_info: dict = None,
  564. min_characters: int = 3500,
  565. text_task_description: str = None,
  566. text_output_format: str = None,
  567. text_rules_str: str = None,
  568. text_few_shot_demo_text_content: str = None,
  569. text_few_shot_demo_key_value_list: str = None,
  570. table_task_description: str = None,
  571. table_output_format: str = None,
  572. table_rules_str: str = None,
  573. table_few_shot_demo_text_content: str = None,
  574. table_few_shot_demo_key_value_list: str = None,
  575. chat_bot_config: dict = None,
  576. retriever_config: dict = None,
  577. ) -> dict:
  578. """
  579. Generates chat results based on the provided key list and visual information.
  580. Args:
  581. key_list (Union[str, list[str]]): A single key or a list of keys to extract information.
  582. visual_info (dict): The visual information result.
  583. use_vector_retrieval (bool): Whether to use vector retrieval.
  584. vector_info (dict): The vector information for retrieval.
  585. min_characters (int): The minimum number of characters required.
  586. text_task_description (str): The description of the text task.
  587. text_output_format (str): The output format for text results.
  588. text_rules_str (str): The rules for generating text results.
  589. text_few_shot_demo_text_content (str): The text content for few-shot demos.
  590. text_few_shot_demo_key_value_list (str): The key-value list for few-shot demos.
  591. table_task_description (str): The description of the table task.
  592. table_output_format (str): The output format for table results.
  593. table_rules_str (str): The rules for generating table results.
  594. table_few_shot_demo_text_content (str): The text content for table few-shot demos.
  595. table_few_shot_demo_key_value_list (str): The key-value list for table few-shot demos.
  596. chat_bot_config(dict): The parameters for LLM chatbot, including api_type, api_key... refer to config file for more details.
  597. retriever_config (dict): The parameters for LLM retriever, including api_type, api_key... refer to config file for more details.
  598. Returns:
  599. dict: A dictionary containing the chat results.
  600. """
  601. key_list = self.format_key(key_list)
  602. if len(key_list) == 0:
  603. return {"chat_res": "Error:输入的key_list无效!"}
  604. if not isinstance(visual_info, list):
  605. visual_info_list = [visual_info]
  606. else:
  607. visual_info_list = visual_info
  608. if self.chat_bot is None:
  609. logging.warning(
  610. "The LLM chat bot is not initialized,will initialize it now."
  611. )
  612. self.inintial_chat_predictor(self.config)
  613. if chat_bot_config is not None:
  614. from .. import create_chat_bot
  615. chat_bot = create_chat_bot(chat_bot_config)
  616. else:
  617. chat_bot = self.chat_bot
  618. all_visual_info = self.merge_visual_info_list(visual_info_list)
  619. (
  620. all_normal_text_list,
  621. all_table_text_list,
  622. all_table_html_list,
  623. ) = all_visual_info
  624. final_results = {}
  625. failed_results = ["大模型调用失败", "未知", "未找到关键信息", "None", ""]
  626. if len(key_list) > 0:
  627. for table_html, table_text in zip(all_table_html_list, all_table_text_list):
  628. if len(table_html) <= min_characters - self.table_structure_len_max:
  629. for table_info in [table_html]:
  630. if len(key_list) > 0:
  631. prompt = self.table_pe.generate_prompt(
  632. table_info,
  633. key_list,
  634. task_description=table_task_description,
  635. output_format=table_output_format,
  636. rules_str=table_rules_str,
  637. few_shot_demo_text_content=table_few_shot_demo_text_content,
  638. few_shot_demo_key_value_list=table_few_shot_demo_key_value_list,
  639. )
  640. self.generate_and_merge_chat_results(
  641. chat_bot,
  642. prompt,
  643. key_list,
  644. final_results,
  645. failed_results,
  646. )
  647. if len(key_list) > 0:
  648. related_text = self.get_related_normal_text(
  649. retriever_config,
  650. use_vector_retrieval,
  651. vector_info,
  652. key_list,
  653. all_normal_text_list,
  654. min_characters,
  655. )
  656. if len(related_text) > 0:
  657. prompt = self.text_pe.generate_prompt(
  658. related_text,
  659. key_list,
  660. task_description=text_task_description,
  661. output_format=text_output_format,
  662. rules_str=text_rules_str,
  663. few_shot_demo_text_content=text_few_shot_demo_text_content,
  664. few_shot_demo_key_value_list=text_few_shot_demo_key_value_list,
  665. )
  666. self.generate_and_merge_chat_results(
  667. chat_bot, prompt, key_list, final_results, failed_results
  668. )
  669. return {"chat_res": final_results}
  670. def predict(self, *args, **kwargs) -> None:
  671. logging.error(
  672. "PP-ChatOCRv3-doc Pipeline do not support to call `predict()` directly! Please invoke `visual_predict`, `build_vector`, `chat` sequentially to obtain the result."
  673. )
  674. return