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
+47 -169
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)
except Exception:
pass
import base64
import requests
import json
import time
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}"
resp = requests.post(url, timeout=10)
data = resp.json()
if 'access_token' in data:
return data['access_token']
raise Exception(f"获取Token失败: {data.get('error_description', data)}")
def parse_page_ranges(pages_str, total_pages):
if not pages_str:
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 not ak or not sk:
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)
def export_pdf_image_tables_local(excel_app, file_path, excel_path, pages_str, log_func=None, debug=False):
import subprocess
import os
import sys
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
# 查找插件路径
plugin_exe = os.path.join(os.getcwd(), "ocr_plugin", "ocr_worker.exe")
if not os.path.exists(plugin_exe):
# 尝试查找相对 main.py / exe 的路径
app_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
plugin_exe = os.path.join(app_dir, "ocr_plugin", "ocr_worker.exe")
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")
if not os.path.exists(plugin_exe):
raise Exception("未检测到本地 AI 插件!请下载 'ocr_plugin' 文件夹并放置在程序同一目录下。")
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 log_func:
log_func(f" [AI] 已唤醒本地 AI 引擎,正在全力识别中,请耐心等待...")
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)
if os.path.exists(abs_excel):
try:
os.remove(abs_excel)
except Exception:
except:
pass
wb.SaveAs(Filename=abs_excel, FileFormat=51)
wb.Close(SaveChanges=False)
if log_func:
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
cmd = [plugin_exe, file_path, abs_excel]
if pages_str:
cmd.extend(["--pages", pages_str])
return table_count
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
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}")