Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,26 +1,107 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
from transformers import
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
# Load sentiment
|
| 5 |
@st.cache_resource
|
| 6 |
-
def
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
if text.strip() == "":
|
| 19 |
-
st.warning("Please
|
| 20 |
else:
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification
|
| 3 |
+
from scipy.special import softmax
|
| 4 |
+
import torch
|
| 5 |
|
| 6 |
+
# Load sentiment model
|
| 7 |
@st.cache_resource
|
| 8 |
+
def load_sentiment_model():
|
| 9 |
+
model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 11 |
+
return model, tokenizer
|
| 12 |
|
| 13 |
+
# Load emotion model
|
| 14 |
+
@st.cache_resource
|
| 15 |
+
def load_emotion_model():
|
| 16 |
+
model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 17 |
+
tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 18 |
+
return model, tokenizer
|
| 19 |
+
|
| 20 |
+
# Load T5 paraphrasing model
|
| 21 |
+
@st.cache_resource
|
| 22 |
+
def load_paraphrase_model():
|
| 23 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("Vamsi/T5_Paraphrase_Paws")
|
| 24 |
+
tokenizer = AutoTokenizer.from_pretrained("Vamsi/T5_Paraphrase_Paws")
|
| 25 |
+
return model, tokenizer
|
| 26 |
+
|
| 27 |
+
# Sentiment analysis
|
| 28 |
+
def get_sentiment(text, model, tokenizer):
|
| 29 |
+
encoded = tokenizer(text, return_tensors="pt", truncation=True)
|
| 30 |
+
with torch.no_grad():
|
| 31 |
+
output = model(**encoded)
|
| 32 |
+
probs = softmax(output.logits.numpy()[0])
|
| 33 |
+
labels = ["Negative", "Neutral", "Positive"]
|
| 34 |
+
return labels[probs.argmax()], float(probs.max()) * 100
|
| 35 |
+
|
| 36 |
+
# Emotion detection
|
| 37 |
+
def get_emotion(text, model, tokenizer):
|
| 38 |
+
encoded = tokenizer(text, return_tensors="pt", truncation=True)
|
| 39 |
+
with torch.no_grad():
|
| 40 |
+
output = model(**encoded)
|
| 41 |
+
probs = softmax(output.logits.numpy()[0])
|
| 42 |
+
labels = ['anger', 'disgust', 'fear', 'joy', 'neutral', 'sadness', 'surprise']
|
| 43 |
+
return labels[probs.argmax()], float(probs.max()) * 100
|
| 44 |
|
| 45 |
+
# Generate feedback
|
| 46 |
+
def generate_feedback(sentiment, emotion):
|
| 47 |
+
if sentiment == "Negative":
|
| 48 |
+
if emotion in ["anger", "disgust", "sadness"]:
|
| 49 |
+
return "⚠️ Your message might sound hurtful or emotionally charged. Consider softening it."
|
| 50 |
+
else:
|
| 51 |
+
return "⚠️ Your message may feel negative. Reflect on your tone before sending."
|
| 52 |
+
elif sentiment == "Neutral":
|
| 53 |
+
return "😐 Your message seems neutral. That's okay, but clarity and warmth often help."
|
| 54 |
+
elif sentiment == "Positive":
|
| 55 |
+
if emotion == "joy":
|
| 56 |
+
return "😊 Great! Your message feels joyful and likely to be well received."
|
| 57 |
+
elif emotion == "love":
|
| 58 |
+
return "💖 Your message feels loving. Expressing emotions like this builds trust."
|
| 59 |
+
else:
|
| 60 |
+
return "🙂 Your message is positive, but think about whether it’s being fully understood."
|
| 61 |
|
| 62 |
+
# Paraphrase / rewrite message
|
| 63 |
+
def rewrite_message(text, model, tokenizer):
|
| 64 |
+
text = "paraphrase: " + text + " </s>"
|
| 65 |
+
encoding = tokenizer.encode_plus(text, return_tensors="pt", max_length=128, truncation=True)
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
output = model.generate(
|
| 68 |
+
input_ids=encoding['input_ids'],
|
| 69 |
+
attention_mask=encoding['attention_mask'],
|
| 70 |
+
max_length=128,
|
| 71 |
+
num_return_sequences=2,
|
| 72 |
+
num_beams=5,
|
| 73 |
+
temperature=1.5
|
| 74 |
+
)
|
| 75 |
+
rewrites = [tokenizer.decode(o, skip_special_tokens=True) for o in output]
|
| 76 |
+
return list(set(rewrites)) # remove duplicates
|
| 77 |
|
| 78 |
+
# UI
|
| 79 |
+
st.title("🗣️ Message Tone & Rewrite Checker (Phase 2)")
|
| 80 |
+
st.write("Before you send that message, check how it might be received — and improve it if needed.")
|
| 81 |
+
|
| 82 |
+
text = st.text_area("✍️ Enter your message here:")
|
| 83 |
+
|
| 84 |
+
if st.button("Analyze"):
|
| 85 |
if text.strip() == "":
|
| 86 |
+
st.warning("Please type a message first.")
|
| 87 |
else:
|
| 88 |
+
sent_model, sent_token = load_sentiment_model()
|
| 89 |
+
emo_model, emo_token = load_emotion_model()
|
| 90 |
+
|
| 91 |
+
sentiment, s_conf = get_sentiment(text, sent_model, sent_token)
|
| 92 |
+
emotion, e_conf = get_emotion(text, emo_model, emo_token)
|
| 93 |
+
feedback = generate_feedback(sentiment, emotion)
|
| 94 |
+
|
| 95 |
+
st.markdown("### 🧠 Analysis Result")
|
| 96 |
+
st.write(f"**Sentiment:** {sentiment} ({s_conf:.2f}%)")
|
| 97 |
+
st.write(f"**Emotion:** {emotion} ({e_conf:.2f}%)")
|
| 98 |
+
st.markdown("### 💡 Feedback")
|
| 99 |
+
st.info(feedback)
|
| 100 |
+
|
| 101 |
+
st.markdown("---")
|
| 102 |
+
st.markdown("### ✨ Try Rewriting Your Message")
|
| 103 |
+
para_model, para_token = load_paraphrase_model()
|
| 104 |
+
rewrites = rewrite_message(text, para_model, para_token)
|
| 105 |
|
| 106 |
+
for i, r in enumerate(rewrites, 1):
|
| 107 |
+
st.write(f"**Version {i}:** {r}")
|