File size: 3,859 Bytes
73c6377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

# Import routers
from api.routers import medical, hbv_assessment
from api.middleware import (
    ProcessTimeMiddleware, 
    LoggingMiddleware, 
    RateLimitMiddleware,
    get_cors_middleware_config
)
from fastapi.middleware.cors import CORSMiddleware
from api.exceptions import (
    http_exception_handler,
    validation_exception_handler,
    general_exception_handler,
    starlette_exception_handler
)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan management with background initialization"""
    # Startup
    logger.info("Starting HBV AI Assistant API...")
    
    # Start background initialization of heavy components (optional for AI chat)
    try:
        from core.background_init import start_background_initialization
        logger.info("🚀 Starting background initialization of components...")
        start_background_initialization()
        logger.info("API started successfully (components loading in background)")
    except Exception as e:
        logger.error(f"Failed to start background initialization: {e}")
        logger.info("API started with lazy loading fallback")
    
    yield
    
    # Shutdown
    logger.info("Shutting down HBV AI Assistant API...")


# Create FastAPI application
app = FastAPI(
    title="HBV AI Assistant API",
    description="HBV Patient Selection System - Evaluates patient eligibility for HBV treatment according to SASLT 2021 guidelines",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# Add middleware
app.add_middleware(CORSMiddleware, **get_cors_middleware_config())
app.add_middleware(ProcessTimeMiddleware)
app.add_middleware(LoggingMiddleware)
app.add_middleware(RateLimitMiddleware, calls_per_minute=100)  # Adjust as needed

# Add exception handlers
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(StarletteHTTPException, starlette_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)

# Include routers
app.include_router(hbv_assessment.router)  # Primary HBV assessment endpoint
app.include_router(medical.router)  # Optional AI chat for guideline exploration

# Root endpoint
@app.get("/")
async def root():
    """Root endpoint with API information"""
    return {
        "name": "HBV AI Assistant API",
        "version": "1.0.0",
        "description": "HBV Patient Selection System - Evaluates patient eligibility for HBV treatment according to SASLT 2021 guidelines",
        "docs": "/docs",
        "endpoints": {
            "assess": "/assess (POST) - Primary endpoint for HBV patient eligibility assessment",
            "assess_text": "/assess/text (POST) - Text-based HBV patient eligibility assessment",
            "ask": "/ask (POST) - Optional AI chat for guideline exploration",
            "ask_stream": "/ask/stream (POST) - Streaming AI chat responses",
            "health": "/health (GET) - Simple health check",
        }
    }


# Simple health check endpoint
@app.get("/health")
async def health_check():
    """Simple health check endpoint"""
    from datetime import datetime
    return {
        "status": "healthy",
        "version": "1.0.0",
        "timestamp": datetime.now().isoformat()
    }




if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "api.app:app",
        host="127.0.0.1",
        port=8000,
        reload=True,
        log_level="info"
    )