Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4a24790d6 | ||
|
|
4a7e170e6a | ||
|
|
c1e0677cf8 | ||
|
|
b9d3482905 | ||
|
|
d582dd5410 | ||
|
|
ba1da8d7bd | ||
|
|
a8ec26e58c | ||
|
|
49c04a231a | ||
|
|
8dcd7c4031 | ||
|
|
c07f958d40 | ||
|
|
2dcd40cf6e | ||
|
|
8f87562feb | ||
|
|
edb390e4f8 | ||
|
|
926a5b7dd1 | ||
|
|
f1b1d4e453 | ||
|
|
d17c52403d | ||
|
|
ebfc197c31 | ||
|
|
c59153253c | ||
|
|
944d2f7888 | ||
|
|
dbab45baaf | ||
|
|
2e7a22c207 | ||
|
|
bd2365f2dd | ||
|
|
fec5ceed33 |
@@ -4,3 +4,5 @@ conversion.csv
|
|||||||
/build
|
/build
|
||||||
/dist
|
/dist
|
||||||
/WordTableExtractor.spec
|
/WordTableExtractor.spec
|
||||||
|
ocr_worker.spec
|
||||||
|
/scratch
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# WordTableExtractor 项目开发规范 (Agent Rules)
|
||||||
|
|
||||||
|
这是一份供 AI Assistant (Agent) 读取的项目级约束规则文件。
|
||||||
|
|
||||||
|
## 1. 代码提交流程 (Git Commits)
|
||||||
|
- **必须使用中文**编写 Git Commit Message。
|
||||||
|
- 每次修改完代码并测试通过后,请养成主动提交代码的习惯,并遵循约定式提交规范(例如:`feat: 增加xxx功能`, `fix: 修复xxx问题`, `docs: 更新文档` 等)。
|
||||||
|
|
||||||
|
## 2. 核心架构约束 (Core Architecture)
|
||||||
|
- **禁止使用 Office COM (win32com) 进行常规的数据提取**。
|
||||||
|
- 必须使用 `python-docx` 读取 Word 文档,使用 `openpyxl` 和 `pandas` 写入 Excel。这是为了保证程序在后台绝对静默运行,不弹出窗口,不抢夺用户焦点。
|
||||||
|
- `win32.DispatchEx` 仅在极少数必须进行前置格式转换(如 `.doc` 转 `.docx`)且没有其他替代方案时才能作为 fallback 使用,并且必须保证 `Visible = False`。
|
||||||
|
|
||||||
|
## 3. UI 交互规范
|
||||||
|
- 点击“开始提取”或拖拽文件时,必须第一时间清空日志窗口,确保运行日志清爽。
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
* **安全的中断与控制**:支持提取过程中途暂停,弹出确认保护防止误触关闭;遇到同名文件可灵活选择直接覆盖、自动重命名或跳过。
|
* **安全的中断与控制**:支持提取过程中途暂停,弹出确认保护防止误触关闭;遇到同名文件可灵活选择直接覆盖、自动重命名或跳过。
|
||||||
* **详尽的历史日志追踪**:内置本地 CSV 转换日志,通过一键“日志”面板随时追溯每次批处理的成功数、耗时、表格数及报错详情。
|
* **详尽的历史日志追踪**:内置本地 CSV 转换日志,通过一键“日志”面板随时追溯每次批处理的成功数、耗时、表格数及报错详情。
|
||||||
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
||||||
|
* **PDF 与扫描件图片支持**:内置百度智能云 OCR 引擎接口,支持将 PDF(含扫描件)和图片文件发送至云端高精度提取表格,无缝汇总为 Excel。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ WordTableExtractor/
|
|||||||
### 2. 安装依赖
|
### 2. 安装依赖
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
pip install pywin32 windnd
|
pip install pywin32 windnd requests pymupdf
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
||||||
@@ -61,7 +62,15 @@ pip install pywin32 windnd
|
|||||||
> python <完整路径> -install
|
> 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
|
```powershell
|
||||||
python src/main.py
|
python src/main.py
|
||||||
@@ -83,23 +92,8 @@ pip install pyinstaller
|
|||||||
|
|
||||||
在项目根目录下执行以下指令,排除不必要的调试模块:
|
在项目根目录下执行以下指令,排除不必要的调试模块:
|
||||||
|
|
||||||
```powershell
|
```bash
|
||||||
pyinstaller -F -w `
|
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
|
||||||
--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
|
|
||||||
```
|
```
|
||||||
|
|
||||||
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。配置信息与运行日志将自动在该 exe 所在的目录中生成 `config.json` 与 `conversion.csv`。
|
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。配置信息与运行日志将自动在该 exe 所在的目录中生成 `config.json` 与 `conversion.csv`。
|
||||||
|
|||||||
@@ -1,2 +1,5 @@
|
|||||||
pywin32
|
pywin32
|
||||||
windnd
|
windnd
|
||||||
|
python-docx
|
||||||
|
openpyxl
|
||||||
|
pandas
|
||||||
|
|||||||
+175
-74
@@ -2,112 +2,213 @@ import os
|
|||||||
import pythoncom
|
import pythoncom
|
||||||
import win32com.client as win32
|
import win32com.client as win32
|
||||||
|
|
||||||
def detect_and_create_apps():
|
def convert_doc_to_docx(doc_path, log_func=None, debug=False):
|
||||||
"""探测并绑定 Microsoft Office 或 WPS 引擎"""
|
"""
|
||||||
# 1. 探测 MS Office
|
静默将 .doc 转换为 .docx,不影响用户已打开的任何 Word 文档。
|
||||||
|
使用独立进程 (DispatchEx) 和只读模式 (ReadOnly=True)。
|
||||||
|
"""
|
||||||
|
import tempfile
|
||||||
|
import pythoncom
|
||||||
|
|
||||||
|
pythoncom.CoInitialize()
|
||||||
|
word_app = None
|
||||||
|
doc = None
|
||||||
try:
|
try:
|
||||||
word = win32.gencache.EnsureDispatch('Word.Application')
|
if debug and log_func:
|
||||||
excel = win32.gencache.EnsureDispatch('Excel.Application')
|
log_func(f" [Debug] 正在启动独立 Word 进程转换 .doc 文件...")
|
||||||
return word, excel, "Microsoft Office"
|
|
||||||
|
# 优先尝试启动全新独立的 MS Word 进程
|
||||||
|
try:
|
||||||
|
word_app = win32.DispatchEx('Word.Application')
|
||||||
|
except Exception:
|
||||||
|
# 如果没有 MS Word,尝试启动 WPS
|
||||||
|
try:
|
||||||
|
word_app = win32.DispatchEx('wps.Application')
|
||||||
except Exception:
|
except Exception:
|
||||||
try:
|
try:
|
||||||
word = win32.Dispatch('Word.Application')
|
word_app = win32.DispatchEx('kwps.Application')
|
||||||
excel = win32.Dispatch('Excel.Application')
|
except Exception:
|
||||||
return word, excel, "Microsoft Office"
|
# 如果当前 WPS 版本不支持 DispatchEx (独立进程),则降级使用普通 Dispatch
|
||||||
|
try:
|
||||||
|
word_app = win32.Dispatch('wps.Application')
|
||||||
|
except Exception:
|
||||||
|
word_app = win32.Dispatch('kwps.Application')
|
||||||
|
word_app.Visible = False
|
||||||
|
word_app.DisplayAlerts = False
|
||||||
|
|
||||||
|
abs_doc = os.path.abspath(doc_path)
|
||||||
|
out_dir = os.path.join(tempfile.gettempdir(), "word_table_extractor_temp")
|
||||||
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# 构造临时 docx 路径
|
||||||
|
base_name = os.path.basename(abs_doc)
|
||||||
|
temp_docx = os.path.join(out_dir, f"{base_name}.docx")
|
||||||
|
|
||||||
|
if os.path.exists(temp_docx):
|
||||||
|
try:
|
||||||
|
os.remove(temp_docx)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 2. 探测 WPS Office
|
# ReadOnly=True 是关键,如果文件正在被用户编辑,这样能确保安全读取,不锁定
|
||||||
try:
|
doc = word_app.Documents.Open(abs_doc, ReadOnly=True, Visible=False)
|
||||||
try:
|
|
||||||
word = win32.gencache.EnsureDispatch('wps.Application')
|
|
||||||
except Exception:
|
|
||||||
word = win32.Dispatch('kwps.Application')
|
|
||||||
|
|
||||||
try:
|
# 16 = wdFormatDocumentDefault (docx)
|
||||||
excel = win32.gencache.EnsureDispatch('et.Application')
|
doc.SaveAs(temp_docx, FileFormat=16)
|
||||||
except Exception:
|
return temp_docx
|
||||||
excel = win32.Dispatch('ket.Application')
|
|
||||||
|
|
||||||
return word, excel, "WPS Office"
|
except Exception as e:
|
||||||
|
if log_func:
|
||||||
|
log_func(f" [Error] .doc 格式转换失败: {e}")
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if doc:
|
||||||
|
try:
|
||||||
|
doc.Close(SaveChanges=False)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
if word_app:
|
||||||
|
try:
|
||||||
|
word_app.Quit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
pythoncom.CoUninitialize()
|
||||||
|
|
||||||
raise RuntimeError("未检测到可用的办公套件!请确保电脑已安装 Microsoft Office 或 WPS。")
|
def export_single_doc_tables(doc_path, excel_path, log_func=None, debug=False):
|
||||||
|
"""
|
||||||
|
提取单个 Word 文件中的所有表格到 Excel。
|
||||||
|
使用 python-docx 和 openpyxl,实现 100% 静默提取。
|
||||||
|
"""
|
||||||
|
from docx import Document
|
||||||
|
from openpyxl import Workbook
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func=None, debug=False):
|
|
||||||
"""提取单个 Word 文件中的所有表格到 Excel"""
|
|
||||||
abs_doc = os.path.abspath(doc_path)
|
abs_doc = os.path.abspath(doc_path)
|
||||||
abs_excel = os.path.abspath(excel_path)
|
abs_excel = os.path.abspath(excel_path)
|
||||||
|
|
||||||
doc = None
|
file_to_clean = None
|
||||||
wb = None
|
is_doc = abs_doc.lower().endswith('.doc')
|
||||||
|
|
||||||
|
if is_doc:
|
||||||
|
if debug and log_func:
|
||||||
|
log_func(f" [Info] 检测到旧版 .doc 格式,正在安全转换为 .docx...")
|
||||||
|
abs_doc = convert_doc_to_docx(abs_doc, log_func=log_func, debug=debug)
|
||||||
|
file_to_clean = abs_doc
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if debug and log_func:
|
if debug and log_func:
|
||||||
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
|
log_func(f" [Debug] 正在使用 python-docx 解析文档...")
|
||||||
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug)
|
|
||||||
table_count = doc.Tables.Count
|
doc = Document(abs_doc)
|
||||||
|
tables = doc.tables
|
||||||
|
table_count = len(tables)
|
||||||
|
|
||||||
if table_count == 0:
|
if table_count == 0:
|
||||||
if log_func:
|
if log_func:
|
||||||
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
|
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
wb = excel_app.Workbooks.Add()
|
wb = Workbook()
|
||||||
|
wb.remove(wb.active) # 移除默认的Sheet
|
||||||
|
|
||||||
for i in range(1, table_count + 1):
|
for i, table in enumerate(tables):
|
||||||
if debug and log_func:
|
sheet_name = f"Table_{i+1}"
|
||||||
log_func(f" [Debug] 正在提取 第 {i}/{table_count} 个表格...")
|
ws = wb.create_sheet(title=sheet_name)
|
||||||
table = doc.Tables.Item(i)
|
|
||||||
table.Range.Copy()
|
|
||||||
|
|
||||||
import time
|
# python-docx 提取表格数据 (简单遍历,处理了基本的合并单元格结构)
|
||||||
time.sleep(0.2) # 给系统剪贴板同步数据留点时间
|
for r_idx, row in enumerate(table.rows):
|
||||||
|
row_data = []
|
||||||
|
for cell in row.cells:
|
||||||
|
row_data.append(cell.text.strip())
|
||||||
|
ws.append(row_data)
|
||||||
|
|
||||||
if i > wb.Sheets.Count:
|
# 如果存在旧文件先删除
|
||||||
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
|
|
||||||
else:
|
|
||||||
ws = wb.Sheets.Item(i)
|
|
||||||
|
|
||||||
ws.Name = f"Table_{i}"
|
|
||||||
|
|
||||||
# Excel的Paste可能会因为剪贴板被占用而报错 0x800A03EC,加入重试机制
|
|
||||||
for retry in range(3):
|
|
||||||
try:
|
|
||||||
ws.Paste()
|
|
||||||
break
|
|
||||||
except Exception as pe:
|
|
||||||
if debug and log_func:
|
|
||||||
log_func(f" [Debug] 粘贴报错 {pe},等待0.5秒后重试...")
|
|
||||||
time.sleep(0.5)
|
|
||||||
else:
|
|
||||||
ws.Paste() # 最后一次尝试,若失败则抛出异常
|
|
||||||
|
|
||||||
ws.Columns.AutoFit()
|
|
||||||
|
|
||||||
while wb.Sheets.Count > table_count:
|
|
||||||
wb.Sheets(wb.Sheets.Count).Delete()
|
|
||||||
|
|
||||||
# 51 = xlOpenXMLWorkbook (.xlsx)
|
|
||||||
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 Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
wb.SaveAs(Filename=abs_excel, FileFormat=51)
|
wb.save(abs_excel)
|
||||||
|
|
||||||
|
if log_func:
|
||||||
|
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
||||||
|
|
||||||
|
return table_count
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if log_func:
|
||||||
|
log_func(f" [Error] 提取失败: {e}")
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
# 清理 .doc 转换产生的临时文件
|
||||||
|
if file_to_clean and os.path.exists(file_to_clean):
|
||||||
|
try:
|
||||||
|
os.remove(file_to_clean)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
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
|
||||||
|
|
||||||
|
# 查找插件路径 (支持直接在 ocr_plugin 下,也支持嵌套在 ocr_worker 下)
|
||||||
|
plugin_paths = [
|
||||||
|
os.path.join(os.getcwd(), "ocr_plugin", "ocr_worker.exe"),
|
||||||
|
os.path.join(os.getcwd(), "ocr_plugin", "ocr_worker", "ocr_worker.exe"),
|
||||||
|
os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "ocr_plugin", "ocr_worker.exe"),
|
||||||
|
os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "ocr_plugin", "ocr_worker", "ocr_worker.exe")
|
||||||
|
]
|
||||||
|
|
||||||
|
plugin_exe = None
|
||||||
|
for p in plugin_paths:
|
||||||
|
if os.path.exists(p):
|
||||||
|
plugin_exe = p
|
||||||
|
break
|
||||||
|
|
||||||
|
if not plugin_exe:
|
||||||
|
raise Exception("未检测到本地 AI 插件!请下载 'ocr_plugin' 文件夹并放置在程序同一目录下。")
|
||||||
|
|
||||||
|
if log_func:
|
||||||
|
log_func(f" [AI] 已唤醒本地 AI 引擎,正在全力识别中,请耐心等待...")
|
||||||
|
|
||||||
|
abs_excel = os.path.abspath(excel_path)
|
||||||
|
if os.path.exists(abs_excel):
|
||||||
|
try:
|
||||||
|
os.remove(abs_excel)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
cmd = [plugin_exe, file_path, abs_excel]
|
||||||
|
if pages_str:
|
||||||
|
cmd.extend(["--pages", pages_str])
|
||||||
|
|
||||||
|
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:
|
if log_func:
|
||||||
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
||||||
return table_count
|
return table_count
|
||||||
finally:
|
|
||||||
if wb:
|
except Exception as e:
|
||||||
try:
|
raise Exception(f"调用本地 AI 失败: {e}")
|
||||||
wb.Close(SaveChanges=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if doc:
|
|
||||||
try:
|
|
||||||
doc.Close(SaveChanges=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|||||||
+158
-46
@@ -7,9 +7,10 @@ from tkinter import filedialog, messagebox, ttk
|
|||||||
import pythoncom
|
import pythoncom
|
||||||
import windnd
|
import windnd
|
||||||
import datetime
|
import datetime
|
||||||
|
import time
|
||||||
|
|
||||||
from utils.config import CONFIG_FILE, APP_DIR
|
from utils.config import CONFIG_FILE, APP_DIR
|
||||||
from core.extractor import detect_and_create_apps, export_single_doc_tables
|
from core.extractor import export_single_doc_tables
|
||||||
from ui.widgets import ProgressButton
|
from ui.widgets import ProgressButton
|
||||||
from ui.history_window import record_log
|
from ui.history_window import record_log
|
||||||
|
|
||||||
@@ -42,6 +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="不处理")
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
self._stop_event = threading.Event()
|
self._stop_event = threading.Event()
|
||||||
self._pause_event = threading.Event()
|
self._pause_event = threading.Event()
|
||||||
@@ -75,6 +78,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.engine_var.set(cfg.get("engine_var", "自动判断 (推荐)"))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -88,7 +93,8 @@ class BatchTableExtractorApp:
|
|||||||
"auto_extract": self.auto_extract_var.get(),
|
"auto_extract": self.auto_extract_var.get(),
|
||||||
"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()
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||||
@@ -97,6 +103,13 @@ class BatchTableExtractorApp:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def _build_ui(self):
|
def _build_ui(self):
|
||||||
|
# 移除只读下拉框丑陋的蓝色背景高亮
|
||||||
|
style = ttk.Style()
|
||||||
|
style.map('TCombobox',
|
||||||
|
fieldbackground=[('readonly', 'white')],
|
||||||
|
selectbackground=[('readonly', 'focus', 'white'), ('readonly', 'white')],
|
||||||
|
selectforeground=[('readonly', 'focus', 'black'), ('readonly', 'black')])
|
||||||
|
|
||||||
frame = ttk.Frame(self.root, padding="15")
|
frame = ttk.Frame(self.root, padding="15")
|
||||||
frame.pack(fill=tk.BOTH, expand=True)
|
frame.pack(fill=tk.BOTH, expand=True)
|
||||||
|
|
||||||
@@ -130,20 +143,33 @@ class BatchTableExtractorApp:
|
|||||||
|
|
||||||
self.lbl_src = ttk.Label(path_box, text="来源目录:")
|
self.lbl_src = ttk.Label(path_box, text="来源目录:")
|
||||||
self.lbl_src.grid(row=0, column=0, sticky=tk.W, pady=5)
|
self.lbl_src.grid(row=0, column=0, sticky=tk.W, pady=5)
|
||||||
ttk.Entry(path_box, textvariable=self.src_path_var, width=46).grid(row=0, column=1, sticky=tk.EW, padx=6)
|
ttk.Entry(path_box, textvariable=self.src_path_var, width=40).grid(row=0, column=1, sticky=tk.EW, padx=6)
|
||||||
self.btn_browse_src = ProgressButton(path_box, text="选择...", command=self._browse_src, height=22, width=65)
|
self.btn_browse_src = ProgressButton(path_box, text="选择...", command=self._browse_src, height=22, width=50)
|
||||||
self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW)
|
self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW, padx=(0, 4))
|
||||||
|
self.btn_open_src = ProgressButton(path_box, text="打开", command=self._open_src_dir, height=22, width=40)
|
||||||
|
self.btn_open_src.grid(row=0, column=3, sticky=tk.EW)
|
||||||
|
|
||||||
ttk.Label(path_box, text="转换目录:").grid(row=1, column=0, sticky=tk.W, pady=5)
|
ttk.Label(path_box, text="转换目录:").grid(row=1, column=0, sticky=tk.W, pady=5)
|
||||||
ttk.Entry(path_box, textvariable=self.out_dir_var, width=46, state="readonly").grid(row=1, column=1, sticky=tk.EW, padx=6)
|
ttk.Entry(path_box, textvariable=self.out_dir_var, width=40, state="readonly").grid(row=1, column=1, sticky=tk.EW, padx=6)
|
||||||
self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=65)
|
self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=50)
|
||||||
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW)
|
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW, padx=(0, 4))
|
||||||
|
self.btn_open_out = ProgressButton(path_box, text="打开", command=self._open_out_dir, height=22, width=40)
|
||||||
|
self.btn_open_out.grid(row=1, column=3, sticky=tk.EW)
|
||||||
|
|
||||||
ttk.Label(path_box, text="遇到同名文件:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
ttk.Label(path_box, text="文件冲突:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
||||||
ttk.Combobox(path_box, textvariable=self.conflict_action_var, values=["直接覆盖 (默认)", "自动重命名", "直接跳过"], state="readonly", width=43).grid(row=2, column=1, sticky=tk.W, padx=6)
|
|
||||||
|
|
||||||
self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=65)
|
combo_frame = ttk.Frame(path_box)
|
||||||
self.btn_view_log.grid(row=2, column=2, sticky=tk.EW)
|
combo_frame.grid(row=2, column=1, sticky=tk.EW, padx=6)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=94)
|
||||||
|
self.btn_view_log.grid(row=2, column=2, columnspan=2, sticky=tk.EW)
|
||||||
|
|
||||||
path_box.columnconfigure(1, weight=1)
|
path_box.columnconfigure(1, weight=1)
|
||||||
|
|
||||||
@@ -164,6 +190,10 @@ class BatchTableExtractorApp:
|
|||||||
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
||||||
self.txt.config(yscrollcommand=sb.set)
|
self.txt.config(yscrollcommand=sb.set)
|
||||||
|
|
||||||
|
# 添加耗时悬浮标签
|
||||||
|
self.lbl_timer = tk.Label(self.txt, text="00:00:00.000", font=("Consolas", 10), bg="white", fg="gray")
|
||||||
|
self.lbl_timer.place(relx=1.0, rely=0.0, anchor=tk.NE, x=-10, y=5)
|
||||||
|
|
||||||
def _on_debug_toggle(self):
|
def _on_debug_toggle(self):
|
||||||
if self.debug_var.get():
|
if self.debug_var.get():
|
||||||
messagebox.showinfo("Debug 模式说明", "开启 Debug 模式后,程序在提取表格时将强制显示 Office/WPS 窗口。\n\n这主要用于排查程序“卡死”的问题。例如:当文档被加密或需要修复时,Office 会在后台弹窗等待用户点击。开启此模式可让你看到这些弹窗并手动处理。")
|
messagebox.showinfo("Debug 模式说明", "开启 Debug 模式后,程序在提取表格时将强制显示 Office/WPS 窗口。\n\n这主要用于排查程序“卡死”的问题。例如:当文档被加密或需要修复时,Office 会在后台弹窗等待用户点击。开启此模式可让你看到这些弹窗并手动处理。")
|
||||||
@@ -190,11 +220,11 @@ class BatchTableExtractorApp:
|
|||||||
|
|
||||||
def _browse_src(self):
|
def _browse_src(self):
|
||||||
if self.mode_var.get() == "dir":
|
if self.mode_var.get() == "dir":
|
||||||
path = filedialog.askdirectory(title="选择包含 Word 文件的目录")
|
path = filedialog.askdirectory(title="选择包含文档的目录")
|
||||||
else:
|
else:
|
||||||
path = filedialog.askopenfilename(
|
path = filedialog.askopenfilename(
|
||||||
title="选择 Word 文档",
|
title="选择文档",
|
||||||
filetypes=[("Word 文档", "*.doc *.docx"), ("所有文件", "*.*")]
|
filetypes=[("支持的文档", "*.doc *.docx *.pdf *.png *.jpg *.jpeg"), ("所有文件", "*.*")]
|
||||||
)
|
)
|
||||||
if path:
|
if path:
|
||||||
path = os.path.normpath(path)
|
path = os.path.normpath(path)
|
||||||
@@ -208,6 +238,34 @@ class BatchTableExtractorApp:
|
|||||||
if path:
|
if path:
|
||||||
self.out_dir_var.set(os.path.normpath(path))
|
self.out_dir_var.set(os.path.normpath(path))
|
||||||
|
|
||||||
|
def _open_src_dir(self):
|
||||||
|
path = self.src_path_var.get().strip()
|
||||||
|
if not path:
|
||||||
|
messagebox.showinfo("提示", "来源目录为空")
|
||||||
|
return
|
||||||
|
if os.path.isfile(path):
|
||||||
|
path = os.path.dirname(path)
|
||||||
|
if os.path.exists(path):
|
||||||
|
try:
|
||||||
|
os.startfile(path)
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showerror("错误", f"无法打开目录: {e}")
|
||||||
|
else:
|
||||||
|
messagebox.showinfo("提示", "该来源路径不存在")
|
||||||
|
|
||||||
|
def _open_out_dir(self):
|
||||||
|
path = self.out_dir_var.get().strip()
|
||||||
|
if not path:
|
||||||
|
messagebox.showinfo("提示", "转换目录为空")
|
||||||
|
return
|
||||||
|
if os.path.exists(path):
|
||||||
|
try:
|
||||||
|
os.startfile(path)
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showerror("错误", f"无法打开目录: {e}")
|
||||||
|
else:
|
||||||
|
messagebox.showinfo("提示", "转换目录目前还不存在,请先提取生成文件")
|
||||||
|
|
||||||
def _on_drop_files(self, files):
|
def _on_drop_files(self, files):
|
||||||
if not files:
|
if not files:
|
||||||
return
|
return
|
||||||
@@ -272,8 +330,33 @@ class BatchTableExtractorApp:
|
|||||||
self._save_config()
|
self._save_config()
|
||||||
self.root.destroy()
|
self.root.destroy()
|
||||||
|
|
||||||
|
def _update_timer(self):
|
||||||
|
if not getattr(self, '_is_running', False):
|
||||||
|
return
|
||||||
|
|
||||||
|
if self._pause_event.is_set():
|
||||||
|
if not getattr(self, '_is_paused_now', False):
|
||||||
|
self._is_paused_now = True
|
||||||
|
self._pause_start = time.time()
|
||||||
|
else:
|
||||||
|
if getattr(self, '_is_paused_now', False):
|
||||||
|
self._is_paused_now = False
|
||||||
|
self._start_time += (time.time() - self._pause_start)
|
||||||
|
|
||||||
|
elapsed = time.time() - getattr(self, '_start_time', time.time())
|
||||||
|
hours, rem = divmod(elapsed, 3600)
|
||||||
|
minutes, seconds = divmod(rem, 60)
|
||||||
|
ms = int((elapsed - int(elapsed)) * 1000)
|
||||||
|
time_str = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}.{ms:03d}"
|
||||||
|
self.lbl_timer.config(text=time_str)
|
||||||
|
|
||||||
|
self.root.after(50, self._update_timer)
|
||||||
|
|
||||||
def _start(self):
|
def _start(self):
|
||||||
self._save_config()
|
self._save_config()
|
||||||
|
# 点击提取按钮时,第一时间清空上一次的运行日志
|
||||||
|
self.txt.delete(1.0, tk.END)
|
||||||
|
|
||||||
src = self.src_path_var.get().strip()
|
src = self.src_path_var.get().strip()
|
||||||
out = self.out_dir_var.get().strip()
|
out = self.out_dir_var.get().strip()
|
||||||
mode = self.mode_var.get()
|
mode = self.mode_var.get()
|
||||||
@@ -300,11 +383,11 @@ class BatchTableExtractorApp:
|
|||||||
# 收集目标文件列表
|
# 收集目标文件列表
|
||||||
files_to_process = []
|
files_to_process = []
|
||||||
if mode == "file":
|
if mode == "file":
|
||||||
if src.lower().endswith(('.doc', '.docx')):
|
if src.lower().endswith(('.doc', '.docx', '.pdf', '.png', '.jpg', '.jpeg')):
|
||||||
files_to_process.append(src)
|
files_to_process.append(src)
|
||||||
else:
|
else:
|
||||||
pattern = "**/*" if recursive 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)
|
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))
|
files_to_process.extend(glob.glob(full_pattern, recursive=recursive))
|
||||||
|
|
||||||
@@ -312,7 +395,7 @@ class BatchTableExtractorApp:
|
|||||||
files_to_process = [f for f in files_to_process if not os.path.basename(f).startswith("~$")]
|
files_to_process = [f for f in files_to_process if not os.path.basename(f).startswith("~$")]
|
||||||
|
|
||||||
if not files_to_process:
|
if not files_to_process:
|
||||||
messagebox.showinfo("提示", "未找到任何待处理的 .doc 或 .docx 文件!")
|
messagebox.showinfo("提示", "未找到任何待处理的文档或图片!")
|
||||||
return
|
return
|
||||||
|
|
||||||
self.btn_run.config_btn(text="启动中... ", command=self._stop_task)
|
self.btn_run.config_btn(text="启动中... ", command=self._stop_task)
|
||||||
@@ -322,6 +405,9 @@ class BatchTableExtractorApp:
|
|||||||
|
|
||||||
self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====")
|
self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====")
|
||||||
|
|
||||||
|
self._start_time = time.time()
|
||||||
|
self._update_timer()
|
||||||
|
|
||||||
threading.Thread(
|
threading.Thread(
|
||||||
target=self._worker,
|
target=self._worker,
|
||||||
args=(files_to_process, out),
|
args=(files_to_process, out),
|
||||||
@@ -350,21 +436,11 @@ class BatchTableExtractorApp:
|
|||||||
return f"{date_str}X{seq:02d}"
|
return f"{date_str}X{seq:02d}"
|
||||||
|
|
||||||
def _worker(self, file_list, out_dir):
|
def _worker(self, file_list, out_dir):
|
||||||
pythoncom.CoInitialize()
|
|
||||||
word_app = None
|
|
||||||
excel_app = None
|
|
||||||
success_count = 0
|
success_count = 0
|
||||||
batch_id = self._generate_batch_id()
|
batch_id = self._generate_batch_id()
|
||||||
|
|
||||||
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):
|
||||||
@@ -378,13 +454,14 @@ class BatchTableExtractorApp:
|
|||||||
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
|
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
|
||||||
break
|
break
|
||||||
|
|
||||||
base_name = os.path.splitext(os.path.basename(file_path))[0]
|
full_name = os.path.basename(file_path)
|
||||||
|
base_name = os.path.splitext(full_name)[0]
|
||||||
target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx")
|
target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx")
|
||||||
|
|
||||||
conflict_action = self.conflict_action_var.get()
|
conflict_action = self.conflict_action_var.get()
|
||||||
if os.path.exists(target_excel):
|
if os.path.exists(target_excel):
|
||||||
if conflict_action == "直接跳过":
|
if conflict_action == "直接跳过":
|
||||||
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 跳过同名: {name}"))
|
self.root.after(0, lambda i=idx, t=total, name=full_name: self.log(f"[{i}/{t}] 跳过同名: {name}"))
|
||||||
record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "发现同名文件,跳过")
|
record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "发现同名文件,跳过")
|
||||||
def update_skip_btn(i=idx, t=total):
|
def update_skip_btn(i=idx, t=total):
|
||||||
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
||||||
@@ -400,15 +477,59 @@ class BatchTableExtractorApp:
|
|||||||
break
|
break
|
||||||
counter += 1
|
counter += 1
|
||||||
|
|
||||||
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 处理中: {name}"))
|
self.root.after(0, lambda i=idx, t=total, name=full_name: self.log(f"[{i}/{t}] 处理中: {name}"))
|
||||||
import time
|
import time
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
try:
|
try:
|
||||||
def my_log(m):
|
def my_log(m):
|
||||||
self.root.after(0, self.log, m)
|
self.root.after(0, self.log, m)
|
||||||
|
|
||||||
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
|
ext = os.path.splitext(file_path)[1].lower()
|
||||||
|
route_target = "word"
|
||||||
|
|
||||||
|
if ext in ['.png', '.jpg', '.jpeg']:
|
||||||
|
route_target = "ocr"
|
||||||
|
elif ext == '.pdf':
|
||||||
|
engine_pref = self.pdf_engine_var.get()
|
||||||
|
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"
|
||||||
|
elif "本地 AI" in engine_pref or "OCR" in engine_pref:
|
||||||
|
route_target = "ocr"
|
||||||
|
else:
|
||||||
|
# 智能判定:读取前3页文本量
|
||||||
|
try:
|
||||||
|
import fitz
|
||||||
|
with fitz.open(file_path) as pdoc:
|
||||||
|
text_len = 0
|
||||||
|
check_pages = min(3, len(pdoc))
|
||||||
|
for p in range(check_pages):
|
||||||
|
text_len += len(pdoc[p].get_text("text").strip())
|
||||||
|
|
||||||
|
if text_len > 100:
|
||||||
|
self.root.after(0, lambda: self.log(" [智能判定] 识别为电子版 PDF,已路由至 Word 极速引擎"))
|
||||||
|
route_target = "word"
|
||||||
|
else:
|
||||||
|
self.root.after(0, lambda: self.log(" [智能判定] 识别为扫描版 PDF,已路由至云端 OCR 引擎"))
|
||||||
|
route_target = "ocr"
|
||||||
|
except Exception:
|
||||||
|
route_target = "ocr" # fallback
|
||||||
|
|
||||||
|
if route_target == "word":
|
||||||
|
tc = export_single_doc_tables(file_path, target_excel,
|
||||||
log_func=my_log, debug=debug_mode)
|
log_func=my_log, debug=debug_mode)
|
||||||
|
else:
|
||||||
|
from core.extractor import export_pdf_image_tables_local
|
||||||
|
tc = export_pdf_image_tables_local(None, file_path, target_excel, "",
|
||||||
|
log_func=my_log, debug=debug_mode)
|
||||||
|
|
||||||
duration = time.time() - t0
|
duration = time.time() - t0
|
||||||
if tc > 0:
|
if tc > 0:
|
||||||
success_count += 1
|
success_count += 1
|
||||||
@@ -419,8 +540,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" ❌ 失败跳过 [{full_name}]: {e}\n{trace_str}"
|
||||||
|
else:
|
||||||
|
err_msg = f" ❌ 失败跳过 [{full_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}")
|
||||||
|
|
||||||
# 更新按钮文字进度
|
# 更新按钮文字进度
|
||||||
@@ -430,23 +554,11 @@ 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}"))
|
||||||
self.root.after(0, lambda err=str(e): messagebox.showerror("错误", f"自动化引擎初始化失败:\n{err}"))
|
self.root.after(0, lambda err=str(e): messagebox.showerror("错误", f"自动化引擎初始化失败:\n{err}"))
|
||||||
finally:
|
finally:
|
||||||
if word_app:
|
|
||||||
try:
|
|
||||||
word_app.Quit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if excel_app:
|
|
||||||
try:
|
|
||||||
excel_app.Quit()
|
|
||||||
except Exception:
|
|
||||||
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)
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import argparse
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
import pandas as pd
|
||||||
|
import io
|
||||||
|
import fitz
|
||||||
|
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):
|
||||||
|
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 main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
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("--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()
|
||||||
|
|
||||||
|
img_path = args.img_path
|
||||||
|
excel_path = args.excel_path
|
||||||
|
is_debug = args.debug
|
||||||
|
|
||||||
|
if not os.path.exists(img_path):
|
||||||
|
print(f"Error: File not found {img_path}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
table_engine = RapidTable()
|
||||||
|
table_engine.ocr_engine = CustomOcrEngine()
|
||||||
|
|
||||||
|
images = [] # (page_num, image_numpy_array)
|
||||||
|
ext = os.path.splitext(img_path)[1].lower()
|
||||||
|
|
||||||
|
if ext == '.pdf':
|
||||||
|
doc = fitz.open(img_path)
|
||||||
|
page_indices = parse_page_ranges(args.pages, len(doc))
|
||||||
|
print(f"[PDF] Processing {len(page_indices)} pages...")
|
||||||
|
for p_idx in page_indices:
|
||||||
|
page = doc[p_idx]
|
||||||
|
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
||||||
|
img_array = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
|
||||||
|
if pix.n == 4:
|
||||||
|
img_array = cv2.cvtColor(img_array, cv2.COLOR_RGBA2RGB)
|
||||||
|
elif pix.n == 1:
|
||||||
|
img_array = cv2.cvtColor(img_array, cv2.COLOR_GRAY2RGB)
|
||||||
|
images.append((p_idx + 1, img_array))
|
||||||
|
doc.close()
|
||||||
|
else:
|
||||||
|
img_array = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||||
|
images.append((1, img_array))
|
||||||
|
|
||||||
|
if not images:
|
||||||
|
print("No images to process.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
tables_found = 0
|
||||||
|
extracted_tables = []
|
||||||
|
|
||||||
|
total_images = len(images)
|
||||||
|
for page_num, img_array in images:
|
||||||
|
print(f"[OCR] 正在扫描第 {page_num} 页, 共 {total_images} 页...")
|
||||||
|
import time
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
table_result = table_engine(img_array)
|
||||||
|
if is_debug:
|
||||||
|
print(f" [Debug] 第 {page_num} 页 AI 推理耗时: {time.time() - start_time:.3f}s")
|
||||||
|
|
||||||
|
if hasattr(table_result, 'pred_htmls') and table_result.pred_htmls:
|
||||||
|
for html_idx, html_str in enumerate(table_result.pred_htmls):
|
||||||
|
if html_str:
|
||||||
|
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:
|
||||||
|
print(f"Error processing page {page_num}: {e}")
|
||||||
|
|
||||||
|
if not extracted_tables:
|
||||||
|
print("No tables detected.")
|
||||||
|
if os.path.exists(excel_path):
|
||||||
|
os.remove(excel_path)
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:
|
||||||
|
for sheet_name, df in extracted_tables:
|
||||||
|
df.to_excel(writer, sheet_name=sheet_name, index=False, header=False)
|
||||||
|
|
||||||
|
print(f"Successfully extracted {tables_found} tables.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user