Mahrukhh commited on
Commit
9fd5b89
Β·
verified Β·
1 Parent(s): 7ebd65e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -21
app.py CHANGED
@@ -1,32 +1,120 @@
1
  import streamlit as st
2
  from transformers import pipeline
 
3
 
4
- # Load Emotion classifier (GoEmotions multilingual)
5
- emotion_model = "joeddav/xlm-roberta-large-xnli"
6
- emotion_classifier = pipeline("text-classification", model=emotion_model, top_k=None)
 
 
7
 
8
- # Load Tone/Sentiment classifier (same as before)
9
- tone_model = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
10
- tone_classifier = pipeline("text-classification", model=tone_model, top_k=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- st.title("🎭 Emotion & Tone Detector (EN / ES / FR)")
 
 
 
 
 
 
13
 
14
- text = st.text_area("✍️ Enter a sentence in English, Spanish, or French:")
 
 
 
 
 
15
 
16
- if st.button("Analyze"):
17
- if text.strip():
18
- # Detect emotion
19
- emotions = emotion_classifier(text, truncation=True)[0]
20
- emotions_sorted = sorted(emotions, key=lambda x: x['score'], reverse=True)
21
- top_emotion = emotions_sorted[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Detect tone (sentiment)
24
- tones = tone_classifier(text, truncation=True)[0]
25
- tones_sorted = sorted(tones, key=lambda x: x['score'], reverse=True)
26
- top_tone = tones_sorted[0]
27
 
28
- st.write(f"**Emotion:** {top_emotion['label']} (confidence {top_emotion['score']:.2f})")
29
- st.write(f"**Tone:** {top_tone['label']} (confidence {top_tone['score']:.2f})")
30
 
 
 
 
31
  else:
32
- st.warning("⚠️ Please enter some text.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
+ import torch
4
 
5
+ # -------------------------
6
+ # Config / Model names
7
+ # -------------------------
8
+ EMOTION_MODEL = "cardiffnlp/twitter-roberta-base-emotion"
9
+ SENTIMENT_MODEL = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
10
 
11
+ # -------------------------
12
+ # Helpers
13
+ # -------------------------
14
+ def map_emotion_to_tts_label(emotion_label: str) -> str:
15
+ e = emotion_label.lower()
16
+ if e in {"joy", "happiness", "happy", "amusement", "excited", "excitement", "optimism"}:
17
+ return "happy / energetic"
18
+ if e in {"sadness", "sad", "grief", "disappointed", "disappointment", " melancholy"}:
19
+ return "sad / soft / calm"
20
+ if e in {"anger", "angry", "annoyance", "annoyed", "disgust"}:
21
+ return "angry / intense"
22
+ if e in {"fear", "scared", "nervous", "anxious"}:
23
+ return "scared / tense"
24
+ if e in {"surprise", "surprised"}:
25
+ return "surprised / alert"
26
+ return "neutral / plain"
27
 
28
+ def map_sentiment_to_tts_label(sentiment_label: str) -> str:
29
+ s = sentiment_label.lower()
30
+ if s == "positive":
31
+ return "positive / warm"
32
+ if s == "negative":
33
+ return "negative / firm"
34
+ return "neutral / plain"
35
 
36
+ # -------------------------
37
+ # Load pipelines (cached)
38
+ # -------------------------
39
+ @st.cache_resource(show_spinner=False)
40
+ def load_pipelines():
41
+ device = 0 if torch.cuda.is_available() else -1
42
 
43
+ emotion_pipe = pipeline(
44
+ "text-classification",
45
+ model=EMOTION_MODEL,
46
+ top_k=None,
47
+ device=device
48
+ )
49
+
50
+ sentiment_pipe = pipeline(
51
+ "text-classification",
52
+ model=SENTIMENT_MODEL,
53
+ top_k=None,
54
+ device=device
55
+ )
56
+
57
+ return emotion_pipe, sentiment_pipe
58
+
59
+ # -------------------------
60
+ # Streamlit UI
61
+ # -------------------------
62
+ st.set_page_config(page_title="Emotion + Tone Detector", page_icon="πŸ‘€", layout="centered")
63
+ st.title("πŸ‘€ Emotion & Tone Detector β€” English / Spanish / French")
64
+ st.write(
65
+ "Type a sentence (English / Spanish / French) and click **Analyze**. "
66
+ "Shows emotion + tone + suggested TTS style."
67
+ )
68
 
69
+ emotion_pipe, sentiment_pipe = load_pipelines()
 
 
 
70
 
71
+ text = st.text_area("✍️ Enter sentence here", height=140, placeholder="Type in English, Spanish, or French...")
 
72
 
73
+ if st.button("Analyze"):
74
+ if not text or not text.strip():
75
+ st.warning("Please enter a sentence to analyze.")
76
  else:
77
+ with st.spinner("Analyzing..."):
78
+ try:
79
+ # Emotion
80
+ emotion_results = emotion_pipe(text, top_k=None)
81
+ if isinstance(emotion_results, dict):
82
+ emotion_results = [emotion_results]
83
+ emotion_results_sorted = sorted(emotion_results, key=lambda x: x["score"], reverse=True)
84
+ top_emotion = emotion_results_sorted[0]["label"]
85
+ top_emotion_score = emotion_results_sorted[0]["score"]
86
+
87
+ # Tone/Sentiment
88
+ sentiment_results = sentiment_pipe(text, top_k=None)
89
+ if isinstance(sentiment_results, dict):
90
+ sentiment_results = [sentiment_results]
91
+ sentiment_sorted = sorted(sentiment_results, key=lambda x: x["score"], reverse=True)
92
+ top_tone = sentiment_sorted[0]["label"]
93
+ top_tone_score = sentiment_sorted[0]["score"]
94
+
95
+ # Map for TTS
96
+ tts_from_emotion = map_emotion_to_tts_label(top_emotion)
97
+ tts_from_tone = map_sentiment_to_tts_label(top_tone)
98
+
99
+ # Show results
100
+ st.subheader("🎭 Detected Emotion")
101
+ st.write(f"**{top_emotion}** (confidence **{top_emotion_score:.2f}**)")
102
+
103
+ st.subheader("🎡 Detected Tone (Sentiment)")
104
+ st.write(f"**{top_tone}** (confidence **{top_tone_score:.2f}**)")
105
+
106
+ st.subheader("πŸ”Š Suggested TTS style (from emotion)")
107
+ st.write(tts_from_emotion)
108
+
109
+ st.subheader("πŸ”Š Suggested TTS style (from tone)")
110
+ st.write(tts_from_tone)
111
+
112
+ st.subheader("πŸ“Š Full emotion scores")
113
+ st.table([{ "label": r["label"], "score": f"{r['score']:.3f}"} for r in emotion_results_sorted])
114
+
115
+ st.subheader("πŸ“Š Full tone (sentiment) scores")
116
+ st.table([{ "label": r["label"], "score": f"{r['score']:.3f}"} for r in sentiment_sorted])
117
+
118
+ except Exception as err:
119
+ st.error("Error during analysis.")
120
+ st.exception(err)