Enhance OCR logic and GUI logging

This commit is contained in:
HONOR
2026-09-20 09:54:39 +08:00
parent c07f958d40
commit 8dcd7c4031
4 changed files with 188 additions and 66 deletions
+3 -1
View File
@@ -3,4 +3,6 @@ config.json
conversion.csv conversion.csv
/build /build
/dist /dist
/WordTableExtractor.spec /WordTableExtractor.spec
ocr_worker.spec
/scratch
+50 -29
View File
@@ -2,36 +2,52 @@ import os
import pythoncom import pythoncom
import win32com.client as win32 import win32com.client as win32
def detect_and_create_apps(): def detect_and_create_apps(engine_choice="自动判断 (推荐)"):
"""探测并绑定 Microsoft Office 或 WPS 引擎""" """探测并绑定 Microsoft Office 或 WPS 引擎"""
# 1. 探测 MS Office
try: def try_ms_office():
word = win32.gencache.EnsureDispatch('Word.Application')
excel = win32.gencache.EnsureDispatch('Excel.Application')
return word, excel, "Microsoft Office"
except Exception:
try: try:
word = win32.Dispatch('Word.Application') word = win32.gencache.EnsureDispatch('Word.Application')
excel = win32.Dispatch('Excel.Application') excel = win32.gencache.EnsureDispatch('Excel.Application')
return word, excel, "Microsoft Office" return word, excel, "Microsoft Office"
except Exception: except Exception:
pass try:
word = win32.Dispatch('Word.Application')
# 2. 探测 WPS Office excel = win32.Dispatch('Excel.Application')
try: return word, excel, "Microsoft Office"
except Exception:
return None
def try_wps():
try: try:
word = win32.gencache.EnsureDispatch('wps.Application') try:
word = win32.gencache.EnsureDispatch('wps.Application')
except Exception:
word = win32.Dispatch('kwps.Application')
try:
excel = win32.gencache.EnsureDispatch('et.Application')
except Exception:
excel = win32.Dispatch('ket.Application')
return word, excel, "WPS Office"
except Exception: except Exception:
word = win32.Dispatch('kwps.Application') return None
try: if engine_choice == "Microsoft Office":
excel = win32.gencache.EnsureDispatch('et.Application') res = try_ms_office()
except Exception: if res: return res
excel = win32.Dispatch('ket.Application') raise RuntimeError("未检测到可用的 Microsoft Office!请尝试选择 WPS Office 或 自动判断。")
return word, excel, "WPS Office" elif engine_choice == "WPS Office":
except Exception: res = try_wps()
pass if res: return res
raise RuntimeError("未检测到可用的 WPS Office!请尝试选择 Microsoft Office 或 自动判断。")
else:
# 自动判断:先看当前机器上哪个注册表优先,通常按原逻辑
res = try_ms_office()
if res: return res
res = try_wps()
if res: return res
raise RuntimeError("未检测到可用的办公套件!请确保电脑已安装 Microsoft Office 或 WPS。") raise RuntimeError("未检测到可用的办公套件!请确保电脑已安装 Microsoft Office 或 WPS。")
@@ -49,20 +65,25 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}") log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
try: try:
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug, ConfirmConversions=False) doc = word_app.Documents.Open(abs_doc)
# 尝试访问属性,如果在“受保护的视图”下,这行会抛出 0x80020009 异常
table_count = doc.Tables.Count
except Exception as e: except Exception as e:
if debug and log_func: if debug and log_func:
log_func(f" [Debug] 打开失败,疑似遇到受保护的视图拦截,尝试启动智能复制逃逸机制...") log_func(f" [Debug] 访问受阻(可能是受保护的视图),启动智能复制逃逸机制...")
import shutil
out_dir = os.path.dirname(abs_excel) out_dir = os.path.dirname(abs_excel)
temp_dir = os.path.join(out_dir, "temp") temp_dir = os.path.join(out_dir, "temp")
if not os.path.exists(temp_dir): if not os.path.exists(temp_dir):
os.makedirs(temp_dir, exist_ok=True) os.makedirs(temp_dir, exist_ok=True)
file_to_clean = os.path.join(temp_dir, f"~temp_bypass_{os.path.basename(abs_doc)}") 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)
table_count = doc.Tables.Count # 使用原生读写剥离 Windows 的 Zone.Identifier (MOTW) 流
with open(abs_doc, 'rb') as f_in:
with open(file_to_clean, 'wb') as f_out:
f_out.write(f_in.read())
doc = word_app.Documents.Open(file_to_clean)
table_count = doc.Tables.Count
if table_count == 0: if table_count == 0:
if log_func: if log_func:
+73 -21
View File
@@ -43,7 +43,8 @@ class BatchTableExtractorApp:
self.topmost_var = tk.BooleanVar(value=False) self.topmost_var = tk.BooleanVar(value=False)
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)") self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
self.pdf_engine_var = tk.StringVar(value="智能判定 (推荐)") self.pdf_engine_var = tk.StringVar(value="不处理")
self.engine_var = tk.StringVar(value="自动判断 (推荐)")
import threading import threading
self._stop_event = threading.Event() self._stop_event = threading.Event()
@@ -78,7 +79,8 @@ class BatchTableExtractorApp:
self.debug_var.set(cfg.get("debug_mode", False)) self.debug_var.set(cfg.get("debug_mode", False))
self.topmost_var.set(cfg.get("topmost", False)) self.topmost_var.set(cfg.get("topmost", False))
self.conflict_action_var.set(cfg.get("conflict_action", "直接覆盖 (默认)")) 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: except Exception:
pass pass
@@ -93,7 +95,8 @@ class BatchTableExtractorApp:
"debug_mode": self.debug_var.get(), "debug_mode": self.debug_var.get(),
"topmost": self.topmost_var.get(), "topmost": self.topmost_var.get(),
"conflict_action": self.conflict_action_var.get(), "conflict_action": self.conflict_action_var.get(),
"pdf_engine": self.pdf_engine_var.get() "pdf_engine": self.pdf_engine_var.get(),
"engine_var": self.engine_var.get()
} }
try: try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f: with open(CONFIG_FILE, "w", encoding="utf-8") as f:
@@ -135,6 +138,11 @@ class BatchTableExtractorApp:
self.chk_topmost = ttk.Checkbutton(mode_box, text="窗口置顶", variable=self.topmost_var, command=self._on_topmost_toggle, takefocus=False) 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) self.chk_topmost.grid(row=1, column=2, sticky=tk.W, padx=10, pady=2)
ttk.Label(mode_box, text="提取引擎:").grid(row=2, column=0, sticky=tk.W, padx=10, pady=2)
engine_cb = ttk.Combobox(mode_box, textvariable=self.engine_var, values=["自动判断 (推荐)", "Microsoft Office", "WPS Office"], state="readonly", width=16)
engine_cb.grid(row=2, column=1, columnspan=2, sticky=tk.W, padx=10, pady=2)
engine_cb.bind("<<ComboboxSelected>>", lambda e: self.root.focus_set())
# 2. 路径配置 # 2. 路径配置
path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10") path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10")
@@ -156,9 +164,18 @@ class BatchTableExtractorApp:
combo_frame = ttk.Frame(path_box) combo_frame = ttk.Frame(path_box)
combo_frame.grid(row=2, column=1, sticky=tk.EW, padx=6) 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) def _clear_combo_focus(event):
self.root.focus_set()
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)
ttk.Label(combo_frame, text=" PDF: ").pack(side=tk.LEFT) 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)
cb_pdf = ttk.Combobox(combo_frame, textvariable=self.pdf_engine_var, values=["智能判定 (推荐)", "强转 Word (极速)", "强制本地 AI (需插件)", "不处理"], state="readonly", width=18)
cb_pdf.pack(side=tk.LEFT, fill=tk.X, expand=True)
cb_pdf.bind("<<ComboboxSelected>>", _clear_combo_focus)
self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=65) 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) self.btn_view_log.grid(row=2, column=2, sticky=tk.EW)
@@ -400,18 +417,43 @@ class BatchTableExtractorApp:
pythoncom.CoInitialize() pythoncom.CoInitialize()
word_app = None word_app = None
excel_app = None excel_app = None
apps_initialized = False
success_count = 0 success_count = 0
batch_id = self._generate_batch_id() batch_id = self._generate_batch_id()
def ensure_apps():
nonlocal word_app, excel_app, apps_initialized
if not apps_initialized:
engine_choice = self.engine_var.get()
word_app, excel_app, engine_name = detect_and_create_apps(engine_choice)
self.root.after(0, lambda: self.log(f"已启动宿主引擎: 【{engine_name}】"))
debug_mode = self.debug_var.get()
# 不要设置 word_app.Visible = False,否则会隐藏用户已经在编辑的其他文档!
try:
word_app.DisplayAlerts = debug_mode
except Exception:
pass
try:
word_app.UserControl = True
except Exception:
pass
# 同理不要设置 excel_app.Visible
try:
excel_app.DisplayAlerts = debug_mode
except Exception:
pass
try:
excel_app.UserControl = True
except Exception:
pass
apps_initialized = True
return word_app, excel_app
try: 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() 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) total = len(file_list)
for idx, file_path in enumerate(file_list, start=1): for idx, file_path in enumerate(file_list, start=1):
@@ -461,9 +503,17 @@ class BatchTableExtractorApp:
route_target = "ocr" route_target = "ocr"
elif ext == '.pdf': elif ext == '.pdf':
engine_pref = self.pdf_engine_var.get() 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" route_target = "word"
elif "OCR" in engine_pref: elif "本地 AI" in engine_pref or "OCR" in engine_pref:
route_target = "ocr" route_target = "ocr"
else: else:
# 智能判定:读取前3页文本量 # 智能判定:读取前3页文本量
@@ -485,11 +535,12 @@ class BatchTableExtractorApp:
route_target = "ocr" # fallback route_target = "ocr" # fallback
if route_target == "word": if route_target == "word":
ensure_apps()
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel, tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
log_func=my_log, debug=debug_mode) log_func=my_log, debug=debug_mode)
else: else:
from core.extractor import export_pdf_image_tables_local 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) log_func=my_log, debug=debug_mode)
duration = time.time() - t0 duration = time.time() - t0
@@ -502,8 +553,11 @@ class BatchTableExtractorApp:
duration = time.time() - t0 duration = time.time() - t0
import traceback import traceback
trace_str = traceback.format_exc() trace_str = traceback.format_exc()
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}" if self.debug_var.get():
self.root.after(0, lambda m=err_msg: self.log(m)) err_msg = f" ❌ 失败跳过 [{base_name}]: {e}\n{trace_str}"
else:
err_msg = f" ❌ 失败跳过 [{base_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}") record_log(batch_id, "失败", base_name, "-", 0, duration, file_path, f"{e}\n{trace_str}")
# 更新按钮文字进度 # 更新按钮文字进度
@@ -513,7 +567,6 @@ class BatchTableExtractorApp:
self.root.after(0, update_btn) 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: 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: except Exception as e:
self.root.after(0, lambda err=str(e): self.log(f"引擎崩溃: {err}")) self.root.after(0, lambda err=str(e): self.log(f"引擎崩溃: {err}"))
@@ -521,15 +574,14 @@ class BatchTableExtractorApp:
finally: finally:
if word_app: if word_app:
try: try:
word_app.Quit() word_app.DisplayAlerts = True
except Exception: except Exception:
pass pass
if excel_app: if excel_app:
try: try:
excel_app.Quit() excel_app.DisplayAlerts = True
except Exception: except Exception:
pass pass
pythoncom.CoUninitialize()
def _reset_btn(): def _reset_btn():
self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start) self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start)
self.btn_run.set_progress(0.0) self.btn_run.set_progress(0.0)
+62 -15
View File
@@ -1,13 +1,31 @@
import os
import sys import sys
import os
import argparse 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 import numpy as np
from PIL import Image
import pandas as pd
import io
import fitz
import cv2 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): def parse_page_ranges(pages_str, total_pages):
if not pages_str: 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("img_path", help="Path to input PDF or Image")
parser.add_argument("excel_path", help="Path to output Excel file") 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("--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() args = parser.parse_args()
img_path = args.img_path img_path = args.img_path
excel_path = args.excel_path excel_path = args.excel_path
is_debug = args.debug
if not os.path.exists(img_path): if not os.path.exists(img_path):
print(f"Error: File not found {img_path}") print(f"Error: File not found {img_path}")
sys.exit(1) sys.exit(1)
table_engine = RapidTable() table_engine = RapidTable()
table_engine.ocr_engine = CustomOcrEngine()
images = [] # (page_num, image_numpy_array) images = [] # (page_num, image_numpy_array)
ext = os.path.splitext(img_path)[1].lower() ext = os.path.splitext(img_path)[1].lower()
@@ -77,17 +98,43 @@ def main():
tables_found = 0 tables_found = 0
extracted_tables = [] extracted_tables = []
total_images = len(images)
for page_num, img_array in 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: try:
table_result, _ = table_engine(img_array) table_result = table_engine(img_array)
html_str = table_result if is_debug:
if html_str: print(f" [Debug] 第 {page_num} 页 AI 推理耗时: {time.time() - start_time:.3f}s")
dfs = pd.read_html(html_str)
for i, df in enumerate(dfs): if hasattr(table_result, 'pred_htmls') and table_result.pred_htmls:
tables_found += 1 for html_idx, html_str in enumerate(table_result.pred_htmls):
sheet_name = f"P{page_num}_T{i+1}" if html_str:
extracted_tables.append((sheet_name, df)) 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: except Exception as e:
print(f"Error processing page {page_num}: {e}") print(f"Error processing page {page_num}: {e}")