Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

presentation.py 5.4KB

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 PIL import Image
  17. from rag.nlp import tokenize, is_english
  18. from rag.nlp import rag_tokenizer
  19. from deepdoc.parser import PdfParser, PptParser, PlainParser
  20. from PyPDF2 import PdfReader as pdf2_read
  21. class Ppt(PptParser):
  22. def __call__(self, fnm, from_page, to_page, callback=None):
  23. txts = super().__call__(fnm, from_page, to_page)
  24. callback(0.5, "Text extraction finished.")
  25. import aspose.slides as slides
  26. import aspose.pydrawing as drawing
  27. imgs = []
  28. with slides.Presentation(BytesIO(fnm)) as presentation:
  29. for i, slide in enumerate(presentation.slides[from_page: to_page]):
  30. buffered = BytesIO()
  31. slide.get_thumbnail(
  32. 0.5, 0.5).save(
  33. buffered, drawing.imaging.ImageFormat.jpeg)
  34. imgs.append(Image.open(buffered))
  35. assert len(imgs) == len(
  36. txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  37. callback(0.9, "Image extraction finished")
  38. self.is_english = is_english(txts)
  39. return [(txts[i], imgs[i]) for i in range(len(txts))]
  40. class Pdf(PdfParser):
  41. def __init__(self):
  42. super().__init__()
  43. def __garbage(self, txt):
  44. txt = txt.lower().strip()
  45. if re.match(r"[0-9\.,%/-]+$", txt):
  46. return True
  47. if len(txt) < 3:
  48. return True
  49. return False
  50. def __call__(self, filename, binary=None, from_page=0,
  51. to_page=100000, zoomin=3, callback=None):
  52. from timeit import default_timer as timer
  53. start = timer()
  54. callback(msg="OCR started")
  55. self.__images__(filename if not binary else binary,
  56. zoomin, from_page, to_page, callback)
  57. callback(msg="Page {}~{}: OCR finished ({:.2f}s)".format(from_page, min(to_page, self.total_page), timer() - start))
  58. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(
  59. len(self.boxes), len(self.page_images))
  60. res = []
  61. for i in range(len(self.boxes)):
  62. lines = "\n".join([b["text"] for b in self.boxes[i]
  63. if not self.__garbage(b["text"])])
  64. res.append((lines, self.page_images[i]))
  65. callback(0.9, "Page {}~{}: Parsing finished".format(
  66. from_page, min(to_page, self.total_page)))
  67. return res
  68. class PlainPdf(PlainParser):
  69. def __call__(self, filename, binary=None, from_page=0,
  70. to_page=100000, callback=None, **kwargs):
  71. self.pdf = pdf2_read(filename if not binary else BytesIO(binary))
  72. page_txt = []
  73. for page in self.pdf.pages[from_page: to_page]:
  74. page_txt.append(page.extract_text())
  75. callback(0.9, "Parsing finished")
  76. return [(txt, None) for txt in page_txt]
  77. def chunk(filename, binary=None, from_page=0, to_page=100000,
  78. lang="Chinese", callback=None, **kwargs):
  79. """
  80. The supported file formats are pdf, pptx.
  81. Every page will be treated as a chunk. And the thumbnail of every page will be stored.
  82. PPT file will be parsed by using this method automatically, setting-up for every PPT file is not necessary.
  83. """
  84. eng = lang.lower() == "english"
  85. doc = {
  86. "docnm_kwd": filename,
  87. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  88. }
  89. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  90. res = []
  91. if re.search(r"\.pptx?$", filename, re.IGNORECASE):
  92. ppt_parser = Ppt()
  93. for pn, (txt, img) in enumerate(ppt_parser(
  94. filename if not binary else binary, from_page, 1000000, callback)):
  95. d = copy.deepcopy(doc)
  96. pn += from_page
  97. d["image"] = img
  98. d["page_num_int"] = [pn + 1]
  99. d["top_int"] = [0]
  100. d["position_int"] = [(pn + 1, 0, img.size[0], 0, img.size[1])]
  101. tokenize(d, txt, eng)
  102. res.append(d)
  103. return res
  104. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  105. pdf_parser = Pdf() if kwargs.get(
  106. "parser_config", {}).get(
  107. "layout_recognize", True) else PlainPdf()
  108. for pn, (txt, img) in enumerate(pdf_parser(filename, binary,
  109. from_page=from_page, to_page=to_page, callback=callback)):
  110. d = copy.deepcopy(doc)
  111. pn += from_page
  112. if img:
  113. d["image"] = img
  114. d["page_num_int"] = [pn + 1]
  115. d["top_int"] = [0]
  116. d["position_int"] = [(pn + 1, 0, img.size[0] if img else 0, 0, img.size[1] if img else 0)]
  117. tokenize(d, txt, eng)
  118. res.append(d)
  119. return res
  120. raise NotImplementedError(
  121. "file type not supported yet(pptx, pdf supported)")
  122. if __name__ == "__main__":
  123. import sys
  124. def dummy(a, b):
  125. pass
  126. chunk(sys.argv[1], callback=dummy)