Compare commits

...
6 changed files with 274 additions and 165 deletions
+2
View File
@@ -4,3 +4,5 @@ conversion.csv
/build
/dist
/WordTableExtractor.spec
ocr_worker.spec
/scratch
+15
View File
@@ -0,0 +1,15 @@
# WordTableExtractor 项目开发规范 (Agent Rules)
这是一份供 AI Assistant (Agent) 读取的项目级约束规则文件。
## 1. 代码提交流程 (Git Commits)
- **必须使用中文**编写 Git Commit Message。
- 每次修改完代码并测试通过后,请养成主动提交代码的习惯,并遵循约定式提交规范(例如:`feat: 增加xxx功能`, `fix: 修复xxx问题`, `docs: 更新文档` 等)。
## 2. 核心架构约束 (Core Architecture)
- **禁止使用 Office COM (win32com) 进行常规的数据提取**。
- 必须使用 `python-docx` 读取 Word 文档,使用 `openpyxl` 和 `pandas` 写入 Excel。这是为了保证程序在后台绝对静默运行,不弹出窗口,不抢夺用户焦点。
- `win32.DispatchEx` 仅在极少数必须进行前置格式转换(如 `.doc` 转 `.docx`)且没有其他替代方案时才能作为 fallback 使用,并且必须保证 `Visible = False`。
## 3. UI 交互规范
- 点击“开始提取”或拖拽文件时,必须第一时间清空日志窗口,确保运行日志清爽。
+3
View File
@@ -1,2 +1,5 @@
pywin32
windnd
python-docx
openpyxl
pandas
+100 -87
View File
@@ -2,136 +2,149 @@ import os
import pythoncom
import win32com.client as win32
def detect_and_create_apps():
"""探测并绑定 Microsoft Office 或 WPS 引擎"""
# 1. 探测 MS Office
def convert_doc_to_docx(doc_path, log_func=None, debug=False):
"""
静默将 .doc 转换为 .docx,不影响用户已打开的任何 Word 文档。
使用独立进程 (DispatchEx) 和只读模式 (ReadOnly=True)。
"""
import tempfile
import pythoncom
pythoncom.CoInitialize()
word_app = None
doc = None
try:
word = win32.gencache.EnsureDispatch('Word.Application')
excel = win32.gencache.EnsureDispatch('Excel.Application')
return word, excel, "Microsoft Office"
if debug and log_func:
log_func(f" [Debug] 正在启动独立 Word 进程转换 .doc 文件...")
# 优先尝试启动全新独立的 MS Word 进程
try:
word_app = win32.DispatchEx('Word.Application')
except Exception:
# 如果没有 MS Word,尝试启动 WPS
try:
word_app = win32.DispatchEx('wps.Application')
except Exception:
try:
word = win32.Dispatch('Word.Application')
excel = win32.Dispatch('Excel.Application')
return word, excel, "Microsoft Office"
word_app = win32.DispatchEx('kwps.Application')
except Exception:
# 如果当前 WPS 版本不支持 DispatchEx (独立进程),则降级使用普通 Dispatch
try:
word_app = win32.Dispatch('wps.Application')
except Exception:
word_app = win32.Dispatch('kwps.Application')
word_app.Visible = False
word_app.DisplayAlerts = False
abs_doc = os.path.abspath(doc_path)
out_dir = os.path.join(tempfile.gettempdir(), "word_table_extractor_temp")
os.makedirs(out_dir, exist_ok=True)
# 构造临时 docx 路径
base_name = os.path.basename(abs_doc)
temp_docx = os.path.join(out_dir, f"{base_name}.docx")
if os.path.exists(temp_docx):
try:
os.remove(temp_docx)
except Exception:
pass
# 2. 探测 WPS Office
try:
try:
word = win32.gencache.EnsureDispatch('wps.Application')
except Exception:
word = win32.Dispatch('kwps.Application')
# ReadOnly=True 是关键,如果文件正在被用户编辑,这样能确保安全读取,不锁定
doc = word_app.Documents.Open(abs_doc, ReadOnly=True, Visible=False)
try:
excel = win32.gencache.EnsureDispatch('et.Application')
except Exception:
excel = win32.Dispatch('ket.Application')
# 16 = wdFormatDocumentDefault (docx)
doc.SaveAs(temp_docx, FileFormat=16)
return temp_docx
return word, excel, "WPS Office"
except Exception as e:
if log_func:
log_func(f" [Error] .doc 格式转换失败: {e}")
raise
finally:
if doc:
try:
doc.Close(SaveChanges=False)
except Exception:
pass
if word_app:
try:
word_app.Quit()
except Exception:
pass
pythoncom.CoUninitialize()
raise RuntimeError("未检测到可用的办公套件!请确保电脑已安装 Microsoft Office 或 WPS。")
def export_single_doc_tables(doc_path, excel_path, log_func=None, debug=False):
"""
提取单个 Word 文件中的所有表格到 Excel。
使用 python-docx 和 openpyxl,实现 100% 静默提取。
"""
from docx import Document
from openpyxl import Workbook
import tempfile
def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func=None, debug=False):
"""提取单个 Word 文件中的所有表格到 Excel"""
abs_doc = os.path.abspath(doc_path)
abs_excel = os.path.abspath(excel_path)
doc = None
wb = None
file_to_clean = None
try:
is_doc = abs_doc.lower().endswith('.doc')
if is_doc:
if debug and log_func:
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
log_func(f" [Info] 检测到旧版 .doc 格式,正在安全转换为 .docx...")
abs_doc = convert_doc_to_docx(abs_doc, log_func=log_func, debug=debug)
file_to_clean = abs_doc
try:
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug, ConfirmConversions=False)
except Exception as e:
if debug and log_func:
log_func(f" [Debug] 打开失败,疑似遇到受保护的视图拦截,尝试启动智能复制逃逸机制...")
import shutil
out_dir = os.path.dirname(abs_excel)
temp_dir = os.path.join(out_dir, "temp")
if not os.path.exists(temp_dir):
os.makedirs(temp_dir, exist_ok=True)
file_to_clean = os.path.join(temp_dir, f"~temp_bypass_{os.path.basename(abs_doc)}")
shutil.copy2(abs_doc, file_to_clean)
doc = word_app.Documents.Open(FileName=file_to_clean, ReadOnly=True, Visible=debug, ConfirmConversions=False)
log_func(f" [Debug] 正在使用 python-docx 解析文档...")
table_count = doc.Tables.Count
doc = Document(abs_doc)
tables = doc.tables
table_count = len(tables)
if table_count == 0:
if log_func:
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
return 0
wb = excel_app.Workbooks.Add()
wb = Workbook()
wb.remove(wb.active) # 移除默认的Sheet
for i in range(1, table_count + 1):
if debug and log_func:
log_func(f" [Debug] 正在提取 第 {i}/{table_count} 个表格...")
table = doc.Tables.Item(i)
table.Range.Copy()
for i, table in enumerate(tables):
sheet_name = f"Table_{i+1}"
ws = wb.create_sheet(title=sheet_name)
import time
time.sleep(0.2) # 给系统剪贴板同步数据留点时间
# python-docx 提取表格数据 (简单遍历,处理了基本的合并单元格结构)
for r_idx, row in enumerate(table.rows):
row_data = []
for cell in row.cells:
row_data.append(cell.text.strip())
ws.append(row_data)
if i > wb.Sheets.Count:
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
else:
ws = wb.Sheets.Item(i)
ws.Name = f"Table_{i}"
# Excel的Paste可能会因为剪贴板被占用而报错 0x800A03EC,加入重试机制
for retry in range(3):
try:
ws.Paste()
break
except Exception as pe:
if debug and log_func:
log_func(f" [Debug] 粘贴报错 {pe},等待0.5秒后重试...")
time.sleep(0.5)
else:
ws.Paste() # 最后一次尝试,若失败则抛出异常
ws.Columns.AutoFit()
while wb.Sheets.Count > table_count:
wb.Sheets(wb.Sheets.Count).Delete()
# 51 = xlOpenXMLWorkbook (.xlsx)
# 如果存在旧文件先删除
if os.path.exists(abs_excel):
try:
os.remove(abs_excel)
except Exception:
pass
wb.SaveAs(Filename=abs_excel, FileFormat=51)
wb.save(abs_excel)
if log_func:
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
return table_count
except Exception as e:
if log_func:
log_func(f" [Error] 提取失败: {e}")
raise
finally:
if wb:
try:
wb.Close(SaveChanges=False)
except Exception:
pass
if doc:
try:
doc.Close(SaveChanges=False)
except Exception:
pass
# 清理 .doc 转换产生的临时文件
if file_to_clean and os.path.exists(file_to_clean):
try:
os.remove(file_to_clean)
temp_dir = os.path.dirname(file_to_clean)
if not os.listdir(temp_dir):
os.rmdir(temp_dir)
except Exception:
pass
def export_pdf_image_tables_local(excel_app, file_path, excel_path, pages_str, log_func=None, debug=False):
+74 -45
View File
@@ -10,7 +10,7 @@ import datetime
import time
from utils.config import CONFIG_FILE, APP_DIR
from core.extractor import detect_and_create_apps, export_single_doc_tables
from core.extractor import export_single_doc_tables
from ui.widgets import ProgressButton
from ui.history_window import record_log
@@ -43,7 +43,7 @@ class BatchTableExtractorApp:
self.topmost_var = tk.BooleanVar(value=False)
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
self.pdf_engine_var = tk.StringVar(value="智能判定 (推荐)")
self.pdf_engine_var = tk.StringVar(value="不处理")
import threading
self._stop_event = threading.Event()
@@ -78,7 +78,8 @@ class BatchTableExtractorApp:
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", "智能判定 (推荐)"))
self.pdf_engine_var.set(cfg.get("pdf_engine", "不处理"))
self.engine_var.set(cfg.get("engine_var", "自动判断 (推荐)"))
except Exception:
pass
@@ -142,26 +143,33 @@ class BatchTableExtractorApp:
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.Entry(path_box, textvariable=self.src_path_var, width=40).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=50)
self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW, padx=(0, 4))
self.btn_open_src = ProgressButton(path_box, text="打开", command=self._open_src_dir, height=22, width=40)
self.btn_open_src.grid(row=0, column=3, 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.Entry(path_box, textvariable=self.out_dir_var, width=40, 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=50)
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW, padx=(0, 4))
self.btn_open_out = ProgressButton(path_box, text="打开", command=self._open_out_dir, height=22, width=40)
self.btn_open_out.grid(row=1, column=3, 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)
def _clear_combo_focus(event):
self.root.focus_set()
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)
cb_conflict = ttk.Combobox(combo_frame, textvariable=self.conflict_action_var, values=["直接覆盖 (默认)", "自动重命名", "直接跳过"], state="readonly", width=18)
cb_conflict.pack(side=tk.LEFT, fill=tk.X, expand=True)
cb_conflict.bind("<<ComboboxSelected>>", _clear_combo_focus)
self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=94)
self.btn_view_log.grid(row=2, column=2, columnspan=2, sticky=tk.EW)
path_box.columnconfigure(1, weight=1)
@@ -230,6 +238,34 @@ class BatchTableExtractorApp:
if path:
self.out_dir_var.set(os.path.normpath(path))
def _open_src_dir(self):
path = self.src_path_var.get().strip()
if not path:
messagebox.showinfo("提示", "来源目录为空")
return
if os.path.isfile(path):
path = os.path.dirname(path)
if os.path.exists(path):
try:
os.startfile(path)
except Exception as e:
messagebox.showerror("错误", f"无法打开目录: {e}")
else:
messagebox.showinfo("提示", "该来源路径不存在")
def _open_out_dir(self):
path = self.out_dir_var.get().strip()
if not path:
messagebox.showinfo("提示", "转换目录为空")
return
if os.path.exists(path):
try:
os.startfile(path)
except Exception as e:
messagebox.showerror("错误", f"无法打开目录: {e}")
else:
messagebox.showinfo("提示", "转换目录目前还不存在,请先提取生成文件")
def _on_drop_files(self, files):
if not files:
return
@@ -318,6 +354,9 @@ class BatchTableExtractorApp:
def _start(self):
self._save_config()
# 点击提取按钮时,第一时间清空上一次的运行日志
self.txt.delete(1.0, tk.END)
src = self.src_path_var.get().strip()
out = self.out_dir_var.get().strip()
mode = self.mode_var.get()
@@ -397,21 +436,11 @@ class BatchTableExtractorApp:
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):
@@ -425,13 +454,14 @@ class BatchTableExtractorApp:
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
break
base_name = os.path.splitext(os.path.basename(file_path))[0]
full_name = os.path.basename(file_path)
base_name = os.path.splitext(full_name)[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}"))
self.root.after(0, lambda i=idx, t=total, name=full_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} | 点击终止操作")
@@ -447,7 +477,7 @@ class BatchTableExtractorApp:
break
counter += 1
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 处理中: {name}"))
self.root.after(0, lambda i=idx, t=total, name=full_name: self.log(f"[{i}/{t}] 处理中: {name}"))
import time
t0 = time.time()
try:
@@ -461,9 +491,17 @@ class BatchTableExtractorApp:
route_target = "ocr"
elif ext == '.pdf':
engine_pref = self.pdf_engine_var.get()
if "Word" in engine_pref:
if "不处理" in engine_pref:
self.root.after(0, lambda: self.log(" [跳过] 用户设置 PDF 不处理"))
record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "PDF设置为不处理")
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 "Word" in engine_pref:
route_target = "word"
elif "OCR" in engine_pref:
elif "本地 AI" in engine_pref or "OCR" in engine_pref:
route_target = "ocr"
else:
# 智能判定:读取前3页文本量
@@ -485,11 +523,11 @@ class BatchTableExtractorApp:
route_target = "ocr" # fallback
if route_target == "word":
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
tc = export_single_doc_tables(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, "",
tc = export_pdf_image_tables_local(None, file_path, target_excel, "",
log_func=my_log, debug=debug_mode)
duration = time.time() - t0
@@ -502,8 +540,11 @@ class BatchTableExtractorApp:
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))
if self.debug_var.get():
err_msg = f" ❌ 失败跳过 [{full_name}]: {e}\n{trace_str}"
else:
err_msg = f" ❌ 失败跳过 [{full_name}]: {e}"
self.root.after(0, lambda m=err_msg: self.log(m, tag="error"))
record_log(batch_id, "失败", base_name, "-", 0, duration, file_path, f"{e}\n{trace_str}")
# 更新按钮文字进度
@@ -513,23 +554,11 @@ class BatchTableExtractorApp:
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)
+57 -10
View File
@@ -1,13 +1,31 @@
import os
import sys
import os
import argparse
import fitz # PyMuPDF
import rapidocr_onnxruntime
sys.modules['rapidocr'] = rapidocr_onnxruntime
from rapid_table import RapidTable
import pandas as pd
import numpy as np
from PIL import Image
import pandas as pd
import io
import fitz
import cv2
from rapid_table import RapidTable
from rapidocr_onnxruntime import RapidOCR
class OcrResultObj:
def __init__(self, res):
self.boxes = None
self.txts = None
self.scores = None
if res:
self.boxes = [r[0] for r in res]
self.txts = [r[1] for r in res]
self.scores = [float(r[2]) for r in res]
class CustomOcrEngine:
def __init__(self):
self.engine = RapidOCR()
def __call__(self, img, **kwargs):
res, _ = self.engine(img)
return OcrResultObj(res)
def parse_page_ranges(pages_str, total_pages):
if not pages_str:
@@ -38,16 +56,19 @@ def main():
parser.add_argument("img_path", help="Path to input PDF or Image")
parser.add_argument("excel_path", help="Path to output Excel file")
parser.add_argument("--pages", default="", help="Page ranges, e.g. 1,3,5-8")
parser.add_argument("--debug", action="store_true", help="Enable detailed debug logs")
args = parser.parse_args()
img_path = args.img_path
excel_path = args.excel_path
is_debug = args.debug
if not os.path.exists(img_path):
print(f"Error: File not found {img_path}")
sys.exit(1)
table_engine = RapidTable()
table_engine.ocr_engine = CustomOcrEngine()
images = [] # (page_num, image_numpy_array)
ext = os.path.splitext(img_path)[1].lower()
@@ -77,17 +98,43 @@ def main():
tables_found = 0
extracted_tables = []
total_images = len(images)
for page_num, img_array in images:
print(f"[OCR] Scanning page {page_num}...")
print(f"[OCR] 正在扫描第 {page_num} 页, 共 {total_images} 页...")
import time
start_time = time.time()
try:
table_result, _ = table_engine(img_array)
html_str = table_result
table_result = table_engine(img_array)
if is_debug:
print(f" [Debug] 第 {page_num} 页 AI 推理耗时: {time.time() - start_time:.3f}s")
if hasattr(table_result, 'pred_htmls') and table_result.pred_htmls:
for html_idx, html_str in enumerate(table_result.pred_htmls):
if html_str:
dfs = pd.read_html(html_str)
if is_debug:
print(f" [Debug] 第 {page_num} 页生成 HTML 代码,长度: {len(html_str)}")
try:
dfs = pd.read_html(io.StringIO(html_str))
for i, df in enumerate(dfs):
tables_found += 1
sheet_name = f"P{page_num}_T{i+1}"
extracted_tables.append((sheet_name, df))
if is_debug:
print(f" [Debug] 第 {page_num} 页保存表格 {i+1}: {df.shape[0]} 行, {df.shape[1]} 列")
except ValueError as e:
if "No tables found" not in str(e):
print(f"Error parsing html on page {page_num}: {e}")
else:
# Fallback if old rapid_table version returned a string directly
if isinstance(table_result, str):
try:
dfs = pd.read_html(io.StringIO(table_result))
for i, df in enumerate(dfs):
tables_found += 1
sheet_name = f"P{page_num}_T{i+1}"
extracted_tables.append((sheet_name, df))
except ValueError as e:
pass
except Exception as e:
print(f"Error processing page {page_num}: {e}")