156 lines
5.7 KiB
Python
156 lines
5.7 KiB
Python
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()
|