Update app/main.py
Browse files- app/main.py +93 -5
app/main.py
CHANGED
|
@@ -1,10 +1,11 @@
|
|
| 1 |
import logging
|
| 2 |
import os
|
|
|
|
| 3 |
from typing import Dict, List
|
| 4 |
|
| 5 |
from fastapi import FastAPI, HTTPException
|
| 6 |
|
| 7 |
-
from .db import fetch_recent_transactions
|
| 8 |
from .schemas import InsightRequest, InsightResponse, Transaction
|
| 9 |
from .services import generate_insights
|
| 10 |
|
|
@@ -56,8 +57,95 @@ def _resolve_transactions(payload: InsightRequest) -> List[Transaction]:
|
|
| 56 |
@app.post("/insights", response_model=InsightResponse)
|
| 57 |
def create_insights(payload: InsightRequest) -> InsightResponse:
|
| 58 |
"""Generate insights from a transaction payload."""
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
|
|
|
| 1 |
import logging
|
| 2 |
import os
|
| 3 |
+
import time
|
| 4 |
from typing import Dict, List
|
| 5 |
|
| 6 |
from fastapi import FastAPI, HTTPException
|
| 7 |
|
| 8 |
+
from .db import fetch_recent_transactions, log_api_hit
|
| 9 |
from .schemas import InsightRequest, InsightResponse, Transaction
|
| 10 |
from .services import generate_insights
|
| 11 |
|
|
|
|
| 57 |
@app.post("/insights", response_model=InsightResponse)
|
| 58 |
def create_insights(payload: InsightRequest) -> InsightResponse:
|
| 59 |
"""Generate insights from a transaction payload."""
|
| 60 |
+
start_time = time.time()
|
| 61 |
+
status = "success"
|
| 62 |
+
# Capture user_id directly from request body - store exactly what is passed
|
| 63 |
+
user_id = payload.user_id
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
logger.info("Received request for user_id=%s", user_id)
|
| 67 |
+
transactions = _resolve_transactions(payload)
|
| 68 |
+
insights, months = generate_insights(transactions)
|
| 69 |
+
response = InsightResponse(user_id=user_id, insights=insights, evaluated_months=months)
|
| 70 |
+
return response
|
| 71 |
+
except HTTPException:
|
| 72 |
+
status = "error"
|
| 73 |
+
raise
|
| 74 |
+
except Exception as exc: # noqa: BLE001
|
| 75 |
+
status = "error"
|
| 76 |
+
logger.exception("Unexpected error processing insights request for user_id=%s", user_id)
|
| 77 |
+
raise HTTPException(status_code=500, detail="Internal server error") from exc
|
| 78 |
+
finally:
|
| 79 |
+
response_time = time.time() - start_time
|
| 80 |
+
try:
|
| 81 |
+
# Log with the exact user_id from request body (can be None if not provided)
|
| 82 |
+
log_api_hit(user_id, status, response_time)
|
| 83 |
+
except Exception as log_exc: # noqa: BLE001
|
| 84 |
+
# Don't fail the request if logging fails
|
| 85 |
+
logger.warning("Failed to log API hit: %s", log_exc)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# import logging
|
| 90 |
+
# import os
|
| 91 |
+
# from typing import Dict, List
|
| 92 |
+
|
| 93 |
+
# from fastapi import FastAPI, HTTPException
|
| 94 |
+
|
| 95 |
+
# from .db import fetch_recent_transactions
|
| 96 |
+
# from .schemas import InsightRequest, InsightResponse, Transaction
|
| 97 |
+
# from .services import generate_insights
|
| 98 |
+
|
| 99 |
+
# logging.basicConfig(
|
| 100 |
+
# level=os.environ.get("LOG_LEVEL", "INFO"),
|
| 101 |
+
# format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
|
| 102 |
+
# )
|
| 103 |
+
# logger = logging.getLogger(__name__)
|
| 104 |
+
|
| 105 |
+
# app = FastAPI(
|
| 106 |
+
# title="AI Financial Insights",
|
| 107 |
+
# description="AI-powered personalized spending insight generator for WalletSync.",
|
| 108 |
+
# version="1.0.0",
|
| 109 |
+
# )
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# @app.get("/")
|
| 113 |
+
# def root() -> Dict[str, str]:
|
| 114 |
+
# """Simple description endpoint."""
|
| 115 |
+
# return {
|
| 116 |
+
# "message": "AI Financial Insights is ready. POST /insights with transactions to receive insights.",
|
| 117 |
+
# "docs": "/docs",
|
| 118 |
+
# }
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# @app.get("/health")
|
| 122 |
+
# def health() -> Dict[str, str]:
|
| 123 |
+
# """Health probe for monitoring."""
|
| 124 |
+
# return {"status": "ok"}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# def _resolve_transactions(payload: InsightRequest) -> List[Transaction]:
|
| 128 |
+
# if payload.transactions:
|
| 129 |
+
# return payload.transactions
|
| 130 |
+
# if not payload.user_id:
|
| 131 |
+
# raise HTTPException(
|
| 132 |
+
# status_code=400,
|
| 133 |
+
# detail="Provide `transactions` or `user_id` to fetch them from MongoDB.",
|
| 134 |
+
# )
|
| 135 |
+
# try:
|
| 136 |
+
# return fetch_recent_transactions(payload.user_id)
|
| 137 |
+
# except ValueError as exc:
|
| 138 |
+
# raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 139 |
+
# except Exception as exc: # noqa: BLE001
|
| 140 |
+
# logger.exception("Failed to fetch MongoDB data for user_id=%s", payload.user_id)
|
| 141 |
+
# raise HTTPException(status_code=502, detail="Unable to query transaction store.") from exc
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# @app.post("/insights", response_model=InsightResponse)
|
| 145 |
+
# def create_insights(payload: InsightRequest) -> InsightResponse:
|
| 146 |
+
# """Generate insights from a transaction payload."""
|
| 147 |
+
# logger.info("Received request for user_id=%s", payload.user_id)
|
| 148 |
+
# transactions = _resolve_transactions(payload)
|
| 149 |
+
# insights, months = generate_insights(transactions)
|
| 150 |
+
# return InsightResponse(user_id=payload.user_id, insights=insights, evaluated_months=months)
|
| 151 |
|