from fastapi import FastAPI, HTTPException, Depends, Request from fastapi.middleware.cors import CORSMiddleware from pymongo import MongoClient from pymongo.errors import ConnectionFailure import os import time from typing import List, Optional from datetime import datetime, timedelta, timezone from app.models import BudgetRecommendation, Expense, Budget, CategoryExpense from app.smart_recommendation import SmartBudgetRecommender app = FastAPI(title="Smart Budget Recommendation API", version="1.0.0") # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # MongoDB connection - Get from environment variable (set as secret in Hugging Face) MONGODB_URI = os.getenv("MONGODB_URI") if not MONGODB_URI: raise ValueError("MONGODB_URI environment variable is required. Please set it in Hugging Face secrets.") try: client = MongoClient(MONGODB_URI) db = client.expense # Test connection client.admin.command('ping') print("Successfully connected to MongoDB") except ConnectionFailure as e: print(f"Failed to connect to MongoDB: {e}") raise # Initialize Smart Budget Recommender recommender = SmartBudgetRecommender(db) # IST timezone (UTC+5:30) IST = timezone(timedelta(hours=5, minutes=30)) def log_api_call(db, name: str, status: str, response_time: float, endpoint: str = None, error: str = None): """ Log API call to MongoDB api_logs collection Args: db: MongoDB database instance name: API name (e.g., "smart budget recommendation") status: "success" or "fail" response_time: Response time in seconds endpoint: Optional endpoint path error: Optional error message """ try: # Get current time in IST ist_time = datetime.now(IST) # Format: DD-MM-YYYY HH:MM:SS:IST timestamp_str = ist_time.strftime("%d-%m-%Y %H:%M:%S:IST") # Extract user_id from endpoint (e.g., "/recommendations/user123" -> "user123") user_id = None if endpoint: # Extract user_id from path patterns like "/recommendations/{user_id}" or "/category-expenses/{user_id}" parts = endpoint.strip("/").split("/") if len(parts) >= 2: user_id = parts[1] # Get the user_id part log_entry = { "name": name, "status": status, "date": timestamp_str, # Combined date and time in IST "response_time": round(response_time, 3), # Round to 3 decimal places "user_id": user_id, } if error: log_entry["error"] = error # Insert into api_logs collection db.api_logs.insert_one(log_entry) except Exception as e: # Don't fail the API call if logging fails print(f"Failed to log API call: {e}") @app.middleware("http") async def log_requests(request: Request, call_next): """Middleware to log API requests and track response time""" start_time = time.time() # Only log specific endpoints endpoint = request.url.path should_log = endpoint in ["/recommendations", "/category-expenses"] or endpoint.startswith("/recommendations/") or endpoint.startswith("/category-expenses/") if should_log: try: response = await call_next(request) process_time = time.time() - start_time # Determine status status = "success" if response.status_code < 400 else "fail" # Log the API call log_api_call( db=db, name="smart budget recommendation", status=status, response_time=process_time, endpoint=endpoint ) return response except Exception as e: process_time = time.time() - start_time # Log failure log_api_call( db=db, name="smart budget recommendation", status="fail", response_time=process_time, endpoint=endpoint, error=str(e) ) raise else: # For other endpoints, just pass through return await call_next(request) @app.get("/") async def root(): return {"message": "Smart Budget Recommendation API", "status": "running"} @app.get("/health") async def health_check(): try: client.admin.command('ping') return {"status": "healthy", "database": "connected"} except Exception as e: return {"status": "unhealthy", "error": str(e)} @app.post("/expenses", response_model=dict) async def create_expense(expense: Expense): """ Disabled: this service does not create expenses. All expenses should be created by the main WalletSync app and stored directly in MongoDB. This API only reads existing data for analytics. """ raise HTTPException( status_code=405, detail="Creating expenses is disabled. Use the main WalletSync app to add expenses.", ) @app.get("/expenses", response_model=List[Expense]) async def get_expenses(user_id: str, limit: int = 100): """Get expenses for a user""" expenses = list(db.expenses.find({"user_id": user_id}).sort("date", -1).limit(limit)) for expense in expenses: expense["id"] = str(expense["_id"]) del expense["_id"] return expenses @app.post("/budgets", response_model=dict) async def create_budget(budget: Budget): """ Disabled: this service does not create budgets. All budgets should be created by the main WalletSync app and stored directly in MongoDB. This API only reads existing data for analytics. """ raise HTTPException( status_code=405, detail="Creating budgets is disabled. Use the main WalletSync app to add budgets.", ) @app.get("/budgets", response_model=List[Budget]) async def get_budgets(user_id: str): """Get budgets for a user""" budgets = list(db.budgets.find({"user_id": user_id})) for budget in budgets: budget["id"] = str(budget["_id"]) del budget["_id"] return budgets @app.get("/recommendations/{user_id}", response_model=List[BudgetRecommendation]) async def get_budget_recommendations(user_id: str, month: Optional[int] = None, year: Optional[int] = None): """ Get smart budget recommendations for a user based on past spending behavior. Example response: { "category": "Groceries", "average_expense": 3800, "recommended_budget": 4000, "reason": "Your average monthly grocery expense is Rs.3,800. We suggest setting your budget to Rs.4,000 for next month." } """ if not month or not year: # Default to next month next_month = datetime.now().replace(day=1) + timedelta(days=32) month = next_month.month year = next_month.year recommendations = recommender.get_recommendations(user_id, month, year) return recommendations @app.get("/category-expenses/{user_id}", response_model=List[CategoryExpense]) async def get_category_expenses(user_id: str, months: int = 3): """Get average expenses by category for the past N months""" category_expenses = recommender.get_category_averages(user_id, months) return category_expenses if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) # from fastapi import FastAPI, HTTPException, Depends # from fastapi.middleware.cors import CORSMiddleware # from pymongo import MongoClient # from pymongo.errors import ConnectionFailure # import os # from typing import List, Optional # from datetime import datetime, timedelta # from app.models import BudgetRecommendation, Expense, Budget, CategoryExpense # from app.smart_recommendation import SmartBudgetRecommender # app = FastAPI(title="Smart Budget Recommendation API", version="1.0.0") # # CORS middleware # app.add_middleware( # CORSMiddleware, # allow_origins=["*"], # allow_credentials=True, # allow_methods=["*"], # allow_headers=["*"], # ) # # MongoDB connection - Get from environment variable (set as secret in Hugging Face) # MONGODB_URI = os.getenv("MONGODB_URI") # if not MONGODB_URI: # raise ValueError("MONGODB_URI environment variable is required. Please set it in Hugging Face secrets.") # try: # client = MongoClient(MONGODB_URI) # db = client.expense # # Test connection # client.admin.command('ping') # print("Successfully connected to MongoDB") # except ConnectionFailure as e: # print(f"Failed to connect to MongoDB: {e}") # raise # # Initialize Smart Budget Recommender # recommender = SmartBudgetRecommender(db) # @app.get("/") # async def root(): # return {"message": "Smart Budget Recommendation API", "status": "running"} # @app.get("/health") # async def health_check(): # try: # client.admin.command('ping') # return {"status": "healthy", "database": "connected"} # except Exception as e: # return {"status": "unhealthy", "error": str(e)} # @app.post("/expenses", response_model=dict) # async def create_expense(expense: Expense): # """ # Disabled: this service does not create expenses. # All expenses should be created by the main WalletSync app and stored # directly in MongoDB. This API only reads existing data for analytics. # """ # raise HTTPException( # status_code=405, # detail="Creating expenses is disabled. Use the main WalletSync app to add expenses.", # ) # @app.get("/expenses", response_model=List[Expense]) # async def get_expenses(user_id: str, limit: int = 100): # """Get expenses for a user""" # expenses = list(db.expenses.find({"user_id": user_id}).sort("date", -1).limit(limit)) # for expense in expenses: # expense["id"] = str(expense["_id"]) # del expense["_id"] # return expenses # @app.post("/budgets", response_model=dict) # async def create_budget(budget: Budget): # """ # Disabled: this service does not create budgets. # All budgets should be created by the main WalletSync app and stored # directly in MongoDB. This API only reads existing data for analytics. # """ # raise HTTPException( # status_code=405, # detail="Creating budgets is disabled. Use the main WalletSync app to add budgets.", # ) # @app.get("/budgets", response_model=List[Budget]) # async def get_budgets(user_id: str): # """Get budgets for a user""" # budgets = list(db.budgets.find({"user_id": user_id})) # for budget in budgets: # budget["id"] = str(budget["_id"]) # del budget["_id"] # return budgets # @app.get("/recommendations/{user_id}", response_model=List[BudgetRecommendation]) # async def get_budget_recommendations(user_id: str, month: Optional[int] = None, year: Optional[int] = None): # """ # Get smart budget recommendations for a user based on past spending behavior. # Example response: # { # "category": "Groceries", # "average_expense": 3800, # "recommended_budget": 4000, # "reason": "Your average monthly grocery expense is Rs.3,800. We suggest setting your budget to Rs.4,000 for next month." # } # """ # if not month or not year: # # Default to next month # next_month = datetime.now().replace(day=1) + timedelta(days=32) # month = next_month.month # year = next_month.year # recommendations = recommender.get_recommendations(user_id, month, year) # return recommendations # @app.get("/category-expenses/{user_id}", response_model=List[CategoryExpense]) # async def get_category_expenses(user_id: str, months: int = 3): # """Get average expenses by category for the past N months""" # category_expenses = recommender.get_category_averages(user_id, months) # return category_expenses # if __name__ == "__main__": # import uvicorn # uvicorn.run(app, host="0.0.0.0", port=8000)