Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import copy
  2. import re
  3. from api.db import ParserType
  4. from rag.nlp import huqie, tokenize, tokenize_table, add_positions, bullets_category, title_frequency, tokenize_chunks
  5. from deepdoc.parser import PdfParser, PlainParser
  6. from rag.utils import num_tokens_from_string
  7. class Pdf(PdfParser):
  8. def __init__(self):
  9. self.model_speciess = ParserType.MANUAL.value
  10. super().__init__()
  11. def __call__(self, filename, binary=None, from_page=0,
  12. to_page=100000, zoomin=3, callback=None):
  13. from timeit import default_timer as timer
  14. start = timer()
  15. callback(msg="OCR is running...")
  16. self.__images__(
  17. filename if not binary else binary,
  18. zoomin,
  19. from_page,
  20. to_page,
  21. callback
  22. )
  23. callback(msg="OCR finished.")
  24. #for bb in self.boxes:
  25. # for b in bb:
  26. # print(b)
  27. print("OCR:", timer()-start)
  28. self._layouts_rec(zoomin)
  29. callback(0.65, "Layout analysis finished.")
  30. print("paddle layouts:", timer() - start)
  31. self._table_transformer_job(zoomin)
  32. callback(0.67, "Table analysis finished.")
  33. self._text_merge()
  34. tbls = self._extract_table_figure(True, zoomin, True, True)
  35. self._concat_downward()
  36. self._filter_forpages()
  37. callback(0.68, "Text merging finished")
  38. # clean mess
  39. for b in self.boxes:
  40. b["text"] = re.sub(r"([\t  ]|\u3000){2,}", " ", b["text"].strip())
  41. return [(b["text"], b.get("layout_no", ""), self.get_position(b, zoomin)) for i, b in enumerate(self.boxes)], tbls
  42. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  43. """
  44. Only pdf is supported.
  45. """
  46. pdf_parser = None
  47. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  48. pdf_parser = Pdf() if kwargs.get("parser_config",{}).get("layout_recognize", True) else PlainParser()
  49. sections, tbls = pdf_parser(filename if not binary else binary,
  50. from_page=from_page, to_page=to_page, callback=callback)
  51. if sections and len(sections[0])<3: sections = [(t, l, [[0]*5]) for t, l in sections]
  52. else: raise NotImplementedError("file type not supported yet(pdf supported)")
  53. doc = {
  54. "docnm_kwd": filename
  55. }
  56. doc["title_tks"] = huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  57. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  58. # is it English
  59. eng = lang.lower() == "english"#pdf_parser.is_english
  60. # set pivot using the most frequent type of title,
  61. # then merge between 2 pivot
  62. if len(sections) > 0 and len(pdf_parser.outlines) / len(sections) > 0.1:
  63. max_lvl = max([lvl for _, lvl in pdf_parser.outlines])
  64. most_level = max(0, max_lvl - 1)
  65. levels = []
  66. for txt, _, _ in sections:
  67. for t, lvl in pdf_parser.outlines:
  68. tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
  69. tks_ = set([txt[i] + txt[i + 1] for i in range(min(len(t), len(txt) - 1))])
  70. if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
  71. levels.append(lvl)
  72. break
  73. else:
  74. levels.append(max_lvl + 1)
  75. else:
  76. bull = bullets_category([txt for txt,_,_ in sections])
  77. most_level, levels = title_frequency(bull, [(txt, l) for txt, l, poss in sections])
  78. assert len(sections) == len(levels)
  79. sec_ids = []
  80. sid = 0
  81. for i, lvl in enumerate(levels):
  82. if lvl <= most_level and i > 0 and lvl != levels[i - 1]: sid += 1
  83. sec_ids.append(sid)
  84. # print(lvl, self.boxes[i]["text"], most_level, sid)
  85. sections = [(txt, sec_ids[i], poss) for i, (txt, _, poss) in enumerate(sections)]
  86. for (img, rows), poss in tbls:
  87. sections.append((rows if isinstance(rows, str) else rows[0], -1,
  88. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  89. def tag(pn, left, right, top, bottom):
  90. if pn+left+right+top+bottom == 0:
  91. return ""
  92. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  93. .format(pn, left, right, top, bottom)
  94. chunks = []
  95. last_sid = -2
  96. tk_cnt = 0
  97. for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  98. poss = "\t".join([tag(*pos) for pos in poss])
  99. if tk_cnt < 2048 and (sec_id == last_sid or sec_id == -1):
  100. if chunks:
  101. chunks[-1] += "\n" + txt + poss
  102. tk_cnt += num_tokens_from_string(txt)
  103. continue
  104. chunks.append(txt + poss)
  105. tk_cnt = num_tokens_from_string(txt)
  106. if sec_id > -1: last_sid = sec_id
  107. res = tokenize_table(tbls, doc, eng)
  108. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  109. return res
  110. if __name__ == "__main__":
  111. import sys
  112. def dummy(prog=None, msg=""):
  113. pass
  114. chunk(sys.argv[1], callback=dummy)