Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,18 +5,30 @@ from typing import List
|
|
| 5 |
from datetime import date, datetime, timedelta
|
| 6 |
from collections import Counter
|
| 7 |
import math
|
|
|
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
| 12 |
|
| 13 |
from itinerary.summary_generator import generate_summary_with_ai
|
| 14 |
from recommender.recommender import Recommender
|
| 15 |
from itinerary.itinerary_scheduler import ItineraryScheduler
|
| 16 |
from recommender.weather_api import get_weather_forecast
|
| 17 |
|
|
|
|
| 18 |
load_dotenv()
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
class ConnectionManager:
|
| 22 |
def __init__(self):
|
|
@@ -61,6 +73,20 @@ class ItineraryRequest(BaseModel):
|
|
| 61 |
}
|
| 62 |
}
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
# --- FastAPI Application Setup ---
|
| 66 |
app = FastAPI(
|
|
@@ -69,7 +95,6 @@ app = FastAPI(
|
|
| 69 |
version="1.0.0"
|
| 70 |
)
|
| 71 |
|
| 72 |
-
|
| 73 |
# --- Database and Recommender Initialization ---
|
| 74 |
db_params = {
|
| 75 |
"host": os.getenv("DB_HOST"),
|
|
@@ -138,7 +163,10 @@ app.add_middleware(
|
|
| 138 |
|
| 139 |
# --- API Endpoint Definition ---
|
| 140 |
@app.post("/schedule", summary="Generate a Scheduled Itinerary")
|
| 141 |
-
def create_scheduled_itinerary(
|
|
|
|
|
|
|
|
|
|
| 142 |
used_place_ids = set()
|
| 143 |
all_itineraries = []
|
| 144 |
|
|
@@ -170,6 +198,17 @@ def create_scheduled_itinerary(request: ItineraryRequest):
|
|
| 170 |
raw_forecast = get_weather_forecast(request.user_lat, request.user_lon, forecast_start, forecast_end)
|
| 171 |
daily_forecast = format_daily_forecast(raw_forecast)
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
# 4. Combine results into the final response
|
| 174 |
return {
|
| 175 |
"scheduled_itineraries": scheduled_result["scheduled"],
|
|
|
|
| 5 |
from datetime import date, datetime, timedelta
|
| 6 |
from collections import Counter
|
| 7 |
import math
|
| 8 |
+
import jwt
|
| 9 |
import json
|
| 10 |
import os
|
| 11 |
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
+
from supabase import create_client, Client
|
| 14 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 15 |
|
| 16 |
from itinerary.summary_generator import generate_summary_with_ai
|
| 17 |
from recommender.recommender import Recommender
|
| 18 |
from itinerary.itinerary_scheduler import ItineraryScheduler
|
| 19 |
from recommender.weather_api import get_weather_forecast
|
| 20 |
|
| 21 |
+
|
| 22 |
load_dotenv()
|
| 23 |
|
| 24 |
+
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "your-super-secret-key-for-local-dev")
|
| 25 |
+
ALGORITHM = "HS256"
|
| 26 |
+
|
| 27 |
+
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 28 |
+
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 29 |
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
|
| 33 |
class ConnectionManager:
|
| 34 |
def __init__(self):
|
|
|
|
| 73 |
}
|
| 74 |
}
|
| 75 |
|
| 76 |
+
security = HTTPBearer()
|
| 77 |
+
def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:
|
| 78 |
+
"""Decodes the JWT token to get the user's ID."""
|
| 79 |
+
token = credentials.credentials
|
| 80 |
+
try:
|
| 81 |
+
payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[ALGORITHM])
|
| 82 |
+
user_id = payload.get("sub") # 'sub' is the standard claim for subject/user ID
|
| 83 |
+
if user_id is None:
|
| 84 |
+
raise HTTPException(status_code=401, detail="Invalid token: User ID not found")
|
| 85 |
+
return user_id
|
| 86 |
+
except jwt.ExpiredSignatureError:
|
| 87 |
+
raise HTTPException(status_code=401, detail="Token has expired")
|
| 88 |
+
except jwt.InvalidTokenError:
|
| 89 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
| 90 |
|
| 91 |
# --- FastAPI Application Setup ---
|
| 92 |
app = FastAPI(
|
|
|
|
| 95 |
version="1.0.0"
|
| 96 |
)
|
| 97 |
|
|
|
|
| 98 |
# --- Database and Recommender Initialization ---
|
| 99 |
db_params = {
|
| 100 |
"host": os.getenv("DB_HOST"),
|
|
|
|
| 163 |
|
| 164 |
# --- API Endpoint Definition ---
|
| 165 |
@app.post("/schedule", summary="Generate a Scheduled Itinerary")
|
| 166 |
+
def create_scheduled_itinerary(
|
| 167 |
+
request: ItineraryRequest,
|
| 168 |
+
user_id: str = Depends(get_current_user_id)
|
| 169 |
+
):
|
| 170 |
used_place_ids = set()
|
| 171 |
all_itineraries = []
|
| 172 |
|
|
|
|
| 198 |
raw_forecast = get_weather_forecast(request.user_lat, request.user_lon, forecast_start, forecast_end)
|
| 199 |
daily_forecast = format_daily_forecast(raw_forecast)
|
| 200 |
|
| 201 |
+
try:
|
| 202 |
+
supabase.table('itineraries').insert({
|
| 203 |
+
"user_id": user_id,
|
| 204 |
+
"itinerary_data": scheduled_result,
|
| 205 |
+
"start_date": request.start_date.isoformat(),
|
| 206 |
+
"end_date": request.end_date.isoformat()
|
| 207 |
+
}).execute()
|
| 208 |
+
print(f"Successfully saved itinerary for user: {user_id}")
|
| 209 |
+
except Exception as e:
|
| 210 |
+
print(f"ERROR: Could not save itinerary to Supabase. Reason: {e}")
|
| 211 |
+
|
| 212 |
# 4. Combine results into the final response
|
| 213 |
return {
|
| 214 |
"scheduled_itineraries": scheduled_result["scheduled"],
|