import os import json import glob import threading import tkinter as tk from tkinter import filedialog, messagebox, ttk import pythoncom import windnd import datetime from utils.config import CONFIG_FILE, APP_DIR from core.extractor import detect_and_create_apps, export_single_doc_tables from ui.widgets import ProgressButton from ui.history_window import record_log class BatchTableExtractorApp: def __init__(self, root): self.root = root self.root.title("WordTableExtractor") self.root.geometry("640x520") self.root.minsize(580, 460) # 尝试设置窗口图标 try: import sys if getattr(sys, 'frozen', False): icon_path = os.path.join(sys._MEIPASS, "app.ico") else: icon_path = os.path.join(APP_DIR, "app.ico") if os.path.exists(icon_path): self.root.iconbitmap(icon_path) except Exception: pass # 状态变量 self.mode_var = tk.StringVar(value="dir") # "file" 或 "dir" self.src_path_var = tk.StringVar() self.out_dir_var = tk.StringVar() self.recursive_var = tk.BooleanVar(value=False) self.auto_extract_var = tk.BooleanVar(value=False) self.debug_var = tk.BooleanVar(value=False) self.topmost_var = tk.BooleanVar(value=False) self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)") self.pdf_engine_var = tk.StringVar(value="智能判定 (推荐)") import threading self._stop_event = threading.Event() self._pause_event = threading.Event() self._is_running = False self._load_config() self.root.attributes("-topmost", self.topmost_var.get()) self._build_ui() self._on_mode_change() # 初始化拖拽支持 try: windnd.hook_dropfiles(self.root, func=self._on_drop_files) except Exception as e: pass # 窗口关闭时自动持久化配置 self.root.protocol("WM_DELETE_WINDOW", self._on_close) def _load_config(self): """读取本地配置文件""" if os.path.exists(CONFIG_FILE): try: with open(CONFIG_FILE, "r", encoding="utf-8") as f: cfg = json.load(f) self.mode_var.set(cfg.get("mode", "dir")) self.src_path_var.set(cfg.get("src_path", "")) self.out_dir_var.set(cfg.get("out_dir", "")) self.recursive_var.set(cfg.get("recursive", False)) self.auto_extract_var.set(cfg.get("auto_extract", False)) self.debug_var.set(cfg.get("debug_mode", False)) self.topmost_var.set(cfg.get("topmost", False)) self.conflict_action_var.set(cfg.get("conflict_action", "直接覆盖 (默认)")) self.pdf_engine_var.set(cfg.get("pdf_engine", "智能判定 (推荐)")) except Exception: pass def _save_config(self): """写入配置到本地 JSON""" cfg = { "mode": self.mode_var.get(), "src_path": self.src_path_var.get(), "out_dir": self.out_dir_var.get(), "recursive": self.recursive_var.get(), "auto_extract": self.auto_extract_var.get(), "debug_mode": self.debug_var.get(), "topmost": self.topmost_var.get(), "conflict_action": self.conflict_action_var.get(), "pdf_engine": self.pdf_engine_var.get() } try: with open(CONFIG_FILE, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=2) except Exception: pass def _build_ui(self): frame = ttk.Frame(self.root, padding="15") frame.pack(fill=tk.BOTH, expand=True) # 1. 模式选择 mode_box = ttk.LabelFrame(frame, text=" 处理模式 ", padding="8") mode_box.pack(fill=tk.X, pady=(0, 10)) # 配置列权重以实现更好的分布 mode_box.columnconfigure(0, weight=1) mode_box.columnconfigure(1, weight=1) mode_box.columnconfigure(2, weight=1) ttk.Radiobutton(mode_box, text="批量处理文件夹", variable=self.mode_var, value="dir", command=self._on_mode_change, takefocus=False).grid(row=0, column=0, sticky=tk.W, padx=10, pady=2) ttk.Radiobutton(mode_box, text="处理单个文件", variable=self.mode_var, value="file", command=self._on_mode_change, takefocus=False).grid(row=0, column=1, sticky=tk.W, padx=10, pady=2) self.chk_recursive = ttk.Checkbutton(mode_box, text="包含子文件夹", variable=self.recursive_var, takefocus=False) self.chk_recursive.grid(row=0, column=2, sticky=tk.W, padx=10, pady=2) self.chk_debug = ttk.Checkbutton(mode_box, text="DEBUG", variable=self.debug_var, command=self._on_debug_toggle, takefocus=False) self.chk_debug.grid(row=1, column=0, sticky=tk.W, padx=10, pady=2) self.chk_auto_extract = ttk.Checkbutton(mode_box, text="拖拽后立即提取", variable=self.auto_extract_var, takefocus=False) self.chk_auto_extract.grid(row=1, column=1, sticky=tk.W, padx=10, pady=2) self.chk_topmost = ttk.Checkbutton(mode_box, text="窗口置顶", variable=self.topmost_var, command=self._on_topmost_toggle, takefocus=False) self.chk_topmost.grid(row=1, column=2, sticky=tk.W, padx=10, pady=2) # 2. 路径配置 path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10") path_box.pack(fill=tk.X, pady=(0, 10)) self.lbl_src = ttk.Label(path_box, text="来源目录:") self.lbl_src.grid(row=0, column=0, sticky=tk.W, pady=5) ttk.Entry(path_box, textvariable=self.src_path_var, width=46).grid(row=0, column=1, sticky=tk.EW, padx=6) self.btn_browse_src = ProgressButton(path_box, text="选择...", command=self._browse_src, height=22, width=65) self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW) ttk.Label(path_box, text="转换目录:").grid(row=1, column=0, sticky=tk.W, pady=5) ttk.Entry(path_box, textvariable=self.out_dir_var, width=46, state="readonly").grid(row=1, column=1, sticky=tk.EW, padx=6) self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=65) self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW) ttk.Label(path_box, text="文件冲突:").grid(row=2, column=0, sticky=tk.W, pady=5) combo_frame = ttk.Frame(path_box) combo_frame.grid(row=2, column=1, sticky=tk.EW, padx=6) ttk.Combobox(combo_frame, textvariable=self.conflict_action_var, values=["直接覆盖 (默认)", "自动重命名", "直接跳过"], state="readonly", width=18).pack(side=tk.LEFT, fill=tk.X, expand=True) ttk.Label(combo_frame, text=" PDF: ").pack(side=tk.LEFT) ttk.Combobox(combo_frame, textvariable=self.pdf_engine_var, values=["智能判定 (推荐)", "强转 Word (极速)", "强制本地 AI (需插件)"], state="readonly", width=18).pack(side=tk.LEFT, fill=tk.X, expand=True) self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=65) self.btn_view_log.grid(row=2, column=2, sticky=tk.EW) path_box.columnconfigure(1, weight=1) # 3. 运行操作区 btn_frame = ttk.Frame(frame) btn_frame.pack(fill=tk.X, pady=(0, 10)) self.btn_run = ProgressButton(btn_frame, text="开始全量提取表格", command=self._start) self.btn_run.pack(side=tk.LEFT, fill=tk.X, expand=True) # 4. 运行日志窗口 log_box = ttk.LabelFrame(frame, text=" 运行日志 ", padding="8") log_box.pack(fill=tk.BOTH, expand=True) self.txt = tk.Text(log_box, wrap=tk.WORD, height=8, font=("Consolas", 9)) self.txt.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) sb = ttk.Scrollbar(log_box, orient=tk.VERTICAL, command=self.txt.yview) sb.pack(side=tk.RIGHT, fill=tk.Y) self.txt.config(yscrollcommand=sb.set) def _on_debug_toggle(self): if self.debug_var.get(): messagebox.showinfo("Debug 模式说明", "开启 Debug 模式后,程序在提取表格时将强制显示 Office/WPS 窗口。\n\n这主要用于排查程序“卡死”的问题。例如:当文档被加密或需要修复时,Office 会在后台弹窗等待用户点击。开启此模式可让你看到这些弹窗并手动处理。") def _on_topmost_toggle(self): self.root.attributes("-topmost", self.topmost_var.get()) def _stop_task(self): self._pause_event.set() ans = messagebox.askyesno("确认", "任务已暂停。\n\n是否确定终止批量提取操作?\n(选择“是”终止操作,选择“否”继续提取)") if ans: self._stop_event.set() self.btn_run.config_btn(state=tk.DISABLED, text="正在终止...") self.log("\n⚠️ 正在尝试终止任务,请等待当前文件处理完毕...") self._pause_event.clear() def _on_mode_change(self): if self.mode_var.get() == "dir": self.lbl_src.config(text="来源目录:") self.chk_recursive.config(state=tk.NORMAL) else: self.lbl_src.config(text="来源文件:") self.chk_recursive.config(state=tk.DISABLED) def _browse_src(self): if self.mode_var.get() == "dir": path = filedialog.askdirectory(title="选择包含文档的目录") else: path = filedialog.askopenfilename( title="选择文档", filetypes=[("支持的文档", "*.doc *.docx *.pdf *.png *.jpg *.jpeg"), ("所有文件", "*.*")] ) if path: path = os.path.normpath(path) self.src_path_var.set(path) if not self.out_dir_var.get().strip(): base_dir = path if self.mode_var.get() == "dir" else os.path.dirname(path) self.out_dir_var.set(os.path.normpath(os.path.join(base_dir, "convert"))) def _browse_out(self): path = filedialog.askdirectory(title="选择输出目录") if path: self.out_dir_var.set(os.path.normpath(path)) def _on_drop_files(self, files): if not files: return try: # windnd 返回的通常是 gbk 编码的字节串 dropped_paths = [f.decode("gbk") for f in files] except Exception: try: dropped_paths = [f.decode("utf-8") for f in files] except Exception: return if not dropped_paths: return if len(dropped_paths) > 1: messagebox.showinfo("提示", "目前仅支持单次拖拽一个文件或文件夹。系统将仅读取拖入的第一个项目!") first_path = dropped_paths[0] if os.path.isdir(first_path): self.mode_var.set("dir") self._on_mode_change() self.src_path_var.set(os.path.normpath(first_path)) if not self.out_dir_var.get().strip(): self.out_dir_var.set(os.path.normpath(os.path.join(first_path, "convert"))) elif os.path.isfile(first_path): self.mode_var.set("file") self._on_mode_change() self.src_path_var.set(os.path.normpath(first_path)) if not self.out_dir_var.get().strip(): self.out_dir_var.set(os.path.normpath(os.path.join(os.path.dirname(first_path), "convert"))) if self.auto_extract_var.get(): self.root.after(100, self._start) def _show_log_window(self): from ui.history_window import show_history_log_window show_history_log_window(self.root, self.topmost_var.get()) def log(self, msg, tag=None): self.txt.tag_config("error", foreground="red") self.txt.tag_config("highlight", foreground="red") if tag: self.txt.insert(tk.END, f"{msg}\n", tag) elif "跳过" in msg or "❌" in msg or "失败" in msg: self.txt.insert(tk.END, f"{msg}\n", "error") else: self.txt.insert(tk.END, f"{msg}\n") self.txt.see(tk.END) def _on_close(self): if getattr(self, '_is_running', False): self._pause_event.set() ans = messagebox.askyesno("确认退出", "当前正在提取表格,强制退出可能会导致部分文件提取不完整。\n\n是否确定要退出程序?") if not ans: self._pause_event.clear() return self._stop_event.set() self._save_config() self.root.destroy() def _start(self): self._save_config() src = self.src_path_var.get().strip() out = self.out_dir_var.get().strip() mode = self.mode_var.get() recursive = self.recursive_var.get() if not src or not os.path.exists(src): messagebox.showwarning("提示", "请选择有效的来源文件或目录!") return if not out: messagebox.showwarning("提示", "请选择有效的输出目录!") return if not os.path.exists(out): try: os.makedirs(out) except Exception as e: messagebox.showwarning("提示", f"无法创建输出目录: {e}") return elif not os.path.isdir(out): messagebox.showwarning("提示", "转换目录路径已被文件占用!") return # 收集目标文件列表 files_to_process = [] if mode == "file": if src.lower().endswith(('.doc', '.docx', '.pdf', '.png', '.jpg', '.jpeg')): files_to_process.append(src) else: pattern = "**/*" if recursive else "*" for ext in ("*.doc", "*.docx", "*.pdf", "*.png", "*.jpg", "*.jpeg"): full_pattern = os.path.join(src, pattern, ext) if recursive else os.path.join(src, ext) files_to_process.extend(glob.glob(full_pattern, recursive=recursive)) # 排除 office 生成的临时文件 (~$开头) files_to_process = [f for f in files_to_process if not os.path.basename(f).startswith("~$")] if not files_to_process: messagebox.showinfo("提示", "未找到任何待处理的文档或图片!") return self.btn_run.config_btn(text="启动中... ", command=self._stop_task) self.btn_run.set_progress(0.0) self._stop_event.clear() self._is_running = True self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====") threading.Thread( target=self._worker, args=(files_to_process, out), daemon=True ).start() def _generate_batch_id(self): date_str = datetime.datetime.now().strftime("%y%m%d") log_path = os.path.join(APP_DIR, "conversion.csv") seq = 1 if os.path.exists(log_path): try: import csv with open(log_path, "r", encoding="utf-8-sig") as f: reader = csv.reader(f) for row in reader: if row and row[0].startswith(f"{date_str}X"): try: current_seq = int(row[0].split("X")[1]) if current_seq >= seq: seq = current_seq + 1 except ValueError: pass except Exception: pass return f"{date_str}X{seq:02d}" def _worker(self, file_list, out_dir): pythoncom.CoInitialize() word_app = None excel_app = None success_count = 0 batch_id = self._generate_batch_id() try: word_app, excel_app, engine_name = detect_and_create_apps() self.root.after(0, lambda: self.log(f"已启动宿主引擎: 【{engine_name}】")) debug_mode = self.debug_var.get() word_app.Visible = debug_mode word_app.DisplayAlerts = debug_mode excel_app.Visible = debug_mode excel_app.DisplayAlerts = debug_mode total = len(file_list) for idx, file_path in enumerate(file_list, start=1): if self._pause_event.is_set(): self.root.after(0, lambda: self.btn_run.config_btn(text="任务已暂停...")) import time while self._pause_event.is_set(): time.sleep(0.1) if self._stop_event.is_set(): self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!")) break base_name = os.path.splitext(os.path.basename(file_path))[0] target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx") conflict_action = self.conflict_action_var.get() if os.path.exists(target_excel): if conflict_action == "直接跳过": self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 跳过同名: {name}")) record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "发现同名文件,跳过") def update_skip_btn(i=idx, t=total): self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作") self.btn_run.set_progress(i / t) self.root.after(0, update_skip_btn) continue elif conflict_action == "自动重命名": counter = 1 while True: new_name = f"{base_name}_表格_{counter}.xlsx" target_excel = os.path.join(out_dir, new_name) if not os.path.exists(target_excel): break counter += 1 self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 处理中: {name}")) import time t0 = time.time() try: def my_log(m): self.root.after(0, self.log, m) ext = os.path.splitext(file_path)[1].lower() route_target = "word" if ext in ['.png', '.jpg', '.jpeg']: route_target = "ocr" elif ext == '.pdf': engine_pref = self.pdf_engine_var.get() if "Word" in engine_pref: route_target = "word" elif "OCR" in engine_pref: route_target = "ocr" else: # 智能判定:读取前3页文本量 try: import fitz with fitz.open(file_path) as pdoc: text_len = 0 check_pages = min(3, len(pdoc)) for p in range(check_pages): text_len += len(pdoc[p].get_text("text").strip()) if text_len > 100: self.root.after(0, lambda: self.log(" [智能判定] 识别为电子版 PDF,已路由至 Word 极速引擎")) route_target = "word" else: self.root.after(0, lambda: self.log(" [智能判定] 识别为扫描版 PDF,已路由至云端 OCR 引擎")) route_target = "ocr" except Exception: route_target = "ocr" # fallback if route_target == "word": tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel, log_func=my_log, debug=debug_mode) else: from core.extractor import export_pdf_image_tables_local tc = export_pdf_image_tables_local(excel_app, file_path, target_excel, "", log_func=my_log, debug=debug_mode) duration = time.time() - t0 if tc > 0: success_count += 1 record_log(batch_id, "成功", base_name, f"{base_name}_表格.xlsx", tc, duration, file_path, "提取完成") else: record_log(batch_id, "跳过", base_name, "-", 0, duration, file_path, "未检测到表格") except Exception as e: duration = time.time() - t0 import traceback trace_str = traceback.format_exc() err_msg = f" ❌ 失败跳过 [{base_name}]: {e}" self.root.after(0, lambda m=err_msg: self.log(m)) record_log(batch_id, "失败", base_name, "-", 0, duration, file_path, f"{e}\n{trace_str}") # 更新按钮文字进度 def update_btn(i=idx, t=total): self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作") self.btn_run.set_progress(i / t) self.root.after(0, update_btn) self.root.after(0, lambda: self.log(f"\n===== 处理完成!成功导出 {success_count}/{total} 个文档的表格 =====\n", tag="highlight")) self.root.after(0, lambda: messagebox.showinfo("批量完成", f"处理完成!\n成功提取: {success_count}/{total} 个文件。")) except Exception as e: self.root.after(0, lambda err=str(e): self.log(f"引擎崩溃: {err}")) self.root.after(0, lambda err=str(e): messagebox.showerror("错误", f"自动化引擎初始化失败:\n{err}")) finally: if word_app: try: word_app.Quit() except Exception: pass if excel_app: try: excel_app.Quit() except Exception: pass pythoncom.CoUninitialize() def _reset_btn(): self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start) self.btn_run.set_progress(0.0) self._is_running = False self.root.after(0, _reset_btn)