ocr_mkcontent.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. from magic_pdf.libs.commons import join_path
  2. from magic_pdf.libs.language import detect_lang
  3. from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
  4. from magic_pdf.libs.ocr_content_type import ContentType
  5. import wordninja
  6. import re
  7. def split_long_words(text):
  8. segments = text.split(' ')
  9. for i in range(len(segments)):
  10. words = re.findall(r'\w+|[^\w\s]', segments[i], re.UNICODE)
  11. for j in range(len(words)):
  12. if len(words[j]) > 15:
  13. words[j] = ' '.join(wordninja.split(words[j]))
  14. segments[i] = ''.join(words)
  15. return ' '.join(segments)
  16. def ocr_mk_nlp_markdown(pdf_info_dict: dict):
  17. markdown = []
  18. for _, page_info in pdf_info_dict.items():
  19. blocks = page_info.get("preproc_blocks")
  20. if not blocks:
  21. continue
  22. for block in blocks:
  23. for line in block['lines']:
  24. line_text = ''
  25. for span in line['spans']:
  26. if not span.get('content'):
  27. continue
  28. content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号
  29. if span['type'] == ContentType.InlineEquation:
  30. content = f"${content}$"
  31. elif span['type'] == ContentType.InterlineEquation:
  32. content = f"$$\n{content}\n$$"
  33. line_text += content + ' '
  34. # 在行末添加两个空格以强制换行
  35. markdown.append(line_text.strip() + ' ')
  36. return '\n'.join(markdown)
  37. def ocr_mk_mm_markdown(pdf_info_dict: dict):
  38. markdown = []
  39. for _, page_info in pdf_info_dict.items():
  40. blocks = page_info.get("preproc_blocks")
  41. if not blocks:
  42. continue
  43. for block in blocks:
  44. for line in block['lines']:
  45. line_text = ''
  46. for span in line['spans']:
  47. if not span.get('content'):
  48. if not span.get('image_path'):
  49. continue
  50. else:
  51. content = f"![]({span['image_path']})"
  52. else:
  53. content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号
  54. if span['type'] == ContentType.InlineEquation:
  55. content = f"${content}$"
  56. elif span['type'] == ContentType.InterlineEquation:
  57. content = f"$$\n{content}\n$$"
  58. line_text += content + ' '
  59. # 在行末添加两个空格以强制换行
  60. markdown.append(line_text.strip() + ' ')
  61. return '\n'.join(markdown)
  62. def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):
  63. markdown = []
  64. for page_info in pdf_info_list:
  65. paras_of_layout = page_info.get("para_blocks")
  66. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm", img_buket_path)
  67. markdown.extend(page_markdown)
  68. return '\n\n'.join(markdown)
  69. def ocr_mk_nlp_markdown_with_para(pdf_info_dict: dict):
  70. markdown = []
  71. for _, page_info in pdf_info_dict.items():
  72. paras_of_layout = page_info.get("para_blocks")
  73. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "nlp")
  74. markdown.extend(page_markdown)
  75. return '\n\n'.join(markdown)
  76. def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: dict):
  77. markdown_with_para_and_pagination = []
  78. for page_no, page_info in pdf_info_dict.items():
  79. paras_of_layout = page_info.get("para_blocks")
  80. if not paras_of_layout:
  81. continue
  82. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm")
  83. markdown_with_para_and_pagination.append({
  84. 'page_no': page_no,
  85. 'md_content': '\n\n'.join(page_markdown)
  86. })
  87. return markdown_with_para_and_pagination
  88. def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path):
  89. page_markdown = []
  90. for paras in paras_of_layout:
  91. for para in paras:
  92. para_text = ''
  93. for line in para:
  94. for span in line['spans']:
  95. span_type = span.get('type')
  96. content = ''
  97. language = ''
  98. if span_type == ContentType.Text:
  99. content = span['content']
  100. language = detect_lang(content)
  101. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  102. content = ocr_escape_special_markdown_char(split_long_words(content))
  103. else:
  104. content = ocr_escape_special_markdown_char(content)
  105. elif span_type == ContentType.InlineEquation:
  106. content = f"${span['content']}$"
  107. elif span_type == ContentType.InterlineEquation:
  108. content = f"\n$$\n{span['content']}\n$$\n"
  109. elif span_type in [ContentType.Image, ContentType.Table]:
  110. if mode == 'mm':
  111. content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
  112. elif mode == 'nlp':
  113. pass
  114. if content != '':
  115. if language == 'en': # 英文语境下 content间需要空格分隔
  116. para_text += content + ' '
  117. else: # 中文语境下,content间不需要空格分隔
  118. para_text += content
  119. if para_text.strip() == '':
  120. continue
  121. else:
  122. page_markdown.append(para_text.strip() + ' ')
  123. return page_markdown
  124. def para_to_standard_format(para, img_buket_path):
  125. para_content = {}
  126. if len(para) == 1:
  127. para_content = line_to_standard_format(para[0], img_buket_path)
  128. elif len(para) > 1:
  129. para_text = ''
  130. inline_equation_num = 0
  131. for line in para:
  132. for span in line['spans']:
  133. language = ''
  134. span_type = span.get('type')
  135. if span_type == ContentType.Text:
  136. content = span['content']
  137. language = detect_lang(content)
  138. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  139. content = ocr_escape_special_markdown_char(split_long_words(content))
  140. else:
  141. content = ocr_escape_special_markdown_char(content)
  142. elif span_type == ContentType.InlineEquation:
  143. content = f"${span['content']}$"
  144. inline_equation_num += 1
  145. if language == 'en': # 英文语境下 content间需要空格分隔
  146. para_text += content + ' '
  147. else: # 中文语境下,content间不需要空格分隔
  148. para_text += content
  149. para_content = {
  150. 'type': 'text',
  151. 'text': para_text,
  152. 'inline_equation_num': inline_equation_num
  153. }
  154. return para_content
  155. def make_standard_format_with_para(pdf_info_dict: dict, img_buket_path: str):
  156. content_list = []
  157. for _, page_info in pdf_info_dict.items():
  158. paras_of_layout = page_info.get("para_blocks")
  159. if not paras_of_layout:
  160. continue
  161. for paras in paras_of_layout:
  162. for para in paras:
  163. para_content = para_to_standard_format(para, img_buket_path)
  164. content_list.append(para_content)
  165. return content_list
  166. def line_to_standard_format(line, img_buket_path):
  167. line_text = ""
  168. inline_equation_num = 0
  169. for span in line['spans']:
  170. if not span.get('content'):
  171. if not span.get('image_path'):
  172. continue
  173. else:
  174. if span['type'] == ContentType.Image:
  175. content = {
  176. 'type': 'image',
  177. 'img_path': join_path(img_buket_path, span['image_path'])
  178. }
  179. return content
  180. elif span['type'] == ContentType.Table:
  181. content = {
  182. 'type': 'table',
  183. 'img_path': join_path(img_buket_path, span['image_path'])
  184. }
  185. return content
  186. else:
  187. if span['type'] == ContentType.InterlineEquation:
  188. interline_equation = span['content']
  189. content = {
  190. 'type': 'equation',
  191. 'latex': f"$$\n{interline_equation}\n$$"
  192. }
  193. return content
  194. elif span['type'] == ContentType.InlineEquation:
  195. inline_equation = span['content']
  196. line_text += f"${inline_equation}$"
  197. inline_equation_num += 1
  198. elif span['type'] == ContentType.Text:
  199. text_content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号
  200. line_text += text_content
  201. content = {
  202. 'type': 'text',
  203. 'text': line_text,
  204. 'inline_equation_num': inline_equation_num
  205. }
  206. return content
  207. def ocr_mk_mm_standard_format(pdf_info_dict: dict):
  208. """
  209. content_list
  210. type string image/text/table/equation(行间的单独拿出来,行内的和text合并)
  211. latex string latex文本字段。
  212. text string 纯文本格式的文本数据。
  213. md string markdown格式的文本数据。
  214. img_path string s3://full/path/to/img.jpg
  215. """
  216. content_list = []
  217. for _, page_info in pdf_info_dict.items():
  218. blocks = page_info.get("preproc_blocks")
  219. if not blocks:
  220. continue
  221. for block in blocks:
  222. for line in block['lines']:
  223. content = line_to_standard_format(line)
  224. content_list.append(content)
  225. return content_list