ocr_mkcontent.py 10.0 KB

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