Yassine Mhirsi
Fix variable name for Hugging Face API key in stance model loading process in main.py
dc6c29a
raw
history blame
2.46 kB
"""Main FastAPI application entry point"""
import sys
from pathlib import Path
# Add the app directory to Python path to ensure imports work
app_dir = Path(__file__).parent
if str(app_dir) not in sys.path:
sys.path.insert(0, str(app_dir))
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import logging
from config import (
API_TITLE,
API_DESCRIPTION,
API_VERSION,
STANCE_MODEL_ID,
HUGGINGFACE_API_KEY,
HUGGINGFACE_STANCE_MODEL_ID,
HOST,
PORT,
RELOAD,
CORS_ORIGINS,
CORS_CREDENTIALS,
CORS_METHODS,
CORS_HEADERS,
)
from services import stance_model_manager
from routes import api_router
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Load models on startup and cleanup on shutdown"""
# Startup: Load all models
logger.info("Loading models on startup...")
# Load stance detection model
try:
logger.info(f"Loading stance model from Hugging Face: {HUGGINGFACE_STANCE_MODEL_ID}")
stance_model_manager.load_model(HUGGINGFACE_STANCE_MODEL_ID, HUGGINGFACE_API_KEY)
except Exception as e:
logger.error(f"✗ Failed to load stance model: {str(e)}")
logger.error("⚠️ Stance detection endpoints will not work!")
logger.info("✓ API startup complete")
logger.info("https://yassine-mhirsi-stance-detection-with-debertav3.hf.space/docs")
yield # Application runs here
# Shutdown: Cleanup (if needed)
# Currently no cleanup needed, but you can add it here if necessary
# Create FastAPI application
app = FastAPI(
title=API_TITLE,
description=API_DESCRIPTION,
version=API_VERSION,
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan,
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=CORS_ORIGINS,
allow_credentials=CORS_CREDENTIALS,
allow_methods=CORS_METHODS,
allow_headers=CORS_HEADERS,
)
# Include API routes
app.include_router(api_router)
if __name__ == "__main__":
# Run the API server
# Access at: http://localhost:8000
# API docs at: http://localhost:8000/docs
# Run the API server
uvicorn.run(
"main:app",
host=HOST,
port=PORT,
reload=RELOAD,
log_level="info"
)