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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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:break
  35. if from_page <= pn < to_page and p.text.strip(): lines.append(self.__clean(p.text))
  36. for run in p.runs:
  37. if 'lastRenderedPageBreak' in run._element.xml:
  38. pn += 1
  39. continue
  40. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  41. pn += 1
  42. return [l for l in lines if l]
  43. class Pdf(PdfParser):
  44. def __call__(self, filename, binary=None, from_page=0,
  45. to_page=100000, zoomin=3, callback=None):
  46. callback(msg="OCR is running...")
  47. self.__images__(
  48. filename if not binary else binary,
  49. zoomin,
  50. from_page,
  51. to_page,
  52. callback
  53. )
  54. callback(msg="OCR finished")
  55. from timeit import default_timer as timer
  56. start = timer()
  57. self._layouts_rec(zoomin)
  58. callback(0.67, "Layout analysis finished")
  59. cron_logger.info("paddle layouts:".format((timer()-start)/(self.total_page+0.1)))
  60. self._naive_vertical_merge()
  61. callback(0.8, "Text extraction finished")
  62. return [(b["text"], self._line_tag(b, zoomin)) for b in self.boxes], None
  63. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  64. """
  65. Supported file formats are docx, pdf, txt.
  66. """
  67. doc = {
  68. "docnm_kwd": filename,
  69. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  70. }
  71. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  72. pdf_parser = None
  73. sections = []
  74. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  75. callback(0.1, "Start to parse.")
  76. for txt in Docx()(filename, binary):
  77. sections.append(txt)
  78. callback(0.8, "Finish parsing.")
  79. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  80. pdf_parser = Pdf() if kwargs.get("parser_config",{}).get("layout_recognize", True) else PlainParser()
  81. for txt, poss in pdf_parser(filename if not binary else binary,
  82. from_page=from_page, to_page=to_page, callback=callback)[0]:
  83. sections.append(txt + poss)
  84. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  85. callback(0.1, "Start to parse.")
  86. txt = ""
  87. if binary:txt = binary.decode("utf-8")
  88. else:
  89. with open(filename, "r") as f:
  90. while True:
  91. l = f.readline()
  92. if not l:break
  93. txt += l
  94. sections = txt.split("\n")
  95. sections = [l for l in sections if l]
  96. callback(0.8, "Finish parsing.")
  97. else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)")
  98. # is it English
  99. eng = lang.lower() == "english"#is_english(sections)
  100. # Remove 'Contents' part
  101. remove_contents_table(sections, eng)
  102. make_colon_as_title(sections)
  103. bull = bullets_category(sections)
  104. chunks = hierarchical_merge(bull, sections, 3)
  105. if not chunks: callback(0.99, "No chunk parsed out.")
  106. return tokenize_chunks(["\n".join(ck) for ck in chunks], doc, eng, pdf_parser)
  107. if __name__ == "__main__":
  108. import sys
  109. def dummy(prog=None, msg=""):
  110. pass
  111. chunk(sys.argv[1], callback=dummy)