pipeline.py 25 KB

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