ocr_mkcontent.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. from loguru import logger
  2. from magic_pdf.libs.MakeContentConfig import DropMode, MakeMode
  3. from magic_pdf.libs.commons import join_path
  4. from magic_pdf.libs.language import detect_lang
  5. from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
  6. from magic_pdf.libs.ocr_content_type import ContentType, BlockType
  7. import wordninja
  8. import re
  9. def __is_hyphen_at_line_end(line):
  10. """
  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 split_long_words(text):
  20. segments = text.split(' ')
  21. for i in range(len(segments)):
  22. words = re.findall(r'\w+|[^\w]', segments[i], re.UNICODE)
  23. for j in range(len(words)):
  24. if len(words[j]) > 10:
  25. words[j] = ' '.join(wordninja.split(words[j]))
  26. segments[i] = ''.join(words)
  27. return ' '.join(segments)
  28. def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):
  29. markdown = []
  30. for page_info in pdf_info_list:
  31. paras_of_layout = page_info.get("para_blocks")
  32. page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)
  33. markdown.extend(page_markdown)
  34. return '\n\n'.join(markdown)
  35. def ocr_mk_nlp_markdown_with_para(pdf_info_dict: list):
  36. markdown = []
  37. for page_info in pdf_info_dict:
  38. paras_of_layout = page_info.get("para_blocks")
  39. page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "nlp")
  40. markdown.extend(page_markdown)
  41. return '\n\n'.join(markdown)
  42. def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list, img_buket_path):
  43. markdown_with_para_and_pagination = []
  44. page_no = 0
  45. for page_info in pdf_info_dict:
  46. paras_of_layout = page_info.get("para_blocks")
  47. if not paras_of_layout:
  48. continue
  49. page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)
  50. markdown_with_para_and_pagination.append({
  51. 'page_no': page_no,
  52. 'md_content': '\n\n'.join(page_markdown)
  53. })
  54. page_no += 1
  55. return markdown_with_para_and_pagination
  56. def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):
  57. page_markdown = []
  58. for paras in paras_of_layout:
  59. for para in paras:
  60. para_text = ''
  61. for line in para:
  62. for span in line['spans']:
  63. span_type = span.get('type')
  64. content = ''
  65. language = ''
  66. if span_type == ContentType.Text:
  67. content = span['content']
  68. language = detect_lang(content)
  69. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  70. content = ocr_escape_special_markdown_char(split_long_words(content))
  71. else:
  72. content = ocr_escape_special_markdown_char(content)
  73. elif span_type == ContentType.InlineEquation:
  74. content = f"${span['content']}$"
  75. elif span_type == ContentType.InterlineEquation:
  76. content = f"\n$$\n{span['content']}\n$$\n"
  77. elif span_type in [ContentType.Image, ContentType.Table]:
  78. if mode == 'mm':
  79. content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
  80. elif mode == 'nlp':
  81. pass
  82. if content != '':
  83. if language == 'en': # 英文语境下 content间需要空格分隔
  84. para_text += content + ' '
  85. else: # 中文语境下,content间不需要空格分隔
  86. para_text += content
  87. if para_text.strip() == '':
  88. continue
  89. else:
  90. page_markdown.append(para_text.strip() + ' ')
  91. return page_markdown
  92. def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):
  93. page_markdown = []
  94. for para_block in paras_of_layout:
  95. para_text = ''
  96. para_type = para_block['type']
  97. if para_type == BlockType.Text:
  98. para_text = merge_para_with_text(para_block)
  99. elif para_type == BlockType.Title:
  100. para_text = f"# {merge_para_with_text(para_block)}"
  101. elif para_type == BlockType.InterlineEquation:
  102. para_text = merge_para_with_text(para_block)
  103. elif para_type == BlockType.Image:
  104. if mode == 'nlp':
  105. continue
  106. elif mode == 'mm':
  107. for block in para_block['blocks']: # 1st.拼image_body
  108. if block['type'] == BlockType.ImageBody:
  109. for line in block['lines']:
  110. for span in line['spans']:
  111. if span['type'] == ContentType.Image:
  112. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  113. for block in para_block['blocks']: # 2nd.拼image_caption
  114. if block['type'] == BlockType.ImageCaption:
  115. para_text += merge_para_with_text(block)
  116. elif para_type == BlockType.Table:
  117. if mode == 'nlp':
  118. continue
  119. elif mode == 'mm':
  120. table_caption = ''
  121. for block in para_block['blocks']: # 1st.拼table_caption
  122. if block['type'] == BlockType.TableCaption:
  123. para_text += merge_para_with_text(block)
  124. for block in para_block['blocks']: # 2nd.拼table_body
  125. if block['type'] == BlockType.TableBody:
  126. for line in block['lines']:
  127. for span in line['spans']:
  128. if span['type'] == ContentType.Table:
  129. # if processed by table model
  130. if span.get('latex', ''):
  131. para_text += f"\n\n$\n {span['latex']}\n$\n\n"
  132. else:
  133. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  134. for block in para_block['blocks']: # 3rd.拼table_footnote
  135. if block['type'] == BlockType.TableFootnote:
  136. para_text += merge_para_with_text(block)
  137. if para_text.strip() == '':
  138. continue
  139. else:
  140. page_markdown.append(para_text.strip() + ' ')
  141. return page_markdown
  142. def merge_para_with_text(para_block):
  143. def detect_language(text):
  144. en_pattern = r'[a-zA-Z]+'
  145. en_matches = re.findall(en_pattern, text)
  146. en_length = sum(len(match) for match in en_matches)
  147. if len(text) > 0:
  148. if en_length / len(text) >= 0.5:
  149. return 'en'
  150. else:
  151. return "unknown"
  152. else:
  153. return "empty"
  154. para_text = ''
  155. for line in para_block['lines']:
  156. line_text = ""
  157. line_lang = ""
  158. for span in line['spans']:
  159. span_type = span['type']
  160. if span_type == ContentType.Text:
  161. line_text += span['content'].strip()
  162. if line_text != "":
  163. line_lang = detect_lang(line_text)
  164. for span in line['spans']:
  165. span_type = span['type']
  166. content = ''
  167. if span_type == ContentType.Text:
  168. content = span['content']
  169. # language = detect_lang(content)
  170. language = detect_language(content)
  171. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  172. content = ocr_escape_special_markdown_char(split_long_words(content))
  173. else:
  174. content = ocr_escape_special_markdown_char(content)
  175. elif span_type == ContentType.InlineEquation:
  176. content = f" ${span['content']}$ "
  177. elif span_type == ContentType.InterlineEquation:
  178. content = f"\n$$\n{span['content']}\n$$\n"
  179. if content != '':
  180. langs = ['zh', 'ja', 'ko']
  181. if line_lang in langs: # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
  182. para_text += content # 中文/日语/韩文语境下,content间不需要空格分隔
  183. elif line_lang == 'en':
  184. # 如果是前一行带有-连字符,那么末尾不应该加空格
  185. if __is_hyphen_at_line_end(para_text):
  186. para_text += content
  187. else:
  188. para_text += content + ' '
  189. else:
  190. para_text += content + ' ' # 西方文本语境下 content间需要空格分隔
  191. return para_text
  192. def para_to_standard_format(para, img_buket_path):
  193. para_content = {}
  194. if len(para) == 1:
  195. para_content = line_to_standard_format(para[0], img_buket_path)
  196. elif len(para) > 1:
  197. para_text = ''
  198. inline_equation_num = 0
  199. for line in para:
  200. for span in line['spans']:
  201. language = ''
  202. span_type = span.get('type')
  203. content = ""
  204. if span_type == ContentType.Text:
  205. content = span['content']
  206. language = detect_lang(content)
  207. if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本
  208. content = ocr_escape_special_markdown_char(split_long_words(content))
  209. else:
  210. content = ocr_escape_special_markdown_char(content)
  211. elif span_type == ContentType.InlineEquation:
  212. content = f"${span['content']}$"
  213. inline_equation_num += 1
  214. if language == 'en': # 英文语境下 content间需要空格分隔
  215. para_text += content + ' '
  216. else: # 中文语境下,content间不需要空格分隔
  217. para_text += content
  218. para_content = {
  219. 'type': 'text',
  220. 'text': para_text,
  221. 'inline_equation_num': inline_equation_num
  222. }
  223. return para_content
  224. def para_to_standard_format_v2(para_block, img_buket_path, page_idx):
  225. para_type = para_block['type']
  226. if para_type == BlockType.Text:
  227. para_content = {
  228. 'type': 'text',
  229. 'text': merge_para_with_text(para_block),
  230. 'page_idx': page_idx
  231. }
  232. elif para_type == BlockType.Title:
  233. para_content = {
  234. 'type': 'text',
  235. 'text': merge_para_with_text(para_block),
  236. 'text_level': 1,
  237. 'page_idx': page_idx
  238. }
  239. elif para_type == BlockType.InterlineEquation:
  240. para_content = {
  241. 'type': 'equation',
  242. 'text': merge_para_with_text(para_block),
  243. 'text_format': "latex",
  244. 'page_idx': page_idx
  245. }
  246. elif para_type == BlockType.Image:
  247. para_content = {
  248. 'type': 'image',
  249. 'page_idx': page_idx
  250. }
  251. for block in para_block['blocks']:
  252. if block['type'] == BlockType.ImageBody:
  253. para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
  254. if block['type'] == BlockType.ImageCaption:
  255. para_content['img_caption'] = merge_para_with_text(block)
  256. elif para_type == BlockType.Table:
  257. para_content = {
  258. 'type': 'table',
  259. 'page_idx': page_idx
  260. }
  261. for block in para_block['blocks']:
  262. if block['type'] == BlockType.TableBody:
  263. if block["lines"][0]["spans"][0].get('latex', ''):
  264. para_content['table_body'] = f"\n\n$\n {block['lines'][0]['spans'][0]['latex']}\n$\n\n"
  265. para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
  266. if block['type'] == BlockType.TableCaption:
  267. para_content['table_caption'] = merge_para_with_text(block)
  268. if block['type'] == BlockType.TableFootnote:
  269. para_content['table_footnote'] = merge_para_with_text(block)
  270. return para_content
  271. def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
  272. content_list = []
  273. for page_info in pdf_info_dict:
  274. paras_of_layout = page_info.get("para_blocks")
  275. if not paras_of_layout:
  276. continue
  277. for para_block in paras_of_layout:
  278. para_content = para_to_standard_format_v2(para_block, img_buket_path)
  279. content_list.append(para_content)
  280. return content_list
  281. def line_to_standard_format(line, img_buket_path):
  282. line_text = ""
  283. inline_equation_num = 0
  284. for span in line['spans']:
  285. if not span.get('content'):
  286. if not span.get('image_path'):
  287. continue
  288. else:
  289. if span['type'] == ContentType.Image:
  290. content = {
  291. 'type': 'image',
  292. 'img_path': join_path(img_buket_path, span['image_path'])
  293. }
  294. return content
  295. elif span['type'] == ContentType.Table:
  296. content = {
  297. 'type': 'table',
  298. 'img_path': join_path(img_buket_path, span['image_path'])
  299. }
  300. return content
  301. else:
  302. if span['type'] == ContentType.InterlineEquation:
  303. interline_equation = span['content']
  304. content = {
  305. 'type': 'equation',
  306. 'latex': f"$$\n{interline_equation}\n$$"
  307. }
  308. return content
  309. elif span['type'] == ContentType.InlineEquation:
  310. inline_equation = span['content']
  311. line_text += f"${inline_equation}$"
  312. inline_equation_num += 1
  313. elif span['type'] == ContentType.Text:
  314. text_content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号
  315. line_text += text_content
  316. content = {
  317. 'type': 'text',
  318. 'text': line_text,
  319. 'inline_equation_num': inline_equation_num
  320. }
  321. return content
  322. def ocr_mk_mm_standard_format(pdf_info_dict: list):
  323. """
  324. content_list
  325. type string image/text/table/equation(行间的单独拿出来,行内的和text合并)
  326. latex string latex文本字段。
  327. text string 纯文本格式的文本数据。
  328. md string markdown格式的文本数据。
  329. img_path string s3://full/path/to/img.jpg
  330. """
  331. content_list = []
  332. for page_info in pdf_info_dict:
  333. blocks = page_info.get("preproc_blocks")
  334. if not blocks:
  335. continue
  336. for block in blocks:
  337. for line in block['lines']:
  338. content = line_to_standard_format(line)
  339. content_list.append(content)
  340. return content_list
  341. def union_make(pdf_info_dict: list, make_mode: str, drop_mode: str, img_buket_path: str = ""):
  342. output_content = []
  343. for page_info in pdf_info_dict:
  344. if page_info.get("need_drop", False):
  345. drop_reason = page_info.get("drop_reason")
  346. if drop_mode == DropMode.NONE:
  347. pass
  348. elif drop_mode == DropMode.WHOLE_PDF:
  349. raise Exception(f"drop_mode is {DropMode.WHOLE_PDF} , drop_reason is {drop_reason}")
  350. elif drop_mode == DropMode.SINGLE_PAGE:
  351. logger.warning(f"drop_mode is {DropMode.SINGLE_PAGE} , drop_reason is {drop_reason}")
  352. continue
  353. else:
  354. raise Exception(f"drop_mode can not be null")
  355. paras_of_layout = page_info.get("para_blocks")
  356. page_idx = page_info.get("page_idx")
  357. if not paras_of_layout:
  358. continue
  359. if make_mode == MakeMode.MM_MD:
  360. page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)
  361. output_content.extend(page_markdown)
  362. elif make_mode == MakeMode.NLP_MD:
  363. page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "nlp")
  364. output_content.extend(page_markdown)
  365. elif make_mode == MakeMode.STANDARD_FORMAT:
  366. for para_block in paras_of_layout:
  367. para_content = para_to_standard_format_v2(para_block, img_buket_path, page_idx)
  368. output_content.append(para_content)
  369. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  370. return '\n\n'.join(output_content)
  371. elif make_mode == MakeMode.STANDARD_FORMAT:
  372. return output_content