File size: 4,524 Bytes
03289af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import joblib
import pandas as pd
import gradio as gr

# ---------------- Load model bundle ----------------
bundle = joblib.load("best_model_v2_calibrated.joblib")
model = bundle["model"]
threshold = float(bundle["threshold"])

# ---------------- Output formatting ----------------
def format_output(lang, label, proba):
    if lang == "বাংলা":
        risk_text = "উচ্চ ঝুঁকি" if label == "High Risk" else "কম ঝুঁকি"
        return (
            f"### ফলাফল: **{risk_text}**\n"
            f"- ঝুঁকির সম্ভাবনা (Probability): **{proba:.3f}**\n"
            f"- Threshold: **{threshold:.2f}**\n\n"
            "⚠️ এটি একটি **স্ক্রিনিং টুল**, চিকিৎসা নির্ণয় নয়। সমস্যা থাকলে ডাক্তারের পরামর্শ নিন।"
        )
    else:
        return (
            f"### Result: **{label}**\n"
            f"- Risk probability: **{proba:.3f}**\n"
            f"- Threshold: **{threshold:.2f}**\n\n"
            "⚠️ This is a **screening tool**, not a medical diagnosis. If you have symptoms, consult a clinician."
        )

def web_speak_html(text, lang):
    voice_lang = "bn-BD" if lang == "বাংলা" else "en-US"
    safe = text.replace("`", "").replace("\\", "\\\\").replace("'", "\\'")
    return f"""

    <div style="display:flex;gap:10px;align-items:center;">

      <button onclick="(function(){{

        const msg = new SpeechSynthesisUtterance('{safe}');

        msg.lang = '{voice_lang}';

        window.speechSynthesis.cancel();

        window.speechSynthesis.speak(msg);

      }})()" style="padding:10px 14px;border-radius:10px;border:1px solid #ccc;cursor:pointer;">

        🔊 Speak / শোনান

      </button>

      <span style="opacity:0.7;">(Voice depends on browser installed voices)</span>

    </div>

    """

# ---------------- Prediction ----------------
def predict(lang, age, gender, bmi, bp_sys, bp_dia, phys_days, dpq, smoking, alcohol, diabetes, cycle):
    sample = pd.DataFrame([{
        "Age": float(age),
        "Gender": gender,
        "BMI": float(bmi),
        "BP_SYS": float(bp_sys),
        "BP_DIA": float(bp_dia),
        "Phys_Activity_Days": float(phys_days),
        "DPQ_Score": float(dpq),
        "Smoking_Indicator": float(smoking),
        "Alcohol_Feature": float(alcohol),
        "Diabetes_Indicator": float(diabetes),
        "Cycle": cycle
    }])

    proba = float(model.predict_proba(sample)[:, 1][0])
    pred = int(proba >= threshold)
    label = "High Risk" if pred == 1 else "Low Risk"

    md = format_output(lang, label, proba)
    speak = web_speak_html(md, lang)
    return md, speak

# ---------------- UI ----------------
with gr.Blocks(title="SleepGuardAI – Sleep Risk Screening") as demo:
    gr.Markdown("# SleepGuardAI – Sleep Risk Screening (NHANES-based)")
    gr.Markdown("Fill the form → get risk score. Bilingual output + Speak button included.")

    lang = gr.Radio(["English", "বাংলা"], value="English", label="Language / ভাষা")

    with gr.Row():
        age = gr.Slider(10, 90, value=30, label="Age / বয়স")
        gender = gr.Dropdown(["Male", "Female"], value="Male", label="Gender")

    with gr.Row():
        bmi = gr.Slider(10, 50, value=25, label="BMI")
        bp_sys = gr.Slider(80, 220, value=120, label="Systolic BP")
        bp_dia = gr.Slider(40, 140, value=80, label="Diastolic BP")

    phys = gr.Slider(0, 7, value=3, step=1, label="Physical Activity Days/Week")

    gr.Markdown("### Optional (improves accuracy if known)")
    with gr.Row():
        dpq = gr.Slider(0, 27, value=0, step=1, label="DPQ Depression Score (0–27)")
        smoking = gr.Dropdown([1, 2], value=2, label="Smoking (1=Yes, 2=No)")
        diabetes = gr.Dropdown([1, 2], value=2, label="Diabetes (1=Yes, 2=No)")
        alcohol = gr.Slider(0, 30, value=0, step=1, label="Alcohol feature (proxy)")

    cycle = gr.Dropdown(["G", "H", "I", "J"], value="J", label="NHANES Cycle")

    btn = gr.Button("Predict / ফলাফল দেখুন")
    out_md = gr.Markdown()
    out_speak = gr.HTML()

    btn.click(
        predict,
        inputs=[lang, age, gender, bmi, bp_sys, bp_dia, phys, dpq, smoking, alcohol, diabetes, cycle],
        outputs=[out_md, out_speak]
    )

demo.launch()