ocr_mkcontent.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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: list):
  17. markdown = []
  18. for page_info in pdf_info_dict:
  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: list):
  38. markdown = []
  39. for page_info in pdf_info_dict:
  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: list):
  70. markdown = []
  71. for page_info in pdf_info_dict:
  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: list):
  77. markdown_with_para_and_pagination = []
  78. page_no = 0
  79. for page_info in pdf_info_dict:
  80. paras_of_layout = page_info.get("para_blocks")
  81. if not paras_of_layout:
  82. continue
  83. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm")
  84. markdown_with_para_and_pagination.append({
  85. 'page_no': page_no,
  86. 'md_content': '\n\n'.join(page_markdown)
  87. })
  88. page_no += 1
  89. return markdown_with_para_and_pagination
  90. def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path):
  91. page_markdown = []
  92. for paras in paras_of_layout:
  93. for para in paras:
  94. para_text = ''
  95. for line in para:
  96. for span in line['spans']:
  97. span_type = span.get('type')
  98. content = ''
  99. language = ''
  100. if span_type == ContentType.Text:
  101. content = span['content']
  102. language = detect_lang(content)
  103. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  104. content = ocr_escape_special_markdown_char(split_long_words(content))
  105. else:
  106. content = ocr_escape_special_markdown_char(content)
  107. elif span_type == ContentType.InlineEquation:
  108. content = f"${span['content']}$"
  109. elif span_type == ContentType.InterlineEquation:
  110. content = f"\n$$\n{span['content']}\n$$\n"
  111. elif span_type in [ContentType.Image, ContentType.Table]:
  112. if mode == 'mm':
  113. content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
  114. elif mode == 'nlp':
  115. pass
  116. if content != '':
  117. if language == 'en': # 英文语境下 content间需要空格分隔
  118. para_text += content + ' '
  119. else: # 中文语境下,content间不需要空格分隔
  120. para_text += content
  121. if para_text.strip() == '':
  122. continue
  123. else:
  124. page_markdown.append(para_text.strip() + ' ')
  125. return page_markdown
  126. def para_to_standard_format(para, img_buket_path):
  127. para_content = {}
  128. if len(para) == 1:
  129. para_content = line_to_standard_format(para[0], img_buket_path)
  130. elif len(para) > 1:
  131. para_text = ''
  132. inline_equation_num = 0
  133. for line in para:
  134. for span in line['spans']:
  135. language = ''
  136. span_type = span.get('type')
  137. if span_type == ContentType.Text:
  138. content = span['content']
  139. language = detect_lang(content)
  140. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  141. content = ocr_escape_special_markdown_char(split_long_words(content))
  142. else:
  143. content = ocr_escape_special_markdown_char(content)
  144. elif span_type == ContentType.InlineEquation:
  145. content = f"${span['content']}$"
  146. inline_equation_num += 1
  147. if language == 'en': # 英文语境下 content间需要空格分隔
  148. para_text += content + ' '
  149. else: # 中文语境下,content间不需要空格分隔
  150. para_text += content
  151. para_content = {
  152. 'type': 'text',
  153. 'text': para_text,
  154. 'inline_equation_num': inline_equation_num
  155. }
  156. return para_content
  157. def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
  158. content_list = []
  159. for page_info in pdf_info_dict:
  160. paras_of_layout = page_info.get("para_blocks")
  161. if not paras_of_layout:
  162. continue
  163. for paras in paras_of_layout:
  164. for para in paras:
  165. para_content = para_to_standard_format(para, img_buket_path)
  166. content_list.append(para_content)
  167. return content_list
  168. def line_to_standard_format(line, img_buket_path):
  169. line_text = ""
  170. inline_equation_num = 0
  171. for span in line['spans']:
  172. if not span.get('content'):
  173. if not span.get('image_path'):
  174. continue
  175. else:
  176. if span['type'] == ContentType.Image:
  177. content = {
  178. 'type': 'image',
  179. 'img_path': join_path(img_buket_path, span['image_path'])
  180. }
  181. return content
  182. elif span['type'] == ContentType.Table:
  183. content = {
  184. 'type': 'table',
  185. 'img_path': join_path(img_buket_path, span['image_path'])
  186. }
  187. return content
  188. else:
  189. if span['type'] == ContentType.InterlineEquation:
  190. interline_equation = span['content']
  191. content = {
  192. 'type': 'equation',
  193. 'latex': f"$$\n{interline_equation}\n$$"
  194. }
  195. return content
  196. elif span['type'] == ContentType.InlineEquation:
  197. inline_equation = span['content']
  198. line_text += f"${inline_equation}$"
  199. inline_equation_num += 1
  200. elif span['type'] == ContentType.Text:
  201. text_content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号
  202. line_text += text_content
  203. content = {
  204. 'type': 'text',
  205. 'text': line_text,
  206. 'inline_equation_num': inline_equation_num
  207. }
  208. return content
  209. def ocr_mk_mm_standard_format(pdf_info_dict: list):
  210. """
  211. content_list
  212. type string image/text/table/equation(行间的单独拿出来,行内的和text合并)
  213. latex string latex文本字段。
  214. text string 纯文本格式的文本数据。
  215. md string markdown格式的文本数据。
  216. img_path string s3://full/path/to/img.jpg
  217. """
  218. content_list = []
  219. for page_info in pdf_info_dict:
  220. blocks = page_info.get("preproc_blocks")
  221. if not blocks:
  222. continue
  223. for block in blocks:
  224. for line in block['lines']:
  225. content = line_to_standard_format(line)
  226. content_list.append(content)
  227. return content_list