Add Word Attachment Extractor GUI app and packaging.
Extract embedded files from Word docs with original names, selectable output, and a Windows exe build script. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
97fcc33283
commit
774f919179
5 files changed
+1599
No files matched your search
@@ -37,5 +37,9 @@ coverage/
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
*.spec
|
||||
.venv/
|
||||
venv/
|
||||
test_data/
|
||||
@@ -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("<Button-1>", self._on_tree_click)
|
||||
self.tree.bind("<space>", 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()
|
||||
@@ -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
|
||||
+1046
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
olefile>=0.47
|
||||
pyinstaller>=6.0.0
|
||||
Reference in new issue
Block a user