forge
Explore
Log in

Don't you dare go Hollow

hezarfen_text_to_podcast

Clone
★ 0

0 watching0 forksPython351.2 KiBbca8bffAhmet Kaan Gümüş2 months ago27 commits

extract.py361 lines, 10.9 KiBHistoryRawDownload
1from __future__ import annotations
2
3import re
4import shutil
5import subprocess
6import zipfile
7from pathlib import Path
8from xml.etree import ElementTree
9
10KIND_PDF = "pdf"
11KIND_DOCX = "docx"
12KIND_PPTX = "pptx"
13KIND_ODT = "odt"
14KIND_ODP = "odp"
15KIND_TEXT = "text"
16KIND_SHEET = "sheet"
17KIND_RTF = "rtf"
18KIND_OLE = "ole"
19KIND_ZIP = "zip"
20KIND_UNKNOWN = "unknown"
21
22UNSUPPORTED_SOURCE = "unsupported_source"
23SOURCE_UNREADABLE = "source_unreadable"
24EXTRACTOR_UNAVAILABLE = "extractor_unavailable"
25NO_TEXT_LAYER = "no_text_layer"
26
27PDF_MAGIC = b"%PDF-"
28ZIP_MAGIC = b"PK\x03\x04"
29ZIP_EMPTY_MAGIC = b"PK\x05\x06"
30OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
31RTF_MAGIC = b"{\\rtf"
32MAGIC_BYTES = 8
33
34TEXT_PROBE_BYTES = 4096
35TEXT_PRINTABLE_RATIO = 0.9
36TEXT_ENCODINGS = ("utf-8-sig", "cp1254", "latin-1")
37
38WORD_NS = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
39DRAWING_NS = "{http://schemas.openxmlformats.org/drawingml/2006/main}"
40
41DOCX_BODY = "word/document.xml"
42PPTX_ROOT = "ppt/presentation.xml"
43XLSX_ROOT = "xl/workbook.xml"
44SLIDE_PATTERN = re.compile(r"^ppt/slides/slide(\d+)\.xml$")
45
46ODF_MIMETYPE = "mimetype"
47ODF_CONTENT = "content.xml"
48ODF_TEXT_MIME = "application/vnd.oasis.opendocument.text"
49ODF_PRESENTATION_MIME = "application/vnd.oasis.opendocument.presentation"
50ODF_SHEET_MIME = "application/vnd.oasis.opendocument.spreadsheet"
51
52TEXT_NS = "{urn:oasis:names:tc:opendocument:xmlns:text:1.0}"
53DRAW_NS = "{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}"
54
55MAX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
56MAX_MEMBER_BYTES = 16 * 1024 * 1024
57MAX_TEXT_BYTES = 16 * 1024 * 1024
58
59READABLE_KINDS = (KIND_PDF, KIND_DOCX, KIND_PPTX, KIND_ODT, KIND_ODP, KIND_TEXT, KIND_OLE)
60SUPPORTED_NOTE = (
61 "desteklenen bicimler: pdf, docx, pptx, doc, ppt, odt, odp, duz metin"
62)
63
64OLE_TOOLS = ("antiword", "catppt")
65OLE_TIMEOUT_SECS = 60
66
67SHEET_HINT = (
68 "hesap tablosu (.xlsx/.ods) anlatima uygun degil; ders metnini "
69 "belge olarak yukleyin"
70)
71RTF_HINT = (
72 "rtf desteklenmiyor; dosyayi .docx veya .odt olarak kaydedip "
73 "yeniden yukleyin"
74)
75
76
77class ExtractError(Exception):
78 def __init__(self, code: str, message: str) -> None:
79 super().__init__(message)
80 self.code = code
81
82
83def _head(path: str | Path, size: int = MAGIC_BYTES) -> bytes:
84 try:
85 with open(path, "rb") as handle:
86 return handle.read(size)
87 except OSError as exc:
88 raise ExtractError(
89 SOURCE_UNREADABLE, f"kaynak dosya okunamadi: {exc}"
90 ) from exc
91
92
93def _odf_kind(names: set[str], archive: zipfile.ZipFile) -> str | None:
94 if ODF_MIMETYPE not in names:
95 return None
96 try:
97 declared = archive.read(ODF_MIMETYPE).decode("ascii", "replace").strip()
98 except (KeyError, OSError, zipfile.BadZipFile):
99 return None
100 if declared == ODF_TEXT_MIME:
101 return KIND_ODT
102 if declared == ODF_PRESENTATION_MIME:
103 return KIND_ODP
104 if declared == ODF_SHEET_MIME:
105 return KIND_SHEET
106 return None
107
108
109def _zip_kind(path: str | Path) -> str:
110 try:
111 with zipfile.ZipFile(path) as archive:
112 names = set(archive.namelist())
113 odf = _odf_kind(names, archive)
114 except (zipfile.BadZipFile, OSError) as exc:
115 raise ExtractError(
116 SOURCE_UNREADABLE, f"zip tabanli belge acilamadi: {exc}"
117 ) from exc
118 if odf is not None:
119 return odf
120 if DOCX_BODY in names:
121 return KIND_DOCX
122 if PPTX_ROOT in names or any(SLIDE_PATTERN.match(name) for name in names):
123 return KIND_PPTX
124 if XLSX_ROOT in names:
125 return KIND_SHEET
126 return KIND_ZIP
127
128
129def _looks_like_text(probe: bytes) -> bool:
130 if not probe:
131 return False
132 if b"\x00" in probe:
133 return False
134 for encoding in TEXT_ENCODINGS:
135 try:
136 decoded = probe.decode(encoding)
137 except (UnicodeDecodeError, LookupError):
138 continue
139 printable = sum(
140 1 for char in decoded if char.isprintable() or char in "\t\n\r"
141 )
142 return printable / len(decoded) >= TEXT_PRINTABLE_RATIO
143 return False
144
145
146def sniff(path: str | Path) -> str:
147 head = _head(path)
148 if head.startswith(PDF_MAGIC):
149 return KIND_PDF
150 if head.startswith(OLE_MAGIC):
151 return KIND_OLE
152 if head.startswith(RTF_MAGIC):
153 return KIND_RTF
154 if head.startswith(ZIP_MAGIC) or head.startswith(ZIP_EMPTY_MAGIC):
155 return _zip_kind(path)
156 if _looks_like_text(_head(path, TEXT_PROBE_BYTES)):
157 return KIND_TEXT
158 return KIND_UNKNOWN
159
160
161def _guard_size(archive: zipfile.ZipFile, members: list[str]) -> None:
162 total = 0
163 for name in members:
164 try:
165 size = archive.getinfo(name).file_size
166 except KeyError:
167 continue
168 if size > MAX_MEMBER_BYTES:
169 raise ExtractError(
170 SOURCE_UNREADABLE,
171 f"{name} acildiginda {size} bayt; uye siniri "
172 f"{MAX_MEMBER_BYTES} bayt",
173 )
174 total += size
175 if total > MAX_UNCOMPRESSED_BYTES:
176 raise ExtractError(
177 SOURCE_UNREADABLE,
178 f"belge acildiginda {MAX_UNCOMPRESSED_BYTES} bayt sinirini asiyor",
179 )
180
181
182def _parse_member(archive: zipfile.ZipFile, name: str) -> ElementTree.Element:
183 try:
184 raw = archive.read(name)
185 except (KeyError, OSError, zipfile.BadZipFile) as exc:
186 raise ExtractError(
187 SOURCE_UNREADABLE, f"{name} okunamadi: {exc}"
188 ) from exc
189 try:
190 return ElementTree.fromstring(raw)
191 except ElementTree.ParseError as exc:
192 raise ExtractError(
193 SOURCE_UNREADABLE, f"{name} xml olarak ayristirilamadi: {exc}"
194 ) from exc
195
196
197def _paragraph_text(paragraph: ElementTree.Element) -> str:
198 parts: list[str] = []
199 for node in paragraph.iter():
200 if node.tag == f"{WORD_NS}t":
201 parts.append(node.text or "")
202 elif node.tag == f"{WORD_NS}tab":
203 parts.append(" ")
204 elif node.tag in (f"{WORD_NS}br", f"{WORD_NS}cr"):
205 parts.append("\n")
206 return "".join(parts).strip()
207
208
209def docx_blocks(path: str | Path) -> list[str]:
210 try:
211 with zipfile.ZipFile(path) as archive:
212 _guard_size(archive, [DOCX_BODY])
213 root = _parse_member(archive, DOCX_BODY)
214 except zipfile.BadZipFile as exc:
215 raise ExtractError(SOURCE_UNREADABLE, f"docx acilamadi: {exc}") from exc
216 blocks: list[str] = []
217 for paragraph in root.iter(f"{WORD_NS}p"):
218 text = _paragraph_text(paragraph)
219 if text:
220 blocks.append(text)
221 return blocks
222
223
224def _slide_names(archive: zipfile.ZipFile) -> list[str]:
225 numbered: list[tuple[int, str]] = []
226 for name in archive.namelist():
227 match = SLIDE_PATTERN.match(name)
228 if match is not None:
229 numbered.append((int(match.group(1)), name))
230 numbered.sort()
231 return [name for _, name in numbered]
232
233
234def pptx_slides(path: str | Path) -> list[str]:
235 try:
236 with zipfile.ZipFile(path) as archive:
237 names = _slide_names(archive)
238 _guard_size(archive, names)
239 slides: list[str] = []
240 for name in names:
241 root = _parse_member(archive, name)
242 parts = [
243 node.text
244 for node in root.iter(f"{DRAWING_NS}t")
245 if node.text and node.text.strip()
246 ]
247 slides.append("\n".join(part.strip() for part in parts))
248 except zipfile.BadZipFile as exc:
249 raise ExtractError(SOURCE_UNREADABLE, f"pptx acilamadi: {exc}") from exc
250 return slides
251
252
253def _odf_root(path: str | Path, label: str) -> ElementTree.Element:
254 try:
255 with zipfile.ZipFile(path) as archive:
256 _guard_size(archive, [ODF_CONTENT])
257 return _parse_member(archive, ODF_CONTENT)
258 except zipfile.BadZipFile as exc:
259 raise ExtractError(
260 SOURCE_UNREADABLE, f"{label} acilamadi: {exc}"
261 ) from exc
262
263
264def _odf_paragraphs(scope: ElementTree.Element) -> list[str]:
265 wanted = (f"{TEXT_NS}p", f"{TEXT_NS}h")
266 consumed: set[int] = set()
267 blocks: list[str] = []
268 for node in scope.iter():
269 if node.tag not in wanted or id(node) in consumed:
270 continue
271 for nested in node.iter():
272 consumed.add(id(nested))
273 text = "".join(node.itertext()).strip()
274 if text:
275 blocks.append(text)
276 return blocks
277
278
279def odt_blocks(path: str | Path) -> list[str]:
280 return _odf_paragraphs(_odf_root(path, "odt"))
281
282
283def odp_slides(path: str | Path) -> list[str]:
284 root = _odf_root(path, "odp")
285 slides: list[str] = []
286 for page in root.iter(f"{DRAW_NS}page"):
287 slides.append("\n".join(_odf_paragraphs(page)))
288 return slides
289
290
291def _decoded_blocks(raw: bytes) -> list[str]:
292 for encoding in TEXT_ENCODINGS:
293 try:
294 decoded = raw.decode(encoding)
295 except (UnicodeDecodeError, LookupError):
296 continue
297 blocks = [
298 block.strip()
299 for block in re.split(r"\n\s*\n", decoded.replace("\r\n", "\n"))
300 ]
301 return [block for block in blocks if block]
302 raise ExtractError(SOURCE_UNREADABLE, "duz metin cozulemedi")
303
304
305def text_blocks(path: str | Path) -> list[str]:
306 raw = _head(path, MAX_TEXT_BYTES + 1)
307 if len(raw) > MAX_TEXT_BYTES:
308 raise ExtractError(
309 SOURCE_UNREADABLE,
310 f"duz metin {MAX_TEXT_BYTES} bayt sinirini asiyor",
311 )
312 return _decoded_blocks(raw)
313
314
315def ole_blocks(path: str | Path) -> list[str]:
316 outputs: list[bytes] = []
317 available = False
318 for tool in OLE_TOOLS:
319 binary = shutil.which(tool)
320 if binary is None:
321 continue
322 available = True
323 try:
324 result = subprocess.run(
325 [binary, str(path)],
326 capture_output=True,
327 timeout=OLE_TIMEOUT_SECS,
328 )
329 except subprocess.TimeoutExpired as exc:
330 raise ExtractError(
331 SOURCE_UNREADABLE,
332 f"{tool} {OLE_TIMEOUT_SECS} sn icinde bitmedi",
333 ) from exc
334 except OSError as exc:
335 raise ExtractError(
336 SOURCE_UNREADABLE, f"{tool} calistirilamadi: {exc}"
337 ) from exc
338 if result.returncode == 0 and result.stdout.strip():
339 outputs.append(result.stdout)
340 break
341 if not outputs:
342 if not available:
343 raise ExtractError(
344 EXTRACTOR_UNAVAILABLE,
345 "antiword/catppt kurulu degil; eski doc/ppt metni "
346 "cikarilamaz",
347 )
348 raise ExtractError(
349 SOURCE_UNREADABLE, "eski doc/ppt belgesi okunamadi"
350 )
351 return _decoded_blocks(outputs[0])
352
353
354def unsupported_message(kind: str) -> str:
355 if kind == KIND_SHEET:
356 return SHEET_HINT
357 if kind == KIND_RTF:
358 return RTF_HINT
359 if kind == KIND_ZIP:
360 return f"zip tabanli ama taninan bir belge degil; {SUPPORTED_NOTE}"
361 return f"taninmayan belge bicimi; {SUPPORTED_NOTE}"