Spaces:
Sleeping
Sleeping
Download app.py from drew3952/split_pdf_financial_report: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/spaces/drew3952/split_pdf_financial_report/resolve/main/app.py
- Command line
-
hf download hf://spaces/drew3952/split_pdf_financial_report/app.py
-
curl -L -o app.py https://huggingface.co/spaces/drew3952/split_pdf_financial_report/resolve/main/app.py
10.9 kB
| """ | |
| Gradio‧PDF 財報分頁 + EasyOCR + Gemini 解析 | |
| 啟動: python app.py | |
| """ | |
| import os, re, json, time, tempfile, shutil, zipfile, fitz, cv2, numpy as np | |
| import pandas as pd | |
| from pdf2image import convert_from_path | |
| from pyzbar.pyzbar import decode | |
| from PIL import Image | |
| import easyocr, gradio as gr | |
| import google.genai as genai | |
| from google.genai import types | |
| import spaces | |
| import functools | |
| # ──────────────── 0. 全域配置 ──────────────── | |
| #os.makedirs("/tmp/gradio", exist_ok=True) # ⬅ 保證上傳檔暫存目錄存在 | |
| WORK_DIR = tempfile.mkdtemp() # runtime 工作目錄 | |
| ID_RE = re.compile(r"[A-Z][0-9]{9}") | |
| rules = { | |
| "遠雄人壽": { | |
| "財報": ["C15002-0004", "pxx205","pxx215"] | |
| }, | |
| "台灣人壽(新)": { | |
| "財報": ["4201011"] | |
| }, | |
| "台新人壽": { | |
| "財報": ["N0300603"] | |
| }, | |
| "全球人壽": { | |
| "財報": ["UNBN01411"] | |
| }, | |
| "元大人壽": { | |
| "財報": ["N00600"] | |
| }, | |
| "友邦人壽": { | |
| "財報": ["N00501"] | |
| }, | |
| "安達國際人壽": { | |
| "財報": ["810"] | |
| }, | |
| "安聯人壽": { | |
| "財報": ["NO00214041"] | |
| }, | |
| "宏泰人壽": { | |
| "財報": ["1A07"] | |
| }, | |
| "法國巴黎人壽": { | |
| "財報": ["NB27401"] | |
| }, | |
| "保誠人壽": { | |
| "財報": ["M0111201"] | |
| }, | |
| "第一金人壽": { | |
| "財報": ["N07"] | |
| }, | |
| "富邦人壽": { | |
| "財報": ["11000069007"] | |
| }, | |
| "新光人壽": { | |
| "財報": ["A18A108"] | |
| } | |
| } | |
| # ========= OCR 關鍵字規則 (新增) ========= | |
| ocr_keywords = { | |
| "遠雄人壽": ["財務核保審核","財務核係審核"],#財務狀況告知書之關鍵字 | |
| "台灣人壽(新)": ["財務狀況告知書"], | |
| "台新人壽": ["財務狀況告知書"], | |
| "全球人壽": ["財務狀況告知書"], | |
| "保誠人壽": ["財務狀況告知書"], | |
| "友邦人壽": ["財務狀況告知書"], | |
| "法國巴黎人壽": ["財務狀況告知書"], | |
| "安達國際人壽": ["財務狀況告知書"], | |
| "宏泰人壽": ["財務狀況告知書"], | |
| "元大人壽": ["財務狀況告知書"], | |
| "富邦人壽": ["財務告知書"], | |
| "新光人壽": ["財務狀況告知書"], | |
| "第一金人壽": ["財務狀況告知書"] | |
| } | |
| PROMPT_DEFAULT = """ | |
| 請解析出文件表格中的財務資料,數字都再乘以10000 | |
| I0.要保人身分證字號 | |
| I1.要保人個人年收入(年薪資、紅利獎金) | |
| I2.要保人其他年收入(房租、利息) | |
| I3.要保人家庭年收入 | |
| I4.要保人動產總額(若無資料則空著) | |
| I5.要保人動產種類-存款(若無資料則空著) | |
| I6.要保人動產種類-股票、基金、債券(若無資料則空著) | |
| I7.要保人動產種類-其他(若無資料則空著) | |
| I8.要保人不動產總和(若無資料則空著) | |
| I9.要保人不動產市價-房屋(若無資料則空著) | |
| I10.要保人不動產市價-土地(若無資料則空著) | |
| I11.要保人負債或借貸總額(若無資料則空著) | |
| I12.要保人負債種類-房屋貸款(抵押貸款)(若無資料則空著) | |
| I13.要保人負債種類-保單貸款(若無資料則空著) | |
| I14.要保人負債種類-信用卡貸款(若無資料則空著) | |
| I15.要保人負債種類-其他貸款(若無資料則空著) | |
| J0.被保險人身份證字號 | |
| J1.被保險人個人年收入(年薪資、紅利獎金) | |
| J2.被保險人其他年收入(房租、利息) | |
| J3.被保險人家庭年收入 | |
| J4.被保險人動產總額(若無資料則空著) | |
| J5.被保險人動產種類-存款(若無資料則空著) | |
| J6.被保險人動產種類-股票、基金、債券(若無資料則空著) | |
| J7.被保險人動產種類-其他(若無資料則空著) | |
| J8.被保險人不動產總和(若無資料則空著) | |
| J9.被保險人不動產市價-房屋(若無資料則空著) | |
| J10.被保險人不動產市價-土地(若無資料則空著) | |
| J11.被保險人負債或借貸總額(若無資料則空著) | |
| J12.被保險人負債種類-房屋貸款(抵押貸款)(若無資料則空著) | |
| J13.被保險人負債種類-保單貸款(若無資料則空著) | |
| J14.被保險人負債種類-信用卡貸款(若無資料則空著) | |
| J15.被保險人負債種類-其他貸款(若無資料則空著) | |
| """ | |
| # ⬅ 延遲建立 EasyOCR reader | |
| def get_reader(): | |
| # ZeroGPU 會把第一次呼叫放進佇列,此時才真正占用 GPU | |
| return easyocr.Reader(['ch_tra', 'en'], gpu=True) | |
| # ──────────────── 1. 公用函式 ──────────────── | |
| def extract_barcodes(img): | |
| return [(b.data.decode(), b.rect) for b in decode(img)] | |
| def extract_barcodes_strong(img): | |
| g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| g = cv2.bilateralFilter(g, 9, 75, 75) | |
| _, th = cv2.threshold(g, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) | |
| return [(b.data.decode(), b.rect) for b in decode(th)] | |
| def pdf_page_to_cv(pdf, idx, dpi=300): | |
| imgs = convert_from_path(pdf, dpi=dpi, | |
| first_page=idx+1, last_page=idx+1) | |
| return None if not imgs else cv2.cvtColor(np.array(imgs[0]), cv2.COLOR_RGB2BGR) | |
| def ocr_text(img): | |
| """呼叫延遲載入的 EasyOCR,回傳整張影像文字""" | |
| reader = get_reader() # ⚡ GPU 內建 reader | |
| return "".join(t for _, t, _ in reader.readtext(img)) | |
| def is_kw_hit(txt, com): | |
| return any(k in txt for k in ocr_keywords.get(com, [])) | |
| # ──────────────── 2. 取財報頁碼(保持不變) ──────────────── | |
| def detect_pages(pdf, company, pats): | |
| doc, hit = fitz.open(pdf), [] | |
| for strong in (False, True): | |
| if hit: break | |
| for i in range(len(doc)): | |
| img = pdf_page_to_cv(pdf, i) | |
| if img is None: continue | |
| codes = extract_barcodes_strong(img) if strong else extract_barcodes(img) | |
| if any(any(p in c for p in pats) for c, _ in codes): | |
| hit.append(i) | |
| if not hit: | |
| for i in range(len(doc)): | |
| img = pdf_page_to_cv(pdf, i) | |
| if img is None: continue | |
| if is_kw_hit(ocr_text(img[: img.shape[0] // 8, :]), company): | |
| hit.append(i) | |
| return sorted(set(hit)) | |
| # ──────────────── 3. 切 PDF(保持不變) ──────────────── | |
| def save_pages(src, dst, pages, company): | |
| doc = fitz.open(src) | |
| if company == "法國巴黎人壽": | |
| imgs = [] | |
| for p in pages: | |
| pix = doc.load_page(p).get_pixmap(dpi=300) | |
| tmp = os.path.join(WORK_DIR, f"tmp_{p}.png") | |
| pix.save(tmp); imgs.append(Image.open(tmp).convert("RGB")) | |
| imgs[0].save(dst, save_all=True, append_images=imgs[1:]) | |
| else: | |
| new = fitz.open() | |
| for p in pages: new.insert_pdf(doc, from_page=p, to_page=p) | |
| new.save(dst); new.close() | |
| # ──────────────── 4. Gemini 解析 → CSV(保持不變) ──────────────── | |
| def gen_financial_csv(pdf_dir, key): | |
| out_csv = os.path.join(pdf_dir, "財務資料整合_修正完成版(財報).csv") | |
| if not key: return out_csv | |
| client, rows = genai.Client(api_key=key), [] | |
| pdfs = [f for f in os.listdir(pdf_dir) if f.lower().endswith(".pdf")] | |
| for f in pdfs: | |
| if "-0-" in f: | |
| rows.append({"財報檔名": f}); continue | |
| try: | |
| resp = client.models.generate_content( | |
| model="gemini-2.5-flash-preview-05-20", | |
| contents=[PROMPT_DEFAULT, | |
| client.files.upload(file=os.path.join(pdf_dir, f))], | |
| config=types.GenerateContentConfig( | |
| temperature=0.0, | |
| response_mime_type="application/json", | |
| thinking_config=types.ThinkingConfig(thinking_budget=0)), | |
| ) | |
| data = json.loads(resp.text) | |
| data = data[0] if isinstance(data, list) else data | |
| data["財報檔名"] = f | |
| rows.append(data) | |
| except Exception: | |
| rows.append({"財報檔名": f}) | |
| pd.DataFrame(rows).to_csv(out_csv, index=False, encoding="utf-8-sig") | |
| return out_csv | |
| # ──────────────── 5. 主要 Pipeline(保持不變) ──────────────── | |
| def process(uploaded, api_key): | |
| if not uploaded: | |
| return "⚠️ 請選擇 PDF", None | |
| split_dir = os.path.join(WORK_DIR, "pdfs") | |
| os.makedirs(split_dir, exist_ok=True) | |
| ocr_rows = [] | |
| for fobj in uploaded: | |
| src = fobj | |
| fname = os.path.basename(src.name) | |
| comp, doc_id, extra = fname.rsplit(".pdf", 1)[0].split("-", 2) | |
| pages = detect_pages(src.name, comp, rules.get(comp, {}).get("財報", [])) | |
| page_str = ",".join(str(p + 1) for p in pages) if pages else "0" | |
| out_pdf = f"{comp}-{doc_id}-{extra}-{page_str}-財報.pdf" | |
| save_pages(src.name, os.path.join(split_dir, out_pdf), pages or [], comp) | |
| d = fitz.open(src.name) | |
| for i in range(len(d)): | |
| img = pdf_page_to_cv(src.name, i) | |
| if img is None: | |
| continue | |
| ocr_rows.append( | |
| {"原始檔名": fname, "頁碼": i + 1, "OCR文字": ocr_text(img)} | |
| ) | |
| ocr_csv = os.path.join(WORK_DIR, "OCR全文.csv") | |
| pd.DataFrame(ocr_rows).to_csv(ocr_csv, index=False, encoding="utf-8-sig") | |
| fin_csv = gen_financial_csv(split_dir, api_key.strip()) | |
| zpath = os.path.join(WORK_DIR, "result.zip") | |
| with zipfile.ZipFile(zpath, "w") as z: | |
| for f in os.listdir(split_dir): | |
| z.write(os.path.join(split_dir, f), arcname=f) | |
| z.write(ocr_csv, arcname=os.path.basename(ocr_csv)) | |
| if os.path.exists(fin_csv): | |
| z.write(fin_csv, arcname=os.path.basename(fin_csv)) | |
| return "✅ 完成!請點擊下載", zpath | |
| # ──────────────── 6. Gradio 介面 & 啟動 ──────────────── | |
| with gr.Blocks(title="PDF 財報切割 + OCR + Gemini 解析") as demo: | |
| gr.Markdown("### 📑 上傳 PDF → 自動切財報 → OCR → Gemini → 下載") | |
| pdf_in = gr.File(label="PDF(可多選)", type="filepath", file_count="multiple") | |
| api_in = gr.Textbox(label="Gemini API Key(選填)", type="password") | |
| run = gr.Button("開始") | |
| status = gr.Textbox(label="狀態") | |
| out_zip = gr.File(label="下載 ZIP") | |
| run.click(process, inputs=[pdf_in, api_in], outputs=[status, out_zip]) | |
| def launch_app(): | |
| demo.queue().launch(show_api=False,ssr_mode=False,debug=True) | |
| if __name__ == "__main__": | |
| launch_app() | |
| #if __name__ == "__main__": | |
| # demo.launch(server_name="0.0.0.0", server_port=7860) | |