ocr_mkcontent.py 9.7 KB

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