spoortishankar commited on
Commit
4736b82
·
verified ·
1 Parent(s): 2dc1f2d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -0
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """app.py - Gradio UI for SentimentDetector (Hugging Face Space entry point)."""
2
+ import gradio as gr
3
+ import matplotlib
4
+
5
+ matplotlib.use("Agg")
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from detector import SentimentDetector, TextProfile
11
+
12
+ MAX_CHARS = 4000
13
+ MAX_EXPLAINED = 12
14
+ ICON = {"positive": "🟢", "negative": "🔴", "neutral": "⚪", "mixed": "🟡"}
15
+
16
+ detector = SentimentDetector()
17
+
18
+ EXAMPLES = [
19
+ ["I got into the coding club! So excited 🎉 Then I found out the first meeting is at 6 AM. "
20
+ "Oh great, just what I needed... 🙄 Whatever, I'll survive. Actually, the seniors were super welcoming ☺️", True, True],
21
+ ["Love waiting 2 hours for a delayed flight. Best. Airline. Ever. 🙃", True, True],
22
+ ["Just shipped my first ML project and it actually works! 🚀🔥", True, True],
23
+ ["Yeah right, because 'group projects' always go smoothly /s", True, True],
24
+ ["Perfect. Just perfect. My laptop died right before the deadline.", True, True],
25
+ ["The package arrived on Tuesday. Nothing special, nothing terrible.", True, True],
26
+ ["I'm literally dying 😂😂 this meme is too good", True, True],
27
+ ]
28
+
29
+
30
+ def summary_md(p: TextProfile) -> str:
31
+ return (
32
+ f"### {ICON[p.overall_label]} Current mood: **{p.overall_label.title()}** ({p.overall:+.2f})\n\n"
33
+ f"| Trend | Volatility | Sarcasm rate | Dominant emotion | Sarcasm-awareness shift |\n"
34
+ f"|---|---|---|---|---|\n"
35
+ f"| {p.trend} ({p.slope:+.2f}/sentence) | {p.volatility:.2f} | {p.sarcasm_rate:.0%} | "
36
+ f"{p.dominant_emotion} | {p.sarcasm_shift:+.2f} |\n\n"
37
+ f"*{len(p.sentences)} sentences, {p.emoji_count} emoji/emoticons. "
38
+ f"“Current mood” weights recent sentences more heavily.*"
39
+ )
40
+
41
+
42
+ def make_figure(p: TextProfile):
43
+ n = len(p.sentences)
44
+ x = np.arange(1, n + 1)
45
+ lit = [r.literal for r in p.sentences]
46
+ inn = [r.intended for r in p.sentences]
47
+ fig, (a1, a2) = plt.subplots(1, 2, figsize=(10, 3.6), gridspec_kw={"width_ratios": [2, 1]})
48
+ a1.axhline(0, color="#999", lw=0.8)
49
+ a1.plot(x, lit, "--o", color="#9ca3af", label="Literal (surface)")
50
+ a1.plot(x, inn, "-o", color="#4f46e5", label="Intended")
51
+ sx = [i + 1 for i, r in enumerate(p.sentences) if r.is_sarcastic]
52
+ if sx:
53
+ a1.scatter(sx, [inn[i - 1] for i in sx], s=200, facecolors="none", edgecolors="#dc2626",
54
+ linewidths=2, label="Sarcasm/irony")
55
+ a1.set_ylim(-1.05, 1.05)
56
+ a1.set_xticks(x if n <= 15 else a1.get_xticks())
57
+ a1.set_xlabel("Sentence")
58
+ a1.set_ylabel("Sentiment")
59
+ a1.set_title("Sentiment trajectory")
60
+ a1.legend(fontsize=8, loc="best")
61
+ labels = list(p.emotion_mean)
62
+ a2.barh(labels, [p.emotion_mean[k] for k in labels], color="#6366f1")
63
+ a2.set_xlim(0, 1)
64
+ a2.set_title("Average emotion")
65
+ fig.tight_layout()
66
+ return fig
67
+
68
+
69
+ def to_dataframe(p: TextProfile) -> pd.DataFrame:
70
+ rows = []
71
+ for i, r in enumerate(p.sentences, 1):
72
+ signals = list(r.cues)
73
+ rows.append({
74
+ "#": i, "Sentence": r.text, "Literal": round(r.literal, 2), "Intended": round(r.intended, 2),
75
+ "Label": f"{ICON[r.label]} {r.label}", "Sarcasm": f"{r.sarcasm:.0%}",
76
+ "Emoji": " ".join(r.emojis), "Emotion": r.emotion, "Signals": "; ".join(signals),
77
+ })
78
+ return pd.DataFrame(rows)
79
+
80
+
81
+ def explanation(p: TextProfile, emoji_aware: bool):
82
+ tokens = []
83
+ for r in p.sentences[:MAX_EXPLAINED]:
84
+ tokens += detector.explain(r.text, emoji_aware) + [("\n", None)]
85
+ return tokens
86
+
87
+
88
+ def analyze_ui(text, sarcasm_aware, emoji_aware):
89
+ text = (text or "").strip()
90
+ if not text:
91
+ raise gr.Error("Please paste some text written by one person.")
92
+ p = detector.analyze(text[:MAX_CHARS], sarcasm_aware=sarcasm_aware, emoji_aware=emoji_aware)
93
+ return summary_md(p), make_figure(p), to_dataframe(p), explanation(p, emoji_aware)
94
+
95
+
96
+ with gr.Blocks(title="SentimentDetector") as demo:
97
+ gr.Markdown(
98
+ "# 🎭 SentimentDetector\n"
99
+ "Sentiment analysis that reads **irony, sarcasm and emojis** - not just words. "
100
+ "Paste several sentences written by one person to see their sentiment trajectory.\n\n"
101
+ "Toggle the switches to run an **ablation** and see what each component contributes."
102
+ )
103
+ with gr.Row():
104
+ with gr.Column(scale=5):
105
+ inp = gr.Textbox(lines=8, label="Text written by one person",
106
+ placeholder="Oh great, another Monday. 🙄 ...")
107
+ with gr.Row():
108
+ sarc = gr.Checkbox(True, label="Sarcasm-aware")
109
+ emo = gr.Checkbox(True, label="Emoji-aware")
110
+ btn = gr.Button("Analyze", variant="primary")
111
+ gr.Examples(EXAMPLES, inputs=[inp, sarc, emo])
112
+ with gr.Column(scale=5):
113
+ summary = gr.Markdown()
114
+ plot = gr.Plot(label="Trajectory")
115
+ table = gr.Dataframe(label="Per-sentence breakdown", interactive=False, wrap=True)
116
+ hl = gr.HighlightedText(
117
+ label="Which words drive the literal sentiment? (leave-one-word-out occlusion)",
118
+ color_map={"pushes positive": "#86efac", "pushes negative": "#fca5a5"},
119
+ combine_adjacent=False, show_legend=True)
120
+ btn.click(analyze_ui, [inp, sarc, emo], [summary, plot, table, hl])
121
+
122
+ gr.Markdown(
123
+ "**Limitations.** English only; models were trained on tweets; sarcasm detection is inherently "
124
+ "ambiguous and fused here from a classifier plus heuristic cues - treat outputs as probabilistic, "
125
+ "not as ground truth. The word-influence view explains the *literal* model read, not the sarcasm layer. "
126
+ "Do not use this to profile people without their consent."
127
+ )
128
+
129
+ if __name__ == "__main__":
130
+ detector.warmup()
131
+ demo.launch()