File size: 2,371 Bytes
68964c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bcdea6
68964c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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"}