pipeline.py 23 KB

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