from dotenv import load_dotenv load_dotenv() import sys from pathlib import Path # Ensure the backend module can be found sys.path.append(str(Path(__file__).resolve().parent.parent)) from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from app.core.db_setup import init_db from app.routes.chat_hf import router as chat_router from app.routes.feedback import router as feedback_router from app.core.logging_setup import setup_logging, logger from app.core.env_setup import setup_environment from app.core.custom_warnings import custom_warning from app.core.device_setup import check_gpu_availability, device import requests import threading import time # Suppress specific warnings custom_warning() app = FastAPI() app.include_router(chat_router) # Include the chat router app.include_router(feedback_router) # Include the feedback router # Allow frontend to access the backend app.add_middleware( CORSMiddleware, allow_origins=["*"], # Change to frontend URL in production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class ChatRequest(BaseModel): message: str class FeedbackRequest(BaseModel): user_input: str arina_reply: str reason: str def delayed_self_ping(): time.sleep(10) # Give the server time to fully boot try: res = requests.get("https://adsurkasur-arina-hf-spaces-api.hf.space/healthz") res.raise_for_status() logger.info("✅ Self-ping to /healthz successful.") except Exception as e: logger.warning(f"⚠️ Self-ping failed after delay: {e}") @app.on_event("startup") def startup_event(): # Initialize the database and logging init_db() setup_logging() logger.info("✅ Database initialized!") setup_environment() logger.info("✅ Environment variables loaded!") logger.info("✅ Logging setup complete!") # Check GPU availability during application startup global device # Ensure device is globally accessible device = check_gpu_availability() # 🔁 Delayed self-ping threading.Thread(target=delayed_self_ping, daemon=True).start() @app.get("/") def root(): logger.info("✅ Arina HF API is running!") return {"message": "Arina HF API is running!"} @app.get("/healthz") def health_check(): return {"status": "ok"}