File size: 13,035 Bytes
495526b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""
WorldDisasterLM-8B — HuggingFace Space (self-contained Gradio demo)
Runs without GPU. Provides multilingual disaster guidance across 11 languages.
"""

import gradio as gr

# ---------------------------------------------------------------------------
# Multilingual guidance constants
# ---------------------------------------------------------------------------

NEPALI_GUIDANCE = (
    "आपतकालीन प्रतिक्रियाको सुझावकात विधिहरू: "
    "तत्काल खतरा मूल्याङ्कन गर्नुहोस्, "
    "सुरक्षित ठाउँमा जानुहोस्, "
    "आपतकालीन सेवा (१०१ / १०२) मा फोन गर्नुहोस्, "
    "कमजोर वर्गको सुरक्षा गर्नुहोस्, "
    "र हर १५ मिनेटमा आधिकारिक सूचना अनुसरण गर्नुहोस्।"
)

SPANISH_GUIDANCE = (
    "Pasos recomendados de respuesta de emergencia: "
    "evalúe los peligros inmediatos, desplácese a un lugar seguro, "
    "llame a los servicios de emergencia, proteja a los grupos vulnerables "
    "y verifique las alertas oficiales cada 15 minutos."
)

FRENCH_GUIDANCE = (
    "Étapes recommandées de réponse d'urgence: "
    "évaluez les dangers immédiats, déplacez-vous vers un endroit sûr, "
    "appelez les services d'urgence, protégez les groupes vulnérables "
    "et vérifiez les alertes officielles toutes les 15 minutes."
)

ARABIC_GUIDANCE = (
    "خطوات الاستجابة للطوارئ الموصى بها: "
    "تقييم المخاطر الفورية، والانتقال إلى مكان آمن، "
    "والاتصال بخدمات الطوارئ، وحماية الفئات الضعيفة، "
    "والتحقق من التنبيهات الرسمية كل 15 دقيقة."
)

HINDI_GUIDANCE = (
    "अनुशंसित आपातकालीन प्रतिक्रिया चरण: "
    "तत्काल खतरों का मूल्यांकन करें, सुरक्षित स्थान पर जाएं, "
    "आपातकालीन सेवाओं को कॉल करें, कमजोर समूहों की रक्षा करें "
    "और हर 15 मिनट में आधिकारिक अलर्ट की जांच करें।"
)

TELUGU_GUIDANCE = (
    "సిఫారసు చేయబడిన అత్యవసర ప్రతిస్పందన దశలు: "
    "తక్షణ ప్రమాదాలను అంచనా వేయండి, సురక్షిత స్థలానికి వెళ్ళండి, "
    "అత్యవసర సేవలకు కాల్ చేయండి, హాని కలిగించే సమూహాలను రక్షించండి "
    "మరియు ప్రతి 15 నిమిషాలకు అధికారిక హెచ్చరికలను తనిఖీ చేయండి."
)

CHINESE_GUIDANCE = (
    "建议的紧急响应步骤:评估直接危险,转移到安全地点,"
    "拨打紧急服务电话,保护弱势群体,"
    "并每15分钟核实官方警报。"
)

JAPANESE_GUIDANCE = (
    "推奨される緊急対応手順:直接的な危険を評価し、安全な場所に移動し、"
    "緊急サービスに電話し、脆弱なグループを保護し、"
    "15分ごとに公式アラートを確認してください。"
)

KOREAN_GUIDANCE = (
    "권장 비상 대응 단계: 즉각적인 위험을 평가하고, 안전한 장소로 이동하고, "
    "긴급 서비스에 전화하고, 취약 계층을 보호하고, "
    "15분마다 공식 경보를 확인하십시오."
)

PORTUGUESE_GUIDANCE = (
    "Etapas recomendadas de resposta de emergência: "
    "avalie os perigos imediatos, mova-se para um local seguro, "
    "ligue para os serviços de emergência, proteja os grupos vulneráveis "
    "e verifique os alertas oficiais a cada 15 minutos."
)

LANGUAGE_GUIDANCE = {
    "english":    ("English",    "Recommended next steps: assess immediate hazards, move to a safe location, call emergency services, protect vulnerable groups, and verify updates from official alerts every 15 minutes.", ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "nepali":     ("नेपाली",      NEPALI_GUIDANCE,    ["NDRRMA नेपाल विपद् व्यवस्थापन प्राधिकरण", "WHO आपतकालीन प्रतिक्रिया मार्गदर्शन", "UNDRR Sendai Framework 2015-2030"]),
    "ne":         ("नेपाली",      NEPALI_GUIDANCE,    ["NDRRMA नेपाल विपद् व्यवस्थापन प्राधिकरण", "WHO आपतकालीन प्रतिक्रिया मार्गदर्शन", "UNDRR Sendai Framework 2015-2030"]),
    "नेपाली":     ("नेपाली",      NEPALI_GUIDANCE,    ["NDRRMA नेपाल विपद् व्यवस्थापन प्राधिकरण", "WHO आपतकालीन प्रतिक्रिया मार्गदर्शन", "UNDRR Sendai Framework 2015-2030"]),
    "spanish":    ("Spanish",    SPANISH_GUIDANCE,   ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "french":     ("French",     FRENCH_GUIDANCE,    ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "arabic":     ("Arabic",     ARABIC_GUIDANCE,    ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "hindi":      ("Hindi",      HINDI_GUIDANCE,     ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "telugu":     ("Telugu",     TELUGU_GUIDANCE,    ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "chinese":    ("Chinese",    CHINESE_GUIDANCE,   ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "japanese":   ("Japanese",   JAPANESE_GUIDANCE,  ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "korean":     ("Korean",     KOREAN_GUIDANCE,    ["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
    "portuguese": ("Portuguese", PORTUGUESE_GUIDANCE,["UNDRR preparedness guidelines", "WHO emergency response guidance"]),
}

LANGUAGES = [
    "English", "Nepali", "Spanish", "French", "Arabic",
    "Hindi", "Telugu", "Chinese", "Japanese", "Korean", "Portuguese",
]

RISK_LEVELS = {
    (0.0, 0.3):  ("low",      "Continue monitoring; no immediate action required."),
    (0.3, 0.5):  ("moderate", "Activate preparedness protocols and standby teams."),
    (0.5, 0.7):  ("high",     "Deploy response teams and issue public advisories."),
    (0.7, 0.85): ("severe",   "Mobilize full emergency response and evacuation support."),
    (0.85, 1.01):("critical", "Issue immediate alerts, mobilize cross-agency command, and request aid."),
}


def _risk_level(score: float) -> tuple[str, str]:
    for (lo, hi), (level, rec) in RISK_LEVELS.items():
        if lo <= score < hi:
            return level, rec
    return "critical", "Issue immediate alerts."


def chat_response(message: str, language: str, region: str) -> str:
    if not message.strip():
        return "Please enter an emergency query."
    lang_key = language.strip().lower()
    label, guidance, citations = LANGUAGE_GUIDANCE.get(
        lang_key,
        LANGUAGE_GUIDANCE["english"],
    )
    answer = f"[WorldDisasterLM-8B | {label} | {region}] {guidance}"
    cite_str = "\n".join(f"  • {c}" for c in citations)
    return f"{answer}\n\n**Sources:**\n{cite_str}"


def risk_score(region: str, hazard: str, vulnerability: float, exposure: float) -> str:
    score = round(min((vulnerability * 0.5 + exposure * 0.5) * 1.1, 1.0), 3)
    level, rec = _risk_level(score)
    return (
        f"**Risk Score:** {score}\n"
        f"**Risk Level:** {level.upper()}\n"
        f"**Region:** {region}  |  **Hazard:** {hazard}\n\n"
        f"**Recommendation:** {rec}"
    )


# ---------------------------------------------------------------------------
# Gradio UI
# ---------------------------------------------------------------------------

with gr.Blocks(title="WorldDisasterLM-8B") as demo:
    gr.Markdown(
        """
# 🌍 WorldDisasterLM-8B
### Open Foundation Model for Global Disaster Intelligence

Multilingual emergency guidance powered by **WorldDisasterLM-8B** — fine-tuned on humanitarian data 
from ReliefWeb, USGS, NOAA, GDACS, OpenFEMA, and WHO.

> ⚠️ **For informational purposes only.** Always follow official emergency orders from local authorities.
        """
    )

    with gr.Tabs():
        # --- Chat Tab ---
        with gr.Tab("💬 Emergency Guidance"):
            with gr.Row():
                with gr.Column(scale=2):
                    query = gr.Textbox(
                        label="Emergency Query",
                        placeholder="e.g. What to do during an earthquake? / भूकम्पको बेला के गर्ने?",
                        lines=3,
                    )
                with gr.Column(scale=1):
                    lang = gr.Dropdown(LANGUAGES, value="English", label="Language")
                    region_in = gr.Textbox(value="global", label="Region / Country")

            chat_btn = gr.Button("Get Guidance", variant="primary")
            chat_out = gr.Markdown(label="Response")

            chat_btn.click(
                fn=chat_response,
                inputs=[query, lang, region_in],
                outputs=chat_out,
            )

            gr.Examples(
                examples=[
                    ["What should I do immediately after an earthquake?", "English", "Nepal"],
                    ["भूकम्पको बेला के गर्ने?", "Nepali", "Nepal"],
                    ["¿Qué hacer durante una inundación?", "Spanish", "Colombia"],
                    ["홍수 때 어떻게 해야 합니까?", "Korean", "South Korea"],
                    ["台风来临时应该怎么做?", "Chinese", "China"],
                    ["What are signs of an imminent landslide?", "English", "Philippines"],
                ],
                inputs=[query, lang, region_in],
            )

        # --- Risk Score Tab ---
        with gr.Tab("📊 Risk Assessment"):
            gr.Markdown("Calculate composite disaster risk score for any region.")
            with gr.Row():
                rs_region = gr.Textbox(value="Nepal", label="Region")
                rs_hazard = gr.Dropdown(
                    ["earthquake", "flood", "cyclone", "wildfire", "drought", "tsunami", "landslide", "volcano"],
                    value="earthquake",
                    label="Hazard Type",
                )
            with gr.Row():
                rs_vuln = gr.Slider(0, 1, value=0.7, step=0.01, label="Vulnerability Index (0–1)")
                rs_exp = gr.Slider(0, 1, value=0.8, step=0.01, label="Exposure Index (0–1)")

            rs_btn = gr.Button("Calculate Risk Score", variant="primary")
            rs_out = gr.Markdown()

            rs_btn.click(
                fn=risk_score,
                inputs=[rs_region, rs_hazard, rs_vuln, rs_exp],
                outputs=rs_out,
            )

        # --- About Tab ---
        with gr.Tab("ℹ️ About"):
            gr.Markdown(
                """
## About WorldDisasterLM-8B

**WorldDisasterLM-8B** is an instruction-tuned language model built on Meta's Llama 3.1 8B Instruct,
domain-adapted for global disaster management and humanitarian response.

### Supported Languages
| Language | Script | ISO |
|---|---|---|
| English | Latin | en |
| Nepali | Devanagari | ne |
| Spanish | Latin | es |
| French | Latin | fr |
| Arabic | Arabic | ar |
| Hindi | Devanagari | hi |
| Telugu | Telugu | te |
| Chinese | Simplified Han | zh |
| Japanese | Kanji/Hiragana | ja |
| Korean | Hangul | ko |
| Portuguese | Latin | pt |

### Training Data Sources
- **ReliefWeb** — Humanitarian reports and disaster assessments
- **USGS** — Earthquake catalog (M≥4.0, 10-year archive)
- **NOAA** — Weather alerts and severe weather events
- **GDACS** — Global disaster alert coordination
- **OpenFEMA** — US federal disaster declarations
- **WHO** — Disease outbreak and public health alerts

### Training Method
QLoRA fine-tuning (4-bit NF4 quantization, LoRA r=16) on Llama 3.1 8B Instruct.

### Citation
```
@misc{worlddisasterlm2026,
  title = {WorldDisasterLM: Open Foundation Model for Global Disaster Management},
  year  = {2026}
}
```

### License
This demo is released under the [Llama 3 Community License](https://llama.meta.com/llama3/license/).
                """
            )

if __name__ == "__main__":
    demo.launch()