ankban commited on
Commit
bf97738
·
verified ·
1 Parent(s): e0baf3c

Create file_utils.py

Browse files
Files changed (1) hide show
  1. file_utils.py +47 -0
file_utils.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fitz # PyMuPDF
2
+ from pptx import Presentation
3
+
4
+
5
+ def extract_text_from_pdf(pdf_path):
6
+ text = ""
7
+ with fitz.open(pdf_path) as doc:
8
+ for page in doc:
9
+ text += page.get_text()
10
+ return text
11
+
12
+
13
+ def extract_text_from_txt(file_path):
14
+ with open(file_path, 'r', encoding='utf-8') as f:
15
+ return f.read()
16
+
17
+
18
+ def extract_text_from_md(file_path):
19
+ with open(file_path, 'r', encoding='utf-8') as f:
20
+ return f.read()
21
+
22
+
23
+ def extract_text_from_pptx(file_path):
24
+ text = ""
25
+ prs = Presentation(file_path)
26
+ for slide in prs.slides:
27
+ for shape in slide.shapes:
28
+ if hasattr(shape, "text"):
29
+ text += shape.text + "\n"
30
+ return text
31
+
32
+
33
+ def extract_text_from_file(file):
34
+ if file is None:
35
+ return ""
36
+
37
+ name = file.name.lower()
38
+ if name.endswith(".pdf"):
39
+ return extract_text_from_pdf(file.name)
40
+ elif name.endswith(".txt"):
41
+ return extract_text_from_txt(file.name)
42
+ elif name.endswith(".md"):
43
+ return extract_text_from_md(file.name)
44
+ elif name.endswith(".pptx"):
45
+ return extract_text_from_pptx(file.name)
46
+ else:
47
+ return "Unsupported file type."