citationmarker_remove.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. 去掉正文的引文引用marker
  3. https://aicarrier.feishu.cn/wiki/YLOPwo1PGiwFRdkwmyhcZmr0n3d
  4. """
  5. import re
  6. from loguru import logger
  7. from libs.nlp_utils import NLPModels
  8. __NLP_MODEL = NLPModels()
  9. def check_1(spans, cur_span_i):
  10. """寻找前一个char,如果是句号,逗号,那么就是角标"""
  11. if cur_span_i==0:
  12. return False # 不是角标
  13. pre_span = spans[cur_span_i-1]
  14. pre_char = pre_span['chars'][-1]['c']
  15. if pre_char in ['。', ',', '.', ',']:
  16. return True
  17. return False
  18. def check_2(spans, cur_span_i):
  19. """检查前面一个span的最后一个单词,如果长度大于5,全都是字母,并且不含大写,就是角标"""
  20. pattern = r'\b[A-Z]\.\s[A-Z][a-z]*\b' # 形如A. Bcde, L. Bcde, 人名的缩写
  21. if cur_span_i==0 and len(spans)>1:
  22. next_span = spans[cur_span_i+1]
  23. next_txt = "".join([c['c'] for c in next_span['chars']])
  24. result = __NLP_MODEL.detect_entity_catgr_using_nlp(next_txt)
  25. if result in ["PERSON", "GPE", "ORG"]:
  26. return True
  27. if re.findall(pattern, next_txt):
  28. return True
  29. return False # 不是角标
  30. elif cur_span_i==0 and len(spans)==1: # 角标占用了整行?谨慎删除
  31. return False
  32. # 如果这个span是最后一个span,
  33. if cur_span_i==len(spans)-1:
  34. pre_span = spans[cur_span_i-1]
  35. pre_txt = "".join([c['c'] for c in pre_span['chars']])
  36. pre_word = pre_txt.split(' ')[-1]
  37. result = __NLP_MODEL.detect_entity_catgr_using_nlp(pre_txt)
  38. if result in ["PERSON", "GPE", "ORG"]:
  39. return True
  40. if re.findall(pattern, pre_txt):
  41. return True
  42. return len(pre_word) > 5 and pre_word.isalpha() and pre_word.islower()
  43. else: # 既不是第一个span,也不是最后一个span,那么此时检查一下这个角标距离前后哪个单词更近就属于谁的角标
  44. pre_span = spans[cur_span_i-1]
  45. next_span = spans[cur_span_i+1]
  46. cur_span = spans[cur_span_i]
  47. # 找到前一个和后一个span里的距离最近的单词
  48. pre_distance = 10000 # 一个很大的数
  49. next_distance = 10000 # 一个很大的数
  50. for c in pre_span['chars'][::-1]:
  51. if c['c'].isalpha():
  52. pre_distance = cur_span['bbox'][0] - c['bbox'][2]
  53. break
  54. for c in next_span['chars']:
  55. if c['c'].isalpha():
  56. next_distance = c['bbox'][0] - cur_span['bbox'][2]
  57. break
  58. if pre_distance<next_distance:
  59. belong_to_span = pre_span
  60. else:
  61. belong_to_span = next_span
  62. txt = "".join([c['c'] for c in belong_to_span['chars']])
  63. pre_word = txt.split(' ')[-1]
  64. result = __NLP_MODEL.detect_entity_catgr_using_nlp(txt)
  65. if result in ["PERSON", "GPE", "ORG"]:
  66. return True
  67. if re.findall(pattern, txt):
  68. return True
  69. return len(pre_word) > 5 and pre_word.isalpha() and pre_word.islower()
  70. def check_3(spans, cur_span_i):
  71. """上标里有[], 有*, 有-, 有逗号"""
  72. # 如[2-3],[22]
  73. # 如 2,3,4
  74. cur_span_txt = ''.join(c['c'] for c in spans[cur_span_i]['chars']).strip()
  75. bad_char = ['[', ']', '*', ',']
  76. if any([c in cur_span_txt for c in bad_char]) and any(character.isdigit() for character in cur_span_txt):
  77. return True
  78. # 如2-3, a-b
  79. patterns = [r'\d+-\d+', r'[a-zA-Z]-[a-zA-Z]', r'[a-zA-Z],[a-zA-Z]']
  80. for pattern in patterns:
  81. match = re.match(pattern, cur_span_txt)
  82. if match is not None:
  83. return True
  84. return False
  85. def remove_citation_marker(with_char_text_blcoks):
  86. for blk in with_char_text_blcoks:
  87. for line in blk['lines']:
  88. # 如果span里的个数少于2个,那只能忽略,角标不可能自己独占一行
  89. if len(line['spans'])<=1:
  90. continue
  91. # 找到高度最高的span作为位置比较的基准
  92. max_hi_span = line['spans'][0]['bbox']
  93. min_font_sz = 10000 # line里最小的字体
  94. max_font_sz = 0 # line里最大的字体
  95. for s in line['spans']:
  96. if max_hi_span[3]-max_hi_span[1]<s['bbox'][3]-s['bbox'][1]:
  97. max_hi_span = s['bbox']
  98. if min_font_sz>s['size']:
  99. min_font_sz = s['size']
  100. if max_font_sz<s['size']:
  101. max_font_sz = s['size']
  102. base_span_mid_y = (max_hi_span[3]+max_hi_span[1])/2
  103. span_to_del = []
  104. for i, span in enumerate(line['spans']):
  105. span_hi = span['bbox'][3]-span['bbox'][1]
  106. span_mid_y = (span['bbox'][3]+span['bbox'][1])/2
  107. span_font_sz = span['size']
  108. if max_font_sz-span_font_sz<1: # 先以字体过滤正文,如果是正文就不再继续判断了
  109. continue
  110. if (base_span_mid_y-span_mid_y)/span_hi>0.2 or (base_span_mid_y-span_mid_y>0 and abs(span_font_sz-min_font_sz)/min_font_sz<0.1):
  111. """
  112. 1. 它的前一个char如果是句号或者逗号的话,那么肯定是角标而不是公式
  113. 2. 如果这个角标的前面是一个单词(长度大于5)而不是任何大写或小写的短字母的话 应该也是角标
  114. 3. 上标里有数字和逗号或者数字+星号的组合,方括号,一般肯定就是角标了
  115. 4. 这个角标属于前文还是后文要根据距离来判断,如果距离前面的文本太近,那么就是前面的角标,否则就是后面的角标
  116. """
  117. if check_1(line['spans'], i) or check_2(line['spans'], i) or check_3(line['spans'], i):
  118. """删除掉这个角标:删除这个span, 同时还要更新line的text"""
  119. span_to_del.append(span)
  120. if len(span_to_del)>0:
  121. for span in span_to_del:
  122. line['spans'].remove(span)
  123. line['text'] = ''.join([c['c'] for s in line['spans'] for c in s['chars']])
  124. return with_char_text_blcoks