Spaces:
Runtime error
Runtime error
Download app.py from mentalys-app/quiz-classification: direct link, hf CLI and curl.
- Browser
- Download file 9.16 kB
-
https://huggingface.co/spaces/mentalys-app/quiz-classification/resolve/main/app.py
- Command line
-
hf download hf://spaces/mentalys-app/quiz-classification/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mentalys-app/quiz-classification/resolve/main/app.py
9.16 kB
| import json | |
| import numpy as np | |
| import tensorflow as tf | |
| from fastapi import FastAPI, Request, Form, HTTPException | |
| from fastapi.templating import Jinja2Templates | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import JSONResponse, HTMLResponse | |
| from typing import Optional | |
| import os | |
| from pathlib import Path | |
| app = FastAPI( | |
| title="Mental Health Disorder Prediction API", | |
| description="API for predicting mental health disorders based on questionnaire responses. " | |
| "This application is a fork of https://github.com/Mentalys-App/tabular_ml and was " | |
| "originally created by I Gede Widnyana (https://github.com/GdWidnyana).", | |
| version="1.0", | |
| contact={ | |
| "name": "Mentalys App", | |
| "url": "https://github.com/Mentalys-App", | |
| }, | |
| license_info={ | |
| "name": "Apache 2.0", | |
| "url": "https://www.apache.org/licenses/LICENSE-2.0.html", | |
| } | |
| ) | |
| # Set up templates directory | |
| templates_path = Path("templates") | |
| if templates_path.exists(): | |
| templates = Jinja2Templates(directory="templates") | |
| # Create static directory if it doesn't exist | |
| static_path = Path("static") | |
| if not static_path.exists(): | |
| os.makedirs("static") | |
| # Mount static files | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| # Memuat model dari JSON | |
| with open("mental_disorder_model.json", "r") as model_file: | |
| model_json = json.load(model_file) | |
| model = tf.keras.models.model_from_json(model_json) | |
| model.load_weights("mental_disorder.weights.h5") | |
| # Memuat scaler dari JSON | |
| with open("scaler.json", "r") as scaler_file: | |
| scaler_data = json.load(scaler_file) | |
| class Scaler: | |
| def __init__(self, data): | |
| self.mean_ = np.array(data["mean"]) | |
| self.scale_ = np.array(data["scale"]) | |
| def transform(self, X): | |
| return (X - self.mean_) / self.scale_ | |
| scaler = Scaler(scaler_data) | |
| # Memuat label encoder dari JSON | |
| with open("label_encoder.json", "r") as le_file: | |
| label_encoder_data = json.load(le_file) | |
| class LabelEncoder: | |
| def __init__(self, classes): | |
| self.classes_ = np.array(classes) | |
| def inverse_transform(self, y): | |
| return self.classes_[y] | |
| label_encoder = LabelEncoder(label_encoder_data["classes"]) | |
| # Mapping label ke Bahasa Indonesia | |
| label_mapping = { | |
| 'MDD': 'Gangguan Depresi Mayor (MDD)', | |
| 'ASD': 'Gangguan Spektrum Autisme (ASD)', | |
| 'Loneliness': 'Kesepian', | |
| 'bipolar': 'Gangguan Bipolar', | |
| 'anexiety': 'Gangguan Kecemasan', | |
| 'PTSD': 'Gangguan Stres Pascatrauma (PTSD)', | |
| 'sleeping disorder': 'Gangguan Tidur', | |
| 'psychotic deprission': 'Depresi Psikotik', | |
| 'eating disorder': 'Gangguan Makan', | |
| 'ADHD': 'Gangguan Pemusatan Perhatian dan Hiperaktivitas (ADHD)', | |
| 'PDD': 'Gangguan Perkembangan Pervasif (PDD)', | |
| 'OCD': 'Gangguan Obsesif-Kompulsif (OCD)', | |
| } | |
| async def index(request: Request): | |
| if templates_path.exists(): | |
| # Pass additional context data to the template | |
| context = { | |
| "request": request, | |
| "result": "", | |
| "app_info": { | |
| "title": "Mental Health Disorder Prediction API", | |
| "description": "This application predicts mental health disorders based on questionnaire responses.", | |
| "author": "I Gede Widnyana (@GdWidnyana)", | |
| "author_url": "https://github.com/GdWidnyana", | |
| "original_repo": "https://github.com/Mentalys-App/tabular_ml", | |
| "organization": "Mentalys App", | |
| "organization_url": "https://github.com/Mentalys-App" | |
| } | |
| } | |
| return templates.TemplateResponse("index.html", context) | |
| else: | |
| return HTMLResponse(content="<h1>Template not found</h1>", status_code=404) | |
| async def predict( | |
| request: Request, | |
| age: int = Form(...), | |
| feeling_nervous: Optional[str] = Form(None), | |
| panic: Optional[str] = Form(None), | |
| breathing_rapidly: Optional[str] = Form(None), | |
| sweating: Optional[str] = Form(None), | |
| trouble_in_concentration: Optional[str] = Form(None), | |
| having_trouble_in_sleeping: Optional[str] = Form(None), | |
| having_trouble_with_work: Optional[str] = Form(None), | |
| hopelessness: Optional[str] = Form(None), | |
| anger: Optional[str] = Form(None), | |
| over_react: Optional[str] = Form(None), | |
| change_in_eating: Optional[str] = Form(None), | |
| suicidal_thought: Optional[str] = Form(None), | |
| feeling_tired: Optional[str] = Form(None), | |
| close_friend: Optional[str] = Form(None), | |
| social_media_addiction: Optional[str] = Form(None), | |
| weight_gain: Optional[str] = Form(None), | |
| introvert: Optional[str] = Form(None), | |
| popping_up_stressful_memory: Optional[str] = Form(None), | |
| having_nightmares: Optional[str] = Form(None), | |
| avoids_people_or_activities: Optional[str] = Form(None), | |
| feeling_negative: Optional[str] = Form(None), | |
| trouble_concentrating: Optional[str] = Form(None), | |
| blaming_yourself: Optional[str] = Form(None), | |
| hallucinations: Optional[str] = Form(None), | |
| repetitive_behaviour: Optional[str] = Form(None), | |
| seasonally: Optional[str] = Form(None), | |
| increased_energy: Optional[str] = Form(None) | |
| ): | |
| # Convert form values to boolean | |
| feeling_nervous_val = feeling_nervous == "Ya" | |
| panic_val = panic == "Ya" | |
| breathing_rapidly_val = breathing_rapidly == "Ya" | |
| sweating_val = sweating == "Ya" | |
| trouble_in_concentration_val = trouble_in_concentration == "Ya" | |
| having_trouble_in_sleeping_val = having_trouble_in_sleeping == "Ya" | |
| having_trouble_with_work_val = having_trouble_with_work == "Ya" | |
| hopelessness_val = hopelessness == "Ya" | |
| anger_val = anger == "Ya" | |
| over_react_val = over_react == "Ya" | |
| change_in_eating_val = change_in_eating == "Ya" | |
| suicidal_thought_val = suicidal_thought == "Ya" | |
| feeling_tired_val = feeling_tired == "Ya" | |
| close_friend_val = close_friend == "Ya" | |
| social_media_addiction_val = social_media_addiction == "Ya" | |
| weight_gain_val = weight_gain == "Ya" | |
| introvert_val = introvert == "Ya" | |
| popping_up_stressful_memory_val = popping_up_stressful_memory == "Ya" | |
| having_nightmares_val = having_nightmares == "Ya" | |
| avoids_people_or_activities_val = avoids_people_or_activities == "Ya" | |
| feeling_negative_val = feeling_negative == "Ya" | |
| trouble_concentrating_val = trouble_concentrating == "Ya" | |
| blaming_yourself_val = blaming_yourself == "Ya" | |
| hallucinations_val = hallucinations == "Ya" | |
| repetitive_behaviour_val = repetitive_behaviour == "Ya" | |
| seasonally_val = seasonally == "Ya" | |
| increased_energy_val = increased_energy == "Ya" | |
| # Konversi input ke array numpy | |
| user_data = np.array([[ | |
| age, feeling_nervous_val, panic_val, breathing_rapidly_val, sweating_val, | |
| trouble_in_concentration_val, having_trouble_in_sleeping_val, having_trouble_with_work_val, | |
| hopelessness_val, anger_val, over_react_val, change_in_eating_val, suicidal_thought_val, | |
| feeling_tired_val, close_friend_val, social_media_addiction_val, weight_gain_val, introvert_val, | |
| popping_up_stressful_memory_val, having_nightmares_val, avoids_people_or_activities_val, | |
| feeling_negative_val, trouble_concentrating_val, blaming_yourself_val, hallucinations_val, | |
| repetitive_behaviour_val, seasonally_val, increased_energy_val | |
| ]]).astype(float) | |
| # Melakukan skalasi | |
| user_data_scaled = scaler.transform(user_data) | |
| # Prediksi | |
| prediction = model.predict(user_data_scaled) | |
| predicted_class = label_encoder.inverse_transform([np.argmax(prediction)]) | |
| confidence_score = float(np.max(prediction) * 100) # Konversi ke persen | |
| # Map ke Bahasa Indonesia | |
| predicted_class_in_indonesian = label_mapping.get(predicted_class[0], predicted_class[0]) | |
| # Return hasil dalam format JSON | |
| return { | |
| "result": f"Hasil Diagnosa bahwa Anda mengalami {predicted_class_in_indonesian} dengan tingkat kepercayaan {confidence_score:.2f}%", | |
| "prediction": predicted_class_in_indonesian, | |
| "confidence": confidence_score | |
| } | |
| # API route for model health check | |
| async def health(): | |
| return {"status": "ok"} | |
| # New JSON API endpoint | |
| async def api_info(): | |
| return { | |
| "api_name": "Mental Health Disorder Prediction API", | |
| "version": "1.0", | |
| "author": "I Gede Widnyana (@GdWidnyana)", | |
| "author_url": "https://github.com/GdWidnyana", | |
| "original_repo": "https://github.com/Mentalys-App/tabular_ml", | |
| "organization": "Mentalys App", | |
| "organization_url": "https://github.com/Mentalys-App", | |
| "endpoints": [ | |
| {"path": "/", "method": "GET", "description": "HTML form interface"}, | |
| {"path": "/", "method": "POST", "description": "Prediction endpoint (form data)"}, | |
| {"path": "/health", "method": "GET", "description": "API health check"}, | |
| {"path": "/api", "method": "GET", "description": "API information"} | |
| ] | |
| } | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True) | |