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

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