-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_format.py
More file actions
93 lines (78 loc) · 2.34 KB
/
Copy pathmulti_format.py
File metadata and controls
93 lines (78 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# multi_format.py
# Loaders for PDF / TXT / MD / VTT / SRT / DOCX / PPTX lecture content.
# Haofei Sun - CSE 5360
import re
from pathlib import Path
def load_text(path: str) -> str:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
def load_pdf(path: str) -> str:
try:
from pypdf import PdfReader
except ImportError:
return load_text(path)
reader = PdfReader(path)
return "\n\n".join((page.extract_text() or "") for page in reader.pages)
def load_vtt(path: str) -> str:
"""WebVTT — drop timing lines and indices, keep speech."""
raw = load_text(path)
lines = []
for line in raw.splitlines():
line = line.strip()
if "-->" in line:
continue
if line.upper().startswith("WEBVTT"):
continue
if re.match(r"^\d+$", line):
continue
if line:
lines.append(line)
return " ".join(lines)
def load_srt(path: str) -> str:
"""SRT — same as VTT but with index lines."""
raw = load_text(path)
lines = []
for line in raw.splitlines():
line = line.strip()
if "-->" in line:
continue
if re.match(r"^\d+$", line):
continue
if line:
lines.append(line)
return " ".join(lines)
def load_docx(path: str) -> str:
try:
from docx import Document
except ImportError:
return ""
doc = Document(path)
return "\n".join(p.text for p in doc.paragraphs if p.text.strip())
def load_pptx(path: str) -> str:
try:
from pptx import Presentation
except ImportError:
return ""
prs = Presentation(path)
chunks = []
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text") and shape.text.strip():
chunks.append(shape.text)
return "\n".join(chunks)
def load_any(path: str) -> str:
"""Pick a loader by extension; fall back to plain text."""
ext = Path(path).suffix.lower()
if ext == ".pdf":
return load_pdf(path)
if ext in (".txt", ".md"):
return load_text(path)
if ext == ".vtt":
return load_vtt(path)
if ext == ".srt":
return load_srt(path)
if ext == ".docx":
return load_docx(path)
if ext == ".pptx":
return load_pptx(path)
return load_text(path)