pipeline.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 re
  15. from time import sleep
  16. from typing import Any, Dict, List, Optional, Tuple, Union
  17. import numpy as np
  18. from ....utils import logging
  19. from ....utils.deps import pipeline_requires_extra
  20. from ...common.batch_sampler import MarkDownBatchSampler
  21. from ...utils.benchmark import benchmark
  22. from ...utils.hpi import HPIConfig
  23. from ...utils.pp_option import PaddlePredictorOption
  24. from ..base import BasePipeline
  25. from .result import MarkdownResult
  26. from .utils import (
  27. split_original_texts,
  28. split_text_recursive,
  29. translate_code_block,
  30. translate_html_block,
  31. )
  32. @benchmark.time_methods
  33. @pipeline_requires_extra("trans")
  34. class PP_DocTranslation_Pipeline(BasePipeline):
  35. """
  36. PP_ DocTranslation_Pipeline
  37. """
  38. entities = ["PP-DocTranslation"]
  39. def __init__(
  40. self,
  41. config: Dict,
  42. device: str = None,
  43. pp_option: PaddlePredictorOption = None,
  44. use_hpip: bool = False,
  45. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  46. initial_predictor: bool = False,
  47. ) -> None:
  48. """Initializes the PP_Translation_Pipeline.
  49. Args:
  50. config (Dict): Configuration dictionary containing various settings.
  51. device (str, optional): Device to run the predictions on. Defaults to None.
  52. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  53. use_hpip (bool, optional): Whether to use the high-performance
  54. inference plugin (HPIP) by default. Defaults to False.
  55. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  56. The default high-performance inference configuration dictionary.
  57. Defaults to None.
  58. initial_predictor (bool, optional): Whether to initialize the predictor. Defaults to True.
  59. """
  60. super().__init__(
  61. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  62. )
  63. self.pipeline_name = config["pipeline_name"]
  64. self.config = config
  65. self.use_layout_parser = config.get("use_layout_parser", True)
  66. self.layout_parsing_pipeline = None
  67. self.chat_bot = None
  68. if initial_predictor:
  69. self.inintial_visual_predictor(config)
  70. self.inintial_chat_predictor(config)
  71. self.markdown_batch_sampler = MarkDownBatchSampler()
  72. def close(self):
  73. if self.layout_parsing_pipeline is not None:
  74. self.layout_parsing_pipeline.close()
  75. def inintial_visual_predictor(self, config: dict) -> None:
  76. """
  77. Initializes the visual predictor with the given configuration.
  78. Args:
  79. config (dict): The configuration dictionary containing the necessary
  80. parameters for initializing the predictor.
  81. Returns:
  82. None
  83. """
  84. self.use_layout_parser = config.get("use_layout_parser", True)
  85. if self.use_layout_parser:
  86. layout_parsing_config = config.get("SubPipelines", {}).get(
  87. "LayoutParser",
  88. {"pipeline_config_error": "config error for layout_parsing_pipeline!"},
  89. )
  90. self.layout_parsing_pipeline = self.create_pipeline(layout_parsing_config)
  91. return
  92. def inintial_chat_predictor(self, config: dict) -> None:
  93. """
  94. Initializes the chat predictor with the given configuration.
  95. Args:
  96. config (dict): The configuration dictionary containing the necessary
  97. parameters for initializing the predictor.
  98. Returns:
  99. None
  100. """
  101. from .. import create_chat_bot
  102. chat_bot_config = config.get("SubModules", {}).get(
  103. "LLM_Chat",
  104. {"chat_bot_config_error": "config error for llm chat bot!"},
  105. )
  106. self.chat_bot = create_chat_bot(chat_bot_config)
  107. from .. import create_prompt_engineering
  108. translate_pe_config = (
  109. config.get("SubModules", {})
  110. .get("PromptEngneering", {})
  111. .get(
  112. "Translate_CommonText",
  113. {"pe_config_error": "config error for translate_pe_config!"},
  114. )
  115. )
  116. self.translate_pe = create_prompt_engineering(translate_pe_config)
  117. return
  118. def predict(self, *args, **kwargs) -> None:
  119. logging.error(
  120. "PP-Translation Pipeline do not support to call `predict()` directly! Please invoke `visual_predict`, `build_vector`, `chat` sequentially to obtain the result."
  121. )
  122. return
  123. def visual_predict(
  124. self,
  125. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  126. use_doc_orientation_classify: Optional[bool] = None,
  127. use_doc_unwarping: Optional[bool] = None,
  128. use_textline_orientation: Optional[bool] = None,
  129. use_seal_recognition: Optional[bool] = None,
  130. use_table_recognition: Optional[bool] = None,
  131. use_formula_recognition: Optional[bool] = None,
  132. use_chart_recognition: Optional[bool] = None,
  133. use_region_detection: Optional[bool] = None,
  134. layout_threshold: Optional[Union[float, dict]] = None,
  135. layout_nms: Optional[bool] = None,
  136. layout_unclip_ratio: Optional[Union[float, Tuple[float, float], dict]] = None,
  137. layout_merge_bboxes_mode: Optional[str] = None,
  138. text_det_limit_side_len: Optional[int] = None,
  139. text_det_limit_type: Optional[str] = None,
  140. text_det_thresh: Optional[float] = None,
  141. text_det_box_thresh: Optional[float] = None,
  142. text_det_unclip_ratio: Optional[float] = None,
  143. text_rec_score_thresh: Optional[float] = None,
  144. seal_det_limit_side_len: Optional[int] = None,
  145. seal_det_limit_type: Optional[str] = None,
  146. seal_det_thresh: Optional[float] = None,
  147. seal_det_box_thresh: Optional[float] = None,
  148. seal_det_unclip_ratio: Optional[float] = None,
  149. seal_rec_score_thresh: Optional[float] = None,
  150. use_wired_table_cells_trans_to_html: bool = False,
  151. use_wireless_table_cells_trans_to_html: bool = False,
  152. use_table_orientation_classify: bool = True,
  153. use_ocr_results_with_table_cells: bool = True,
  154. use_e2e_wired_table_rec_model: bool = False,
  155. use_e2e_wireless_table_rec_model: bool = True,
  156. **kwargs,
  157. ) -> dict:
  158. """
  159. This function takes an input image or a list of images and performs various visual
  160. prediction tasks such as document orientation classification, document unwarping,
  161. general OCR, seal recognition, and table recognition based on the provided flags.
  162. Args:
  163. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): Input image path, list of image paths,
  164. numpy array of an image, or list of numpy arrays.
  165. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  166. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  167. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  168. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  169. use_table_recognition (Optional[bool]): Whether to use table recognition.
  170. use_formula_recognition (Optional[bool]): Whether to use formula recognition.
  171. use_region_detection (Optional[bool]): Whether to use region detection.
  172. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  173. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  174. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  175. Defaults to None.
  176. If it's a single number, then both width and height are used.
  177. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  178. If it's None, then no unclipping will be performed.
  179. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  180. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  181. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  182. text_det_thresh (Optional[float]): Threshold for text detection.
  183. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  184. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  185. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  186. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  187. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  188. seal_det_thresh (Optional[float]): Threshold for seal detection.
  189. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  190. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  191. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  192. use_wired_table_cells_trans_to_html (bool): Whether to use wired table cells trans to HTML.
  193. use_wireless_table_cells_trans_to_html (bool): Whether to use wireless table cells trans to HTML.
  194. use_table_orientation_classify (bool): Whether to use table orientation classification.
  195. use_ocr_results_with_table_cells (bool): Whether to use OCR results processed by table cells.
  196. use_e2e_wired_table_rec_model (bool): Whether to use end-to-end wired table recognition model.
  197. use_e2e_wireless_table_rec_model (bool): Whether to use end-to-end wireless table recognition model.
  198. **kwargs (Any): Additional settings to extend functionality.
  199. Returns:
  200. dict: A dictionary containing the layout parsing result.
  201. """
  202. if self.use_layout_parser == False:
  203. logging.error("The models for layout parser are not initialized.")
  204. yield {"error": "The models for layout parser are not initialized."}
  205. if self.layout_parsing_pipeline is None:
  206. logging.warning(
  207. "The layout parsing pipeline is not initialized, will initialize it now."
  208. )
  209. self.inintial_visual_predictor(self.config)
  210. for layout_parsing_result in self.layout_parsing_pipeline.predict(
  211. input,
  212. use_doc_orientation_classify=use_doc_orientation_classify,
  213. use_doc_unwarping=use_doc_unwarping,
  214. use_textline_orientation=use_textline_orientation,
  215. use_seal_recognition=use_seal_recognition,
  216. use_table_recognition=use_table_recognition,
  217. use_formula_recognition=use_formula_recognition,
  218. use_chart_recognition=use_chart_recognition,
  219. use_region_detection=use_region_detection,
  220. layout_threshold=layout_threshold,
  221. layout_nms=layout_nms,
  222. layout_unclip_ratio=layout_unclip_ratio,
  223. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  224. text_det_limit_side_len=text_det_limit_side_len,
  225. text_det_limit_type=text_det_limit_type,
  226. text_det_thresh=text_det_thresh,
  227. text_det_box_thresh=text_det_box_thresh,
  228. text_det_unclip_ratio=text_det_unclip_ratio,
  229. text_rec_score_thresh=text_rec_score_thresh,
  230. seal_det_box_thresh=seal_det_box_thresh,
  231. seal_det_limit_side_len=seal_det_limit_side_len,
  232. seal_det_limit_type=seal_det_limit_type,
  233. seal_det_thresh=seal_det_thresh,
  234. seal_det_unclip_ratio=seal_det_unclip_ratio,
  235. seal_rec_score_thresh=seal_rec_score_thresh,
  236. use_wired_table_cells_trans_to_html=use_wired_table_cells_trans_to_html,
  237. use_wireless_table_cells_trans_to_html=use_wireless_table_cells_trans_to_html,
  238. use_table_orientation_classify=use_table_orientation_classify,
  239. use_ocr_results_with_table_cells=use_ocr_results_with_table_cells,
  240. use_e2e_wired_table_rec_model=use_e2e_wired_table_rec_model,
  241. use_e2e_wireless_table_rec_model=use_e2e_wireless_table_rec_model,
  242. ):
  243. visual_predict_res = {
  244. "layout_parsing_result": layout_parsing_result,
  245. }
  246. yield visual_predict_res
  247. def load_from_markdown(self, input):
  248. markdown_info_list = []
  249. for markdown_sample in self.markdown_batch_sampler.sample(input):
  250. markdown_content = markdown_sample.instances[0]
  251. input_path = markdown_sample.input_paths[0]
  252. markdown_info = {
  253. "input_path": input_path,
  254. "page_index": None,
  255. "markdown_texts": markdown_content,
  256. "page_continuation_flags": (True, True),
  257. }
  258. markdown_info_list.append(MarkdownResult(markdown_info))
  259. return markdown_info_list
  260. def chunk_translate(self, md_blocks, chunk_size, translate_func):
  261. """
  262. Chunks the given markdown blocks into smaller chunks of size `chunk_size` and translates them using the given
  263. translate function.
  264. Args:
  265. md_blocks (list): A list of tuples representing each block of markdown content. Each tuple consists of a string
  266. indicating the block type ('text', 'code') and the actual content of the block.
  267. chunk_size (int): The maximum size of each chunk.
  268. translate_func (callable): A callable that accepts a string argument and returns the translated version of that string.
  269. Returns:
  270. str: A string containing all the translated chunks concatenated together with newlines between them.
  271. """
  272. translation_results = []
  273. chunk = ""
  274. logging.info(f"Split the original text into {len(md_blocks)} blocks")
  275. logging.info("Starting translation...")
  276. for idx, block in enumerate(md_blocks):
  277. block_type, block_content = block
  278. if block_type == "code":
  279. if chunk.strip():
  280. translation_results.append(translate_func(chunk.strip()))
  281. chunk = "" # Clear the chunk
  282. logging.info(f"Translating block {idx+1}/{len(md_blocks)}...")
  283. translate_code_block(
  284. block_content, chunk_size, translate_func, translation_results
  285. )
  286. elif len(block_content) < chunk_size and block_type == "text":
  287. if len(chunk) + len(block_content) < chunk_size:
  288. chunk += "\n\n" + block_content
  289. else:
  290. if chunk.strip():
  291. logging.info(f"Translating block {idx+1}/{len(md_blocks)}...")
  292. translation_results.append(translate_func(chunk.strip()))
  293. chunk = block_content
  294. else:
  295. logging.info(f"Translating block {idx+1}/{len(md_blocks)}...")
  296. if chunk.strip():
  297. translation_results.append(translate_func(chunk.strip()))
  298. chunk = "" # Clear the chunk
  299. if block_type == "text":
  300. translation_results.append(
  301. split_text_recursive(block_content, chunk_size, translate_func)
  302. )
  303. elif block_type == "text_with_html" or block_type == "html":
  304. translate_html_block(
  305. block_content, chunk_size, translate_func, translation_results
  306. )
  307. else:
  308. raise ValueError(f"Unknown block type: {block_type}")
  309. if chunk.strip():
  310. translation_results.append(translate_func(chunk.strip()))
  311. return "\n\n".join(translation_results)
  312. def translate(
  313. self,
  314. ori_md_info_list: List[Dict],
  315. target_language: str = "zh",
  316. chunk_size: int = 3000,
  317. task_description: str = None,
  318. output_format: str = None,
  319. rules_str: str = None,
  320. few_shot_demo_text_content: str = None,
  321. few_shot_demo_key_value_list: str = None,
  322. glossary: Dict = None,
  323. llm_request_interval: float = 0.0,
  324. chat_bot_config: Dict = None,
  325. **kwargs,
  326. ):
  327. """
  328. Translate the given original text into the specified target language using the configured translation model.
  329. Args:
  330. ori_md_info_list (List[Dict]): A list of dictionaries containing information about the original markdown text to be translated.
  331. target_language (str, optional): The desired target language code. Defaults to "zh".
  332. chunk_size (int, optional): The maximum number of characters allowed per chunk when splitting long texts. Defaults to 5000.
  333. task_description (str, optional): A description of the task being performed by the translation model. Defaults to None.
  334. output_format (str, optional): The desired output format of the translation result. Defaults to None.
  335. rules_str (str, optional): Rules or guidelines for the translation model to follow. Defaults to None.
  336. few_shot_demo_text_content (str, optional): Demo text content for the translation model. Defaults to None.
  337. few_shot_demo_key_value_list (str, optional): Demo text key-value list for the translation model. Defaults to None.
  338. glossary (Dict, optional): A dictionary containing terms and their corresponding definitions. Defaults to None.
  339. llm_request_interval (float, optional): The interval in seconds between each request to the LLM. Defaults to 0.0.
  340. chat_bot_config (Dict, optional): Configuration for the chat bot used in the translation process. Defaults to None.
  341. **kwargs: Additional keyword arguments passed to the translation model.
  342. Yields:
  343. MarkdownResult: A dictionary containing the translation result in the target language.
  344. """
  345. if self.chat_bot is None:
  346. logging.warning(
  347. "The LLM chat bot is not initialized,will initialize it now."
  348. )
  349. self.inintial_chat_predictor(self.config)
  350. if chat_bot_config is not None:
  351. from .. import create_chat_bot
  352. chat_bot = create_chat_bot(chat_bot_config)
  353. else:
  354. chat_bot = self.chat_bot
  355. if (
  356. isinstance(ori_md_info_list, list)
  357. and ori_md_info_list[0].get("page_index") is not None
  358. ):
  359. # for multi page pdf
  360. ori_md_info_list = [self.concatenate_markdown_pages(ori_md_info_list)]
  361. if not isinstance(llm_request_interval, float):
  362. llm_request_interval = float(llm_request_interval)
  363. assert isinstance(glossary, dict) or glossary is None, "glossary must be a dict"
  364. glossary_str = ""
  365. if glossary is not None:
  366. for k, v in glossary.items():
  367. if isinstance(v, list):
  368. v = "或".join(v)
  369. glossary_str += f"{k}: {v}\n"
  370. if glossary_str != "":
  371. if few_shot_demo_key_value_list is None:
  372. few_shot_demo_key_value_list = glossary_str
  373. else:
  374. few_shot_demo_key_value_list += "\n"
  375. few_shot_demo_key_value_list += glossary_str
  376. def translate_func(text):
  377. """
  378. Translate the given text using the configured translation model.
  379. Args:
  380. text (str): The text to be translated.
  381. Returns:
  382. str: The translated text in the target language.
  383. """
  384. sleep(llm_request_interval)
  385. prompt = self.translate_pe.generate_prompt(
  386. original_text=text,
  387. language=target_language,
  388. task_description=task_description,
  389. output_format=output_format,
  390. rules_str=rules_str,
  391. few_shot_demo_text_content=few_shot_demo_text_content,
  392. few_shot_demo_key_value_list=few_shot_demo_key_value_list,
  393. )
  394. translate = chat_bot.generate_chat_results(prompt=prompt).get("content", "")
  395. if translate is None:
  396. raise Exception("The call to the large model failed.")
  397. return translate
  398. base_prompt_content = self.translate_pe.generate_prompt(
  399. original_text="",
  400. language=target_language,
  401. task_description=task_description,
  402. output_format=output_format,
  403. rules_str=rules_str,
  404. few_shot_demo_text_content=few_shot_demo_text_content,
  405. few_shot_demo_key_value_list=few_shot_demo_key_value_list,
  406. )
  407. base_prompt_length = len(base_prompt_content)
  408. if chunk_size > base_prompt_length:
  409. chunk_size = chunk_size - base_prompt_length
  410. else:
  411. raise ValueError(
  412. f"Chunk size should be greater than the base prompt length ({base_prompt_length}), but got {chunk_size}."
  413. )
  414. for ori_md in ori_md_info_list:
  415. original_texts = ori_md["markdown_texts"]
  416. md_blocks = split_original_texts(original_texts)
  417. target_language_texts = self.chunk_translate(
  418. md_blocks, chunk_size, translate_func
  419. )
  420. yield MarkdownResult(
  421. {
  422. "language": target_language,
  423. "input_path": ori_md["input_path"],
  424. "page_index": ori_md["page_index"],
  425. "page_continuation_flags": ori_md["page_continuation_flags"],
  426. "markdown_texts": target_language_texts,
  427. }
  428. )
  429. def concatenate_markdown_pages(self, markdown_list: list) -> tuple:
  430. """
  431. Concatenate Markdown content from multiple pages into a single document.
  432. Args:
  433. markdown_list (list): A list containing Markdown data for each page.
  434. Returns:
  435. tuple: A tuple containing the processed Markdown text.
  436. """
  437. markdown_texts = ""
  438. previous_page_last_element_paragraph_end_flag = True
  439. if len(markdown_list) == 0:
  440. raise ValueError("The length of markdown_list is zero.")
  441. for res in markdown_list:
  442. # Get the paragraph flags for the current page
  443. page_first_element_paragraph_start_flag: bool = res[
  444. "page_continuation_flags"
  445. ][0]
  446. page_last_element_paragraph_end_flag: bool = res["page_continuation_flags"][
  447. 1
  448. ]
  449. # Determine whether to add a space or a newline
  450. if (
  451. not page_first_element_paragraph_start_flag
  452. and not previous_page_last_element_paragraph_end_flag
  453. ):
  454. last_char_of_markdown = markdown_texts[-1] if markdown_texts else ""
  455. first_char_of_handler = (
  456. res["markdown_texts"][0] if res["markdown_texts"] else ""
  457. )
  458. # Check if the last character and the first character are Chinese characters
  459. last_is_chinese_char = (
  460. re.match(r"[\u4e00-\u9fff]", last_char_of_markdown)
  461. if last_char_of_markdown
  462. else False
  463. )
  464. first_is_chinese_char = (
  465. re.match(r"[\u4e00-\u9fff]", first_char_of_handler)
  466. if first_char_of_handler
  467. else False
  468. )
  469. if not (last_is_chinese_char or first_is_chinese_char):
  470. markdown_texts += " " + res["markdown_texts"]
  471. else:
  472. markdown_texts += res["markdown_texts"]
  473. else:
  474. markdown_texts += "\n\n" + res["markdown_texts"]
  475. previous_page_last_element_paragraph_end_flag = (
  476. page_last_element_paragraph_end_flag
  477. )
  478. concatenate_result = {
  479. "input_path": markdown_list[0]["input_path"],
  480. "page_index": None,
  481. "page_continuation_flags": (True, True),
  482. "markdown_texts": markdown_texts,
  483. }
  484. return MarkdownResult(concatenate_result)