feat: 集成百度智能云表格 OCR 支持处理 PDF 和图片
This commit is contained in:
@@ -134,3 +134,183 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
|
||||
os.rmdir(temp_dir)
|
||||
except Exception:
|
||||
pass
|
||||
import base64
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
|
||||
def get_baidu_token(ak, sk):
|
||||
url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}"
|
||||
resp = requests.post(url, timeout=10)
|
||||
data = resp.json()
|
||||
if 'access_token' in data:
|
||||
return data['access_token']
|
||||
raise Exception(f"获取Token失败: {data.get('error_description', data)}")
|
||||
|
||||
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 export_pdf_image_tables(excel_app, file_path, excel_path, ak, sk, pages_str, log_func=None, debug=False):
|
||||
if not ak or not sk:
|
||||
raise Exception("未配置 Baidu API Key 或 Secret Key,请点击 ⚙️ OCR API 设置 填写!")
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
raise Exception("缺少 requests 库,请使用 pip install requests 安装")
|
||||
|
||||
token = get_baidu_token(ak, sk)
|
||||
|
||||
images = [] # list of (page_num, image_bytes)
|
||||
ext = os.path.splitext(file_path)[1].lower()
|
||||
|
||||
if ext == '.pdf':
|
||||
try:
|
||||
import fitz
|
||||
except ImportError:
|
||||
raise Exception("缺少 pymupdf 库,请使用 pip install pymupdf 安装")
|
||||
|
||||
doc = fitz.open(file_path)
|
||||
page_indices = parse_page_ranges(pages_str, len(doc))
|
||||
if log_func:
|
||||
log_func(f" [PDF] 共有 {len(doc)} 页,本次提取 {len(page_indices)} 页...")
|
||||
|
||||
for p_idx in page_indices:
|
||||
page = doc[p_idx]
|
||||
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
||||
img_bytes = pix.tobytes("png")
|
||||
|
||||
if len(img_bytes) > 4 * 1024 * 1024:
|
||||
pix = page.get_pixmap(matrix=fitz.Matrix(1.0, 1.0))
|
||||
img_bytes = pix.tobytes("jpeg")
|
||||
|
||||
images.append((p_idx + 1, img_bytes))
|
||||
doc.close()
|
||||
else:
|
||||
with open(file_path, "rb") as f:
|
||||
images.append((1, f.read()))
|
||||
|
||||
if not images:
|
||||
return 0
|
||||
|
||||
wb = excel_app.Workbooks.Add()
|
||||
table_count = 0
|
||||
import tempfile
|
||||
|
||||
for page_num, img_bytes in images:
|
||||
if log_func:
|
||||
log_func(f" [OCR] 正在提交第 {page_num} 页到云端识别...")
|
||||
|
||||
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
||||
|
||||
req_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/table_recognize?access_token={token}"
|
||||
resp = requests.post(req_url, data={"image": img_b64, "is_sync": "false"}, timeout=30)
|
||||
res_data = resp.json()
|
||||
|
||||
if "error_code" in res_data:
|
||||
if res_data["error_code"] == 18:
|
||||
raise Exception("QPS 超限,请稍后再试!")
|
||||
else:
|
||||
raise Exception(f"识别失败: {res_data.get('error_msg', res_data)}")
|
||||
|
||||
req_id = res_data["result"][0]["request_id"]
|
||||
|
||||
if log_func:
|
||||
log_func(f" [OCR] 第 {page_num} 页识别中,等待结果...")
|
||||
|
||||
get_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/table_result_get?access_token={token}"
|
||||
download_url = None
|
||||
for _ in range(30):
|
||||
time.sleep(2)
|
||||
poll_resp = requests.post(get_url, data={"request_id": req_id, "result_type": "excel"}, timeout=10)
|
||||
poll_data = poll_resp.json()
|
||||
|
||||
if "error_code" in poll_data:
|
||||
raise Exception(f"获取结果失败: {poll_data.get('error_msg', poll_data)}")
|
||||
|
||||
ret_code = poll_data["result"]["ret_code"]
|
||||
if ret_code == 3: # Completed
|
||||
download_url = poll_data["result"]["result_data"]
|
||||
break
|
||||
elif ret_code == 4: # Failed
|
||||
download_url = None
|
||||
break
|
||||
|
||||
if not download_url:
|
||||
if log_func:
|
||||
log_func(f" [OCR] 第 {page_num} 页未检测到表格。")
|
||||
continue
|
||||
|
||||
xls_resp = requests.get(download_url, timeout=30)
|
||||
temp_xls_path = os.path.join(tempfile.gettempdir(), f"~ocr_temp_{req_id}.xls")
|
||||
with open(temp_xls_path, "wb") as f:
|
||||
f.write(xls_resp.content)
|
||||
|
||||
try:
|
||||
temp_wb = excel_app.Workbooks.Open(temp_xls_path, ReadOnly=True, Visible=debug)
|
||||
for i in range(1, temp_wb.Sheets.Count + 1):
|
||||
temp_ws = temp_wb.Sheets(i)
|
||||
table_count += 1
|
||||
if table_count > wb.Sheets.Count:
|
||||
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
|
||||
else:
|
||||
ws = wb.Sheets.Item(table_count)
|
||||
|
||||
ws.Name = f"P{page_num}_T{i}"
|
||||
temp_ws.Cells.Copy(Destination=ws.Cells)
|
||||
ws.Columns.AutoFit()
|
||||
|
||||
temp_wb.Close(SaveChanges=False)
|
||||
except Exception as e:
|
||||
raise Exception(f"处理第 {page_num} 页返回的 Excel 失败: {e}")
|
||||
finally:
|
||||
if os.path.exists(temp_xls_path):
|
||||
try:
|
||||
os.remove(temp_xls_path)
|
||||
except:
|
||||
pass
|
||||
|
||||
if table_count == 0:
|
||||
if log_func:
|
||||
log_func(f" [跳过] 未检测到任何表格。")
|
||||
wb.Close(SaveChanges=False)
|
||||
return 0
|
||||
|
||||
while wb.Sheets.Count > table_count:
|
||||
wb.Sheets(wb.Sheets.Count).Delete()
|
||||
|
||||
abs_excel = os.path.abspath(excel_path)
|
||||
if os.path.exists(abs_excel):
|
||||
try:
|
||||
os.remove(abs_excel)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
wb.SaveAs(Filename=abs_excel, FileFormat=51)
|
||||
wb.Close(SaveChanges=False)
|
||||
|
||||
if log_func:
|
||||
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
||||
|
||||
return table_count
|
||||
|
||||
Reference in New Issue
Block a user