Spaces:
Sleeping
Sleeping
File size: 5,618 Bytes
fbb917f 37c76c3 fbb917f 37c76c3 c58f0d0 fbb917f bd29861 205f25f bd29861 205f25f bd29861 74f156f | 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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | """
BeFree REST API Backend
Bridges the frontend with bank-extractor and bank-hitl packages.
Implements the API contract defined in web/API_CONTRACT.md
"""
import os
import logging
from dotenv import load_dotenv
# ===== Load Environment Variables =====
load_dotenv()
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
# Auth database imports
from auth.database import engine, Base
import auth.rule_models
from core.state import _uploads_dir, _output_dir, discover_and_load_statements
# Loggers
logger = logging.getLogger("befree")
# ===== Lifespan =====
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
print("BeFree API Server starting...")
# Auto-create auth DB tables (safe to run every startup — no-op if tables exist)
Base.metadata.create_all(bind=engine)
logger.info("Auth database tables created/verified")
_uploads_dir().mkdir(parents=True, exist_ok=True)
_output_dir().mkdir(parents=True, exist_ok=True)
# Run dynamic recovery search to repopulate the in-memory cache
try:
discover_and_load_statements()
logger.info("Initial statement discovery sweep complete")
except Exception as e:
logger.error(f"Error during initial statement discovery: {e}")
# Initialise Overwatch store (creates DB file, WAL, tables, starts cleanup thread)
try:
from overwatch.store import get_store as _get_overwatch_store
_get_overwatch_store()
logger.info("Overwatch store initialised")
except Exception as _ow_err:
logger.warning("Overwatch store init failed (non-fatal): %s", _ow_err)
yield
# Shutdown
print("BeFree API Server shutting down...")
# ===== Create FastAPI App =====
_is_production = os.environ.get("ENVIRONMENT", "development") == "production"
app = FastAPI(
title="BeFree Bank Statement Processor API",
description="REST API for bank statement extraction and review",
version="1.0.0",
lifespan=lifespan,
docs_url=None if _is_production else "/docs",
redoc_url=None if _is_production else "/redoc",
)
# CORS
_cors_origins_env = os.environ.get("CORS_ORIGINS", "")
_cors_origins = [o.strip() for o in _cors_origins_env.split(",") if o.strip()] if _cors_origins_env else ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ===== Middlewares =====
from core.middleware import add_request_id_handler, audit_logging_handler, global_exception_handler_fn
@app.middleware("http")
async def add_request_id(request: Request, call_next):
return await add_request_id_handler(request, call_next)
@app.middleware("http")
async def audit_logging_middleware(request: Request, call_next):
return await audit_logging_handler(request, call_next)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
return await global_exception_handler_fn(request, exc)
# ===== Mount Routers =====
# 1. Overwatch Router
from overwatch.router import router as overwatch_router
app.include_router(overwatch_router)
# 2. Auth Router
from routers.auth import router as auth_router
app.include_router(auth_router)
# 3. Settings Router
from routers.settings_router import router as settings_router
app.include_router(settings_router)
# 4. PDF Router
from routers.pdf import router as pdf_router
app.include_router(pdf_router)
# 5. History Router
from routers.history import router as history_router
app.include_router(history_router)
# 6. Flagged Router
from routers.flagged import router as flagged_router
app.include_router(flagged_router)
# 7. Dashboard Router
from routers.dashboard import router as dashboard_router
app.include_router(dashboard_router)
# 8. Upload Router
from routers.upload import router as upload_router
app.include_router(upload_router)
# 9. Layout Router
from routers.layout import router as layout_router
app.include_router(layout_router)
# 10. Processing Router
from routers.processing import router as processing_router
app.include_router(processing_router)
# 11. Classification Router
from routers.classification import router as classification_router
app.include_router(classification_router)
# 12. Review Router
from routers.review import router as review_router
app.include_router(review_router)
# 13. Transactions Router
from routers.transactions import router as transactions_router
app.include_router(transactions_router)
# 14. Export Router
from routers.export import router as export_router
app.include_router(export_router)
# 15. Admin Router
from routers.admin import router as admin_router
app.include_router(admin_router)
# 16. Admin Rules Router
from routers.admin_rules import router as admin_rules_router
app.include_router(admin_rules_router)
# 17. Rule Requests Router
from routers.rule_requests import router as rule_requests_router
app.include_router(rule_requests_router)
# 18. Practices Router
from routers.practices import router as practices_router
app.include_router(practices_router)
# ===== Health & Info =====
@app.get("/health")
async def health():
"""Health check."""
return {"status": "ok"}
@app.get("/")
async def root():
"""API info."""
return {
"name": "BeFree Bank Statement Processor API",
"version": "1.0.0",
"docs": "/docs" if not _is_production else None,
"health": "/health",
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
|