Spaces:
Configuration error
Configuration error
| import os | |
| import sys | |
| import joblib | |
| import pandas as pd | |
| from fastapi import FastAPI, HTTPException | |
| # Add the root directory to the system path so Python can find the 'backend' folder | |
| sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from backend.schema.user_input import WorkoutFeatures | |
| MODEL_PATH = "backend/deploy_model.joblib" | |
| try: | |
| # Look for the file in the same folder as main.py | |
| model = joblib.load(MODEL_PATH) | |
| print("✅ BACKEND: Model loaded successfully!") | |
| except Exception as e: | |
| print(f"❌ BACKEND ERROR: Could not load model. Reason: {e}") | |
| model = None | |
| app = FastAPI() | |
| def predict_workout(data: WorkoutFeatures): | |
| if model is None: | |
| raise HTTPException(status_code=500, detail="Model not loaded on server.") | |
| # 1. Process Diet Columns (Same logic as before) | |
| diet_columns = ['diet_type_Keto', 'diet_type_Low-Carb', 'diet_type_Paleo', 'diet_type_Vegan', 'diet_type_Vegetarian'] | |
| diet_values = [1 if col == f"diet_type_{data.diet_type}" else 0 for col in diet_columns] | |
| # 2. Build the exact feature list your model expects | |
| input_list = [ | |
| data.Age, data.Session_Duration_hours, data.Calories_Burned, | |
| data.Fat_Percentage, data.Water_Intake_liters, data.workout_frequency, | |
| data.experience_level, data.bmi, data.daily_meals_frequency, | |
| data.carbs, data.proteins, data.fats, data.calories, data.Gender, | |
| *diet_values | |
| ] | |
| try: | |
| # 3. Local Prediction (No more 'requests.post'!) | |
| # We wrap in [input_list] because sklearn models expect a 2D array | |
| prediction = model.predict([input_list]) | |
| # Convert to float to make it JSON serializable | |
| return {"prediction": float(prediction[0])} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Prediction Error: {str(e)}") |