File size: 2,116 Bytes
9db766f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Main FastAPI application entry point"""

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,
    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: {STANCE_MODEL_ID}")
        stance_model_manager.load_model(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")
    
    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"
    )