109 lines
3.5 KiB
Python
109 lines
3.5 KiB
Python
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()
|