ocr_mkcontent.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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_mm_markdown_with_para(pdf_info_list: list, img_buket_path):
  18. markdown = []
  19. for page_info in pdf_info_list:
  20. paras_of_layout = page_info.get("para_blocks")
  21. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm", img_buket_path)
  22. markdown.extend(page_markdown)
  23. return '\n\n'.join(markdown)
  24. def ocr_mk_nlp_markdown_with_para(pdf_info_dict: list):
  25. markdown = []
  26. for page_info in pdf_info_dict:
  27. paras_of_layout = page_info.get("para_blocks")
  28. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "nlp")
  29. markdown.extend(page_markdown)
  30. return '\n\n'.join(markdown)
  31. def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list, img_buket_path):
  32. markdown_with_para_and_pagination = []
  33. page_no = 0
  34. for page_info in pdf_info_dict:
  35. paras_of_layout = page_info.get("para_blocks")
  36. if not paras_of_layout:
  37. continue
  38. page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm", img_buket_path)
  39. markdown_with_para_and_pagination.append({
  40. 'page_no': page_no,
  41. 'md_content': '\n\n'.join(page_markdown)
  42. })
  43. page_no += 1
  44. return markdown_with_para_and_pagination
  45. def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):
  46. page_markdown = []
  47. for paras in paras_of_layout:
  48. for para in paras:
  49. para_text = ''
  50. for line in para:
  51. for span in line['spans']:
  52. span_type = span.get('type')
  53. content = ''
  54. language = ''
  55. if span_type == ContentType.Text:
  56. content = span['content']
  57. language = detect_lang(content)
  58. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  59. content = ocr_escape_special_markdown_char(split_long_words(content))
  60. else:
  61. content = ocr_escape_special_markdown_char(content)
  62. elif span_type == ContentType.InlineEquation:
  63. content = f"${span['content']}$"
  64. elif span_type == ContentType.InterlineEquation:
  65. content = f"\n$$\n{span['content']}\n$$\n"
  66. elif span_type in [ContentType.Image, ContentType.Table]:
  67. if mode == 'mm':
  68. content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
  69. elif mode == 'nlp':
  70. pass
  71. if content != '':
  72. if language == 'en': # 英文语境下 content间需要空格分隔
  73. para_text += content + ' '
  74. else: # 中文语境下,content间不需要空格分隔
  75. para_text += content
  76. if para_text.strip() == '':
  77. continue
  78. else:
  79. page_markdown.append(para_text.strip() + ' ')
  80. return page_markdown
  81. def para_to_standard_format(para, img_buket_path):
  82. para_content = {}
  83. if len(para) == 1:
  84. para_content = line_to_standard_format(para[0], img_buket_path)
  85. elif len(para) > 1:
  86. para_text = ''
  87. inline_equation_num = 0
  88. for line in para:
  89. for span in line['spans']:
  90. language = ''
  91. span_type = span.get('type')
  92. content = ""
  93. if span_type == ContentType.Text:
  94. content = span['content']
  95. language = detect_lang(content)
  96. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  97. content = ocr_escape_special_markdown_char(split_long_words(content))
  98. else:
  99. content = ocr_escape_special_markdown_char(content)
  100. elif span_type == ContentType.InlineEquation:
  101. content = f"${span['content']}$"
  102. inline_equation_num += 1
  103. if language == 'en': # 英文语境下 content间需要空格分隔
  104. para_text += content + ' '
  105. else: # 中文语境下,content间不需要空格分隔
  106. para_text += content
  107. para_content = {
  108. 'type': 'text',
  109. 'text': para_text,
  110. 'inline_equation_num': inline_equation_num
  111. }
  112. return para_content
  113. def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
  114. content_list = []
  115. for page_info in pdf_info_dict:
  116. paras_of_layout = page_info.get("para_blocks")
  117. if not paras_of_layout:
  118. continue
  119. for paras in paras_of_layout:
  120. for para in paras:
  121. para_content = para_to_standard_format(para, img_buket_path)
  122. content_list.append(para_content)
  123. return content_list
  124. def line_to_standard_format(line, img_buket_path):
  125. line_text = ""
  126. inline_equation_num = 0
  127. for span in line['spans']:
  128. if not span.get('content'):
  129. if not span.get('image_path'):
  130. continue
  131. else:
  132. if span['type'] == ContentType.Image:
  133. content = {
  134. 'type': 'image',
  135. 'img_path': join_path(img_buket_path, span['image_path'])
  136. }
  137. return content
  138. elif span['type'] == ContentType.Table:
  139. content = {
  140. 'type': 'table',
  141. 'img_path': join_path(img_buket_path, span['image_path'])
  142. }
  143. return content
  144. else:
  145. if span['type'] == ContentType.InterlineEquation:
  146. interline_equation = span['content']
  147. content = {
  148. 'type': 'equation',
  149. 'latex': f"$$\n{interline_equation}\n$$"
  150. }
  151. return content
  152. elif span['type'] == ContentType.InlineEquation:
  153. inline_equation = span['content']
  154. line_text += f"${inline_equation}$"
  155. inline_equation_num += 1
  156. elif span['type'] == ContentType.Text:
  157. text_content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号
  158. line_text += text_content
  159. content = {
  160. 'type': 'text',
  161. 'text': line_text,
  162. 'inline_equation_num': inline_equation_num
  163. }
  164. return content
  165. def ocr_mk_mm_standard_format(pdf_info_dict: list):
  166. """
  167. content_list
  168. type string image/text/table/equation(行间的单独拿出来,行内的和text合并)
  169. latex string latex文本字段。
  170. text string 纯文本格式的文本数据。
  171. md string markdown格式的文本数据。
  172. img_path string s3://full/path/to/img.jpg
  173. """
  174. content_list = []
  175. for page_info in pdf_info_dict:
  176. blocks = page_info.get("preproc_blocks")
  177. if not blocks:
  178. continue
  179. for block in blocks:
  180. for line in block['lines']:
  181. content = line_to_standard_format(line)
  182. content_list.append(content)
  183. return content_list