Spaces:
Sleeping
Sleeping
Download app/api/convert.py from rudratoshs/exportstatement: direct link, hf CLI and curl.
- Browser
- Download file 7.28 kB
-
https://huggingface.co/spaces/rudratoshs/exportstatement/resolve/main/app/api/convert.py
- Command line
-
hf download hf://spaces/rudratoshs/exportstatement/app/api/convert.py
-
curl -L -o convert.py https://huggingface.co/spaces/rudratoshs/exportstatement/resolve/main/app/api/convert.py
7.28 kB
| """POST /convert — PDF in, reconciled statement data out (JSON or .xlsx). | |
| Stateless: the uploaded PDF is read into memory, processed in an isolated temp | |
| dir, and deleted before the response is built. Nothing is persisted. | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import re | |
| import logging | |
| from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile | |
| from fastapi.responses import JSONResponse, StreamingResponse | |
| from openpyxl import Workbook | |
| from app.core.config import API_KEY, MAX_UPLOAD_BYTES | |
| from app.core.files import temp_pdf | |
| from app.engine.converter import BankStatementConverter, ExtractedStatement | |
| router = APIRouter() | |
| logger = logging.getLogger("ebs.convert") | |
| XLSX_MEDIA = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| def _is_pdf(file: UploadFile) -> bool: | |
| if (file.content_type or "").lower() in {"application/pdf", "application/x-pdf"}: | |
| return True | |
| return (file.filename or "").lower().endswith(".pdf") | |
| def _statement_dict(st: ExtractedStatement) -> dict: | |
| return { | |
| "account": st.account, | |
| "accountHolder": st.account_holder, | |
| "period": st.period, | |
| "openingBalance": st.opening_balance, | |
| "closingBalance": st.closing_balance, | |
| "reconciles": st.reconciles, | |
| "reconcileStatus": st.reconcile_status, | |
| "runningBalanceOk": st.running_balance_ok, | |
| "statedSummaryOk": st.stated_summary_ok, | |
| "reconciliationDetail": st.reconciliation_detail, | |
| "transactions": [ | |
| { | |
| "date": t.date, | |
| "description": t.description, | |
| "debit": t.debit, | |
| "credit": t.credit, | |
| "balance": t.balance, | |
| } | |
| for t in st.transactions | |
| ], | |
| } | |
| def _xlsx_bytes(statements: list[ExtractedStatement]) -> io.BytesIO: | |
| wb = Workbook() | |
| wb.remove(wb.active) | |
| for n, st in enumerate(statements, 1): | |
| ws = wb.create_sheet(f"Account{n}") | |
| ws.append(["Date", "Description", "Debit", "Credit", "Balance"]) | |
| for t in st.transactions: | |
| ws.append([t.date, t.description, t.debit, t.credit, t.balance]) | |
| buf = io.BytesIO() | |
| wb.save(buf) | |
| buf.seek(0) | |
| return buf | |
| # --- failure diagnostics ------------------------------------------------------- | |
| # When a conversion fails, the web app records WHY (a short code) and WHICH BANK | |
| # (matched against a fixed list), so the common failures can be fixed. Nothing | |
| # from the statement itself — no names, numbers or transactions — is returned. | |
| _BANKS = [ | |
| ("SBI", r"state bank of india|\bsbi\b"), ("HDFC", r"hdfc bank"), ("ICICI", r"icici bank"), | |
| ("Axis", r"axis bank"), ("Kotak", r"kotak mahindra"), ("PNB", r"punjab national bank"), | |
| ("Bank of Baroda", r"bank of baroda"), ("Canara", r"canara bank"), ("Union Bank", r"union bank of india"), | |
| ("Bank of India", r"\bbank of india\b"), ("IDFC First", r"idfc first"), ("IndusInd", r"indusind"), | |
| ("Yes Bank", r"\byes bank\b"), ("Federal Bank", r"federal bank"), ("IDBI", r"\bidbi\b"), | |
| ("Indian Bank", r"\bindian bank\b"), ("Central Bank of India", r"central bank of india"), | |
| ("Indian Overseas", r"indian overseas bank"), ("UCO", r"\buco bank\b"), ("Karnataka Bank", r"karnataka bank"), | |
| ("South Indian Bank", r"south indian bank"), ("RBL", r"\brbl bank\b"), ("AU SFB", r"au small finance"), | |
| ("Standard Chartered", r"standard chartered"), ("Paytm Payments Bank", r"paytm payments bank"), | |
| ("Barclays", r"barclays"), ("HSBC", r"\bhsbc\b"), ("Lloyds", r"\blloyds\b"), ("NatWest", r"natwest"), | |
| ("Santander", r"santander"), ("Nationwide", r"nationwide"), ("Monzo", r"\bmonzo\b"), ("Starling", r"starling"), | |
| ("Halifax", r"halifax"), ("Revolut", r"revolut"), ("Chase", r"\bchase\b"), ("Bank of America", r"bank of america"), | |
| ("Wells Fargo", r"wells fargo"), ("Citi", r"\bcitibank\b|\bciti\b"), ("Capital One", r"capital one"), | |
| ("CommBank", r"commonwealth bank|commbank"), ("ANZ", r"\banz\b"), ("Westpac", r"westpac"), ("NAB", r"national australia bank"), | |
| ("AIB", r"allied irish|\baib\b"), ("Bank of Ireland", r"bank of ireland"), | |
| ] | |
| _HEADER_RE = re.compile(r"\bdate\b.*\b(balance|amount|debit|credit|withdraw\w*|deposit\w*|dr|cr)\b", re.I) | |
| def _diagnose(conv: "BankStatementConverter | None", reason: str) -> dict: | |
| text = (conv.text if conv else "") or "" | |
| low = text.lower() | |
| bank = next((name for name, pat in _BANKS if re.search(pat, low)), "unknown") | |
| chars = len(text.strip()) | |
| layer = "none" if chars == 0 else ("thin" if chars < 400 else "text") | |
| header = bool(_HEADER_RE.search(text)) | |
| return {"reason": reason, "bank": bank, "layer": layer, "header": header} | |
| def _fail(detail: str, diag: dict) -> JSONResponse: | |
| logger.info("convert failed: %s", diag) | |
| return JSONResponse(status_code=422, content={"detail": detail, **diag}) | |
| async def convert( | |
| file: UploadFile = File(...), | |
| format: str = Query("json", pattern="^(json|xlsx)$"), | |
| x_api_key: str | None = Header(default=None), | |
| ): | |
| if API_KEY and x_api_key != API_KEY: | |
| raise HTTPException(status_code=401, detail="Unauthorized.") | |
| if not _is_pdf(file): | |
| raise HTTPException(status_code=415, detail="Only PDF files are accepted.") | |
| data = await file.read() | |
| if not data: | |
| raise HTTPException(status_code=400, detail="Empty file.") | |
| if len(data) > MAX_UPLOAD_BYTES: | |
| mb = MAX_UPLOAD_BYTES // (1024 * 1024) | |
| raise HTTPException(status_code=413, detail=f"File too large (max {mb} MB).") | |
| conv = None | |
| try: | |
| with temp_pdf(data) as pdf_path: | |
| conv = BankStatementConverter(pdf_path) | |
| statements = conv.extract() | |
| except Exception: | |
| # Bad user input (corrupt / password-protected / not a real PDF) must | |
| # surface as 4xx, never a 500. Logged for observability. | |
| logger.exception("extraction failed for upload %r", file.filename) | |
| return _fail( | |
| "Couldn't read this PDF. It may be corrupt, password-protected, or not a valid PDF.", | |
| _diagnose(conv, "unreadable"), | |
| ) | |
| has_txns = any(s.transactions for s in statements) | |
| if not has_txns and not conv.text.strip(): | |
| return _fail( | |
| "Couldn't read any transactions from this scan. A clearer, straight-on scan " | |
| "or the bank's original PDF usually works.", | |
| _diagnose(conv, "scan_no_rows"), | |
| ) | |
| if not has_txns or not conv.looks_like_statement(): | |
| diag = _diagnose(conv, "no_rows" if not has_txns else "not_statement") | |
| return _fail( | |
| "This doesn't look like a bank statement. We couldn't find a list of dated " | |
| "transactions with amounts and a balance. Please upload the statement PDF from your bank.", | |
| diag, | |
| ) | |
| if format == "xlsx": | |
| return StreamingResponse( | |
| _xlsx_bytes(statements), | |
| media_type=XLSX_MEDIA, | |
| headers={"Content-Disposition": 'attachment; filename="statement.xlsx"'}, | |
| ) | |
| return JSONResponse( | |
| { | |
| "count": sum(len(s.transactions) for s in statements), | |
| "statements": [_statement_dict(s) for s in statements], | |
| } | |
| ) | |