Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +100 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,102 @@
|
|
| 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 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 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 numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
from transformers import RobertaTokenizerFast, TFRobertaModel
|
| 5 |
+
|
| 6 |
+
MAX_LEN = 96
|
| 7 |
+
MODEL_PATH = "src/roberta_fold_1.h5"
|
| 8 |
+
|
| 9 |
+
#MODEL ARCHITECTURE
|
| 10 |
+
def build_model():
|
| 11 |
+
ids = tf.keras.layers.Input((MAX_LEN,), dtype=tf.int32, name="input_ids")
|
| 12 |
+
att = tf.keras.layers.Input((MAX_LEN,), dtype=tf.int32, name="attention_mask")
|
| 13 |
+
|
| 14 |
+
roberta = TFRobertaModel.from_pretrained('roberta-base')
|
| 15 |
+
x = roberta(ids, attention_mask=att)[0]
|
| 16 |
+
x1 = tf.keras.layers.Dropout(0.1)(x)
|
| 17 |
+
start_logits = tf.keras.layers.Dense(1)(x1)
|
| 18 |
+
start_logits = tf.keras.layers.Flatten()(start_logits)
|
| 19 |
+
end_logits = tf.keras.layers.Dense(1)(x1)
|
| 20 |
+
end_logits = tf.keras.layers.Flatten()(end_logits)
|
| 21 |
+
|
| 22 |
+
model = tf.keras.Model(inputs=[ids, att], outputs=[start_logits, end_logits])
|
| 23 |
+
return model
|
| 24 |
+
|
| 25 |
+
#MODEL
|
| 26 |
+
@st.cache_resource
|
| 27 |
+
def load_model_and_tokenizer():
|
| 28 |
+
tokenizer = RobertaTokenizerFast.from_pretrained('roberta-base')
|
| 29 |
+
model = build_model()
|
| 30 |
+
model.load_weights(MODEL_PATH)
|
| 31 |
+
return model, tokenizer
|
| 32 |
+
|
| 33 |
+
with st.spinner('Loading model and tokenizer... Please wait.'):
|
| 34 |
+
model, tokenizer = load_model_and_tokenizer()
|
| 35 |
+
|
| 36 |
+
st.success("Model Loaded Successfully! 🚀")
|
| 37 |
+
|
| 38 |
+
#PREDICTION
|
| 39 |
+
def predict_sentiment(tweet, sentiment):
|
| 40 |
+
# Preprocessing
|
| 41 |
+
tweet = " " + " ".join(str(tweet).split())
|
| 42 |
+
# Tokenization
|
| 43 |
+
enc = tokenizer.encode_plus(
|
| 44 |
+
sentiment,
|
| 45 |
+
tweet,
|
| 46 |
+
add_special_tokens=True,
|
| 47 |
+
max_length=MAX_LEN,
|
| 48 |
+
padding='max_length',
|
| 49 |
+
truncation=True,
|
| 50 |
+
return_attention_mask=True)
|
| 51 |
+
|
| 52 |
+
input_ids = np.array([enc['input_ids']])
|
| 53 |
+
attention_mask = np.array([enc['attention_mask']])
|
| 54 |
+
# Inference
|
| 55 |
+
preds = model.predict([input_ids, attention_mask])
|
| 56 |
+
start_logits = preds[0]
|
| 57 |
+
end_logits = preds[1]
|
| 58 |
+
|
| 59 |
+
idx_start = np.argmax(start_logits)
|
| 60 |
+
idx_end = np.argmax(end_logits)
|
| 61 |
+
# Decoding
|
| 62 |
+
if sentiment == "neutral" or len(tweet.split()) < 2:
|
| 63 |
+
return tweet.strip()
|
| 64 |
+
# Validation check
|
| 65 |
+
if idx_start > idx_end:
|
| 66 |
+
return tweet.strip()
|
| 67 |
+
else:
|
| 68 |
+
text_tokens = tokenizer.decode(enc['input_ids'][idx_start:idx_end+1])
|
| 69 |
+
return text_tokens.strip()
|
| 70 |
+
|
| 71 |
+
#INTERFACE
|
| 72 |
+
st.title("🐦 Tweet Sentiment Extraction")
|
| 73 |
+
st.markdown("""
|
| 74 |
+
This AI model analyzes a tweet and extracts the **specific phrase or word** that supports the selected sentiment.
|
| 75 |
+
*Built with TensorFlow & RoBERTa*
|
| 76 |
+
""")
|
| 77 |
|
| 78 |
+
#Inputs
|
| 79 |
+
col1, col2 = st.columns([1, 2])
|
| 80 |
+
with col1:
|
| 81 |
+
sentiment = st.selectbox(
|
| 82 |
+
"Select Sentiment:",
|
| 83 |
+
["positive", "negative", "neutral"])
|
| 84 |
+
with col2:
|
| 85 |
+
text = st.text_area(
|
| 86 |
+
"Enter Tweet:",
|
| 87 |
+
value="This movie was really fantastic and I loved it!",
|
| 88 |
+
height=100)
|
| 89 |
+
#Prediction
|
| 90 |
+
if st.button("Extract Phrase", type="primary"):
|
| 91 |
+
if text:
|
| 92 |
+
result = predict_sentiment(text, sentiment)
|
| 93 |
+
st.write("### Result:")
|
| 94 |
+
# Highlight Logic for Visualization
|
| 95 |
+
if result in text and len(result) > 2:
|
| 96 |
+
highlighted_text = text.replace(result, f"<span style='background-color: #ffd700; color: black; padding: 2px; font-weight: bold; border-radius: 3px;'>{result}</span>")
|
| 97 |
+
st.markdown(f"**Context:** {highlighted_text}", unsafe_allow_html=True)
|
| 98 |
+
else:
|
| 99 |
+
st.markdown(f"**Context:** {text}")
|
| 100 |
+
st.success(f"Extracted Text: **{result}**")
|
| 101 |
+
else:
|
| 102 |
+
st.warning("Please enter a tweet to analyze.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|