You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

laws.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import copy
  2. import re
  3. from io import BytesIO
  4. from docx import Document
  5. import numpy as np
  6. from rag.app import bullets_category, BULLET_PATTERN, is_english, tokenize
  7. from rag.nlp import huqie
  8. from rag.parser.docx_parser import HuDocxParser
  9. from rag.parser.pdf_parser import HuParser
  10. class Docx(HuDocxParser):
  11. def __init__(self):
  12. pass
  13. def __clean(self, line):
  14. line = re.sub(r"\u3000", " ", line).strip()
  15. return line
  16. def __call__(self, filename, binary=None):
  17. self.doc = Document(
  18. filename) if not binary else Document(BytesIO(binary))
  19. lines = [self.__clean(p.text) for p in self.doc.paragraphs]
  20. return [l for l in lines if l]
  21. class Pdf(HuParser):
  22. def __call__(self, filename, binary=None, from_page=0,
  23. to_page=100000, zoomin=3, callback=None):
  24. self.__images__(
  25. filename if not binary else binary,
  26. zoomin,
  27. from_page,
  28. to_page)
  29. callback(0.1, "OCR finished")
  30. from timeit import default_timer as timer
  31. start = timer()
  32. self._layouts_paddle(zoomin)
  33. callback(0.77, "Layout analysis finished")
  34. print("paddle layouts:", timer()-start)
  35. bxs = self.sort_Y_firstly(self.boxes, np.median(self.mean_height) / 3)
  36. # is it English
  37. eng = is_english([b["text"] for b in bxs])
  38. # Merge vertically
  39. i = 0
  40. while i + 1 < len(bxs):
  41. b = bxs[i]
  42. b_ = bxs[i + 1]
  43. if b["page_number"] < b_["page_number"] and re.match(r"[0-9 •一—-]+$", b["text"]):
  44. bxs.pop(i)
  45. continue
  46. concatting_feats = [
  47. b["text"].strip()[-1] in ",;:'\",、‘“;:-",
  48. len(b["text"].strip())>1 and b["text"].strip()[-2] in ",;:'\",‘“、;:",
  49. b["text"].strip()[0] in "。;?!?”)),,、:",
  50. ]
  51. # features for not concating
  52. feats = [
  53. b.get("layoutno",0) != b.get("layoutno",0),
  54. b["text"].strip()[-1] in "。?!?",
  55. eng and b["text"].strip()[-1] in ".!?",
  56. b["page_number"] == b_["page_number"] and b_["top"] - \
  57. b["bottom"] > self.mean_height[b["page_number"] - 1] * 1.5,
  58. b["page_number"] < b_["page_number"] and abs(
  59. b["x0"] - b_["x0"]) > self.mean_width[b["page_number"] - 1] * 4
  60. ]
  61. if any(feats) and not any(concatting_feats):
  62. i += 1
  63. continue
  64. # merge up and down
  65. b["bottom"] = b_["bottom"]
  66. b["text"] += b_["text"]
  67. b["x0"] = min(b["x0"], b_["x0"])
  68. b["x1"] = max(b["x1"], b_["x1"])
  69. bxs.pop(i + 1)
  70. callback(0.8, "Text extraction finished")
  71. return [b["text"] + self._line_tag(b, zoomin) for b in bxs]
  72. def chunk(filename, binary=None, from_page=0, to_page=100000, callback=None):
  73. doc = {
  74. "docnm_kwd": filename,
  75. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  76. }
  77. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  78. pdf_parser = None
  79. sections = []
  80. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  81. callback(0.1, "Start to parse.")
  82. for txt in Docx()(filename, binary):
  83. sections.append(txt)
  84. callback(0.8, "Finish parsing.")
  85. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  86. pdf_parser = Pdf()
  87. for txt in pdf_parser(filename if not binary else binary,
  88. from_page=from_page, to_page=to_page, callback=callback):
  89. sections.append(txt)
  90. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  91. callback(0.1, "Start to parse.")
  92. txt = ""
  93. if binary:txt = binary.decode("utf-8")
  94. else:
  95. with open(filename, "r") as f:
  96. while True:
  97. l = f.readline()
  98. if not l:break
  99. txt += l
  100. sections = txt.split("\n")
  101. sections = [l for l in sections if l]
  102. callback(0.8, "Finish parsing.")
  103. else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)")
  104. # is it English
  105. eng = is_english(sections)
  106. # Remove 'Contents' part
  107. i = 0
  108. while i < len(sections):
  109. if not re.match(r"(contents|目录|目次|table of contents)$", re.sub(r"( | |\u3000)+", "", sections[i].split("@@")[0], re.IGNORECASE)):
  110. i += 1
  111. continue
  112. sections.pop(i)
  113. if i >= len(sections): break
  114. prefix = sections[i].strip()[:3] if not eng else " ".join(sections[i].strip().split(" ")[:2])
  115. while not prefix:
  116. sections.pop(i)
  117. if i >= len(sections): break
  118. prefix = sections[i].strip()[:3] if not eng else " ".join(sections[i].strip().split(" ")[:2])
  119. sections.pop(i)
  120. if i >= len(sections) or not prefix: break
  121. for j in range(i, min(i+128, len(sections))):
  122. if not re.match(prefix, sections[j]):
  123. continue
  124. for _ in range(i, j):sections.pop(i)
  125. break
  126. bull = bullets_category(sections)
  127. projs = [len(BULLET_PATTERN[bull])] * len(sections)
  128. for i, sec in enumerate(sections):
  129. for j,p in enumerate(BULLET_PATTERN[bull]):
  130. if re.match(p, sec.strip()):
  131. projs[i] = j
  132. break
  133. readed = [0] * len(sections)
  134. cks = []
  135. for pr in range(len(BULLET_PATTERN[bull])-1, 1, -1):
  136. for i in range(len(sections)):
  137. if readed[i] or projs[i] < pr:
  138. continue
  139. # find father and grand-father and grand...father
  140. p = projs[i]
  141. readed[i] = 1
  142. ck = [sections[i]]
  143. for j in range(i-1, -1, -1):
  144. if projs[j] >= p:continue
  145. ck.append(sections[j])
  146. readed[j] = 1
  147. p = projs[j]
  148. if p == 0: break
  149. cks.append(ck[::-1])
  150. res = []
  151. # wrap up to es documents
  152. for ck in cks:
  153. print("\n-".join(ck))
  154. ck = "\n".join(ck)
  155. d = copy.deepcopy(doc)
  156. if pdf_parser:
  157. d["image"] = pdf_parser.crop(ck)
  158. ck = pdf_parser.remove_tag(ck)
  159. tokenize(d, ck, eng)
  160. res.append(d)
  161. return res
  162. if __name__ == "__main__":
  163. import sys
  164. chunk(sys.argv[1])