feat: 集成百度智能云表格 OCR 支持处理 PDF 和图片

This commit is contained in:
HONOR
2026-09-16 12:33:34 +08:00
parent bd2365f2dd
commit 2e7a22c207
3 changed files with 263 additions and 28 deletions
+180
View File
@@ -134,3 +134,183 @@ 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)
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)
if os.path.exists(abs_excel):
try:
os.remove(abs_excel)
except Exception:
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)}")
return table_count
+70 -9
View File
@@ -42,6 +42,10 @@ class BatchTableExtractorApp:
self.topmost_var = tk.BooleanVar(value=False)
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="")
import threading
self._stop_event = threading.Event()
self._pause_event = threading.Event()
@@ -75,6 +79,9 @@ 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.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", ""))
except Exception:
pass
@@ -88,7 +95,10 @@ class BatchTableExtractorApp:
"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()
"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()
}
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
@@ -144,6 +154,16 @@ class BatchTableExtractorApp:
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.lbl_pdf_pages = ttk.Label(path_box, text="PDF提取页码:")
self.lbl_pdf_pages.grid(row=3, column=0, sticky=tk.W, pady=5)
self.entry_pdf_pages = ttk.Entry(path_box, textvariable=self.pdf_pages_var, width=46)
self.entry_pdf_pages.grid(row=3, column=1, sticky=tk.EW, padx=6)
self.entry_pdf_pages.insert(0, "") # Placeholder text hint can be added if needed
# Create a small hint label or just rely on the label
self.btn_api_settings = ProgressButton(path_box, text="⚙️ OCR API", command=self._show_api_settings, height=22, width=65)
self.btn_api_settings.grid(row=3, column=2, sticky=tk.EW)
path_box.columnconfigure(1, weight=1)
@@ -171,6 +191,37 @@ class BatchTableExtractorApp:
def _on_topmost_toggle(self):
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):
self._pause_event.set()
ans = messagebox.askyesno("确认", "任务已暂停。\n\n是否确定终止批量提取操作?\n(选择“是”终止操作,选择“否”继续提取)")
@@ -190,11 +241,11 @@ class BatchTableExtractorApp:
def _browse_src(self):
if self.mode_var.get() == "dir":
path = filedialog.askdirectory(title="选择包含 Word 文件的目录")
path = filedialog.askdirectory(title="选择包含文档的目录")
else:
path = filedialog.askopenfilename(
title="选择 Word 文档",
filetypes=[("Word 文档", "*.doc *.docx"), ("所有文件", "*.*")]
title="选择文档",
filetypes=[("支持的文档", "*.doc *.docx *.pdf *.png *.jpg *.jpeg"), ("所有文件", "*.*")]
)
if path:
path = os.path.normpath(path)
@@ -300,11 +351,11 @@ class BatchTableExtractorApp:
# 收集目标文件列表
files_to_process = []
if mode == "file":
if src.lower().endswith(('.doc', '.docx')):
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"):
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))
@@ -312,7 +363,7 @@ class BatchTableExtractorApp:
files_to_process = [f for f in files_to_process if not os.path.basename(f).startswith("~$")]
if not files_to_process:
messagebox.showinfo("提示", "未找到任何待处理的 .doc 或 .docx 文件!")
messagebox.showinfo("提示", "未找到任何待处理的文档或图片!")
return
self.btn_run.config_btn(text="启动中... ", command=self._stop_task)
@@ -407,8 +458,18 @@ class BatchTableExtractorApp:
def my_log(m):
self.root.after(0, self.log, m)
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
log_func=my_log, debug=debug_mode)
ext = os.path.splitext(file_path)[1].lower()
if ext in ['.doc', '.docx']:
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
ak = self.api_key_var.get().strip()
sk = self.secret_key_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,
log_func=my_log, debug=debug_mode)
duration = time.time() - t0
if tc > 0:
success_count += 1