adityaardak commited on
Commit
e54c024
Β·
verified Β·
1 Parent(s): 0f13cee

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +349 -0
app.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from transformers import pipeline
4
+
5
+
6
+ # ------------------------------------------------------------
7
+ # Lazy-load pipelines (loads only when you use that tab)
8
+ # ------------------------------------------------------------
9
+ PIPES = {}
10
+
11
+ def get_pipe(task: str, model: str = None):
12
+ key = (task, model)
13
+ if key not in PIPES:
14
+ if model:
15
+ PIPES[key] = pipeline(task, model=model)
16
+ else:
17
+ PIPES[key] = pipeline(task)
18
+ return PIPES[key]
19
+
20
+
21
+ # ------------------------------------------------------------
22
+ # Helpers
23
+ # ------------------------------------------------------------
24
+ def meter(label: str, score: float):
25
+ # A cute "meter" bar using text (works everywhere)
26
+ score = float(score)
27
+ blocks = int(round(score * 20))
28
+ bar = "β–ˆ" * blocks + "β–‘" * (20 - blocks)
29
+ return f"{label}\n{bar} {score:.2f}"
30
+
31
+
32
+ # ------------------------------------------------------------
33
+ # Tasks
34
+ # ------------------------------------------------------------
35
+ def run_sentiment(text, model_choice):
36
+ model_map = {
37
+ "Fast (default)": None,
38
+ "DistilBERT (SST-2)": "distilbert-base-uncased-finetuned-sst-2-english",
39
+ }
40
+ pipe = get_pipe("sentiment-analysis", model_map[model_choice])
41
+ r = pipe(text)[0]
42
+ label = r["label"]
43
+ score = r["score"]
44
+ emoji = "😊" if "POS" in label.upper() else "😞"
45
+ return (
46
+ f"{emoji} Prediction: {label}",
47
+ meter("Confidence", score),
48
+ pd.DataFrame([{"label": label, "confidence": score}]),
49
+ )
50
+
51
+
52
+ def run_qa(context, question):
53
+ pipe = get_pipe("question-answering", None)
54
+ r = pipe(question=question, context=context)
55
+ answer = r["answer"]
56
+ score = float(r["score"])
57
+ return (
58
+ f"βœ… Answer: {answer}",
59
+ meter("Confidence", score),
60
+ pd.DataFrame([{"answer": answer, "confidence": score}]),
61
+ )
62
+
63
+
64
+ def run_summary(text, length_mode):
65
+ pipe = get_pipe("summarization", None)
66
+ if length_mode == "Short":
67
+ max_len, min_len = 60, 20
68
+ elif length_mode == "Medium":
69
+ max_len, min_len = 90, 30
70
+ else:
71
+ max_len, min_len = 130, 40
72
+ r = pipe(text, max_length=max_len, min_length=min_len, do_sample=False)[0]
73
+ return r["summary_text"]
74
+
75
+
76
+ def run_translate(text, direction):
77
+ # Keep it simple: only two directions (more can be added)
78
+ if direction == "English β†’ French":
79
+ pipe = get_pipe("translation_en_to_fr", None)
80
+ else:
81
+ pipe = get_pipe("translation_fr_to_en", "Helsinki-NLP/opus-mt-fr-en")
82
+ r = pipe(text)[0]
83
+ # key differs by pipeline type; handle safely
84
+ return r.get("translation_text", str(r))
85
+
86
+
87
+ def run_generate(prompt, style, max_new_tokens, temperature):
88
+ # GPT-2 is lightweight and common; great for demos
89
+ pipe = get_pipe("text-generation", "gpt2")
90
+
91
+ # Add a tiny "story style" prefix (kid-friendly)
92
+ if style == "Story πŸ“–":
93
+ prompt2 = f"Once upon a time, {prompt.strip()}"
94
+ elif style == "Robot πŸ€–":
95
+ prompt2 = f"[Robot voice] {prompt.strip()}"
96
+ else:
97
+ prompt2 = prompt.strip()
98
+
99
+ r = pipe(
100
+ prompt2,
101
+ max_new_tokens=int(max_new_tokens),
102
+ do_sample=True,
103
+ temperature=float(temperature),
104
+ num_return_sequences=1,
105
+ )[0]["generated_text"]
106
+
107
+ return r
108
+
109
+
110
+ def run_fill_mask(text):
111
+ # Must contain [MASK]
112
+ pipe = get_pipe("fill-mask", "bert-base-uncased")
113
+ if "[MASK]" not in text:
114
+ return "⚠️ Please include [MASK] in the text.", pd.DataFrame()
115
+
116
+ results = pipe(text)
117
+ rows = []
118
+ for r in results[:10]:
119
+ rows.append({"prediction": r["sequence"], "score": float(r["score"])})
120
+ df = pd.DataFrame(rows)
121
+ return "βœ… Top predictions shown below", df
122
+
123
+
124
+ def run_zero_shot(text, labels):
125
+ pipe = get_pipe("zero-shot-classification", None)
126
+ label_list = [x.strip() for x in labels.split(",") if x.strip()]
127
+ if not label_list:
128
+ return "⚠️ Please type labels separated by commas.", pd.DataFrame()
129
+
130
+ r = pipe(text, candidate_labels=label_list)
131
+ df = pd.DataFrame({"label": r["labels"], "score": r["scores"]})
132
+ return "βœ… Sorted scores (bigger = more likely)", df
133
+
134
+
135
+ def run_ner(text):
136
+ pipe = get_pipe("ner", None)
137
+ ents = pipe(text, grouped_entities=True)
138
+ if not ents:
139
+ return "No entities found.", pd.DataFrame()
140
+
141
+ rows = []
142
+ for e in ents:
143
+ rows.append({
144
+ "text": e.get("word", ""),
145
+ "type": e.get("entity_group", e.get("entity", "")),
146
+ "score": float(e.get("score", 0.0)),
147
+ })
148
+ df = pd.DataFrame(rows).sort_values("score", ascending=False)
149
+ return "βœ… Entities found", df
150
+
151
+
152
+ # ------------------------------------------------------------
153
+ # UI
154
+ # ------------------------------------------------------------
155
+ THEME = gr.themes.Soft(
156
+ primary_hue="indigo",
157
+ secondary_hue="pink",
158
+ neutral_hue="slate",
159
+ )
160
+
161
+ with gr.Blocks(theme=THEME, title="οΏ½οΏ½ Transformers Playground (Kid Friendly)", css="""
162
+ #title {text-align:center}
163
+ .bigcard {border-radius: 18px; padding: 18px; background: white}
164
+ """) as demo:
165
+ gr.Markdown("""
166
+ <div id="title">
167
+
168
+ # πŸ€— Transformers Superpowers Playground
169
+ ### Same library, many amazing language powers ✨
170
+
171
+ </div>
172
+
173
+ **How to use this app (students):**
174
+ 1. Pick a tab (Sentiment, Q&A, Summary, Translate, etc.)
175
+ 2. Change the text ✍️
176
+ 3. Click the big button πŸš€
177
+ 4. Observe what the Transformer can do 🧠
178
+ """)
179
+
180
+ with gr.Row():
181
+ gr.Markdown("""
182
+ <div class="bigcard">
183
+
184
+ ## What can Transformers do?
185
+ - 😊 Detect feelings (Sentiment)
186
+ - ❓ Answer questions (Q&A)
187
+ - πŸ“ Summarize long text
188
+ - 🌍 Translate languages
189
+ - ✍️ Continue stories (Generation)
190
+ - 🧩 Fill missing words ([MASK])
191
+ - 🏷️ Classify topics (Zero-shot)
192
+ - πŸ‘€ Find names/places (NER)
193
+
194
+ </div>
195
+ """)
196
+
197
+ with gr.Tabs():
198
+
199
+ # ------------------ Sentiment ------------------
200
+ with gr.Tab("😊 Sentiment"):
201
+ gr.Markdown("### Detect if text feels **positive** or **negative**.")
202
+ with gr.Row():
203
+ sent_text = gr.Textbox(
204
+ label="Type a sentence",
205
+ value="I love this game! It is so fun and exciting!",
206
+ lines=3
207
+ )
208
+ with gr.Column():
209
+ sent_model = gr.Dropdown(
210
+ ["Fast (default)", "DistilBERT (SST-2)"],
211
+ value="Fast (default)",
212
+ label="Model choice"
213
+ )
214
+ sent_btn = gr.Button("πŸš€ Analyze Sentiment", variant="primary")
215
+
216
+ sent_out1 = gr.Textbox(label="Result", lines=1)
217
+ sent_out2 = gr.Textbox(label="Confidence Meter", lines=2)
218
+ sent_table = gr.Dataframe(label="Details", interactive=False)
219
+
220
+ gr.Examples(
221
+ examples=[
222
+ ["This movie was amazing! I want to watch it again!"],
223
+ ["This is the worst day ever. I feel upset."],
224
+ ["It was okay, not great, not bad."],
225
+ ],
226
+ inputs=sent_text,
227
+ label="Try examples"
228
+ )
229
+
230
+ sent_btn.click(run_sentiment, [sent_text, sent_model], [sent_out1, sent_out2, sent_table])
231
+
232
+ # ------------------ Q&A ------------------
233
+ with gr.Tab("❓ Question Answering"):
234
+ gr.Markdown("### Ask a question using a paragraph as the β€œbook”.")
235
+ qa_context = gr.Textbox(
236
+ label="Context (the paragraph)",
237
+ value="Paris is the capital of France. It is famous for the Eiffel Tower and beautiful museums.",
238
+ lines=5
239
+ )
240
+ qa_question = gr.Textbox(label="Question", value="What is the capital of France?")
241
+ qa_btn = gr.Button("πŸ”Ž Find Answer", variant="primary")
242
+
243
+ qa_out1 = gr.Textbox(label="Answer", lines=1)
244
+ qa_out2 = gr.Textbox(label="Confidence Meter", lines=2)
245
+ qa_table = gr.Dataframe(label="Details", interactive=False)
246
+
247
+ qa_btn.click(run_qa, [qa_context, qa_question], [qa_out1, qa_out2, qa_table])
248
+
249
+ # ------------------ Summarization ------------------
250
+ with gr.Tab("πŸ“ Summarization"):
251
+ gr.Markdown("### Make long text short (like a mini version).")
252
+ sum_text = gr.Textbox(
253
+ label="Long text",
254
+ value=("Artificial intelligence is a field of computer science. "
255
+ "It tries to make machines smart. AI can help with images, language, and robots. "
256
+ "Some AI systems learn from data and improve over time."),
257
+ lines=6
258
+ )
259
+ sum_mode = gr.Radio(["Short", "Medium", "Long"], value="Short", label="Summary size")
260
+ sum_btn = gr.Button("✨ Summarize", variant="primary")
261
+ sum_out = gr.Textbox(label="Summary", lines=4)
262
+
263
+ sum_btn.click(run_summary, [sum_text, sum_mode], sum_out)
264
+
265
+ # ------------------ Translation ------------------
266
+ with gr.Tab("🌍 Translation"):
267
+ gr.Markdown("### Translate between languages.")
268
+ tr_text = gr.Textbox(label="Text", value="I love learning AI.", lines=3)
269
+ tr_dir = gr.Radio(["English β†’ French", "French β†’ English"], value="English β†’ French", label="Direction")
270
+ tr_btn = gr.Button("🌟 Translate", variant="primary")
271
+ tr_out = gr.Textbox(label="Translation", lines=3)
272
+
273
+ tr_btn.click(run_translate, [tr_text, tr_dir], tr_out)
274
+
275
+ # ------------------ Text Generation ------------------
276
+ with gr.Tab("✍️ Text Generation"):
277
+ gr.Markdown("### Let the model continue your writing.")
278
+ gen_prompt = gr.Textbox(
279
+ label="Start a sentence / story",
280
+ value="a brave kid builds a friendly robot that helps at school",
281
+ lines=3
282
+ )
283
+ with gr.Row():
284
+ gen_style = gr.Radio(["Story πŸ“–", "Normal ✨", "Robot πŸ€–"], value="Story πŸ“–", label="Style")
285
+ gen_tokens = gr.Slider(20, 150, value=60, step=5, label="How long?")
286
+ gen_temp = gr.Slider(0.2, 1.5, value=0.9, step=0.1, label="Creativity (temperature)")
287
+
288
+ gen_btn = gr.Button("πŸš€ Generate", variant="primary")
289
+ gen_out = gr.Textbox(label="Generated text", lines=10)
290
+
291
+ gen_btn.click(run_generate, [gen_prompt, gen_style, gen_tokens, gen_temp], gen_out)
292
+
293
+ # ------------------ Fill Mask ------------------
294
+ with gr.Tab("🧩 Fill Missing Word"):
295
+ gr.Markdown("### Put **[MASK]** and the model guesses the missing word.")
296
+ fm_text = gr.Textbox(
297
+ label="Text with [MASK]",
298
+ value="I love to play [MASK] with my friends.",
299
+ lines=3
300
+ )
301
+ fm_btn = gr.Button("🧠 Predict Missing Word", variant="primary")
302
+ fm_msg = gr.Textbox(label="Message", lines=1)
303
+ fm_table = gr.Dataframe(label="Top predictions", interactive=False)
304
+
305
+ fm_btn.click(run_fill_mask, fm_text, [fm_msg, fm_table])
306
+
307
+ # ------------------ Zero-shot classification ------------------
308
+ with gr.Tab("🏷️ Classify Topics"):
309
+ gr.Markdown("### Classify text using labels you invent (no training needed).")
310
+ zs_text = gr.Textbox(
311
+ label="Text",
312
+ value="I love playing football after school and practicing with my team.",
313
+ lines=4
314
+ )
315
+ zs_labels = gr.Textbox(
316
+ label="Labels (comma separated)",
317
+ value="sports, school, food, music, games"
318
+ )
319
+ zs_btn = gr.Button("🎯 Classify", variant="primary")
320
+ zs_msg = gr.Textbox(label="Message", lines=1)
321
+ zs_table = gr.Dataframe(label="Scores", interactive=False)
322
+
323
+ zs_btn.click(run_zero_shot, [zs_text, zs_labels], [zs_msg, zs_table])
324
+
325
+ # ------------------ NER ------------------
326
+ with gr.Tab("πŸ‘€ Find Names & Places"):
327
+ gr.Markdown("### Find **people, places, and organizations** in text.")
328
+ ner_text = gr.Textbox(
329
+ label="Text",
330
+ value="Elon Musk founded SpaceX in the United States and talked about Mars.",
331
+ lines=4
332
+ )
333
+ ner_btn = gr.Button("πŸ” Detect Entities", variant="primary")
334
+ ner_msg = gr.Textbox(label="Message", lines=1)
335
+ ner_table = gr.Dataframe(label="Entities", interactive=False)
336
+
337
+ ner_btn.click(run_ner, ner_text, [ner_msg, ner_table])
338
+
339
+ gr.Markdown("""
340
+ ---
341
+ ## ⭐ Teacher / Demo Tips
342
+ - Start with **Sentiment** (instant β€œwow”).
343
+ - Then **Q&A** (shows understanding).
344
+ - Then **Translate** (feels magical).
345
+ - Then **Generation** (kids LOVE it).
346
+ - For a challenge: ask students to write examples that β€œtrick” the model.
347
+ """)
348
+
349
+ demo.launch()