Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

presentation.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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 huqie
  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(0.5, 0.5).save(buffered, drawing.imaging.ImageFormat.jpeg)
  32. imgs.append(Image.open(buffered))
  33. assert len(imgs) == len(txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  34. callback(0.9, "Image extraction finished")
  35. self.is_english = is_english(txts)
  36. return [(txts[i], imgs[i]) for i in range(len(txts))]
  37. class Pdf(PdfParser):
  38. def __init__(self):
  39. super().__init__()
  40. def __garbage(self, txt):
  41. txt = txt.lower().strip()
  42. if re.match(r"[0-9\.,%/-]+$", txt): return True
  43. if len(txt) < 3:return True
  44. return False
  45. def __call__(self, filename, binary=None, from_page=0, to_page=100000, zoomin=3, callback=None):
  46. callback(msg="OCR is running...")
  47. self.__images__(filename if not binary else binary, zoomin, from_page, to_page, callback)
  48. callback(0.8, "Page {}~{}: OCR finished".format(from_page, min(to_page, self.total_page)))
  49. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(len(self.boxes), len(self.page_images))
  50. res = []
  51. for i in range(len(self.boxes)):
  52. lines = "\n".join([b["text"] for b in self.boxes[i] if not self.__garbage(b["text"])])
  53. res.append((lines, self.page_images[i]))
  54. callback(0.9, "Page {}~{}: Parsing finished".format(from_page, min(to_page, self.total_page)))
  55. return res
  56. class PlainPdf(PlainParser):
  57. def __call__(self, filename, binary=None, callback=None, **kwargs):
  58. self.pdf = pdf2_read(filename if not binary else BytesIO(filename))
  59. page_txt = []
  60. for page in self.pdf.pages:
  61. page_txt.append(page.extract_text())
  62. callback(0.9, "Parsing finished")
  63. return [(txt, None) for txt in page_txt]
  64. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  65. """
  66. The supported file formats are pdf, pptx.
  67. Every page will be treated as a chunk. And the thumbnail of every page will be stored.
  68. PPT file will be parsed by using this method automatically, setting-up for every PPT file is not necessary.
  69. """
  70. eng = lang.lower() == "english"
  71. doc = {
  72. "docnm_kwd": filename,
  73. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  74. }
  75. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  76. res = []
  77. if re.search(r"\.pptx?$", filename, re.IGNORECASE):
  78. ppt_parser = Ppt()
  79. for pn, (txt,img) in enumerate(ppt_parser(filename if not binary else binary, from_page, 1000000, callback)):
  80. d = copy.deepcopy(doc)
  81. pn += from_page
  82. d["image"] = img
  83. d["page_num_int"] = [pn+1]
  84. d["top_int"] = [0]
  85. d["position_int"] = [(pn + 1, 0, img.size[0], 0, img.size[1])]
  86. tokenize(d, txt, eng)
  87. res.append(d)
  88. return res
  89. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  90. pdf_parser = Pdf() if kwargs.get("parser_config",{}).get("layout_recognize", True) else PlainPdf()
  91. for pn, (txt,img) in enumerate(pdf_parser(filename, binary, from_page=from_page, to_page=to_page, callback=callback)):
  92. d = copy.deepcopy(doc)
  93. pn += from_page
  94. if img: d["image"] = img
  95. d["page_num_int"] = [pn+1]
  96. d["top_int"] = [0]
  97. d["position_int"] = [(pn + 1, 0, img.size[0] if img else 0, 0, img.size[1] if img else 0)]
  98. tokenize(d, txt, eng)
  99. res.append(d)
  100. return res
  101. raise NotImplementedError("file type not supported yet(pptx, pdf supported)")
  102. if __name__== "__main__":
  103. import sys
  104. def dummy(a, b):
  105. pass
  106. chunk(sys.argv[1], callback=dummy)