Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. from io import BytesIO
  15. import re
  16. from rag.app import laws
  17. from rag.nlp import rag_tokenizer, tokenize, find_codec
  18. from deepdoc.parser import PdfParser, ExcelParser, PlainParser, HtmlParser
  19. class Pdf(PdfParser):
  20. def __call__(self, filename, binary=None, from_page=0,
  21. to_page=100000, zoomin=3, callback=None):
  22. callback(msg="OCR is running...")
  23. self.__images__(
  24. filename if not binary else binary,
  25. zoomin,
  26. from_page,
  27. to_page,
  28. callback
  29. )
  30. callback(msg="OCR finished")
  31. from timeit import default_timer as timer
  32. start = timer()
  33. self._layouts_rec(zoomin, drop=False)
  34. callback(0.63, "Layout analysis finished.")
  35. print("layouts:", timer() - start)
  36. self._table_transformer_job(zoomin)
  37. callback(0.65, "Table analysis finished.")
  38. self._text_merge()
  39. callback(0.67, "Text merging finished")
  40. tbls = self._extract_table_figure(True, zoomin, True, True)
  41. self._concat_downward()
  42. sections = [(b["text"], self.get_position(b, zoomin))
  43. for i, b in enumerate(self.boxes)]
  44. for (img, rows), poss in tbls:
  45. if not rows:continue
  46. sections.append((rows if isinstance(rows, str) else rows[0],
  47. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  48. return [(txt, "") for txt, _ in sorted(sections, key=lambda x: (
  49. x[-1][0][0], x[-1][0][3], x[-1][0][1]))], None
  50. def chunk(filename, binary=None, from_page=0, to_page=100000,
  51. lang="Chinese", callback=None, **kwargs):
  52. """
  53. Supported file formats are docx, pdf, excel, txt.
  54. One file forms a chunk which maintains original text order.
  55. """
  56. eng = lang.lower() == "english" # is_english(cks)
  57. if re.search(r"\.docx$", filename, re.IGNORECASE):
  58. callback(0.1, "Start to parse.")
  59. sections = [txt for txt in laws.Docx()(filename, binary) if txt]
  60. callback(0.8, "Finish parsing.")
  61. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  62. pdf_parser = Pdf() if kwargs.get(
  63. "parser_config", {}).get(
  64. "layout_recognize", True) else PlainParser()
  65. sections, _ = pdf_parser(
  66. filename if not binary else binary, to_page=to_page, callback=callback)
  67. sections = [s for s, _ in sections if s]
  68. elif re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  69. callback(0.1, "Start to parse.")
  70. excel_parser = ExcelParser()
  71. sections = excel_parser.html(binary, 1000000000)
  72. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  73. callback(0.1, "Start to parse.")
  74. txt = ""
  75. if binary:
  76. encoding = find_codec(binary)
  77. txt = binary.decode(encoding, errors="ignore")
  78. else:
  79. with open(filename, "r") as f:
  80. while True:
  81. l = f.readline()
  82. if not l:
  83. break
  84. txt += l
  85. sections = txt.split("\n")
  86. sections = [s for s in sections if s]
  87. callback(0.8, "Finish parsing.")
  88. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  89. callback(0.1, "Start to parse.")
  90. sections = HtmlParser()(filename, binary)
  91. sections = [s for s in sections if s]
  92. callback(0.8, "Finish parsing.")
  93. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  94. callback(0.1, "Start to parse.")
  95. binary = BytesIO(binary)
  96. doc_parsed = parser.from_buffer(binary)
  97. sections = doc_parsed['content'].split('\n')
  98. sections = [l for l in sections if l]
  99. callback(0.8, "Finish parsing.")
  100. else:
  101. raise NotImplementedError(
  102. "file type not supported yet(doc, docx, pdf, txt supported)")
  103. doc = {
  104. "docnm_kwd": filename,
  105. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  106. }
  107. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  108. tokenize(doc, "\n".join(sections), eng)
  109. return [doc]
  110. if __name__ == "__main__":
  111. import sys
  112. def dummy(prog=None, msg=""):
  113. pass
  114. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)