meisaicheck-api / main.py
vumichien's picture
Update model to cl-nagoya-sup-simcse-ja-nss-v1_0_8_3, add new data files, and enhance startup process with directory creation and model loading.
b26c508
import sys
import os
from fastapi import FastAPI, HTTPException, Depends
import uvicorn
import traceback
from contextlib import asynccontextmanager
from fastapi.middleware.cors import CORSMiddleware
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
sys.path.append(os.path.join(current_dir, "meisai-check-ai"))
from routes import auth, predict, health
from services.sentence_transformer_service import sentence_transformer_service
from utils import create_directories
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan context manager for startup and shutdown events"""
try:
# Load models and data ONCE at startup
sentence_transformer_service.load_model_data()
except Exception as e:
print(f"Error during startup: {e}")
traceback.print_exc()
yield # App chạy tại đây
print("Shutting down application")
# Initialize FastAPI
app = FastAPI(
title="MeisaiCheck API",
description="API for MeisaiCheck AI System",
version="1.0",
lifespan=lifespan,
openapi_tags=[
{
"name": "Health",
"description": "Health check endpoints",
},
{
"name": "Authentication",
"description": "User authentication and token management",
},
{
"name": "AI Model",
"description": "AI model endpoints for prediction and embedding",
},
],
# Removed root_path since HF Spaces already handles it
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
expose_headers=["*"], # Expose all headers
)
# Create upload and output directories
os.makedirs("uploads", exist_ok=True)
os.makedirs("outputs", exist_ok=True)
@app.on_event("startup")
async def startup_event():
"""Load model and data on startup"""
print("Loading sentence transformer model and data...")
sentence_transformer_service.load_model_data()
print("Model and data loaded successfully!")
# Include Routers
app.include_router(health.router, tags=["Health"])
app.include_router(auth.router, tags=["Authentication"])
app.include_router(predict.router, tags=["AI Model"])
@app.get("/", tags=["Health"])
async def root():
return {"message": "Meisai Check API is running!"}
if __name__ == "__main__":
create_directories()
uvicorn.run(app, host="0.0.0.0", port=7860)