utils.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. def _find_split_pos(text, chunk_size):
  16. """
  17. Find the position to split the text into two chunks.
  18. Args:
  19. text (str): The original text to be split.
  20. chunk_size (int): The maximum size of each chunk.
  21. Returns:
  22. int: The index where the text should be split.
  23. """
  24. center = len(text) // 2
  25. # Search forward
  26. for i in range(center, len(text)):
  27. if text[i] in ["\n", ".", "。", ";", ";", "!", "!", "?", "?"]:
  28. if i + 1 < len(text) and len(text[: i + 1]) <= chunk_size:
  29. return i + 1
  30. # Search backward
  31. for i in range(center, 0, -1):
  32. if text[i] in ["\n", ".", "。", ";", ";", "!", "!", "?", "?"]:
  33. if len(text[: i + 1]) <= chunk_size:
  34. return i + 1
  35. # If no suitable position is found, split directly
  36. return min(chunk_size, len(text))
  37. def split_text_recursive(text, chunk_size, translate_func, results):
  38. """
  39. Split the text recursively and translate each chunk.
  40. Args:
  41. text (str): The original text to be split.
  42. chunk_size (int): The maximum size of each chunk.
  43. translate_func (callable): A function that translates a single chunk of text.
  44. results (list): A list to store the translated chunks.
  45. Returns:
  46. None
  47. """
  48. text = text.strip()
  49. if len(text) <= chunk_size:
  50. results.append(translate_func(text))
  51. else:
  52. split_pos = _find_split_pos(text, chunk_size)
  53. left = text[:split_pos].strip()
  54. right = text[split_pos:].strip()
  55. if left:
  56. split_text_recursive(left, chunk_size, translate_func, results)
  57. if right:
  58. split_text_recursive(right, chunk_size, translate_func, results)
  59. def translate_code_block(code_block, chunk_size, translate_func, results):
  60. """
  61. Translate a code block and append the result to the results list.
  62. Args:
  63. code_block (str): The code block to be translated.
  64. chunk_size (int): The maximum size of each chunk.
  65. translate_func (callable): A function that translates a single chunk of text.
  66. results (list): A list to store the translated chunks.
  67. Returns:
  68. None
  69. """
  70. lines = code_block.strip().split("\n")
  71. if lines[0].startswith("```") or lines[0].startswith("~~~"):
  72. header = lines[0]
  73. footer = (
  74. lines[-1]
  75. if (lines[-1].startswith("```") or lines[-1].startswith("~~~"))
  76. else ""
  77. )
  78. code_content = "\n".join(lines[1:-1]) if footer else "\n".join(lines[1:])
  79. else:
  80. header = ""
  81. footer = ""
  82. code_content = code_block
  83. translated_code_lines = []
  84. split_text_recursive(
  85. code_content, chunk_size, translate_func, translated_code_lines
  86. )
  87. # drop ``` or ~~~
  88. filtered_code_lines = [
  89. line
  90. for line in translated_code_lines
  91. if not (line.strip().startswith("```") or line.strip().startswith("~~~"))
  92. ]
  93. translated_code = "\n".join(filtered_code_lines)
  94. result = f"{header}\n{translated_code}\n{footer}" if header else translated_code
  95. results.append(result)
  96. def translate_html_block(html_block, chunk_size, translate_func, results):
  97. """
  98. Translate a HTML block and append the result to the results list.
  99. Args:
  100. html_block (str): The HTML block to be translated.
  101. chunk_size (int): The maximum size of each chunk.
  102. translate_func (callable): A function that translates a single chunk of text.
  103. results (list): A list to store the translated chunks.
  104. Returns:
  105. None
  106. """
  107. from bs4 import BeautifulSoup
  108. soup = BeautifulSoup(html_block, "html.parser")
  109. # collect text nodes
  110. text_nodes = []
  111. for node in soup.find_all(string=True, recursive=True):
  112. text = node.strip()
  113. if text:
  114. text_nodes.append(node)
  115. idx = 0
  116. total = len(text_nodes)
  117. while idx < total:
  118. batch_nodes = []
  119. li_texts = []
  120. current_length = len("<ol></ol>")
  121. while idx < total:
  122. node_text = text_nodes[idx].strip()
  123. if len(node_text) > chunk_size:
  124. # if node_text is too long, split it
  125. translated_lines = []
  126. split_text_recursive(
  127. node_text, chunk_size, translate_func, translated_lines
  128. )
  129. # concatenate translated lines with \n
  130. text_nodes[idx].replace_with("\n".join(translated_lines))
  131. idx += 1
  132. continue
  133. li_str = f"<li>{node_text}</li>"
  134. if current_length + len(li_str) > chunk_size:
  135. break
  136. batch_nodes.append(text_nodes[idx])
  137. li_texts.append(li_str)
  138. current_length += len(li_str)
  139. idx += 1
  140. if not batch_nodes:
  141. # if all individual nodes are longer than chunk_size, translate it alone
  142. node_text = text_nodes[idx - 1].strip()
  143. li_str = f"<li>{node_text}</li>"
  144. batch_nodes = [text_nodes[idx - 1]]
  145. li_texts = [li_str]
  146. if batch_nodes:
  147. batch_text = "<ol>" + "".join(li_texts) + "</ol>"
  148. translated = translate_func(batch_text)
  149. trans_soup = BeautifulSoup(translated, "html.parser")
  150. translated_lis = trans_soup.find_all("li")
  151. for orig_node, li_tag in zip(batch_nodes, translated_lis):
  152. orig_node.replace_with(li_tag.decode_contents())
  153. results.append(str(soup))
  154. def split_original_texts(text):
  155. """
  156. Split the original text into chunks.
  157. """
  158. from bs4 import BeautifulSoup
  159. # find all html blocks and replace them with placeholders
  160. soup = BeautifulSoup(text, "html.parser")
  161. html_blocks = []
  162. html_placeholders = []
  163. placeholder_fmt = "<<HTML_BLOCK_{}>>"
  164. text_after_placeholder = ""
  165. index = 0
  166. for elem in soup.contents:
  167. if hasattr(elem, "name") and elem.name is not None:
  168. html_str = str(elem)
  169. placeholder = placeholder_fmt.format(index)
  170. html_blocks.append(html_str)
  171. html_placeholders.append(placeholder)
  172. text_after_placeholder += placeholder
  173. index += 1
  174. else:
  175. text_after_placeholder += str(elem)
  176. # split text into paragraphs
  177. splited_block = []
  178. splited_block = split_and_append_text(splited_block, text_after_placeholder)
  179. # replace placeholders with html blocks
  180. current_index = 0
  181. for idx, block in enumerate(splited_block):
  182. _, content = block
  183. while (
  184. current_index < len(html_placeholders)
  185. and html_placeholders[current_index] in content
  186. ):
  187. content = content.replace(
  188. html_placeholders[current_index], html_blocks[current_index]
  189. )
  190. current_index += 1
  191. splited_block[idx] = ("html", content)
  192. return splited_block
  193. def split_and_append_text(result, text_content):
  194. """
  195. Split the text and append the result to the result list.
  196. Args:
  197. result (list): The current result list.
  198. text_content (str): The text content to be processed.
  199. Returns:
  200. list: The updated result list after processing the text content.
  201. """
  202. if text_content.strip():
  203. # match all code block interval
  204. code_pattern = re.compile(r"(```.*?\n.*?```|~~~.*?\n.*?~~~)", re.DOTALL)
  205. last_pos = 0
  206. for m in code_pattern.finditer(text_content):
  207. # process text before code block
  208. if m.start() > last_pos:
  209. non_code = text_content[last_pos : m.start()]
  210. paragraphs = re.split(r"\n{2,}", non_code)
  211. for p in paragraphs:
  212. if p.strip():
  213. result.append(("text", p.strip()))
  214. # process code block
  215. result.append(("code", m.group()))
  216. last_pos = m.end()
  217. # process remaining text
  218. if last_pos < len(text_content):
  219. non_code = text_content[last_pos:]
  220. paragraphs = re.split(r"\n{2,}", non_code)
  221. for p in paragraphs:
  222. if p.strip():
  223. result.append(("text", p.strip()))
  224. return result