disaster-final / app.py
iffazainab's picture
Update app.py
9990469 verified
import streamlit as st
from transformers import pipeline
from PIL import Image
# ----------------- Model -----------------
@st.cache_resource
def load_model():
return pipeline("image-classification", model="Luwayy/disaster_images_model")
classifier = load_model()
# ----------------- Mappings & Precautions -----------------
LABEL_MAP = {
"Fire_Disaster": "fire",
"Water_Disaster": "flood",
"Land_Disaster": "landslide",
"Human_Damage": "earthquake",
"Damaged_Infrastructure": "building_collapse",
"Non_Damage": "no disaster"
}
PRECAUTIONS = {
"fire": [
"Evacuate the area immediately.",
"Use a wet cloth to cover nose and mouth.",
"Stay low to avoid smoke.",
"Call emergency services.",
"Do not use elevators."
],
"flood": [
"Move to higher ground immediately.",
"Avoid walking or driving through flood waters.",
"Turn off electricity if safe.",
"Boil or treat water before drinking.",
"Listen to official evacuation instructions."
],
"landslide": [
"Evacuate immediately if you hear rumbling or see debris flow.",
"Stay away from steep slopes and channels.",
"Follow evacuation orders.",
"Check for structural damage before re-entering buildings.",
"Be alert for sudden changes in water flow."
],
"earthquake": [
"Drop, cover, and hold on.",
"Stay away from windows.",
"Turn off gas and electricity if possible.",
"Prepare an emergency kit.",
"Follow evacuation routes."
],
"building_collapse": [
"Evacuate the structure if safe.",
"Avoid using elevators.",
"Stay away from damaged areas.",
"Call emergency services immediately.",
"Help others only if it’s safe to do so."
],
"tsunami": [
"Move to higher ground immediately.",
"Stay away from the coastlines.",
"Follow evacuation routes and warnings.",
"Do not return until authorities declare it safe.",
"Avoid rivers and streams connected to the ocean."
],
"cyclone": [
"Stay indoors and away from windows.",
"Stock emergency supplies and drinking water.",
"Evacuate if instructed by authorities.",
"Stay tuned to weather alerts.",
"Secure loose outdoor items."
],
"drought": [
"Conserve water whenever possible.",
"Store extra drinking water.",
"Avoid unnecessary water usage.",
"Follow water rationing rules if issued.",
"Use water-efficient appliances."
],
"storm": [
"Stay indoors during severe storms.",
"Unplug electrical devices.",
"Avoid flood-prone areas.",
"Keep emergency supplies ready.",
"Listen to weather updates."
],
"tornado": [
"Take shelter in a basement or interior room.",
"Stay away from windows.",
"Protect your head and neck with sturdy coverings.",
"Avoid mobile homes or temporary shelters.",
"Monitor weather alerts closely."
],
"hurricane": [
"Evacuate coastal areas if warned.",
"Stay in a safe, reinforced building.",
"Stock up on food, water, and medicine.",
"Keep flashlights and batteries ready.",
"Avoid going outside during the hurricane."
]
}
def get_precautions(label: str):
return PRECAUTIONS.get(label.lower(), [
"Contact local authorities and follow official guidance.",
"Prepare an emergency kit.",
"Monitor verified alerts."
])
# ----------------- UI -----------------
st.title("🚨 Disaster Detection App")
st.write("Upload an **image** (left) **or** pick a disaster **manually** (right). Manual choice overrides the model.")
col1, col2 = st.columns(2)
with col1:
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
with col2:
manual_disaster = st.selectbox(
"Manually select a disaster (optional):",
[
"None",
"fire",
"flood",
"landslide",
"earthquake",
"building_collapse",
"tsunami",
"cyclone",
"drought",
"storm",
"tornado",
"hurricane"
]
)
disaster_label = None
confidence = None
source = None
# If user chose manually, that wins
if manual_disaster != "None":
disaster_label = manual_disaster
source = "manual"
# Otherwise, if an image is provided, classify it
elif uploaded_file is not None:
img = Image.open(uploaded_file).convert("RGB")
st.image(img, caption="Uploaded Image", use_column_width=True)
with st.spinner("Analyzing image..."):
results = classifier(img)
predicted_label = results[0]['label']
confidence = results[0]['score']
mapped = LABEL_MAP.get(predicted_label, "unknown")
disaster_label = mapped
source = "model"
st.info(f"Model prediction: **{disaster_label}** (raw: {predicted_label}, confidence: {confidence:.2%})")
# Output
if disaster_label is None:
st.warning("Please upload an image or manually select a disaster type to see precautions.")
elif disaster_label == "no disaster":
st.info("Model says: **no disaster detected**. You can still select a disaster type on the right to view tips.")
else:
title = "User-selected disaster" if source == "manual" else "Model-detected disaster"
st.subheader(f"{title}: **{disaster_label}**")
if confidence is not None and source == "model":
st.caption(f"Confidence: {confidence:.2%}")
st.markdown("### Precautionary Measures")
for i, tip in enumerate(get_precautions(disaster_label), 1):
st.write(f"{i}. {tip}")