您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. from tika import parser
  14. import re
  15. from io import BytesIO
  16. from docx import Document
  17. from api.db import ParserType
  18. from deepdoc.parser.utils import get_text
  19. from rag.nlp import bullets_category, remove_contents_table, hierarchical_merge, \
  20. make_colon_as_title, tokenize_chunks, docx_question_level
  21. from rag.nlp import rag_tokenizer
  22. from deepdoc.parser import PdfParser, DocxParser, PlainParser, HtmlParser
  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 old_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. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  47. self.doc = Document(
  48. filename) if not binary else Document(BytesIO(binary))
  49. pn = 0
  50. lines = []
  51. bull = bullets_category([p.text for p in self.doc.paragraphs])
  52. for p in self.doc.paragraphs:
  53. if pn > to_page:
  54. break
  55. question_level, p_text = docx_question_level(p, bull)
  56. if not p_text.strip("\n"):continue
  57. lines.append((question_level, p_text))
  58. for run in p.runs:
  59. if 'lastRenderedPageBreak' in run._element.xml:
  60. pn += 1
  61. continue
  62. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  63. pn += 1
  64. visit = [False for _ in range(len(lines))]
  65. sections = []
  66. for s in range(len(lines)):
  67. e = s + 1
  68. while e < len(lines):
  69. if lines[e][0] <= lines[s][0]:
  70. break
  71. e += 1
  72. if e - s == 1 and visit[s]: continue
  73. sec = []
  74. next_level = lines[s][0] + 1
  75. while not sec and next_level < 22:
  76. for i in range(s+1, e):
  77. if lines[i][0] != next_level: continue
  78. sec.append(lines[i][1])
  79. visit[i] = True
  80. next_level += 1
  81. sec.insert(0, lines[s][1])
  82. sections.append("\n".join(sec))
  83. return [l for l in sections if l]
  84. def __str__(self) -> str:
  85. return f'''
  86. question:{self.question},
  87. answer:{self.answer},
  88. level:{self.level},
  89. childs:{self.childs}
  90. '''
  91. class Pdf(PdfParser):
  92. def __init__(self):
  93. self.model_speciess = ParserType.LAWS.value
  94. super().__init__()
  95. def __call__(self, filename, binary=None, from_page=0,
  96. to_page=100000, zoomin=3, callback=None):
  97. callback(msg="OCR is running...")
  98. self.__images__(
  99. filename if not binary else binary,
  100. zoomin,
  101. from_page,
  102. to_page,
  103. callback
  104. )
  105. callback(msg="OCR finished")
  106. from timeit import default_timer as timer
  107. start = timer()
  108. self._layouts_rec(zoomin)
  109. callback(0.67, "Layout analysis finished")
  110. logging.debug("layouts:".format(
  111. ))
  112. self._naive_vertical_merge()
  113. callback(0.8, "Text extraction finished")
  114. return [(b["text"], self._line_tag(b, zoomin))
  115. for b in self.boxes], None
  116. def chunk(filename, binary=None, from_page=0, to_page=100000,
  117. lang="Chinese", callback=None, **kwargs):
  118. """
  119. Supported file formats are docx, pdf, txt.
  120. """
  121. doc = {
  122. "docnm_kwd": filename,
  123. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  124. }
  125. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  126. pdf_parser = None
  127. sections = []
  128. # is it English
  129. eng = lang.lower() == "english" # is_english(sections)
  130. if re.search(r"\.docx$", filename, re.IGNORECASE):
  131. callback(0.1, "Start to parse.")
  132. for txt in Docx()(filename, binary):
  133. sections.append(txt)
  134. callback(0.8, "Finish parsing.")
  135. chunks = sections
  136. return tokenize_chunks(chunks, doc, eng, pdf_parser)
  137. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  138. pdf_parser = Pdf() if kwargs.get(
  139. "parser_config", {}).get(
  140. "layout_recognize", True) else PlainParser()
  141. for txt, poss in pdf_parser(filename if not binary else binary,
  142. from_page=from_page, to_page=to_page, callback=callback)[0]:
  143. sections.append(txt + poss)
  144. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  145. callback(0.1, "Start to parse.")
  146. txt = get_text(filename, binary)
  147. sections = txt.split("\n")
  148. sections = [l for l in sections if l]
  149. callback(0.8, "Finish parsing.")
  150. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  151. callback(0.1, "Start to parse.")
  152. sections = HtmlParser()(filename, binary)
  153. sections = [l for l in sections if l]
  154. callback(0.8, "Finish parsing.")
  155. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  156. callback(0.1, "Start to parse.")
  157. binary = BytesIO(binary)
  158. doc_parsed = parser.from_buffer(binary)
  159. sections = doc_parsed['content'].split('\n')
  160. sections = [l for l in sections if l]
  161. callback(0.8, "Finish parsing.")
  162. else:
  163. raise NotImplementedError(
  164. "file type not supported yet(doc, docx, pdf, txt supported)")
  165. # Remove 'Contents' part
  166. remove_contents_table(sections, eng)
  167. make_colon_as_title(sections)
  168. bull = bullets_category(sections)
  169. chunks = hierarchical_merge(bull, sections, 5)
  170. if not chunks:
  171. callback(0.99, "No chunk parsed out.")
  172. return tokenize_chunks(["\n".join(ck)
  173. for ck in chunks], doc, eng, pdf_parser)
  174. if __name__ == "__main__":
  175. import sys
  176. def dummy(prog=None, msg=""):
  177. pass
  178. chunk(sys.argv[1], callback=dummy)