feat: 重构架构,彻底移除云端OCR,集成离线本地插件调用机制

This commit is contained in:
HONOR
2026-09-16 12:54:29 +08:00
parent 944d2f7888
commit c59153253c
2 changed files with 52 additions and 213 deletions
+46 -168
View File
@@ -134,183 +134,61 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
os.rmdir(temp_dir) os.rmdir(temp_dir)
except Exception: except Exception:
pass pass
import base64 def export_pdf_image_tables_local(excel_app, file_path, excel_path, pages_str, log_func=None, debug=False):
import requests import subprocess
import json import os
import time import sys
def get_baidu_token(ak, sk): # 查找插件路径
url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}" plugin_exe = os.path.join(os.getcwd(), "ocr_plugin", "ocr_worker.exe")
resp = requests.post(url, timeout=10) if not os.path.exists(plugin_exe):
data = resp.json() # 尝试查找相对 main.py / exe 的路径
if 'access_token' in data: app_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
return data['access_token'] plugin_exe = os.path.join(app_dir, "ocr_plugin", "ocr_worker.exe")
raise Exception(f"获取Token失败: {data.get('error_description', data)}")
def parse_page_ranges(pages_str, total_pages): if not os.path.exists(plugin_exe):
if not pages_str: raise Exception("未检测到本地 AI 插件!请下载 'ocr_plugin' 文件夹并放置在程序同一目录下。")
return list(range(total_pages))
pages = set()
for part in pages_str.split(','):
part = part.strip()
if not part: continue
if '-' in part:
try:
start, end = part.split('-')
start = max(1, int(start))
end = min(total_pages, int(end))
pages.update(range(start - 1, end))
except:
pass
else:
try:
p = int(part)
if 1 <= p <= total_pages:
pages.add(p - 1)
except:
pass
return sorted(list(pages)) if pages else list(range(total_pages))
def export_pdf_image_tables(excel_app, file_path, excel_path, ak, sk, pages_str, log_func=None, debug=False): if log_func:
if not ak or not sk: log_func(f" [AI] 已唤醒本地 AI 引擎,正在全力识别中,请耐心等待...")
raise Exception("未配置 Baidu API Key 或 Secret Key,请点击 ⚙️ OCR API 设置 填写!")
try:
import requests
except ImportError:
raise Exception("缺少 requests 库,请使用 pip install requests 安装")
token = get_baidu_token(ak, sk)
images = [] # list of (page_num, image_bytes)
ext = os.path.splitext(file_path)[1].lower()
if ext == '.pdf':
try:
import fitz
except ImportError:
raise Exception("缺少 pymupdf 库,请使用 pip install pymupdf 安装")
doc = fitz.open(file_path)
page_indices = parse_page_ranges(pages_str, len(doc))
if log_func:
log_func(f" [PDF] 共有 {len(doc)} 页,本次提取 {len(page_indices)} 页...")
for p_idx in page_indices:
page = doc[p_idx]
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
img_bytes = pix.tobytes("png")
if len(img_bytes) > 4 * 1024 * 1024:
pix = page.get_pixmap(matrix=fitz.Matrix(1.0, 1.0))
img_bytes = pix.tobytes("jpeg")
images.append((p_idx + 1, img_bytes))
doc.close()
else:
with open(file_path, "rb") as f:
images.append((1, f.read()))
if not images:
return 0
wb = excel_app.Workbooks.Add()
table_count = 0
import tempfile
for page_num, img_bytes in images:
if log_func:
log_func(f" [OCR] 正在提交第 {page_num} 页到云端识别...")
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
req_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/table_recognize?access_token={token}"
resp = requests.post(req_url, data={"image": img_b64, "is_sync": "false"}, timeout=30)
res_data = resp.json()
if "error_code" in res_data:
if res_data["error_code"] == 18:
raise Exception("QPS 超限,请稍后再试!")
else:
raise Exception(f"识别失败: {res_data.get('error_msg', res_data)}")
req_id = res_data["result"][0]["request_id"]
if log_func:
log_func(f" [OCR] 第 {page_num} 页识别中,等待结果...")
get_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/table_result_get?access_token={token}"
download_url = None
for _ in range(30):
time.sleep(2)
poll_resp = requests.post(get_url, data={"request_id": req_id, "result_type": "excel"}, timeout=10)
poll_data = poll_resp.json()
if "error_code" in poll_data:
raise Exception(f"获取结果失败: {poll_data.get('error_msg', poll_data)}")
ret_code = poll_data["result"]["ret_code"]
if ret_code == 3: # Completed
download_url = poll_data["result"]["result_data"]
break
elif ret_code == 4: # Failed
download_url = None
break
if not download_url:
if log_func:
log_func(f" [OCR] 第 {page_num} 页未检测到表格。")
continue
xls_resp = requests.get(download_url, timeout=30)
temp_xls_path = os.path.join(tempfile.gettempdir(), f"~ocr_temp_{req_id}.xls")
with open(temp_xls_path, "wb") as f:
f.write(xls_resp.content)
try:
temp_wb = excel_app.Workbooks.Open(temp_xls_path, ReadOnly=True, Visible=debug)
for i in range(1, temp_wb.Sheets.Count + 1):
temp_ws = temp_wb.Sheets(i)
table_count += 1
if table_count > wb.Sheets.Count:
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
else:
ws = wb.Sheets.Item(table_count)
ws.Name = f"P{page_num}_T{i}"
temp_ws.Cells.Copy(Destination=ws.Cells)
ws.Columns.AutoFit()
temp_wb.Close(SaveChanges=False)
except Exception as e:
raise Exception(f"处理第 {page_num} 页返回的 Excel 失败: {e}")
finally:
if os.path.exists(temp_xls_path):
try:
os.remove(temp_xls_path)
except:
pass
if table_count == 0:
if log_func:
log_func(f" [跳过] 未检测到任何表格。")
wb.Close(SaveChanges=False)
return 0
while wb.Sheets.Count > table_count:
wb.Sheets(wb.Sheets.Count).Delete()
abs_excel = os.path.abspath(excel_path) abs_excel = os.path.abspath(excel_path)
if os.path.exists(abs_excel): if os.path.exists(abs_excel):
try: try:
os.remove(abs_excel) os.remove(abs_excel)
except Exception: except:
pass pass
wb.SaveAs(Filename=abs_excel, FileFormat=51) cmd = [plugin_exe, file_path, abs_excel]
wb.Close(SaveChanges=False) if pages_str:
cmd.extend(["--pages", pages_str])
if log_func: startupinfo = None
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}") if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return table_count try:
result = subprocess.run(cmd, startupinfo=startupinfo, capture_output=True, text=True, encoding='utf-8', errors='replace')
if result.returncode != 0:
if "No tables detected" in result.stdout:
if log_func:
log_func(f" [跳过] 未检测到任何表格。")
return 0
raise Exception(f"AI 引擎运行失败: {result.stderr or result.stdout}")
if "No tables detected" in result.stdout:
if log_func:
log_func(f" [跳过] 未检测到任何表格。")
return 0
import re
m = re.search(r"Successfully extracted (\d+) tables", result.stdout)
table_count = int(m.group(1)) if m else 1
if log_func:
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
return table_count
except Exception as e:
raise Exception(f"调用本地 AI 失败: {e}")
+5 -44
View File
@@ -42,8 +42,6 @@ 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.api_key_var = tk.StringVar()
self.secret_key_var = tk.StringVar()
self.pdf_pages_var = tk.StringVar(value="") self.pdf_pages_var = tk.StringVar(value="")
self.pdf_engine_var = tk.StringVar(value="智能判定 (推荐)") self.pdf_engine_var = tk.StringVar(value="智能判定 (推荐)")
@@ -80,8 +78,6 @@ 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.api_key_var.set(cfg.get("api_key", ""))
self.secret_key_var.set(cfg.get("secret_key", ""))
self.pdf_pages_var.set(cfg.get("pdf_pages", "")) self.pdf_pages_var.set(cfg.get("pdf_pages", ""))
self.pdf_engine_var.set(cfg.get("pdf_engine", "智能判定 (推荐)")) self.pdf_engine_var.set(cfg.get("pdf_engine", "智能判定 (推荐)"))
except Exception: except Exception:
@@ -98,8 +94,6 @@ 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(),
"api_key": self.api_key_var.get(),
"secret_key": self.secret_key_var.get(),
"pdf_pages": self.pdf_pages_var.get(), "pdf_pages": self.pdf_pages_var.get(),
"pdf_engine": self.pdf_engine_var.get() "pdf_engine": self.pdf_engine_var.get()
} }
@@ -163,15 +157,15 @@ class BatchTableExtractorApp:
pdf_frame = ttk.Frame(path_box) pdf_frame = ttk.Frame(path_box)
pdf_frame.grid(row=3, column=1, sticky=tk.EW, padx=6) pdf_frame.grid(row=3, column=1, sticky=tk.EW, padx=6)
ttk.Combobox(pdf_frame, textvariable=self.pdf_engine_var, values=["智能判定 (推荐)", "强转 Word (免费/极速)", "云端 OCR (高精度/耗额度)"], state="readonly", width=22).pack(side=tk.LEFT, fill=tk.X, expand=True) ttk.Combobox(pdf_frame, textvariable=self.pdf_engine_var, values=["智能判定 (推荐)", "强转 Word (极速)", "强制本地 AI (需插件)"], state="readonly", width=30).pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Label(pdf_frame, text=" 提取页码: ").pack(side=tk.LEFT) ttk.Label(pdf_frame, text=" 提取页码: ").pack(side=tk.LEFT)
self.entry_pdf_pages = ttk.Entry(pdf_frame, textvariable=self.pdf_pages_var, width=12) self.entry_pdf_pages = ttk.Entry(pdf_frame, textvariable=self.pdf_pages_var, width=12)
self.entry_pdf_pages.pack(side=tk.LEFT) self.entry_pdf_pages.pack(side=tk.LEFT)
self.entry_pdf_pages.insert(0, "") self.entry_pdf_pages.insert(0, "")
self.btn_api_settings = ProgressButton(path_box, text="⚙️ OCR API", command=self._show_api_settings, height=22, width=65) # 移除云端OCR设置按钮,由空白标签占位,保持原有的列宽比例
self.btn_api_settings.grid(row=3, column=2, sticky=tk.EW) ttk.Label(path_box, text="", width=9).grid(row=3, column=2)
path_box.columnconfigure(1, weight=1) path_box.columnconfigure(1, weight=1)
@@ -199,37 +193,6 @@ class BatchTableExtractorApp:
def _on_topmost_toggle(self): def _on_topmost_toggle(self):
self.root.attributes("-topmost", self.topmost_var.get()) self.root.attributes("-topmost", self.topmost_var.get())
def _show_api_settings(self):
settings_win = tk.Toplevel(self.root)
settings_win.title("百度智能云 OCR API 设置")
settings_win.geometry("420x250")
settings_win.transient(self.root)
settings_win.grab_set()
frame = ttk.Frame(settings_win, padding="20")
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="API Key (AK):").pack(anchor=tk.W, pady=(0, 5))
ak_entry = ttk.Entry(frame, width=50)
ak_entry.pack(fill=tk.X, pady=(0, 10))
ak_entry.insert(0, self.api_key_var.get())
ttk.Label(frame, text="Secret Key (SK):").pack(anchor=tk.W, pady=(0, 5))
sk_entry = ttk.Entry(frame, width=50)
sk_entry.pack(fill=tk.X, pady=(0, 15))
sk_entry.insert(0, self.secret_key_var.get())
def save_and_close():
self.api_key_var.set(ak_entry.get().strip())
self.secret_key_var.set(sk_entry.get().strip())
self._save_config()
settings_win.destroy()
btn_save = ttk.Button(frame, text="保存设置", command=save_and_close)
btn_save.pack(fill=tk.X)
ttk.Label(frame, text="* 此凭证直接保存在本地 config.json 中", foreground="gray").pack(pady=(10, 0))
def _stop_task(self): def _stop_task(self):
self._pause_event.set() self._pause_event.set()
ans = messagebox.askyesno("确认", "任务已暂停。\n\n是否确定终止批量提取操作?\n(选择“是”终止操作,选择“否”继续提取)") ans = messagebox.askyesno("确认", "任务已暂停。\n\n是否确定终止批量提取操作?\n(选择“是”终止操作,选择“否”继续提取)")
@@ -500,11 +463,9 @@ class BatchTableExtractorApp:
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 from core.extractor import export_pdf_image_tables_local
ak = self.api_key_var.get().strip()
sk = self.secret_key_var.get().strip()
pages_str = self.pdf_pages_var.get().strip() pages_str = self.pdf_pages_var.get().strip()
tc = export_pdf_image_tables(excel_app, file_path, target_excel, ak, sk, pages_str, tc = export_pdf_image_tables_local(excel_app, file_path, target_excel, pages_str,
log_func=my_log, debug=debug_mode) log_func=my_log, debug=debug_mode)
duration = time.time() - t0 duration = time.time() - t0