profplate commited on
Commit
947baca
·
verified ·
1 Parent(s): a3de68d

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +412 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import re
4
+ import json
5
+
6
+ # ── Same model as Session 1's Silly Phrase Finder ──
7
+ classifier = pipeline(
8
+ "zero-shot-classification",
9
+ model="valhalla/distilbart-mnli-12-3",
10
+ )
11
+
12
+ # ── Four analytical lenses ──
13
+ LENSES = {
14
+ "Tone": [
15
+ "dramatic and intense",
16
+ "humorous and playful",
17
+ "melancholic and sad",
18
+ "suspenseful and tense",
19
+ "warm and affectionate",
20
+ "dry and matter-of-fact",
21
+ ],
22
+ "Formality": [
23
+ "academic and scholarly",
24
+ "casual and conversational",
25
+ "poetic and lyrical",
26
+ "journalistic and reportorial",
27
+ ],
28
+ "Energy": [
29
+ "fast-paced and urgent",
30
+ "slow and contemplative",
31
+ "building tension",
32
+ "calm and steady",
33
+ ],
34
+ "Genre Feel": [
35
+ "literary fiction",
36
+ "thriller or mystery",
37
+ "romance",
38
+ "comedy",
39
+ "memoir or personal essay",
40
+ "news report",
41
+ ],
42
+ }
43
+
44
+ # Short display names (strip the "and ..." qualifiers)
45
+ def short_label(label):
46
+ return label.split(" and ")[0].split(" or ")[0].strip()
47
+
48
+
49
+ # ── Sentence splitter ──
50
+ def split_sentences(text):
51
+ sentences = [
52
+ s.strip()
53
+ for s in re.split(r'(?<=[.!?])\s+', text)
54
+ if len(s.strip()) > 15
55
+ ]
56
+ return sentences[:8] # cap for free-CPU performance
57
+
58
+
59
+ # ── Main analysis function ──
60
+ def analyze_passage(text):
61
+ if not text or not text.strip():
62
+ return placeholder_html("Paste a passage above to begin analysis.")
63
+
64
+ sentences = split_sentences(text)
65
+ if len(sentences) < 2:
66
+ return placeholder_html(
67
+ "Please paste a longer passage — at least a few sentences."
68
+ )
69
+
70
+ # 1) Passage-level analysis through every lens
71
+ passage_scores = {}
72
+ for lens_name, labels in LENSES.items():
73
+ result = classifier(text[:512], candidate_labels=labels)
74
+ passage_scores[lens_name] = {
75
+ label: score
76
+ for label, score in zip(result["labels"], result["scores"])
77
+ }
78
+
79
+ # 2) Sentence-level analysis through the Tone lens
80
+ tone_labels = LENSES["Tone"]
81
+ sentence_data = []
82
+ for sentence in sentences:
83
+ result = classifier(sentence, candidate_labels=tone_labels)
84
+ sentence_data.append(
85
+ {
86
+ "text": sentence,
87
+ "tone": result["labels"][0],
88
+ "score": result["scores"][0],
89
+ }
90
+ )
91
+
92
+ return build_dashboard_html(passage_scores, sentence_data)
93
+
94
+
95
+ # ── HTML builder ──
96
+
97
+ TONE_COLORS = {
98
+ "dramatic and intense": "#e74c3c",
99
+ "humorous and playful": "#f39c12",
100
+ "melancholic and sad": "#3498db",
101
+ "suspenseful and tense": "#9b59b6",
102
+ "warm and affectionate": "#e91e63",
103
+ "dry and matter-of-fact": "#78909c",
104
+ }
105
+
106
+
107
+ def placeholder_html(msg):
108
+ return (
109
+ f'<p style="color:#999;text-align:center;padding:48px 0;'
110
+ f'font-family:system-ui;font-size:1.05em;">{msg}</p>'
111
+ )
112
+
113
+
114
+ def build_dashboard_html(passage_scores, sentence_data):
115
+ # ── Lens summary cards ──
116
+ lens_icons = {"Tone": "🎭", "Formality": "📐", "Energy": "⚡", "Genre Feel": "📚"}
117
+ cards = ""
118
+ for lens_name, scores in passage_scores.items():
119
+ top_label = max(scores, key=scores.get)
120
+ top_score = scores[top_label]
121
+ icon = lens_icons.get(lens_name, "")
122
+ cards += f"""
123
+ <div class="lens-card">
124
+ <div class="lens-icon">{icon}</div>
125
+ <div class="lens-title">{lens_name}</div>
126
+ <div class="lens-result">{short_label(top_label)}</div>
127
+ <div class="lens-score">{top_score:.0%} confidence</div>
128
+ </div>"""
129
+
130
+ # ── Sentence rows ──
131
+ sentence_rows = ""
132
+ for i, sd in enumerate(sentence_data):
133
+ color = TONE_COLORS.get(sd["tone"], "#78909c")
134
+ pct = sd["score"] * 100
135
+ sentence_rows += f"""
136
+ <div class="s-row" style="animation-delay:{i * 0.12}s">
137
+ <div class="s-num" style="background:{color}">{i + 1}</div>
138
+ <div class="s-body">
139
+ <div class="s-text">{sd['text']}</div>
140
+ <div class="s-meta">
141
+ <span class="s-badge" style="background:{color}">{short_label(sd['tone'])}</span>
142
+ <div class="bar-bg"><div class="bar-fill" style="width:{pct}%;background:{color}"></div></div>
143
+ <span class="s-pct">{sd['score']:.0%}</span>
144
+ </div>
145
+ </div>
146
+ </div>"""
147
+
148
+ # ── Radar chart data ──
149
+ # Prepare all four lenses for a tabbed radar
150
+ radar_json = json.dumps(
151
+ {
152
+ lens: {
153
+ "labels": [short_label(l) for l in scores.keys()],
154
+ "values": [round(v * 100, 1) for v in scores.values()],
155
+ }
156
+ for lens, scores in passage_scores.items()
157
+ }
158
+ )
159
+
160
+ html = f"""
161
+ <style>
162
+ /* ── Reset & base ── */
163
+ .mlta *,.mlta *::before,.mlta *::after{{box-sizing:border-box;margin:0;padding:0}}
164
+ .mlta{{
165
+ font-family:'Segoe UI',system-ui,-apple-system,sans-serif;
166
+ max-width:920px;margin:0 auto;color:#1a1a2e;
167
+ }}
168
+
169
+ /* ── Header ── */
170
+ .mlta-header{{
171
+ text-align:center;padding:24px 16px 16px;
172
+ border-bottom:2px solid #e8e8f0;margin-bottom:24px;
173
+ }}
174
+ .mlta-header h2{{font-size:1.5em;font-weight:800;
175
+ background:linear-gradient(135deg,#667eea,#764ba2);
176
+ -webkit-background-clip:text;-webkit-text-fill-color:transparent;
177
+ background-clip:text;margin-bottom:4px;
178
+ }}
179
+ .mlta-header p{{color:#888;font-size:0.88em;}}
180
+
181
+ /* ── Lens cards ── */
182
+ .lens-grid{{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:28px;}}
183
+ .lens-card{{
184
+ background:#fff;border:1px solid #e8e8f0;border-radius:14px;
185
+ padding:18px 12px;text-align:center;
186
+ transition:transform .2s,box-shadow .2s;
187
+ }}
188
+ .lens-card:hover{{transform:translateY(-3px);box-shadow:0 6px 18px rgba(102,126,234,.12);}}
189
+ .lens-icon{{font-size:1.5em;margin-bottom:6px;}}
190
+ .lens-title{{font-size:.7em;text-transform:uppercase;letter-spacing:1.2px;color:#999;font-weight:700;margin-bottom:6px;}}
191
+ .lens-result{{font-size:1.05em;font-weight:700;color:#16213e;margin-bottom:2px;text-transform:capitalize;}}
192
+ .lens-score{{font-size:.78em;color:#667eea;font-weight:600;}}
193
+
194
+ /* ── Two-column layout ── */
195
+ .two-col{{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:20px;}}
196
+
197
+ /* ── Radar section ── */
198
+ .radar-sec{{background:#fafafe;border-radius:14px;border:1px solid #e8e8f0;padding:20px;}}
199
+ .radar-sec h3{{font-size:.95em;color:#16213e;margin-bottom:4px;}}
200
+ .radar-tabs{{display:flex;gap:6px;margin-bottom:14px;flex-wrap:wrap;}}
201
+ .radar-tab{{
202
+ font-size:.72em;padding:4px 10px;border-radius:8px;border:1px solid #ddd;
203
+ background:#fff;cursor:pointer;font-weight:600;color:#666;
204
+ transition:all .2s;
205
+ }}
206
+ .radar-tab.active{{background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;border-color:transparent;}}
207
+ .radar-canvas-wrap{{position:relative;width:100%;aspect-ratio:1;}}
208
+ .radar-canvas-wrap canvas{{position:absolute;top:0;left:0;width:100%!important;height:100%!important;}}
209
+
210
+ /* ── Sentence section ── */
211
+ .sent-sec{{background:#fafafe;border-radius:14px;border:1px solid #e8e8f0;padding:20px;overflow-y:auto;max-height:420px;}}
212
+ .sent-sec h3{{font-size:.95em;color:#16213e;margin-bottom:14px;}}
213
+ .s-row{{
214
+ display:flex;gap:10px;padding:10px 0;border-bottom:1px solid #f0f0f5;
215
+ opacity:0;animation:fadeIn .45s ease forwards;
216
+ }}
217
+ .s-row:last-child{{border-bottom:none;}}
218
+ @keyframes fadeIn{{from{{opacity:0;transform:translateX(-8px)}}to{{opacity:1;transform:translateX(0)}}}}
219
+ .s-num{{
220
+ width:26px;height:26px;border-radius:50%;color:#fff;
221
+ display:flex;align-items:center;justify-content:center;
222
+ font-size:.72em;font-weight:700;flex-shrink:0;margin-top:2px;
223
+ }}
224
+ .s-body{{flex:1;min-width:0;}}
225
+ .s-text{{font-size:.83em;line-height:1.45;color:#333;margin-bottom:5px;}}
226
+ .s-meta{{display:flex;align-items:center;gap:8px;}}
227
+ .s-badge{{font-size:.68em;color:#fff;padding:2px 9px;border-radius:10px;font-weight:600;white-space:nowrap;text-transform:capitalize;}}
228
+ .bar-bg{{flex:1;height:4px;background:#e8e8f0;border-radius:2px;overflow:hidden;}}
229
+ .bar-fill{{height:100%;border-radius:2px;transition:width .7s ease;}}
230
+ .s-pct{{font-size:.73em;color:#999;font-weight:600;min-width:32px;text-align:right;}}
231
+
232
+ /* ── Footer note ── */
233
+ .mlta-foot{{
234
+ text-align:center;font-size:.76em;color:#aaa;
235
+ padding:16px 0 4px;border-top:1px solid #e8e8f0;margin-top:20px;line-height:1.6;
236
+ }}
237
+ .mlta-foot code{{background:#f0f0f5;padding:1px 6px;border-radius:4px;font-size:.95em;}}
238
+
239
+ /* ── Responsive ── */
240
+ @media(max-width:720px){{
241
+ .lens-grid{{grid-template-columns:repeat(2,1fr);}}
242
+ .two-col{{grid-template-columns:1fr;}}
243
+ }}
244
+ </style>
245
+
246
+ <div class="mlta">
247
+ <div class="mlta-header">
248
+ <h2>Passage Analysis Dashboard</h2>
249
+ <p>Four analytical lenses — one zero-shot model — no task-specific training</p>
250
+ </div>
251
+
252
+ <div class="lens-grid">{cards}</div>
253
+
254
+ <div class="two-col">
255
+ <div class="radar-sec">
256
+ <h3>Passage Profile</h3>
257
+ <div class="radar-tabs" id="radar-tabs"></div>
258
+ <div class="radar-canvas-wrap"><canvas id="radarChart"></canvas></div>
259
+ </div>
260
+ <div class="sent-sec">
261
+ <h3>Sentence-by-Sentence Tone</h3>
262
+ {sentence_rows}
263
+ </div>
264
+ </div>
265
+
266
+ <div class="mlta-foot">
267
+ Powered by the same model as the Silly Phrase Finder:
268
+ <code>valhalla/distilbart-mnli-12-3</code><br>
269
+ Nobody trained it on tone, formality, energy, or genre.
270
+ It figures it out from language alone.
271
+ </div>
272
+ </div>
273
+
274
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
275
+ <script>
276
+ (function(){{
277
+ const R={radar_json};
278
+ const lenses=Object.keys(R);
279
+ const colors=[
280
+ ['rgba(102,126,234,0.75)','rgba(102,126,234,0.08)'],
281
+ ['rgba(118,75,162,0.75)','rgba(118,75,162,0.08)'],
282
+ ['rgba(233,30,99,0.75)','rgba(233,30,99,0.08)'],
283
+ ['rgba(0,188,212,0.75)','rgba(0,188,212,0.08)'],
284
+ ];
285
+ const tabsEl=document.getElementById('radar-tabs');
286
+ const ctx=document.getElementById('radarChart');
287
+ if(!ctx||!tabsEl) return;
288
+
289
+ let chart=null;
290
+ function render(idx){{
291
+ const d=R[lenses[idx]];
292
+ if(chart) chart.destroy();
293
+ chart=new Chart(ctx,{{
294
+ type:'radar',
295
+ data:{{
296
+ labels:d.labels.map(l=>l.charAt(0).toUpperCase()+l.slice(1)),
297
+ datasets:[{{
298
+ label:lenses[idx],
299
+ data:d.values,
300
+ borderColor:colors[idx][0],
301
+ backgroundColor:colors[idx][1],
302
+ borderWidth:2.5,
303
+ pointBackgroundColor:colors[idx][0],
304
+ pointRadius:4,
305
+ pointHoverRadius:6,
306
+ }}]
307
+ }},
308
+ options:{{
309
+ responsive:true,maintainAspectRatio:true,
310
+ plugins:{{legend:{{display:false}}}},
311
+ scales:{{r:{{
312
+ beginAtZero:true,max:100,
313
+ ticks:{{stepSize:25,font:{{size:9}},backdropColor:'transparent'}},
314
+ pointLabels:{{font:{{size:10,weight:'600'}},color:'#555'}},
315
+ grid:{{color:'rgba(0,0,0,0.05)'}},
316
+ angleLines:{{color:'rgba(0,0,0,0.05)'}},
317
+ }}}},
318
+ animation:{{duration:800,easing:'easeOutQuart'}},
319
+ }}
320
+ }});
321
+ document.querySelectorAll('.radar-tab').forEach((t,i)=>{{
322
+ t.classList.toggle('active',i===idx);
323
+ }});
324
+ }}
325
+
326
+ lenses.forEach((name,i)=>{{
327
+ const btn=document.createElement('span');
328
+ btn.textContent=name;
329
+ btn.className='radar-tab'+(i===0?' active':'');
330
+ btn.onclick=()=>render(i);
331
+ tabsEl.appendChild(btn);
332
+ }});
333
+ render(0);
334
+ }})();
335
+ </script>
336
+ """
337
+ return html
338
+
339
+
340
+ # ── Example passages ──
341
+ EXAMPLES = [
342
+ [
343
+ "The old house stood at the end of the lane, its windows dark as closed eyes. "
344
+ "Nobody had lived there since the winter of 1987, when Mrs. Bellweather vanished "
345
+ "during the first snowfall. Children crossed the street to avoid it. Dogs pulled "
346
+ "at their leashes. Even the mailman, who feared nothing, left packages at the gate "
347
+ "and walked briskly away. But tonight, for the first time in decades, a light "
348
+ "flickered behind the upstairs curtain."
349
+ ],
350
+ [
351
+ "The committee has reviewed the quarterly earnings and finds them satisfactory. "
352
+ "Revenue increased by twelve percent over the previous quarter. However, operating "
353
+ "costs in the Northeast division remain above target. We recommend a full audit of "
354
+ "vendor contracts before the next fiscal year. The board will convene on Tuesday to "
355
+ "discuss the findings."
356
+ ],
357
+ [
358
+ "She laughed so hard the milk came out of her nose, which made everyone else laugh "
359
+ "even harder. Uncle Roberto tried to keep a straight face but lost it when the dog "
360
+ "jumped onto the table and stole an entire chicken leg. Grandma just shook her head "
361
+ "and muttered something about heathens. It was, by all accounts, a perfectly normal "
362
+ "Sunday dinner."
363
+ ],
364
+ ]
365
+
366
+ # ── Gradio app ──
367
+ with gr.Blocks(
368
+ title="Multi-Lens Text Analyzer",
369
+ theme=gr.themes.Soft(),
370
+ css="""
371
+ .gradio-container { max-width: 980px !important; }
372
+ #go-btn {
373
+ background: linear-gradient(135deg, #667eea, #764ba2) !important;
374
+ color: white !important;
375
+ font-weight: 600 !important;
376
+ font-size: 1.05em !important;
377
+ min-height: 44px !important;
378
+ }
379
+ """,
380
+ ) as demo:
381
+
382
+ gr.Markdown(
383
+ "## Multi-Lens Text Analyzer\n"
384
+ "Paste any passage and watch a single zero-shot model analyze it through "
385
+ "four different lenses — tone, formality, energy, and genre feel.\n\n"
386
+ "*Uses the same model and the same approach as the Silly Phrase Finder — "
387
+ "just with a richer interface and more ambitious questions.*"
388
+ )
389
+
390
+ with gr.Row():
391
+ text_input = gr.Textbox(
392
+ lines=5,
393
+ placeholder="Paste a paragraph or passage here…",
394
+ label="Your Passage",
395
+ scale=5,
396
+ )
397
+ analyze_btn = gr.Button(
398
+ "Analyze ✦", elem_id="go-btn", scale=1, size="lg"
399
+ )
400
+
401
+ output_html = gr.HTML(label="Analysis Dashboard")
402
+
403
+ gr.Examples(examples=EXAMPLES, inputs=text_input, label="Try a Passage")
404
+
405
+ analyze_btn.click(
406
+ fn=analyze_passage, inputs=text_input, outputs=output_html
407
+ )
408
+ text_input.submit(
409
+ fn=analyze_passage, inputs=text_input, outputs=output_html
410
+ )
411
+
412
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ transformers
2
+ torch
3
+ gradio