ocr_mkcontent.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import re
  2. from loguru import logger
  3. from magic_pdf.config.make_content_config import DropMode, MakeMode
  4. from magic_pdf.config.ocr_content_type import BlockType, ContentType
  5. from magic_pdf.libs.commons import join_path
  6. from magic_pdf.libs.language import detect_lang
  7. from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
  8. from magic_pdf.post_proc.para_split_v3 import ListLineTag
  9. def __is_hyphen_at_line_end(line):
  10. """Check if a line ends with one or more letters followed by a hyphen.
  11. Args:
  12. line (str): The line of text to check.
  13. Returns:
  14. bool: True if the line ends with one or more letters followed by a hyphen, False otherwise.
  15. """
  16. # Use regex to check if the line ends with one or more letters followed by a hyphen
  17. return bool(re.search(r'[A-Za-z]+-\s*$', line))
  18. def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list,
  19. img_buket_path):
  20. markdown_with_para_and_pagination = []
  21. page_no = 0
  22. for page_info in pdf_info_dict:
  23. paras_of_layout = page_info.get('para_blocks')
  24. if not paras_of_layout:
  25. markdown_with_para_and_pagination.append({
  26. 'page_no':
  27. page_no,
  28. 'md_content':
  29. '',
  30. })
  31. page_no += 1
  32. continue
  33. page_markdown = ocr_mk_markdown_with_para_core_v2(
  34. paras_of_layout, 'mm', img_buket_path)
  35. markdown_with_para_and_pagination.append({
  36. 'page_no':
  37. page_no,
  38. 'md_content':
  39. '\n\n'.join(page_markdown)
  40. })
  41. page_no += 1
  42. return markdown_with_para_and_pagination
  43. def ocr_mk_markdown_with_para_core_v2(paras_of_layout,
  44. mode,
  45. img_buket_path='',
  46. ):
  47. page_markdown = []
  48. for para_block in paras_of_layout:
  49. para_text = ''
  50. para_type = para_block['type']
  51. if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
  52. para_text = merge_para_with_text(para_block)
  53. elif para_type == BlockType.Title:
  54. title_level = get_title_level(para_block)
  55. para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'
  56. elif para_type == BlockType.InterlineEquation:
  57. para_text = merge_para_with_text(para_block)
  58. elif para_type == BlockType.Image:
  59. if mode == 'nlp':
  60. continue
  61. elif mode == 'mm':
  62. for block in para_block['blocks']: # 1st.拼image_body
  63. if block['type'] == BlockType.ImageBody:
  64. for line in block['lines']:
  65. for span in line['spans']:
  66. if span['type'] == ContentType.Image:
  67. if span.get('image_path', ''):
  68. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  69. for block in para_block['blocks']: # 2nd.拼image_caption
  70. if block['type'] == BlockType.ImageCaption:
  71. para_text += merge_para_with_text(block) + ' \n'
  72. for block in para_block['blocks']: # 3rd.拼image_footnote
  73. if block['type'] == BlockType.ImageFootnote:
  74. para_text += merge_para_with_text(block) + ' \n'
  75. elif para_type == BlockType.Table:
  76. if mode == 'nlp':
  77. continue
  78. elif mode == 'mm':
  79. for block in para_block['blocks']: # 1st.拼table_caption
  80. if block['type'] == BlockType.TableCaption:
  81. para_text += merge_para_with_text(block) + ' \n'
  82. for block in para_block['blocks']: # 2nd.拼table_body
  83. if block['type'] == BlockType.TableBody:
  84. for line in block['lines']:
  85. for span in line['spans']:
  86. if span['type'] == ContentType.Table:
  87. # if processed by table model
  88. if span.get('latex', ''):
  89. para_text += f"\n\n$\n {span['latex']}\n$\n\n"
  90. elif span.get('html', ''):
  91. para_text += f"\n\n{span['html']}\n\n"
  92. elif span.get('image_path', ''):
  93. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  94. for block in para_block['blocks']: # 3rd.拼table_footnote
  95. if block['type'] == BlockType.TableFootnote:
  96. para_text += merge_para_with_text(block) + ' \n'
  97. if para_text.strip() == '':
  98. continue
  99. else:
  100. page_markdown.append(para_text.strip() + ' ')
  101. return page_markdown
  102. def detect_language(text):
  103. en_pattern = r'[a-zA-Z]+'
  104. en_matches = re.findall(en_pattern, text)
  105. en_length = sum(len(match) for match in en_matches)
  106. if len(text) > 0:
  107. if en_length / len(text) >= 0.5:
  108. return 'en'
  109. else:
  110. return 'unknown'
  111. else:
  112. return 'empty'
  113. def full_to_half(text: str) -> str:
  114. """Convert full-width characters to half-width characters using code point manipulation.
  115. Args:
  116. text: String containing full-width characters
  117. Returns:
  118. String with full-width characters converted to half-width
  119. """
  120. result = []
  121. for char in text:
  122. code = ord(char)
  123. # Full-width letters and numbers (FF21-FF3A for A-Z, FF41-FF5A for a-z, FF10-FF19 for 0-9)
  124. if (0xFF21 <= code <= 0xFF3A) or (0xFF41 <= code <= 0xFF5A) or (0xFF10 <= code <= 0xFF19):
  125. result.append(chr(code - 0xFEE0)) # Shift to ASCII range
  126. else:
  127. result.append(char)
  128. return ''.join(result)
  129. def merge_para_with_text(para_block):
  130. block_text = ''
  131. for line in para_block['lines']:
  132. for span in line['spans']:
  133. if span['type'] in [ContentType.Text]:
  134. span['content'] = full_to_half(span['content'])
  135. block_text += span['content']
  136. block_lang = detect_lang(block_text)
  137. para_text = ''
  138. for i, line in enumerate(para_block['lines']):
  139. if i >= 1 and line.get(ListLineTag.IS_LIST_START_LINE, False):
  140. para_text += ' \n'
  141. for j, span in enumerate(line['spans']):
  142. span_type = span['type']
  143. content = ''
  144. if span_type == ContentType.Text:
  145. content = ocr_escape_special_markdown_char(span['content'])
  146. elif span_type == ContentType.InlineEquation:
  147. content = f"${span['content']}$"
  148. elif span_type == ContentType.InterlineEquation:
  149. content = f"\n$$\n{span['content']}\n$$\n"
  150. content = content.strip()
  151. if content:
  152. langs = ['zh', 'ja', 'ko']
  153. # logger.info(f'block_lang: {block_lang}, content: {content}')
  154. if block_lang in langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
  155. if j == len(line['spans']) - 1 and span_type not in [ContentType.InlineEquation]:
  156. para_text += content
  157. else:
  158. para_text += f'{content} '
  159. else:
  160. if span_type in [ContentType.Text, ContentType.InlineEquation]:
  161. # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
  162. if j == len(line['spans'])-1 and span_type == ContentType.Text and __is_hyphen_at_line_end(content):
  163. para_text += content[:-1]
  164. else: # 西方文本语境下 content间需要空格分隔
  165. para_text += f'{content} '
  166. elif span_type == ContentType.InterlineEquation:
  167. para_text += content
  168. else:
  169. continue
  170. # 连写字符拆分
  171. # para_text = __replace_ligatures(para_text)
  172. return para_text
  173. def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
  174. para_type = para_block['type']
  175. para_content = {}
  176. if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
  177. para_content = {
  178. 'type': 'text',
  179. 'text': merge_para_with_text(para_block),
  180. }
  181. elif para_type == BlockType.Title:
  182. para_content = {
  183. 'type': 'text',
  184. 'text': merge_para_with_text(para_block),
  185. }
  186. title_level = get_title_level(para_block)
  187. if title_level != 0:
  188. para_content['text_level'] = title_level
  189. elif para_type == BlockType.InterlineEquation:
  190. para_content = {
  191. 'type': 'equation',
  192. 'text': merge_para_with_text(para_block),
  193. 'text_format': 'latex',
  194. }
  195. elif para_type == BlockType.Image:
  196. para_content = {'type': 'image', 'img_path': '', 'img_caption': [], 'img_footnote': []}
  197. for block in para_block['blocks']:
  198. if block['type'] == BlockType.ImageBody:
  199. for line in block['lines']:
  200. for span in line['spans']:
  201. if span['type'] == ContentType.Image:
  202. if span.get('image_path', ''):
  203. para_content['img_path'] = join_path(img_buket_path, span['image_path'])
  204. if block['type'] == BlockType.ImageCaption:
  205. para_content['img_caption'].append(merge_para_with_text(block))
  206. if block['type'] == BlockType.ImageFootnote:
  207. para_content['img_footnote'].append(merge_para_with_text(block))
  208. elif para_type == BlockType.Table:
  209. para_content = {'type': 'table', 'img_path': '', 'table_caption': [], 'table_footnote': []}
  210. for block in para_block['blocks']:
  211. if block['type'] == BlockType.TableBody:
  212. for line in block['lines']:
  213. for span in line['spans']:
  214. if span['type'] == ContentType.Table:
  215. if span.get('latex', ''):
  216. para_content['table_body'] = f"\n\n$\n {span['latex']}\n$\n\n"
  217. elif span.get('html', ''):
  218. para_content['table_body'] = f"\n\n{span['html']}\n\n"
  219. if span.get('image_path', ''):
  220. para_content['img_path'] = join_path(img_buket_path, span['image_path'])
  221. if block['type'] == BlockType.TableCaption:
  222. para_content['table_caption'].append(merge_para_with_text(block))
  223. if block['type'] == BlockType.TableFootnote:
  224. para_content['table_footnote'].append(merge_para_with_text(block))
  225. para_content['page_idx'] = page_idx
  226. if drop_reason is not None:
  227. para_content['drop_reason'] = drop_reason
  228. return para_content
  229. def union_make(pdf_info_dict: list,
  230. make_mode: str,
  231. drop_mode: str,
  232. img_buket_path: str = '',
  233. ):
  234. output_content = []
  235. for page_info in pdf_info_dict:
  236. drop_reason_flag = False
  237. drop_reason = None
  238. if page_info.get('need_drop', False):
  239. drop_reason = page_info.get('drop_reason')
  240. if drop_mode == DropMode.NONE:
  241. pass
  242. elif drop_mode == DropMode.NONE_WITH_REASON:
  243. drop_reason_flag = True
  244. elif drop_mode == DropMode.WHOLE_PDF:
  245. raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
  246. f'drop_reason is {drop_reason}'))
  247. elif drop_mode == DropMode.SINGLE_PAGE:
  248. logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
  249. f'drop_reason is {drop_reason}'))
  250. continue
  251. else:
  252. raise Exception('drop_mode can not be null')
  253. paras_of_layout = page_info.get('para_blocks')
  254. page_idx = page_info.get('page_idx')
  255. if not paras_of_layout:
  256. continue
  257. if make_mode == MakeMode.MM_MD:
  258. page_markdown = ocr_mk_markdown_with_para_core_v2(
  259. paras_of_layout, 'mm', img_buket_path)
  260. output_content.extend(page_markdown)
  261. elif make_mode == MakeMode.NLP_MD:
  262. page_markdown = ocr_mk_markdown_with_para_core_v2(
  263. paras_of_layout, 'nlp')
  264. output_content.extend(page_markdown)
  265. elif make_mode == MakeMode.STANDARD_FORMAT:
  266. for para_block in paras_of_layout:
  267. if drop_reason_flag:
  268. para_content = para_to_standard_format_v2(
  269. para_block, img_buket_path, page_idx)
  270. else:
  271. para_content = para_to_standard_format_v2(
  272. para_block, img_buket_path, page_idx)
  273. output_content.append(para_content)
  274. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  275. return '\n\n'.join(output_content)
  276. elif make_mode == MakeMode.STANDARD_FORMAT:
  277. return output_content
  278. def get_title_level(block):
  279. title_level = block.get('level', 1)
  280. if title_level > 4:
  281. title_level = 4
  282. elif title_level < 1:
  283. title_level = 0
  284. return title_level