feat: 集成百度智能云表格 OCR 支持处理 PDF 和图片
This commit is contained in:
@@ -15,6 +15,7 @@
|
||||
* **安全的中断与控制**:支持提取过程中途暂停,弹出确认保护防止误触关闭;遇到同名文件可灵活选择直接覆盖、自动重命名或跳过。
|
||||
* **详尽的历史日志追踪**:内置本地 CSV 转换日志,通过一键“日志”面板随时追溯每次批处理的成功数、耗时、表格数及报错详情。
|
||||
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
||||
* **PDF 与扫描件图片支持**:内置百度智能云 OCR 引擎接口,支持将 PDF(含扫描件)和图片文件发送至云端高精度提取表格,无缝汇总为 Excel。
|
||||
|
||||
---
|
||||
|
||||
@@ -50,7 +51,7 @@ WordTableExtractor/
|
||||
### 2. 安装依赖
|
||||
|
||||
```powershell
|
||||
pip install pywin32 windnd
|
||||
pip install pywin32 windnd requests pymupdf
|
||||
```
|
||||
|
||||
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
||||
@@ -61,7 +62,15 @@ pip install pywin32 windnd
|
||||
> python <完整路径> -install
|
||||
> ```
|
||||
|
||||
### 3. 运行程序
|
||||
### 3. 配置百度 OCR 接口(仅在需要提取 PDF/图片 时需要)
|
||||
|
||||
为了提取 PDF 扫描件和图片,你需要前往 **[百度智能云控制台](https://console.bce.baidu.com/ai/#/ai/ocr/overview/index)** 免费申请表格识别的 API 密钥:
|
||||
1. 注册并实名认证百度智能云账号。
|
||||
2. 找到“人工智能” -> “文字识别”,点击“创建应用”。
|
||||
3. 勾选需要包含的接口(确保勾选“表格文字识别”),创建完毕后即可获得 **API Key (AK)** 和 **Secret Key (SK)**。
|
||||
4. 打开本工具主界面,点击 **⚙️ OCR API** 设置,将 AK 和 SK 填入并保存。
|
||||
|
||||
### 4. 运行程序
|
||||
|
||||
```powershell
|
||||
python src/main.py
|
||||
@@ -83,23 +92,8 @@ pip install pyinstaller
|
||||
|
||||
在项目根目录下执行以下指令,排除不必要的调试模块:
|
||||
|
||||
```powershell
|
||||
pyinstaller -F -w `
|
||||
--icon="app.ico" `
|
||||
--add-data "app.ico;." `
|
||||
--hidden-import "win32com.client" `
|
||||
--hidden-import "pythoncom" `
|
||||
--hidden-import "pywintypes" `
|
||||
--exclude-module "win32com.test" `
|
||||
--exclude-module "win32com.demos" `
|
||||
--exclude-module "win32com.axdebug" `
|
||||
--exclude-module "win32com.axscript" `
|
||||
--exclude-module "win32com.directsound" `
|
||||
--exclude-module "win32com.mapi" `
|
||||
--exclude-module "setuptools" `
|
||||
--exclude-module "distutils" `
|
||||
--name "WordTableExtractor" `
|
||||
src/main.py
|
||||
```bash
|
||||
python -m PyInstaller -y -F -w --icon="app.ico" --add-data "app.ico;." --hidden-import "win32com.client" --hidden-import "pythoncom" --hidden-import "pywintypes" --hidden-import "requests" --hidden-import "fitz" --exclude-module "win32com.test" --exclude-module "win32com.demos" --exclude-module "win32com.axdebug" --exclude-module "win32com.axscript" --exclude-module "win32com.directsound" --exclude-module "win32com.mapi" --exclude-module "setuptools" --exclude-module "distutils" --name "WordTableExtractor" src/main.py
|
||||
```
|
||||
|
||||
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。配置信息与运行日志将自动在该 exe 所在的目录中生成 `config.json` 与 `conversion.csv`。
|
||||
|
||||
@@ -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
@@ -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:
|
||||
@@ -145,6 +155,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)
|
||||
|
||||
# 3. 运行操作区
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user