pipeline_v3.py 29 KB

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