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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import copy
  14. import re
  15. from io import BytesIO
  16. from docx import Document
  17. from rag.nlp import bullets_category, is_english, tokenize, remove_contents_table, hierarchical_merge, \
  18. make_colon_as_title, add_positions, tokenize_chunks
  19. from rag.nlp import huqie
  20. from deepdoc.parser import PdfParser, DocxParser, PlainParser
  21. from rag.settings import cron_logger
  22. class Docx(DocxParser):
  23. def __init__(self):
  24. pass
  25. def __clean(self, line):
  26. line = re.sub(r"\u3000", " ", line).strip()
  27. return line
  28. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  29. self.doc = Document(
  30. filename) if not binary else Document(BytesIO(binary))
  31. pn = 0
  32. lines = []
  33. for p in self.doc.paragraphs:
  34. if pn > to_page:
  35. break
  36. if from_page <= pn < to_page and p.text.strip():
  37. lines.append(self.__clean(p.text))
  38. for run in p.runs:
  39. if 'lastRenderedPageBreak' in run._element.xml:
  40. pn += 1
  41. continue
  42. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  43. pn += 1
  44. return [l for l in lines if l]
  45. class Pdf(PdfParser):
  46. def __call__(self, filename, binary=None, from_page=0,
  47. to_page=100000, zoomin=3, callback=None):
  48. callback(msg="OCR is running...")
  49. self.__images__(
  50. filename if not binary else binary,
  51. zoomin,
  52. from_page,
  53. to_page,
  54. callback
  55. )
  56. callback(msg="OCR finished")
  57. from timeit import default_timer as timer
  58. start = timer()
  59. self._layouts_rec(zoomin)
  60. callback(0.67, "Layout analysis finished")
  61. cron_logger.info("paddle layouts:".format(
  62. (timer() - start) / (self.total_page + 0.1)))
  63. self._naive_vertical_merge()
  64. callback(0.8, "Text extraction finished")
  65. return [(b["text"], self._line_tag(b, zoomin))
  66. for b in self.boxes], None
  67. def chunk(filename, binary=None, from_page=0, to_page=100000,
  68. lang="Chinese", callback=None, **kwargs):
  69. """
  70. Supported file formats are docx, pdf, txt.
  71. """
  72. doc = {
  73. "docnm_kwd": filename,
  74. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  75. }
  76. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  77. pdf_parser = None
  78. sections = []
  79. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  80. callback(0.1, "Start to parse.")
  81. for txt in Docx()(filename, binary):
  82. sections.append(txt)
  83. callback(0.8, "Finish parsing.")
  84. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  85. pdf_parser = Pdf() if kwargs.get(
  86. "parser_config", {}).get(
  87. "layout_recognize", True) else PlainParser()
  88. for txt, poss in pdf_parser(filename if not binary else binary,
  89. from_page=from_page, to_page=to_page, callback=callback)[0]:
  90. sections.append(txt + poss)
  91. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  92. callback(0.1, "Start to parse.")
  93. txt = ""
  94. if binary:
  95. txt = binary.decode("utf-8")
  96. else:
  97. with open(filename, "r") as f:
  98. while True:
  99. l = f.readline()
  100. if not l:
  101. break
  102. txt += l
  103. sections = txt.split("\n")
  104. sections = [l for l in sections if l]
  105. callback(0.8, "Finish parsing.")
  106. else:
  107. raise NotImplementedError(
  108. "file type not supported yet(docx, pdf, txt supported)")
  109. # is it English
  110. eng = lang.lower() == "english" # is_english(sections)
  111. # Remove 'Contents' part
  112. remove_contents_table(sections, eng)
  113. make_colon_as_title(sections)
  114. bull = bullets_category(sections)
  115. chunks = hierarchical_merge(bull, sections, 3)
  116. if not chunks:
  117. callback(0.99, "No chunk parsed out.")
  118. return tokenize_chunks(["\n".join(ck)
  119. for ck in chunks], doc, eng, pdf_parser)
  120. if __name__ == "__main__":
  121. import sys
  122. def dummy(prog=None, msg=""):
  123. pass
  124. chunk(sys.argv[1], callback=dummy)