diff --git a/.gitignore b/.gitignore index 4090514..e8e4d10 100644 --- a/.gitignore +++ b/.gitignore @@ -37,5 +37,9 @@ coverage/ # Python __pycache__/ *.py[cod] +*.egg-info/ +.pytest_cache/ +*.spec .venv/ venv/ +test_data/ diff --git a/app.py b/app.py new file mode 100644 index 0000000..624c69f --- /dev/null +++ b/app.py @@ -0,0 +1,529 @@ +"""GUI for extracting attached files from Word documents.""" + +from __future__ import annotations + +import sys +import threading +import tkinter as tk +from pathlib import Path +from tkinter import filedialog, messagebox, ttk + +from extractor import ( + DiscoveredAttachment, + ExtractResult, + discover_attachments, + extract_attachments, + list_word_files, +) + + +def _enable_windows_dpi_awareness() -> None: + """Reduce blurry / oddly scaled Tk widgets on high-DPI Windows displays.""" + if sys.platform != "win32": + return + try: + import ctypes + + # SYSTEM_DPI_AWARE plays nicest with Tk on Windows + try: + ctypes.windll.shcore.SetProcessDpiAwareness(1) + return + except Exception: + pass + ctypes.windll.user32.SetProcessDPIAware() + except Exception: + pass + + +class WordAttachmentApp(tk.Tk): + def __init__(self) -> None: + super().__init__() + self.title("Word Attachment Extractor") + self.minsize(820, 560) + self.geometry("980x680") + + # Keep tk scaling consistent with the OS (avoid oversized/tiny controls) + try: + dpi = self.winfo_fpixels("1i") + self.tk.call("tk", "scaling", dpi / 72.0) + except Exception: + pass + + self.input_paths: list[Path] = [] + self.attachments: list[DiscoveredAttachment] = [] + self.selected: dict[str, bool] = {} + self.output_dir = tk.StringVar(value="") + self.include_media = tk.BooleanVar(value=False) + self.busy = False + + self._build_ui() + self._set_status("Add Word files, scan for attachments, then choose what to extract.") + + def _build_ui(self) -> None: + self.columnconfigure(0, weight=1) + self.rowconfigure(0, weight=1) + + root = ttk.Frame(self, padding=10) + root.grid(row=0, column=0, sticky="nsew") + root.columnconfigure(0, weight=1) + # Only the attachments row grows + root.rowconfigure(2, weight=1) + + # --- Header --- + header = ttk.Frame(root) + header.grid(row=0, column=0, sticky="ew", pady=(0, 8)) + ttk.Label( + header, + text="Word Attachment Extractor", + font=("Segoe UI", 14, "bold"), + ).pack(anchor=tk.W) + ttk.Label( + header, + text="Scan Word documents, pick attachments, then extract them.", + font=("Segoe UI", 9), + ).pack(anchor=tk.W, pady=(2, 0)) + + # --- Word documents (fixed height) --- + input_frame = ttk.LabelFrame(root, text="Word documents", padding=8) + input_frame.grid(row=1, column=0, sticky="ew", pady=(0, 8)) + input_frame.columnconfigure(0, weight=1) + + btn_row = ttk.Frame(input_frame) + btn_row.grid(row=0, column=0, sticky="ew") + ttk.Button(btn_row, text="Add files…", command=self._add_files).pack( + side=tk.LEFT, padx=(0, 6) + ) + ttk.Button(btn_row, text="Add folder…", command=self._add_folder).pack( + side=tk.LEFT, padx=(0, 6) + ) + ttk.Button(btn_row, text="Clear", command=self._clear_inputs).pack(side=tk.LEFT) + ttk.Button(btn_row, text="Scan attachments", command=self._start_scan).pack( + side=tk.RIGHT + ) + + self.doc_list = tk.Listbox( + input_frame, + height=3, + selectmode=tk.EXTENDED, + activestyle="dotbox", + font=("Segoe UI", 9), + ) + self.doc_list.grid(row=1, column=0, sticky="ew", pady=(6, 0)) + + # --- Attachments (only expanding section) --- + attach_frame = ttk.LabelFrame(root, text="Attachments found", padding=8) + attach_frame.grid(row=2, column=0, sticky="nsew", pady=(0, 8)) + attach_frame.columnconfigure(0, weight=1) + attach_frame.rowconfigure(1, weight=1) + + sel_row = ttk.Frame(attach_frame) + sel_row.grid(row=0, column=0, sticky="ew", pady=(0, 6)) + ttk.Button(sel_row, text="Select all", command=self._select_all).pack( + side=tk.LEFT, padx=(0, 6) + ) + ttk.Button(sel_row, text="Deselect all", command=self._deselect_all).pack( + side=tk.LEFT, padx=(0, 6) + ) + ttk.Button(sel_row, text="Invert", command=self._invert_selection).pack( + side=tk.LEFT + ) + self.attach_count = ttk.Label(sel_row, text="0 attachments") + self.attach_count.pack(side=tk.RIGHT) + + tree_wrap = ttk.Frame(attach_frame) + tree_wrap.grid(row=1, column=0, sticky="nsew") + tree_wrap.columnconfigure(0, weight=1) + tree_wrap.rowconfigure(0, weight=1) + + columns = ("selected", "name", "source", "size", "note") + self.tree = ttk.Treeview( + tree_wrap, + columns=columns, + show="headings", + selectmode="extended", + height=8, + ) + self.tree.heading("selected", text="Keep") + self.tree.heading("name", text="Attachment name") + self.tree.heading("source", text="Word document") + self.tree.heading("size", text="Size") + self.tree.heading("note", text="Details") + self.tree.column("selected", width=50, minwidth=50, stretch=False, anchor=tk.CENTER) + self.tree.column("name", width=320, minwidth=140, stretch=True) + self.tree.column("source", width=180, minwidth=100, stretch=True) + self.tree.column("size", width=80, minwidth=70, stretch=False, anchor=tk.E) + self.tree.column("note", width=150, minwidth=80, stretch=True) + self.tree.bind("", self._on_tree_click) + self.tree.bind("", self._toggle_focused) + + yscroll = ttk.Scrollbar(tree_wrap, orient=tk.VERTICAL, command=self.tree.yview) + xscroll = ttk.Scrollbar(tree_wrap, orient=tk.HORIZONTAL, command=self.tree.xview) + self.tree.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set) + self.tree.grid(row=0, column=0, sticky="nsew") + yscroll.grid(row=0, column=1, sticky="ns") + xscroll.grid(row=1, column=0, sticky="ew") + + # --- Bottom controls: always visible (never pushed off-screen) --- + bottom = ttk.Frame(root) + bottom.grid(row=3, column=0, sticky="ew") + bottom.columnconfigure(0, weight=1) + + output_frame = ttk.LabelFrame(bottom, text="Output folder", padding=8) + output_frame.grid(row=0, column=0, sticky="ew", pady=(0, 6)) + output_frame.columnconfigure(0, weight=1) + + out_row = ttk.Frame(output_frame) + out_row.grid(row=0, column=0, sticky="ew") + out_row.columnconfigure(0, weight=1) + ttk.Entry(out_row, textvariable=self.output_dir).grid( + row=0, column=0, sticky="ew", padx=(0, 6) + ) + ttk.Button(out_row, text="Browse…", command=self._choose_output).grid( + row=0, column=1 + ) + ttk.Label( + output_frame, + text="Leave blank to create a “*_attachments” folder next to each Word file.", + font=("Segoe UI", 8), + foreground="#555555", + ).grid(row=1, column=0, sticky="w", pady=(4, 0)) + + options = ttk.Frame(bottom) + options.grid(row=1, column=0, sticky="ew", pady=(0, 6)) + ttk.Checkbutton( + options, + text="Also include images/media when scanning", + variable=self.include_media, + command=self._maybe_rescan_hint, + ).pack(side=tk.LEFT) + + action_row = ttk.Frame(bottom) + action_row.grid(row=2, column=0, sticky="ew", pady=(0, 6)) + self.extract_btn = ttk.Button( + action_row, + text="Extract selected", + command=self._start_extract, + ) + self.extract_btn.pack(side=tk.LEFT) + self.progress = ttk.Progressbar(action_row, mode="indeterminate", length=200) + self.progress.pack(side=tk.LEFT, padx=(12, 0), fill=tk.X, expand=True) + + log_frame = ttk.LabelFrame(bottom, text="Results", padding=6) + log_frame.grid(row=3, column=0, sticky="ew") + log_frame.columnconfigure(0, weight=1) + self.log = tk.Text( + log_frame, + height=4, + wrap=tk.WORD, + state=tk.DISABLED, + font=("Consolas", 9), + ) + scroll = ttk.Scrollbar(log_frame, command=self.log.yview) + self.log.configure(yscrollcommand=scroll.set) + self.log.grid(row=0, column=0, sticky="ew") + scroll.grid(row=0, column=1, sticky="ns") + + self.status = ttk.Label(self, text="", relief=tk.SUNKEN, anchor=tk.W) + self.status.grid(row=1, column=0, sticky="ew") + + def _set_status(self, text: str) -> None: + self.status.configure(text=f" {text}") + + def _log(self, text: str) -> None: + self.log.configure(state=tk.NORMAL) + self.log.insert(tk.END, text + "\n") + self.log.see(tk.END) + self.log.configure(state=tk.DISABLED) + + def _clear_log(self) -> None: + self.log.configure(state=tk.NORMAL) + self.log.delete("1.0", tk.END) + self.log.configure(state=tk.DISABLED) + + def _refresh_docs(self) -> None: + self.doc_list.delete(0, tk.END) + for path in self.input_paths: + self.doc_list.insert(tk.END, str(path)) + + def _format_size(self, size: int) -> str: + if size < 1024: + return f"{size} B" + if size < 1024 * 1024: + return f"{size / 1024:.1f} KB" + return f"{size / (1024 * 1024):.1f} MB" + + def _mark(self, attachment_id: str) -> str: + # ASCII marks scale more reliably than emoji/unicode checkboxes + return "[x]" if self.selected.get(attachment_id, False) else "[ ]" + + def _refresh_attachments(self) -> None: + self.tree.delete(*self.tree.get_children()) + for item in self.attachments: + self.tree.insert( + "", + tk.END, + iid=item.id, + values=( + self._mark(item.id), + item.display_name, + item.source_doc.name, + self._format_size(item.size_bytes), + item.note, + ), + ) + selected_count = sum(1 for v in self.selected.values() if v) + self.attach_count.configure( + text=f"{len(self.attachments)} found · {selected_count} selected" + ) + + def _add_files(self) -> None: + files = filedialog.askopenfilenames( + title="Select Word documents", + filetypes=[ + ("Word documents", "*.docx *.docm"), + ("All files", "*.*"), + ], + ) + if not files: + return + for f in files: + path = Path(f) + if path not in self.input_paths: + self.input_paths.append(path) + self._refresh_docs() + count = len(list_word_files(self.input_paths)) + self._set_status(f"{count} Word file(s) ready. Click “Scan attachments”.") + + def _add_folder(self) -> None: + folder = filedialog.askdirectory(title="Select folder containing Word files") + if not folder: + return + path = Path(folder) + if path not in self.input_paths: + self.input_paths.append(path) + self._refresh_docs() + count = len(list_word_files(self.input_paths)) + self._set_status(f"{count} Word file(s) found. Click “Scan attachments”.") + + def _clear_inputs(self) -> None: + self.input_paths.clear() + self.attachments.clear() + self.selected.clear() + self._refresh_docs() + self._refresh_attachments() + self._set_status("Selection cleared.") + + def _choose_output(self) -> None: + folder = filedialog.askdirectory(title="Choose output folder") + if folder: + self.output_dir.set(folder) + + def _maybe_rescan_hint(self) -> None: + if self.attachments: + self._set_status("Media option changed — scan again to refresh the list.") + + def _set_busy(self, busy: bool) -> None: + self.busy = busy + state = tk.DISABLED if busy else tk.NORMAL + self.extract_btn.configure(state=state) + if busy: + self.progress.start(12) + else: + self.progress.stop() + + def _on_tree_click(self, event: tk.Event) -> str | None: + region = self.tree.identify_region(event.x, event.y) + if region != "cell": + return None + column = self.tree.identify_column(event.x) + row_id = self.tree.identify_row(event.y) + if not row_id: + return None + if column == "#1": + self.selected[row_id] = not self.selected.get(row_id, False) + values = list(self.tree.item(row_id, "values")) + values[0] = self._mark(row_id) + self.tree.item(row_id, values=values) + selected_count = sum(1 for v in self.selected.values() if v) + self.attach_count.configure( + text=f"{len(self.attachments)} found · {selected_count} selected" + ) + return "break" + return None + + def _toggle_focused(self, _event: tk.Event | None = None) -> str: + focused = self.tree.focus() + targets = list(self.tree.selection()) or ([focused] if focused else []) + for row_id in targets: + self.selected[row_id] = not self.selected.get(row_id, False) + values = list(self.tree.item(row_id, "values")) + if values: + values[0] = self._mark(row_id) + self.tree.item(row_id, values=values) + selected_count = sum(1 for v in self.selected.values() if v) + self.attach_count.configure( + text=f"{len(self.attachments)} found · {selected_count} selected" + ) + return "break" + + def _select_all(self) -> None: + for item in self.attachments: + self.selected[item.id] = True + self._refresh_attachments() + + def _deselect_all(self) -> None: + for item in self.attachments: + self.selected[item.id] = False + self._refresh_attachments() + + def _invert_selection(self) -> None: + for item in self.attachments: + self.selected[item.id] = not self.selected.get(item.id, False) + self._refresh_attachments() + + def _start_scan(self) -> None: + if self.busy: + return + if not self.input_paths: + messagebox.showwarning("No files selected", "Add Word files or a folder first.") + return + word_files = list_word_files(self.input_paths) + if not word_files: + messagebox.showwarning( + "No Word files", + "No .docx or .docm files were found in your selection.", + ) + return + + self._set_busy(True) + self._clear_log() + self._set_status(f"Scanning {len(word_files)} Word file(s)…") + thread = threading.Thread( + target=self._run_scan, + args=(list(self.input_paths), self.include_media.get()), + daemon=True, + ) + thread.start() + + def _run_scan(self, paths: list[Path], include_media: bool) -> None: + try: + found, errors = discover_attachments(paths, include_media=include_media) + self.after(0, lambda: self._finish_scan(found, errors, None)) + except Exception as exc: + self.after(0, lambda: self._finish_scan([], [], exc)) + + def _finish_scan( + self, + found: list[DiscoveredAttachment], + errors: list[str], + error: Exception | None, + ) -> None: + self._set_busy(False) + if error is not None: + self._log(f"ERROR: {error}") + self._set_status("Scan failed.") + messagebox.showerror("Scan failed", str(error)) + return + + self.attachments = found + self.selected = {item.id: True for item in found} + self._refresh_attachments() + + for err in errors: + self._log(f"✗ {err}") + + if not found: + self._log("No attachments found in the selected Word documents.") + self._set_status("Scan complete — nothing found.") + else: + self._log(f"Found {len(found)} attachment(s). Uncheck any you do not want.") + self._set_status( + f"Scan complete — {len(found)} attachment(s). Select what to extract." + ) + + def _start_extract(self) -> None: + if self.busy: + return + chosen = [a for a in self.attachments if self.selected.get(a.id, False)] + if not chosen: + messagebox.showwarning( + "Nothing selected", + "Scan for attachments first, then keep at least one checked.", + ) + return + + out_text = self.output_dir.get().strip() + output_root = Path(out_text) if out_text else None + + self._set_busy(True) + self._clear_log() + self._set_status(f"Extracting {len(chosen)} attachment(s)…") + thread = threading.Thread( + target=self._run_extract, + args=(chosen, output_root), + daemon=True, + ) + thread.start() + + def _run_extract( + self, + chosen: list[DiscoveredAttachment], + output_root: Path | None, + ) -> None: + try: + results = extract_attachments( + chosen, + output_root=output_root, + per_document_subfolder=True, + ) + self.after(0, lambda: self._finish_extract(results, None)) + except Exception as exc: + self.after(0, lambda: self._finish_extract([], exc)) + + def _finish_extract( + self, + results: list[ExtractResult], + error: Exception | None, + ) -> None: + self._set_busy(False) + + if error is not None: + self._log(f"ERROR: {error}") + self._set_status("Extraction failed.") + messagebox.showerror("Extraction failed", str(error)) + return + + total_files = 0 + total_errors = 0 + for result in results: + self._log(f"—— {result.source_doc.name} ——") + if result.extracted: + self._log(f" Output: {result.extracted[0].output_path.parent}") + for item in result.extracted: + total_files += 1 + self._log( + f" ✓ {item.original_name} ({item.size_bytes:,} bytes)" + ) + else: + self._log(" (nothing extracted)") + for err in result.errors: + total_errors += 1 + self._log(f" ✗ {err}") + self._log("") + + summary = f"Done. Extracted {total_files} file(s)" + if total_errors: + summary += f", {total_errors} error(s)" + summary += "." + self._set_status(summary) + messagebox.showinfo("Extraction complete", summary) + + +def main() -> None: + _enable_windows_dpi_awareness() + app = WordAttachmentApp() + app.mainloop() + + +if __name__ == "__main__": + main() diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..ed47328 --- /dev/null +++ b/build.bat @@ -0,0 +1,18 @@ +@echo off +setlocal +cd /d "%~dp0" + +echo Installing dependencies... +python -m pip install -r requirements.txt +if errorlevel 1 exit /b 1 + +echo. +echo Building WordAttachmentExtractor.exe ... +python -m PyInstaller --noconfirm --clean --onefile --windowed --name "WordAttachmentExtractor" app.py +if errorlevel 1 exit /b 1 + +echo. +echo Done. EXE is here: +echo %cd%\dist\WordAttachmentExtractor.exe +echo. +pause diff --git a/extractor.py b/extractor.py new file mode 100644 index 0000000..2e3d02a --- /dev/null +++ b/extractor.py @@ -0,0 +1,1046 @@ +"""Extract embedded / attached files from Word (.docx, .docm) documents.""" + +from __future__ import annotations + +import io +import re +import zipfile +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field +from pathlib import Path + +import olefile + +WORD_EXTENSIONS = {".docx", ".docm"} +EMBEDDINGS_PREFIX = "word/embeddings/" +MEDIA_PREFIX = "word/media/" + +REL_NS = {"r": "http://schemas.openxmlformats.org/package/2006/relationships"} +OLE_OBJECT_TYPES = { + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package", +} + +# Names Word/OLE invent that are never the user's original filename. +_JUNK_NAMES = { + "attachment", + "embedded", + "embedded.bin", + "embedded.pdf", + "embedded.doc", + "embedded.docx", + "embedded.xls", + "embedded.xlsx", + "oleobject.bin", + "ole package", + "package", + "acrobat document", + "adobe acrobat document", + "contents", + "microsoft excel worksheet", + "microsoft excel worksheet.xlsx", + "microsoft excel worksheet.xls", + "microsoft_excel_worksheet", + "microsoft_excel_worksheet.xlsx", + "microsoft_excel_worksheet.xls", + "worksheet", + "workbook", +} + +_FILE_EXT_RE = re.compile( + r"(?i)\.(pdf|docx?|xlsx?|pptx?|zip|txt|csv|rtf|msg|png|jpe?g|gif|tif{1,2}|bin)$" +) + +# ASCII-only filenames scraped from icon images (avoid UTF-16 binary noise). +_ICON_NAME_RE = re.compile( + rb"[A-Za-z0-9 ._+()\-,&'[\]]{3,200}\.(?:pdf|docx?|xlsx?|xlsm?|pptx?|zip|txt|csv|rtf|msg)", + flags=re.IGNORECASE, +) + +OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + + +@dataclass +class DiscoveredAttachment: + """One extractable attachment found inside a Word document.""" + + id: str + source_doc: Path + display_name: str + zip_path: str + kind: str # embedding | media | ole + size_bytes: int + payload: bytes = field(repr=False) + note: str = "" + + +@dataclass +class ExtractedFile: + source_doc: Path + original_name: str + output_path: Path + size_bytes: int + + +@dataclass +class ExtractResult: + source_doc: Path + extracted: list[ExtractedFile] + skipped: list[str] + errors: list[str] + + +def _safe_filename(name: str) -> str: + name = (name or "").strip().replace("\\", "/").split("/")[-1] + name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", name) + name = name.strip(". ") + return name or "attachment" + + +def _is_junk_name(name: str | None) -> bool: + if not name: + return True + cleaned = _safe_filename(name) + lower = cleaned.lower() + if lower in _JUNK_NAMES: + return True + # word/embeddings part names like oleObject1.bin / oleObject12.bin + if re.fullmatch(r"oleobject\d*\.bin", lower): + return True + if re.fullmatch(r"image\d+\.(emf|wmf|png|jpe?g|bin)", lower): + return True + return False + + +def _unique_path(directory: Path, filename: str) -> Path: + path = directory / filename + if not path.exists(): + return path + stem = path.stem + suffix = path.suffix + counter = 1 + while True: + candidate = directory / f"{stem}_{counter}{suffix}" + if not candidate.exists(): + return candidate + counter += 1 + + +def _carve_pdf(data: bytes) -> bytes | None: + """Find a PDF payload inside raw bytes (Acrobat OLE often wraps it).""" + start = data.find(b"%PDF") + if start < 0: + return None + end = data.rfind(b"%%EOF") + if end < start: + return data[start:] + end = end + 5 + while end < len(data) and data[end] in (0x0A, 0x0D, 0x00, 0x20): + end += 1 + return data[start:end] + + +def _carve_zip(data: bytes) -> bytes | None: + """Find a ZIP/OOXML payload that may be nested inside an OLE stream.""" + start = data.find(b"PK\x03\x04") + if start < 0: + return None + candidate = data[start:] + if zipfile.is_zipfile(io.BytesIO(candidate)): + return candidate + return None + + +def _ooxml_extension(data: bytes) -> str | None: + """If data is an Office Open XML zip, return .xlsx / .docx / .pptx / etc.""" + if data[:4] != b"PK\x03\x04" and not zipfile.is_zipfile(io.BytesIO(data)): + carved = _carve_zip(data) + if not carved: + return None + data = carved + try: + with zipfile.ZipFile(io.BytesIO(data)) as zf: + names = {n.lower() for n in zf.namelist()} + if any(n.startswith("xl/") for n in names): + if any("vbaproject" in n for n in names): + return ".xlsm" + return ".xlsx" + if any(n.startswith("word/") for n in names): + return ".docx" + if any(n.startswith("ppt/") for n in names): + return ".pptx" + # content types fallback + if "[content_types].xml" in names: + try: + ct = zf.read("[Content_Types].xml").decode("utf-8", errors="ignore").lower() + except Exception: + ct = "" + if "spreadsheetml" in ct: + return ".xlsx" + if "wordprocessingml" in ct: + return ".docx" + if "presentationml" in ct: + return ".pptx" + except zipfile.BadZipFile: + return None + return None + + +def _ole_stream_names(ole: olefile.OleFileIO) -> set[str]: + names: set[str] = set() + for entry in ole.listdir(): + names.add(entry[-1].lstrip("\x01").lower()) + return names + + +def _detect_kind(data: bytes) -> str: + """Return a short kind / extension hint from magic bytes / structure.""" + if not data: + return "bin" + if data.startswith(b"%PDF") or 0 <= data.find(b"%PDF") < 2048: + return "pdf" + + # OLE before zip checks — Excel .xls files are OLE and can contain stray PK bytes. + if data[:8] == OLE_MAGIC or olefile.isOleFile(io.BytesIO(data)): + try: + ole = olefile.OleFileIO(io.BytesIO(data)) + try: + streams = _ole_stream_names(ole) + if "workbook" in streams or "book" in streams: + return "xls" + if "worddocument" in streams: + return "doc" + if "powerpoint document" in streams: + return "ppt" + finally: + ole.close() + except Exception: + pass + return "ole" + + if data[:4] == b"PK\x03\x04" or zipfile.is_zipfile(io.BytesIO(data)): + ooxml = _ooxml_extension(data) + if ooxml: + return ooxml.lstrip(".") + return "zip" + + if data[:2] == b"BM": + return "bmp" + if data[:3] == b"\xff\xd8\xff": + return "jpg" + if data[:8] == b"\x89PNG\r\n\x1a\n": + return "png" + return "bin" + + +def _extension_for(data: bytes, hint_name: str | None = None) -> str: + kind = _detect_kind(data) + kind_to_ext = { + "pdf": ".pdf", + "png": ".png", + "jpg": ".jpg", + "bmp": ".bmp", + "xlsx": ".xlsx", + "xlsm": ".xlsm", + "docx": ".docx", + "pptx": ".pptx", + "xls": ".xls", + "doc": ".doc", + "ppt": ".ppt", + "zip": ".zip", + } + if kind in kind_to_ext: + return kind_to_ext[kind] + + hint_suffix = "" + if hint_name: + hint_suffix = Path(_safe_filename(hint_name)).suffix.lower() + + if kind == "ole": + # Never trust an OOXML extension for a raw OLE container. + if hint_suffix in {".xls", ".doc", ".ppt", ".msg"}: + return hint_suffix + return ".bin" + + if hint_suffix and hint_suffix != ".bin": + return hint_suffix + return ".bin" + + +def _repair_xlsx_for_standalone(data: bytes) -> bytes: + """ + Word embeds Excel with workbookView visibility=\"hidden\". + That still previews in Explorer, but double-click opens a blank/black Excel window. + Make the workbook viewable when opened on its own. + """ + if not zipfile.is_zipfile(io.BytesIO(data)): + return data + try: + source = zipfile.ZipFile(io.BytesIO(data), "r") + except zipfile.BadZipFile: + return data + + try: + if "xl/workbook.xml" not in source.namelist(): + return data + workbook_xml = source.read("xl/workbook.xml").decode("utf-8", errors="replace") + original = workbook_xml + workbook_xml = re.sub( + r'\bvisibility="(?:hidden|veryHidden)"', + 'visibility="visible"', + workbook_xml, + flags=re.IGNORECASE, + ) + # If every sheet is hidden, unhide them so Excel has something to show + sheet_states = re.findall(r']*>', workbook_xml, flags=re.IGNORECASE) + if sheet_states and all(re.search(r'\bstate="(?:hidden|veryHidden)"', s, re.I) for s in sheet_states): + workbook_xml = re.sub( + r'(]*?)\sstate="(?:hidden|veryHidden)"', + r"\1", + workbook_xml, + flags=re.IGNORECASE, + ) + if workbook_xml == original: + return data + + out = io.BytesIO() + with zipfile.ZipFile(out, "w") as target: + for info in source.infolist(): + payload = source.read(info.filename) + if info.filename == "xl/workbook.xml": + payload = workbook_xml.encode("utf-8") + # Keep entries compressible; Excel accepts standard deflate packages + compress = ( + zipfile.ZIP_STORED + if info.compress_type == zipfile.ZIP_STORED + else zipfile.ZIP_DEFLATED + ) + target.writestr(info.filename, payload, compress_type=compress) + return out.getvalue() + except Exception: + return data + finally: + source.close() + + +def _normalize_payload(data: bytes) -> tuple[bytes, str]: + """Return (payload, kind), unwrapping PDFs / OOXML buried in containers.""" + if not data: + return data, "bin" + + # Whole OLE compound files must stay intact (.xls/.doc). Nested OOXML is + # extracted from Package/CONTENTS streams by the OLE walker instead. + if data[:8] == OLE_MAGIC or olefile.isOleFile(io.BytesIO(data)): + return data, _detect_kind(data) + + # PDF directly or lightly wrapped + if data.startswith(b"%PDF") or 0 <= data.find(b"%PDF") < 4096: + carved_pdf = _carve_pdf(data) + if carved_pdf: + return carved_pdf, "pdf" + + # OOXML / zip + if data[:4] == b"PK\x03\x04" or zipfile.is_zipfile(io.BytesIO(data)): + ext = _ooxml_extension(data) + if ext in {".xlsx", ".xlsm"}: + return _repair_xlsx_for_standalone(data), ext.lstrip(".") + if ext: + return data, ext.lstrip(".") + return data, "zip" + + carved_zip = _carve_zip(data) + if carved_zip: + ext = _ooxml_extension(carved_zip) + if ext in {".xlsx", ".xlsm"}: + return _repair_xlsx_for_standalone(carved_zip), ext.lstrip(".") + if ext: + return carved_zip, ext.lstrip(".") + return carved_zip, "zip" + + return data, _detect_kind(data) + + +def _best_name(*candidates: str | None, data: bytes | None = None) -> str: + ranked: list[str] = [] + for c in candidates: + if _is_junk_name(c): + continue + cleaned = _safe_filename(c) # type: ignore[arg-type] + # Reject mostly-non-ascii garbage scraped from EMF binaries + ascii_ratio = sum(1 for ch in cleaned if ord(ch) < 128) / max(len(cleaned), 1) + if ascii_ratio < 0.8: + continue + ranked.append(cleaned) + + chosen: str | None = None + if ranked: + with_ext = [n for n in ranked if _FILE_EXT_RE.search(n)] + chosen = with_ext[0] if with_ext else ranked[0] + + if not chosen: + chosen = "attachment" + + # Always force extension to match actual payload bytes + if data is not None: + ext = _extension_for(data, chosen) + stem = Path(chosen).stem or "attachment" + chosen = f"{stem}{ext}" + + return _safe_filename(chosen) + + +def _read_cstring(buf: bytes, start: int) -> tuple[str, int] | None: + end = buf.find(b"\x00", start) + if end < 0: + return None + text = buf[start:end].decode("latin-1", errors="replace") + return text, end + 1 + + +def _read_len_prefixed_ansi(buf: bytes, start: int) -> tuple[str, int] | None: + if start + 4 > len(buf): + return None + length = int.from_bytes(buf[start : start + 4], "little") + start += 4 + if length < 0 or start + length > len(buf): + return None + raw = buf[start : start + length] + if raw.endswith(b"\x00"): + raw = raw[:-1] + return raw.decode("latin-1", errors="replace"), start + length + + +def _read_len_prefixed_utf16(buf: bytes, start: int) -> tuple[str, int] | None: + if start + 4 > len(buf): + return None + length = int.from_bytes(buf[start : start + 4], "little") + start += 4 + if length < 0 or start + length > len(buf): + return None + raw = buf[start : start + length] + if len(raw) >= 2 and raw.endswith(b"\x00\x00"): + raw = raw[:-2] + try: + text = raw.decode("utf-16-le", errors="replace") + except Exception: + return None + return text, start + length + + +def _parse_ole10_native(data: bytes) -> tuple[str, bytes] | None: + """Parse Ole10Native / OLE Package stream into (original_filename, file_bytes).""" + if len(data) < 10: + return None + + offset = 0 + _ = int.from_bytes(data[offset : offset + 4], "little") + offset += 4 + + if offset + 2 <= len(data): + sig = int.from_bytes(data[offset : offset + 2], "little") + if sig == 0x0002: + offset += 2 + + while offset < len(data) and data[offset] == 0: + offset += 1 + + label_result = _read_cstring(data, offset) + if not label_result: + return None + label, offset = label_result + + path_result = _read_cstring(data, offset) + if not path_result: + return None + src_path, offset = path_result + + unicode_name: str | None = None + file_bytes: bytes | None = None + + if offset + 8 <= len(data): + unused = data[offset : offset + 2] + fmt = int.from_bytes(data[offset + 2 : offset + 4], "little") + probe = offset + 4 + temp = _read_len_prefixed_ansi(data, probe) + if temp is not None and unused == b"\x00\x00" and fmt in (0x0001, 0x0003): + _temp_path, probe = temp + if fmt == 0x0003 and probe + 4 <= len(data): + size = int.from_bytes(data[probe : probe + 4], "little") + probe += 4 + if 0 <= size <= len(data) - probe: + file_bytes = data[probe : probe + size] + probe += size + u_name = _read_len_prefixed_utf16(data, probe) + if u_name: + unicode_name, probe = u_name + u_path = _read_len_prefixed_utf16(data, probe) + if u_path and not unicode_name: + unicode_name = u_path[0] + + if file_bytes is None: + classic_off = offset + if classic_off + 6 > len(data): + return None + classic_off += 2 + if classic_off + 4 > len(data): + return None + temp_len = int.from_bytes(data[classic_off : classic_off + 4], "little") + classic_off += 4 + if temp_len < 0 or classic_off + temp_len + 4 > len(data): + return None + classic_off += temp_len + size = int.from_bytes(data[classic_off : classic_off + 4], "little") + classic_off += 4 + if size < 0 or classic_off + size > len(data): + return None + file_bytes = data[classic_off : classic_off + size] + classic_off += size + u_name = _read_len_prefixed_utf16(data, classic_off) + if u_name: + unicode_name = u_name[0] + + if not file_bytes: + return None + + file_bytes, _kind = _normalize_payload(file_bytes) + filename = _best_name(unicode_name, label, src_path, data=file_bytes) + return filename, file_bytes + + +def _compobj_user_type(ole: olefile.OleFileIO) -> str | None: + for entry in ole.listdir(): + if entry[-1].lstrip("\x01") == "CompObj": + try: + data = ole.openstream(entry).read() + except Exception: + return None + text = data.decode("latin-1", errors="ignore") + for marker in ("OLE Package", "Package", "Acrobat Document", "Adobe Acrobat Document"): + if marker in text: + return marker + chunk = data[28:] + end = chunk.find(b"\x00") + if end > 0: + return chunk[:end].decode("latin-1", errors="ignore") + return None + + +def _filenames_from_icon_bytes(data: bytes) -> list[str]: + """ + Pull filename-like strings from EMF/WMF icon images. + Word often only stores the attachment caption inside these icons. + """ + found: list[str] = [] + + # UTF-16LE as ASCII code units only (high bytes zero) — avoids binary noise + chars: list[str] = [] + for i in range(0, len(data) - 1, 2): + lo, hi = data[i], data[i + 1] + if hi == 0 and 32 <= lo < 127: + chars.append(chr(lo)) + else: + chars.append("\n") + utf16_ascii = "".join(chars) + for match in re.finditer( + r"[A-Za-z0-9 ._+()\-,&'[\]]{3,200}\.(?:pdf|docx?|xlsx?|xlsm?|pptx?|zip|txt|csv|rtf|msg)", + utf16_ascii, + flags=re.IGNORECASE, + ): + found.append(match.group(0).strip()) + + for match in _ICON_NAME_RE.finditer(data): + found.append(match.group(0).decode("ascii", errors="ignore").strip()) + + unique: list[str] = [] + for name in sorted({_safe_filename(n) for n in found}, key=len, reverse=True): + if _is_junk_name(name): + continue + if any(u.endswith(name) and u != name for u in unique): + continue + unique.append(name) + return unique + + +def _extract_from_ole_bin( + ole_bytes: bytes, + preferred_name: str | None = None, +) -> list[tuple[str, bytes, str]]: + """Pull packaged files out of an OLE compound document.""" + results: list[tuple[str, bytes, str]] = [] + + def add(fname: str | None, payload: bytes, note: str) -> None: + payload, _kind = _normalize_payload(payload) + name = _best_name(preferred_name, fname, data=payload) + results.append((name, payload, note)) + + # Non-OLE container: still try to carve useful payloads + if not olefile.isOleFile(io.BytesIO(ole_bytes)): + payload, kind = _normalize_payload(ole_bytes) + if kind != "bin": + add(preferred_name, payload, f"raw {kind}") + return results + + try: + ole = olefile.OleFileIO(io.BytesIO(ole_bytes)) + except Exception: + payload, kind = _normalize_payload(ole_bytes) + if kind != "bin": + add(preferred_name, payload, f"carved {kind}") + return results + + try: + user_type = _compobj_user_type(ole) or "" + streams = _ole_stream_names(ole) + + # Classic Excel workbook: the OLE file itself is a valid .xls + if "workbook" in streams or "book" in streams: + if "ole10native" not in streams and "package" not in streams: + add(preferred_name, ole_bytes, "Excel workbook OLE (.xls)") + return results + + # Classic Word: whole OLE is a valid .doc + if "worddocument" in streams and "ole10native" not in streams and "package" not in streams: + if "contents" not in streams: + add(preferred_name, ole_bytes, "Word document OLE (.doc)") + return results + + for entry in ole.listdir(): + leaf = entry[-1] + lower_leaf = leaf.lower().lstrip("\x01") + is_ole10 = "ole10native" in lower_leaf + is_package = leaf in ("CONTENTS", "Package") or lower_leaf == "package" + if not is_ole10 and not is_package: + continue + + try: + stream_data = ole.openstream(entry).read() + except Exception: + continue + + if is_ole10: + parsed = _parse_ole10_native(stream_data) + if parsed: + fname, fbytes = parsed + add(fname, fbytes, "OLE Package") + else: + payload, kind = _normalize_payload(stream_data) + if kind != "bin": + add(preferred_name, payload, f"carved {kind} from Ole10Native") + continue + + # CONTENTS / Package may be OOXML, PDF, or nested OLE + if stream_data[:8] == OLE_MAGIC or olefile.isOleFile(io.BytesIO(stream_data)): + nested = _extract_from_ole_bin(stream_data, preferred_name=preferred_name) + if nested: + results.extend(nested) + continue + + payload, kind = _normalize_payload(stream_data) + note = user_type or "OLE CONTENTS" + if kind == "pdf": + note = "Acrobat / PDF OLE" + elif kind in {"xlsx", "xlsm"}: + note = "Excel workbook" + elif kind == "xls": + note = "Excel workbook OLE (.xls)" + elif kind == "docx": + note = "Word document" + add(preferred_name, payload, note) + + if not results: + # Carve from any stream / whole file + for entry in ole.listdir(): + try: + stream_data = ole.openstream(entry).read() + except Exception: + continue + payload, kind = _normalize_payload(stream_data) + if kind in {"pdf", "xlsx", "xlsm", "docx", "pptx", "zip"}: + add(preferred_name, payload, f"carved {kind}") + break + if not results: + payload, kind = _normalize_payload(ole_bytes) + if kind in {"pdf", "xlsx", "xlsm", "docx", "pptx", "xls", "doc"}: + add(preferred_name, payload, f"carved {kind}") + elif "excel" in user_type.lower(): + # Excel-tagged OLE with no Package stream: treat as .xls + add(preferred_name, ole_bytes, "Excel OLE (.xls)") + finally: + ole.close() + + return results + + +def _is_word_package(path: Path) -> bool: + return path.suffix.lower() in WORD_EXTENSIONS and zipfile.is_zipfile(path) + + +def list_word_files(paths: list[Path], recurse: bool = True) -> list[Path]: + files: list[Path] = [] + for path in paths: + if path.is_file() and path.suffix.lower() in WORD_EXTENSIONS: + files.append(path) + elif path.is_dir(): + pattern = "**/*" if recurse else "*" + for child in path.glob(pattern): + if child.is_file() and child.suffix.lower() in WORD_EXTENSIONS: + files.append(child) + seen: set[Path] = set() + unique: list[Path] = [] + for f in sorted(files, key=lambda p: str(p).lower()): + resolved = f.resolve() + if resolved not in seen: + seen.add(resolved) + unique.append(f) + return unique + + +def _local_name(tag: str) -> str: + if "}" in tag: + return tag.rsplit("}", 1)[-1] + return tag + + +def _normalize_zip_target(target: str) -> str: + target = target.replace("\\", "/").split("?")[0] + if target.startswith("/"): + target = target.lstrip("/") + if not target.startswith("word/"): + target = f"word/{target.lstrip('./')}" + return target + + +def _relationship_map(zf: zipfile.ZipFile) -> dict[str, tuple[str, str]]: + """Map rId -> (zip_target, type) from document relationships.""" + mapping: dict[str, tuple[str, str]] = {} + rels_path = "word/_rels/document.xml.rels" + if rels_path not in zf.namelist(): + return mapping + try: + root = ET.fromstring(zf.read(rels_path)) + except Exception: + return mapping + for rel in root.findall("r:Relationship", REL_NS): + rid = rel.attrib.get("Id", "") + target = rel.attrib.get("Target", "") + rtype = rel.attrib.get("Type", "") + if rid and target: + mapping[rid] = (_normalize_zip_target(target), rtype) + return mapping + + +def _rid_from_attrs(attrib: dict[str, str]) -> str: + attrs = {_local_name(k): v for k, v in attrib.items()} + for key in ("id", "embed", "link"): + val = attrs.get(key, "") + if val: + return val + for k, v in attrib.items(): + if _local_name(k) in {"id", "embed", "link"} and str(v).startswith("rId"): + return v + return "" + + +def _icon_and_display_names(zf: zipfile.ZipFile) -> dict[str, str]: + """ + Map embedding zip path -> best display name. + Uses OLEObject Name, then the caption text inside the linked icon EMF/WMF. + """ + names: dict[str, str] = {} + rels = _relationship_map(zf) + if "word/document.xml" not in zf.namelist(): + return names + + try: + root = ET.fromstring(zf.read("word/document.xml")) + except Exception: + return names + + # shape id -> image zip path (icon) + shape_icons: dict[str, str] = {} + # Collect shapes with imagedata + for elem in root.iter(): + if _local_name(elem.tag) != "shape": + continue + shape_id = "" + for k, v in elem.attrib.items(): + if _local_name(k) == "id": + shape_id = v + break + if not shape_id: + continue + for child in elem.iter(): + if _local_name(child.tag) != "imagedata": + continue + rid = _rid_from_attrs(child.attrib) + if rid in rels: + shape_icons[shape_id] = rels[rid][0] + # o:title sometimes has a caption + for k, v in child.attrib.items(): + if _local_name(k) == "title" and v and not _is_junk_name(v): + # Title alone isn't tied to ole yet; store on shape via side map later + shape_icons.setdefault(f"title:{shape_id}", v) + + # Walk OLEObject elements and pair with their shape icon + for elem in root.iter(): + if _local_name(elem.tag) not in {"OLEObject", "oleObject"}: + continue + + attrs = {_local_name(k): v for k, v in elem.attrib.items()} + display = attrs.get("Name") or attrs.get("name") or "" + shape_id = attrs.get("ShapeID") or attrs.get("shapeId") or "" + rid = _rid_from_attrs(elem.attrib) + if not rid or rid not in rels: + continue + + zip_path = rels[rid][0] + candidates: list[str] = [] + if display and not _is_junk_name(display): + candidates.append(display) + + title_key = f"title:{shape_id}" + if title_key in shape_icons and not shape_icons[title_key].startswith("word/"): + candidates.append(shape_icons[title_key]) + + icon_path = shape_icons.get(shape_id) + if icon_path and icon_path in zf.namelist(): + try: + icon_bytes = zf.read(icon_path) + candidates.extend(_filenames_from_icon_bytes(icon_bytes)) + except Exception: + pass + + # Pick best candidate (longest real filename wins) + best = "" + for c in sorted(candidates, key=lambda s: len(s), reverse=True): + if not _is_junk_name(c): + best = _safe_filename(c) + break + if best: + names[zip_path] = best + + return names + + +def discover_attachments_in_docx( + docx_path: Path, + *, + include_media: bool = False, +) -> tuple[list[DiscoveredAttachment], list[str]]: + """Scan a Word file and return discoverable attachments (payload kept in memory).""" + found: list[DiscoveredAttachment] = [] + errors: list[str] = [] + + if not _is_word_package(docx_path): + return [], [f"Not a valid .docx/.docm file: {docx_path.name}"] + + try: + with zipfile.ZipFile(docx_path, "r") as zf: + names = zf.namelist() + display_map = _icon_and_display_names(zf) + embed_names = [ + n for n in names if n.startswith(EMBEDDINGS_PREFIX) and not n.endswith("/") + ] + media_names = ( + [n for n in names if n.startswith(MEDIA_PREFIX) and not n.endswith("/")] + if include_media + else [] + ) + + for zip_path in embed_names: + try: + raw = zf.read(zip_path) + except Exception as exc: + errors.append(f"{docx_path.name}: failed to read {zip_path}: {exc}") + continue + + preferred = display_map.get(zip_path) + base = Path(zip_path).name + + if not base.lower().endswith(".bin") and not olefile.isOleFile(io.BytesIO(raw)): + payload, _kind = _normalize_payload(raw) + display = _best_name(preferred, base, data=payload) + found.append( + DiscoveredAttachment( + id=f"{docx_path.resolve()}::{zip_path}::0", + source_doc=docx_path, + display_name=display, + zip_path=zip_path, + kind="embedding", + size_bytes=len(payload), + payload=payload, + ) + ) + continue + + ole_files = _extract_from_ole_bin(raw, preferred_name=preferred) + if ole_files: + for idx, (fname, fbytes, note) in enumerate(ole_files): + display = _best_name(preferred, fname, data=fbytes) + found.append( + DiscoveredAttachment( + id=f"{docx_path.resolve()}::{zip_path}::{idx}", + source_doc=docx_path, + display_name=display, + zip_path=zip_path, + kind="ole", + size_bytes=len(fbytes), + payload=fbytes, + note=note, + ) + ) + else: + payload, kind = _normalize_payload(raw) + display = _best_name(preferred, data=payload) + found.append( + DiscoveredAttachment( + id=f"{docx_path.resolve()}::{zip_path}::0", + source_doc=docx_path, + display_name=display, + zip_path=zip_path, + kind="ole", + size_bytes=len(payload), + payload=payload, + note="Opaque OLE object" + if kind != "pdf" + else "PDF carved from OLE container", + ) + ) + + for zip_path in media_names: + # Skip EMF/WMF icons that belong to OLE objects — they aren't attachments + lower = zip_path.lower() + if lower.endswith((".emf", ".wmf")): + continue + try: + raw = zf.read(zip_path) + except Exception as exc: + errors.append(f"{docx_path.name}: failed to read {zip_path}: {exc}") + continue + found.append( + DiscoveredAttachment( + id=f"{docx_path.resolve()}::{zip_path}::0", + source_doc=docx_path, + display_name=_safe_filename(Path(zip_path).name), + zip_path=zip_path, + kind="media", + size_bytes=len(raw), + payload=raw, + note="media", + ) + ) + except zipfile.BadZipFile: + errors.append(f"Corrupt or unreadable Word file: {docx_path.name}") + except Exception as exc: + errors.append(f"Unexpected error on {docx_path.name}: {exc}") + + return found, errors + + +def discover_attachments( + paths: list[Path], + *, + include_media: bool = False, + recurse: bool = True, +) -> tuple[list[DiscoveredAttachment], list[str]]: + attachments: list[DiscoveredAttachment] = [] + errors: list[str] = [] + for doc in list_word_files(paths, recurse=recurse): + found, errs = discover_attachments_in_docx(doc, include_media=include_media) + attachments.extend(found) + errors.extend(errs) + return attachments, errors + + +def extract_attachments( + attachments: list[DiscoveredAttachment], + output_root: Path | None = None, + *, + per_document_subfolder: bool = True, +) -> list[ExtractResult]: + """Write selected discovered attachments to disk.""" + by_doc: dict[Path, list[DiscoveredAttachment]] = {} + for item in attachments: + by_doc.setdefault(item.source_doc, []).append(item) + + multi = len(by_doc) > 1 + results: list[ExtractResult] = [] + + for doc, items in by_doc.items(): + extracted: list[ExtractedFile] = [] + errors: list[str] = [] + + if output_root is None: + dest = doc.parent / f"{doc.stem}_attachments" + elif per_document_subfolder and multi: + dest = output_root / _safe_filename(doc.stem) + else: + dest = output_root + + try: + dest.mkdir(parents=True, exist_ok=True) + except Exception as exc: + results.append( + ExtractResult(doc, [], [], [f"Cannot create output folder: {exc}"]) + ) + continue + + for item in items: + try: + # Final safety: never write a PDF payload as .bin + name = _best_name(item.display_name, data=item.payload) + out = _unique_path(dest, name) + out.write_bytes(item.payload) + extracted.append( + ExtractedFile(doc, name, out, len(item.payload)) + ) + except Exception as exc: + errors.append(f"Failed to save {item.display_name}: {exc}") + + results.append(ExtractResult(doc, extracted, [], errors)) + + return results + + +def extract_from_docx( + docx_path: Path, + output_dir: Path, + *, + include_media: bool = False, +) -> ExtractResult: + found, scan_errors = discover_attachments_in_docx( + docx_path, include_media=include_media + ) + if not found and scan_errors: + return ExtractResult(docx_path, [], [], scan_errors) + if not found: + return ExtractResult(docx_path, [], ["No embedded attachments found"], []) + result = extract_attachments(found, output_root=output_dir, per_document_subfolder=False)[0] + result.errors = scan_errors + result.errors + return result + + +def extract_from_paths( + paths: list[Path], + output_root: Path | None = None, + *, + include_media: bool = False, + recurse: bool = True, + per_document_subfolder: bool = True, +) -> list[ExtractResult]: + found, errors = discover_attachments( + paths, include_media=include_media, recurse=recurse + ) + results = extract_attachments( + found, + output_root=output_root, + per_document_subfolder=per_document_subfolder, + ) + if errors and results: + results[0].errors = errors + results[0].errors + elif errors: + for path in list_word_files(paths, recurse=recurse): + doc_errs = [e for e in errors if path.name in e] + results.append(ExtractResult(path, [], [], doc_errs or errors)) + break + return results diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c98599e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +olefile>=0.47 +pyinstaller>=6.0.0