handex commited on
Commit
13a39f1
·
verified ·
1 Parent(s): 054f0bc

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. 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
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
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 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.")