Enhance OCR logic and GUI logging

This commit is contained in:
HONOR
2026-09-20 09:54:39 +08:00
parent c07f958d40
commit 8dcd7c4031
4 changed files with 188 additions and 66 deletions
+62 -15
View File
@@ -1,13 +1,31 @@
import os
import sys
import os
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
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:
@@ -38,16 +56,19 @@ def main():
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()
@@ -77,17 +98,43 @@ def main():
tables_found = 0
extracted_tables = []
total_images = len(images)
for page_num, img_array in images:
print(f"[OCR] Scanning page {page_num}...")
print(f"[OCR] 正在扫描第 {page_num} 页, 共 {total_images} 页...")
import time
start_time = time.time()
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))
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}")