ocr_mkcontent.py 15 KB

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