Spaces:
Runtime error
Runtime error
Antigravity Deploy Agent
Deploy Suicide Risk Detection web application to Hugging Face Spaces
0be18fb | import os | |
| import sys | |
| import uvicorn | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, Field | |
| # Ensure project root is in python path | |
| project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| if project_root not in sys.path: | |
| sys.path.append(project_root) | |
| from src.predict import SuicideRiskPredictor | |
| app = FastAPI( | |
| title="Suicide Risk Detection System", | |
| description="Real-time web application fusing Chat Brain and Profile Brain for suicide risk level prediction." | |
| ) | |
| # Enable CORS | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Instantiate predictor (loads BanglaBERT by default) | |
| print("Initializing SuicideRiskPredictor with BanglaBERT...") | |
| predictor = SuicideRiskPredictor(model_name="banglabert") | |
| print("Predictor loaded successfully.") | |
| class ProfileData(BaseModel): | |
| age_group: str = None | |
| age: float = None | |
| gender: str = None | |
| profession_group: str = None | |
| religion: str = None | |
| hometown: str = None | |
| reason: str = None | |
| reason_description: str = None | |
| time: str = None | |
| temperature: float = None | |
| feels_like: float = None | |
| temp_min: float = None | |
| temp_max: float = None | |
| air_pressure: float = None | |
| air_humidity: float = None | |
| wind_speed: float = None | |
| wind_deg: float = None | |
| clouds_sky: float = None | |
| weather_main: str = None | |
| weather_description: str = None | |
| class PredictionRequest(BaseModel): | |
| text: str | |
| profile: ProfileData = Field(default_factory=ProfileData) | |
| def get_metadata(): | |
| return { | |
| "categories": { | |
| "gender": ["Male", "Female", "3rd Gender"], | |
| "profession_group": ["Student", "Unemployed", "Worker", "Housewife", "Service holder", "Day labourer", "Teacher", "Farmer", "Doctor", "Other"], | |
| "religion": ["Muslim", "Hindu", "Buddhism", "Christian", "Other"], | |
| "hometown": ["Dhaka", "Sylhet", "Rajshahi", "Barisal", "Chittagong", "Khulna", "Rangpur", "Mymensingh", "Bogra", "Pabna", "Brahmanbaria", "Manikganj", "Other"], | |
| "reason": ["Relationship problem", "Harassment", "Marital affair", "Family issue", "Violence and mental issue", "Humiliation", "Poverty", "Physical issue", "Academic Fail", "Other"], | |
| "time": ["morning", "noon", "afternoon", "evening", "night"], | |
| "weather_main": ["Clear", "Clouds", "Rain", "Drizzle", "Mist", "Haze", "Fog", "Thunderstorm"] | |
| }, | |
| "defaults": { | |
| "age": 24.0, | |
| "gender": "Male", | |
| "profession_group": "Student", | |
| "religion": "Muslim", | |
| "hometown": "Dhaka", | |
| "reason": "relationship problem", | |
| "time": "afternoon", | |
| "temperature": 299.1, | |
| "feels_like": 302.2, | |
| "temp_min": 298.7, | |
| "temp_max": 298.6, | |
| "air_pressure": 1005.0, | |
| "air_humidity": 82.2, | |
| "wind_speed": 4.1, | |
| "wind_deg": 148.7, | |
| "clouds_sky": 58.3, | |
| "weather_main": "Clear" | |
| } | |
| } | |
| def predict_risk(req: PredictionRequest): | |
| try: | |
| # Convert Pydantic model to raw dict, filtering out None values | |
| profile_dict = {k: v for k, v in req.profile.dict().items() if v is not None} | |
| # Call the predictor | |
| results = predictor.predict_one(text=req.text, profile=profile_dict) | |
| return results | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Configure static assets path | |
| static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") | |
| os.makedirs(static_dir, exist_ok=True) | |
| # Serve the static files | |
| app.mount("/static", StaticFiles(directory=static_dir), name="static") | |
| def read_root(): | |
| index_path = os.path.join(static_dir, "index.html") | |
| if os.path.exists(index_path): | |
| return FileResponse(index_path) | |
| return {"message": "Suicide Risk Detection System backend is running. Create static/index.html to view UI."} | |
| if __name__ == "__main__": | |
| uvicorn.run("server:app", host="127.0.0.1", port=8000, reload=True) | |