Spaces:
Sleeping
Sleeping
File size: 7,279 Bytes
0ebef7d 7aa828a 0ebef7d 7aa828a 0ebef7d 7aa828a 0ebef7d 3dfe050 0ebef7d 7aa828a 0ebef7d 3dfe050 7aa828a 3dfe050 7aa828a 3dfe050 7aa828a 3dfe050 7aa828a 0ebef7d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | """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})
@router.post("/convert")
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],
}
)
|