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 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import copy
  2. import re
  3. from io import BytesIO
  4. from docx import Document
  5. import numpy as np
  6. from rag.parser import bullets_category, is_english, tokenize, remove_contents_table, hierarchical_merge, \
  7. make_colon_as_title
  8. from rag.nlp import huqie
  9. from rag.parser.docx_parser import HuDocxParser
  10. from rag.parser.pdf_parser import HuParser
  11. from rag.settings import cron_logger
  12. class Docx(HuDocxParser):
  13. def __init__(self):
  14. pass
  15. def __clean(self, line):
  16. line = re.sub(r"\u3000", " ", line).strip()
  17. return line
  18. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  19. self.doc = Document(
  20. filename) if not binary else Document(BytesIO(binary))
  21. pn = 0
  22. lines = []
  23. for p in self.doc.paragraphs:
  24. if pn > to_page:break
  25. if from_page <= pn < to_page and p.text.strip(): lines.append(self.__clean(p.text))
  26. for run in p.runs:
  27. if 'lastRenderedPageBreak' in run._element.xml:
  28. pn += 1
  29. continue
  30. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  31. pn += 1
  32. return [l for l in lines if l]
  33. class Pdf(HuParser):
  34. def __call__(self, filename, binary=None, from_page=0,
  35. to_page=100000, zoomin=3, callback=None):
  36. self.__images__(
  37. filename if not binary else binary,
  38. zoomin,
  39. from_page,
  40. to_page)
  41. callback(0.1, "OCR finished")
  42. from timeit import default_timer as timer
  43. start = timer()
  44. self._layouts_paddle(zoomin)
  45. callback(0.77, "Layout analysis finished")
  46. cron_logger.info("paddle layouts:".format((timer()-start)/(self.total_page+0.1)))
  47. self._naive_vertical_merge()
  48. callback(0.8, "Text extraction finished")
  49. return [b["text"] + self._line_tag(b, zoomin) for b in self.boxes]
  50. def chunk(filename, binary=None, from_page=0, to_page=100000, callback=None, **kwargs):
  51. doc = {
  52. "docnm_kwd": filename,
  53. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  54. }
  55. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  56. pdf_parser = None
  57. sections = []
  58. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  59. callback(0.1, "Start to parse.")
  60. for txt in Docx()(filename, binary):
  61. sections.append(txt)
  62. callback(0.8, "Finish parsing.")
  63. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  64. pdf_parser = Pdf()
  65. for txt in pdf_parser(filename if not binary else binary,
  66. from_page=from_page, to_page=to_page, callback=callback):
  67. sections.append(txt)
  68. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  69. callback(0.1, "Start to parse.")
  70. txt = ""
  71. if binary:txt = binary.decode("utf-8")
  72. else:
  73. with open(filename, "r") as f:
  74. while True:
  75. l = f.readline()
  76. if not l:break
  77. txt += l
  78. sections = txt.split("\n")
  79. sections = txt.split("\n")
  80. sections = [l for l in sections if l]
  81. callback(0.8, "Finish parsing.")
  82. else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)")
  83. # is it English
  84. eng = is_english(sections)
  85. # Remove 'Contents' part
  86. remove_contents_table(sections, eng)
  87. make_colon_as_title(sections)
  88. bull = bullets_category(sections)
  89. cks = hierarchical_merge(bull, sections, 3)
  90. if not cks: callback(0.99, "No chunk parsed out.")
  91. res = []
  92. # wrap up to es documents
  93. for ck in cks:
  94. print("\n-".join(ck))
  95. ck = "\n".join(ck)
  96. d = copy.deepcopy(doc)
  97. if pdf_parser:
  98. d["image"] = pdf_parser.crop(ck)
  99. ck = pdf_parser.remove_tag(ck)
  100. tokenize(d, ck, eng)
  101. res.append(d)
  102. return res
  103. if __name__ == "__main__":
  104. import sys
  105. def dummy(a, b):
  106. pass
  107. chunk(sys.argv[1], callback=dummy)