"""Bounded text extraction in a disposable process; no document bytes enter Lua.""" import codecs import json import shutil import subprocess import sys import zipfile from pathlib import Path from docx import Document from docx.table import Table from docx.text.paragraph import Paragraph class TextBuffer: def __init__(self, maximum): self.maximum = maximum self.parts = [] self.size = 0 self.partial = False def add(self, text): raw = text.encode("utf-8") available = self.maximum - self.size if len(raw) > available: raw = raw[:available].decode("utf-8", errors="ignore").encode("utf-8") self.partial = True self.parts.append(raw.decode("utf-8")) self.size += len(raw) def result(self): return "".join(self.parts), "partial" if self.partial else "complete" def docx_text(path, limits): # Inspect every archive member before python-docx expands any XML. with zipfile.ZipFile(path) as archive: entries = archive.infolist() if ( len(entries) > limits["max_attachment_zip_entries"] or sum(entry.file_size for entry in entries) > limits["max_attachment_unpacked_bytes"] ): raise ValueError("archive limit") if any(entry.flag_bits & 1 for entry in entries): raise ValueError("encrypted archive") if "word/document.xml" not in archive.namelist(): raise ValueError("not a Word document") document = Document(path) buffer = TextBuffer(limits["max_attachment_text_bytes"]) def blocks(container): for block in container.iter_inner_content(): if isinstance(block, Paragraph): buffer.add(block.text + "\n") elif isinstance(block, Table): for row in block.rows: seen = set() for cell in row.cells: # A merged cell appears repeatedly in row.cells. if cell._tc in seen: continue seen.add(cell._tc) blocks(cell) if buffer.partial: return if buffer.partial: return blocks(document) return buffer.result() def extract(path, declared_type, limits): detected = declared_type try: with path.open("rb") as source: signature = source.read(8) if declared_type == "txt": raw = path.read_bytes() if raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)): raise ValueError("unsupported encoding") encoding = ( "utf-16" if raw.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)) else "utf-8-sig" ) text = raw.decode(encoding, errors="strict") if "\x00" in text: raise ValueError("binary content") buffer = TextBuffer(limits["max_attachment_text_bytes"]) buffer.add(text) text, status = buffer.result() elif declared_type == "docx": if not signature.startswith(b"PK"): raise ValueError("invalid docx") text, status = docx_text(path, limits) elif declared_type == "doc": if signature != bytes.fromhex("d0cf11e0a1b11ae1"): raise ValueError("invalid doc") executable = shutil.which("soffice") or shutil.which("libreoffice") if not executable: raise ValueError("converter unavailable") profile = path.parent / "lo-profile" profile.mkdir() (profile / "user").mkdir() (profile / "user" / "registrymodifications.xcu").write_text( '' '' '3' "", encoding="utf-8", ) subprocess.run( [ executable, f"-env:UserInstallation={profile.as_uri()}", "--headless", "--nologo", "--nodefault", "--norestore", "--convert-to", "docx", "--outdir", str(path.parent), str(path), ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, # The supervisor owns the deadline and kills the entire process tree. ) converted = path.with_suffix(".docx") if converted.stat().st_size > limits["max_attachment_unpacked_bytes"]: raise ValueError("conversion limit") text, status = docx_text(converted, limits) else: return {"text": "", "extraction_status": "unsupported", "detected_type": "unknown"} return {"text": text, "extraction_status": status, "detected_type": detected} except Exception: # Never expose parser errors, local paths or document fragments. return {"text": "", "extraction_status": "failed", "detected_type": detected} def main(): path = Path(sys.argv[1]) limits = json.loads(sys.argv[3]) result = extract(path, sys.argv[2], limits) Path(sys.argv[4]).write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8") if __name__ == "__main__": main()