Compare commits
14
Commits
1fce2a6271
...
c07f958d40
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c07f958d40 | ||
|
|
2dcd40cf6e | ||
|
|
8f87562feb | ||
|
|
edb390e4f8 | ||
|
|
926a5b7dd1 | ||
|
|
f1b1d4e453 | ||
|
|
d17c52403d | ||
|
|
ebfc197c31 | ||
|
|
c59153253c | ||
|
|
944d2f7888 | ||
|
|
dbab45baaf | ||
|
|
2e7a22c207 | ||
|
|
bd2365f2dd | ||
|
|
fec5ceed33 |
@@ -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`。
|
||||
|
||||
+89
-1
@@ -43,10 +43,25 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
|
||||
|
||||
doc = None
|
||||
wb = None
|
||||
file_to_clean = None
|
||||
try:
|
||||
if debug and log_func:
|
||||
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
|
||||
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug)
|
||||
|
||||
try:
|
||||
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug, ConfirmConversions=False)
|
||||
except Exception as e:
|
||||
if debug and log_func:
|
||||
log_func(f" [Debug] 打开失败,疑似遇到受保护的视图拦截,尝试启动智能复制逃逸机制...")
|
||||
import shutil
|
||||
out_dir = os.path.dirname(abs_excel)
|
||||
temp_dir = os.path.join(out_dir, "temp")
|
||||
if not os.path.exists(temp_dir):
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
file_to_clean = os.path.join(temp_dir, f"~temp_bypass_{os.path.basename(abs_doc)}")
|
||||
shutil.copy2(abs_doc, file_to_clean)
|
||||
doc = word_app.Documents.Open(FileName=file_to_clean, ReadOnly=True, Visible=debug, ConfirmConversions=False)
|
||||
|
||||
table_count = doc.Tables.Count
|
||||
|
||||
if table_count == 0:
|
||||
@@ -111,3 +126,76 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
|
||||
doc.Close(SaveChanges=False)
|
||||
except Exception:
|
||||
pass
|
||||
if file_to_clean and os.path.exists(file_to_clean):
|
||||
try:
|
||||
os.remove(file_to_clean)
|
||||
temp_dir = os.path.dirname(file_to_clean)
|
||||
if not os.listdir(temp_dir):
|
||||
os.rmdir(temp_dir)
|
||||
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:
|
||||
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
||||
return table_count
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"调用本地 AI 失败: {e}")
|
||||
|
||||
+94
-11
@@ -7,6 +7,7 @@ from tkinter import filedialog, messagebox, ttk
|
||||
import pythoncom
|
||||
import windnd
|
||||
import datetime
|
||||
import time
|
||||
|
||||
from utils.config import CONFIG_FILE, APP_DIR
|
||||
from core.extractor import detect_and_create_apps, export_single_doc_tables
|
||||
@@ -42,6 +43,8 @@ class BatchTableExtractorApp:
|
||||
self.topmost_var = tk.BooleanVar(value=False)
|
||||
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
|
||||
|
||||
self.pdf_engine_var = tk.StringVar(value="智能判定 (推荐)")
|
||||
|
||||
import threading
|
||||
self._stop_event = threading.Event()
|
||||
self._pause_event = threading.Event()
|
||||
@@ -75,6 +78,7 @@ 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.pdf_engine_var.set(cfg.get("pdf_engine", "智能判定 (推荐)"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -88,7 +92,8 @@ 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(),
|
||||
"pdf_engine": self.pdf_engine_var.get()
|
||||
}
|
||||
try:
|
||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||
@@ -97,6 +102,13 @@ class BatchTableExtractorApp:
|
||||
pass
|
||||
|
||||
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.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
@@ -139,8 +151,14 @@ class BatchTableExtractorApp:
|
||||
self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=65)
|
||||
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW)
|
||||
|
||||
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)
|
||||
ttk.Label(path_box, text="文件冲突:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
||||
|
||||
combo_frame = ttk.Frame(path_box)
|
||||
combo_frame.grid(row=2, column=1, sticky=tk.EW, padx=6)
|
||||
|
||||
ttk.Combobox(combo_frame, textvariable=self.conflict_action_var, values=["直接覆盖 (默认)", "自动重命名", "直接跳过"], state="readonly", width=18).pack(side=tk.LEFT, fill=tk.X, expand=True)
|
||||
ttk.Label(combo_frame, text=" PDF: ").pack(side=tk.LEFT)
|
||||
ttk.Combobox(combo_frame, textvariable=self.pdf_engine_var, values=["智能判定 (推荐)", "强转 Word (极速)", "强制本地 AI (需插件)"], state="readonly", width=18).pack(side=tk.LEFT, fill=tk.X, expand=True)
|
||||
|
||||
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)
|
||||
@@ -164,6 +182,10 @@ class BatchTableExtractorApp:
|
||||
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
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):
|
||||
if self.debug_var.get():
|
||||
messagebox.showinfo("Debug 模式说明", "开启 Debug 模式后,程序在提取表格时将强制显示 Office/WPS 窗口。\n\n这主要用于排查程序“卡死”的问题。例如:当文档被加密或需要修复时,Office 会在后台弹窗等待用户点击。开启此模式可让你看到这些弹窗并手动处理。")
|
||||
@@ -190,11 +212,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)
|
||||
@@ -272,6 +294,28 @@ class BatchTableExtractorApp:
|
||||
self._save_config()
|
||||
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):
|
||||
self._save_config()
|
||||
src = self.src_path_var.get().strip()
|
||||
@@ -300,11 +344,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 +356,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)
|
||||
@@ -322,6 +366,9 @@ class BatchTableExtractorApp:
|
||||
|
||||
self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====")
|
||||
|
||||
self._start_time = time.time()
|
||||
self._update_timer()
|
||||
|
||||
threading.Thread(
|
||||
target=self._worker,
|
||||
args=(files_to_process, out),
|
||||
@@ -407,8 +454,44 @@ 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()
|
||||
route_target = "word"
|
||||
|
||||
if ext in ['.png', '.jpg', '.jpeg']:
|
||||
route_target = "ocr"
|
||||
elif ext == '.pdf':
|
||||
engine_pref = self.pdf_engine_var.get()
|
||||
if "Word" in engine_pref:
|
||||
route_target = "word"
|
||||
elif "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(word_app, excel_app, file_path, target_excel,
|
||||
log_func=my_log, debug=debug_mode)
|
||||
else:
|
||||
from core.extractor import export_pdf_image_tables_local
|
||||
tc = export_pdf_image_tables_local(excel_app, file_path, target_excel, "",
|
||||
log_func=my_log, debug=debug_mode)
|
||||
|
||||
duration = time.time() - t0
|
||||
if tc > 0:
|
||||
success_count += 1
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import fitz # PyMuPDF
|
||||
import rapidocr_onnxruntime
|
||||
sys.modules['rapidocr'] = rapidocr_onnxruntime
|
||||
from rapid_table import RapidTable
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import cv2
|
||||
|
||||
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")
|
||||
args = parser.parse_args()
|
||||
|
||||
img_path = args.img_path
|
||||
excel_path = args.excel_path
|
||||
|
||||
if not os.path.exists(img_path):
|
||||
print(f"Error: File not found {img_path}")
|
||||
sys.exit(1)
|
||||
|
||||
table_engine = RapidTable()
|
||||
|
||||
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 = []
|
||||
|
||||
for page_num, img_array in images:
|
||||
print(f"[OCR] Scanning page {page_num}...")
|
||||
try:
|
||||
table_result, _ = table_engine(img_array)
|
||||
html_str = table_result
|
||||
if html_str:
|
||||
dfs = pd.read_html(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))
|
||||
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