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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 rag.nlp import tokenize, is_english
  17. from rag.nlp import huqie
  18. from deepdoc.parser import PdfParser, PptParser
  19. class Ppt(PptParser):
  20. def __call__(self, fnm, from_page, to_page, callback=None):
  21. txts = super().__call__(fnm, from_page, to_page)
  22. callback(0.5, "Text extraction finished.")
  23. import aspose.slides as slides
  24. import aspose.pydrawing as drawing
  25. imgs = []
  26. with slides.Presentation(BytesIO(fnm)) as presentation:
  27. for i, slide in enumerate(presentation.slides[from_page: to_page]):
  28. buffered = BytesIO()
  29. slide.get_thumbnail(0.5, 0.5).save(buffered, drawing.imaging.ImageFormat.jpeg)
  30. imgs.append(buffered.getvalue())
  31. assert len(imgs) == len(txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  32. callback(0.9, "Image extraction finished")
  33. self.is_english = is_english(txts)
  34. return [(txts[i], imgs[i]) for i in range(len(txts))]
  35. class Pdf(PdfParser):
  36. def __init__(self):
  37. super().__init__()
  38. def __garbage(self, txt):
  39. txt = txt.lower().strip()
  40. if re.match(r"[0-9\.,%/-]+$", txt): return True
  41. if len(txt) < 3:return True
  42. return False
  43. def __call__(self, filename, binary=None, from_page=0, to_page=100000, zoomin=3, callback=None):
  44. self.__images__(filename if not binary else binary, zoomin, from_page, to_page)
  45. callback(0.8, "Page {}~{}: OCR finished".format(from_page, min(to_page, self.total_page)))
  46. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(len(self.boxes), len(self.page_images))
  47. res = []
  48. #################### More precisely ###################
  49. # self._layouts_rec(zoomin)
  50. # self._text_merge()
  51. # pages = {}
  52. # for b in self.boxes:
  53. # if self.__garbage(b["text"]):continue
  54. # if b["page_number"] not in pages: pages[b["page_number"]] = []
  55. # pages[b["page_number"]].append(b["text"])
  56. # for i, lines in pages.items():
  57. # res.append(("\n".join(lines), self.page_images[i-1]))
  58. # return res
  59. ########################################
  60. for i in range(len(self.boxes)):
  61. lines = "\n".join([b["text"] for b in self.boxes[i] if not self.__garbage(b["text"])])
  62. res.append((lines, self.page_images[i]))
  63. callback(0.9, "Page {}~{}: Parsing finished".format(from_page, min(to_page, self.total_page)))
  64. return res
  65. def chunk(filename, binary=None, from_page=0, to_page=100000, callback=None, **kwargs):
  66. """
  67. The supported file formats are pdf, pptx.
  68. Every page will be treated as a chunk. And the thumbnail of every page will be stored.
  69. PPT file will be parsed by using this method automatically, setting-up for every PPT file is not necessary.
  70. """
  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 txt,img in ppt_parser(filename if not binary else binary, from_page, 1000000, callback):
  80. d = copy.deepcopy(doc)
  81. d["image"] = img
  82. tokenize(d, txt, ppt_parser.is_english)
  83. res.append(d)
  84. return res
  85. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  86. pdf_parser = Pdf()
  87. for txt,img in pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page, callback=callback):
  88. d = copy.deepcopy(doc)
  89. d["image"] = img
  90. tokenize(d, txt, pdf_parser.is_english)
  91. res.append(d)
  92. return res
  93. raise NotImplementedError("file type not supported yet(pptx, pdf supported)")
  94. if __name__== "__main__":
  95. import sys
  96. def dummy(a, b):
  97. pass
  98. chunk(sys.argv[1], callback=dummy)