Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +96 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,98 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
from transformers import BertTokenizer, TFBertForSequenceClassification
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# --- Page Configuration ---
|
| 7 |
+
st.set_page_config(
|
| 8 |
+
page_title="Disaster Tweet Classifier",
|
| 9 |
+
page_icon="🚨",
|
| 10 |
+
layout="centered"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
# --- Title and Description ---
|
| 14 |
+
st.title("🚨 Disaster Tweet Classifier")
|
| 15 |
+
st.markdown("""
|
| 16 |
+
This AI application determines whether a tweet is about a **real disaster** (e.g., earthquake, fire)
|
| 17 |
+
or just uses **metaphorical language** (e.g., 'This movie was a disaster').
|
| 18 |
+
\n**Powered by:** BERT (Bidirectional Encoder Representations from Transformers)
|
| 19 |
+
""")
|
| 20 |
+
|
| 21 |
+
# --- Model Loading Logic ---
|
| 22 |
+
# @st.cache_resource is critical! It ensures the model is loaded only once,
|
| 23 |
+
# not every time a user interacts with the app.
|
| 24 |
+
@st.cache_resource
|
| 25 |
+
def load_model():
|
| 26 |
+
# Since files (tf_model.h5, config.json, vocab.txt) are in the root directory
|
| 27 |
+
model_path = "./"
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
# Load Tokenizer and Model
|
| 31 |
+
tokenizer = BertTokenizer.from_pretrained(model_path)
|
| 32 |
+
model = TFBertForSequenceClassification.from_pretrained(model_path)
|
| 33 |
+
return tokenizer, model
|
| 34 |
+
except Exception as e:
|
| 35 |
+
st.error(f"❌ Error loading model: {e}")
|
| 36 |
+
st.info("Make sure you uploaded all files (config.json, tf_model.h5, vocab.txt) to the root directory.")
|
| 37 |
+
return None, None
|
| 38 |
+
|
| 39 |
+
# Load the model immediately
|
| 40 |
+
with st.spinner("Loading AI Model... Please wait..."):
|
| 41 |
+
tokenizer, model = load_model()
|
| 42 |
+
|
| 43 |
+
# --- Prediction Logic ---
|
| 44 |
+
def predict_tweet(text, tokenizer, model, max_len=80):
|
| 45 |
+
# 1. Prepare text for BERT
|
| 46 |
+
encoded = tokenizer.encode_plus(
|
| 47 |
+
text,
|
| 48 |
+
add_special_tokens=True,
|
| 49 |
+
max_length=max_len,
|
| 50 |
+
padding='max_length',
|
| 51 |
+
return_attention_mask=True,
|
| 52 |
+
truncation=True
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# Convert to Tensor (Batch size of 1)
|
| 56 |
+
input_ids = tf.convert_to_tensor([encoded['input_ids']])
|
| 57 |
+
attention_masks = tf.convert_to_tensor([encoded['attention_mask']])
|
| 58 |
+
|
| 59 |
+
# 2. Predict (Get Logits)
|
| 60 |
+
prediction = model([input_ids, attention_masks]) # Using direct call instead of .predict for speed
|
| 61 |
+
logits = prediction.logits
|
| 62 |
+
|
| 63 |
+
# 3. Softmax to get probabilities
|
| 64 |
+
probs = tf.nn.softmax(logits, axis=1).numpy()[0]
|
| 65 |
+
|
| 66 |
+
# 4. Result
|
| 67 |
+
pred_class = np.argmax(probs) # 0 or 1
|
| 68 |
+
confidence = probs[pred_class]
|
| 69 |
+
|
| 70 |
+
return pred_class, confidence
|
| 71 |
+
|
| 72 |
+
# --- User Interface ---
|
| 73 |
+
st.divider()
|
| 74 |
+
user_input = st.text_area("Enter a tweet below:", height=100, placeholder="Example: The forest fire is spreading rapidly!")
|
| 75 |
+
|
| 76 |
+
col1, col2 = st.columns([1, 2])
|
| 77 |
+
with col1:
|
| 78 |
+
analyze_button = st.button("Analyze Tweet", type="primary", use_container_width=True)
|
| 79 |
|
| 80 |
+
if analyze_button:
|
| 81 |
+
if not user_input.strip():
|
| 82 |
+
st.warning("⚠️ Please enter some text first.")
|
| 83 |
+
elif model is None:
|
| 84 |
+
st.error("Model is not loaded properly.")
|
| 85 |
+
else:
|
| 86 |
+
# Run Prediction
|
| 87 |
+
pred_class, confidence = predict_tweet(user_input, tokenizer, model)
|
| 88 |
+
|
| 89 |
+
# Display Output
|
| 90 |
+
st.divider()
|
| 91 |
+
if pred_class == 1:
|
| 92 |
+
st.error(f"### 🚨 Prediction: REAL DISASTER")
|
| 93 |
+
st.write(f"Confidence Score: **%{confidence * 100:.2f}**")
|
| 94 |
+
st.progress(int(confidence * 100))
|
| 95 |
+
else:
|
| 96 |
+
st.success(f"### 😌 Prediction: NOT A DISASTER")
|
| 97 |
+
st.write(f"Confidence Score: **%{confidence * 100:.2f}**")
|
| 98 |
+
st.progress(int(confidence * 100))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|