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
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM
5
+
6
+ # Helper function to handle empty values
7
+ def safe_value(value, default):
8
+ """Return default if value is empty or None"""
9
+ if value is None or value == "":
10
+ return default
11
+ return value
12
+
13
+ # Get Hugging Face token from environment variable (as fallback)
14
+ DEFAULT_HF_TOKEN = os.environ.get("HUGGINGFACE_TOKEN", None)
15
+
16
+ # Create global variables for model and tokenizer
17
+ global_model = None
18
+ global_tokenizer = None
19
+ model_loaded = False
20
+
21
+ def load_model(hf_token):
22
+ """Load the model with the provided token"""
23
+ global global_model, global_tokenizer, model_loaded
24
+
25
+ if not hf_token:
26
+ return False, "Please enter your Hugging Face token to use the model."
27
+
28
+ model_name = "google/gemma-3-4b-pt"
29
+ try:
30
+ global_tokenizer = AutoTokenizer.from_pretrained(model_name, token=hf_token)
31
+ global_model = AutoModelForCausalLM.from_pretrained(
32
+ model_name,
33
+ torch_dtype=torch.float16,
34
+ device_map="auto",
35
+ token=hf_token
36
+ )
37
+ model_loaded = True
38
+ return True, "Model loaded successfully!"
39
+ except Exception as e:
40
+ model_loaded = False
41
+ error_msg = str(e)
42
+ if "401 Client Error" in error_msg:
43
+ return False, "Authentication failed. Please check your token and make sure you've accepted the model license on Hugging Face."
44
+ else:
45
+ return False, f"Error loading model: {error_msg}"
46
+
47
+ def generate_prompt(task_type, **kwargs):
48
+ """Generate appropriate prompts based on task type and parameters"""
49
+ if task_type == "creative":
50
+ style = kwargs.get("style", "")
51
+ topic = kwargs.get("topic", "")
52
+ return f"Write a {style} about {topic}. Be creative and engaging."
53
+
54
+ elif task_type == "informational":
55
+ format_type = kwargs.get("format_type", "")
56
+ topic = kwargs.get("topic", "")
57
+ return f"Write an {format_type} about {topic}. Be clear, factual, and informative."
58
+
59
+ elif task_type == "summarize":
60
+ text = kwargs.get("text", "")
61
+ return f"Summarize the following text in a concise way:\n\n{text}"
62
+
63
+ elif task_type == "translate":
64
+ text = kwargs.get("text", "")
65
+ target_lang = kwargs.get("target_lang", "")
66
+ return f"Translate the following text to {target_lang}:\n\n{text}"
67
+
68
+ elif task_type == "qa":
69
+ text = kwargs.get("text", "")
70
+ question = kwargs.get("question", "")
71
+ return f"Based on the following text:\n\n{text}\n\nAnswer this question: {question}"
72
+
73
+ elif task_type == "code_generate":
74
+ language = kwargs.get("language", "")
75
+ task = kwargs.get("task", "")
76
+ return f"Write {language} code to {task}. Include helpful comments."
77
+
78
+ elif task_type == "code_explain":
79
+ code = kwargs.get("code", "")
80
+ return f"Explain what the following code does in simple terms:\n\n```\n{code}\n```"
81
+
82
+ elif task_type == "code_debug":
83
+ code = kwargs.get("code", "")
84
+ return f"The following code has an issue. Identify and fix the problem:\n\n```\n{code}\n```"
85
+
86
+ elif task_type == "brainstorm":
87
+ topic = kwargs.get("topic", "")
88
+ category = kwargs.get("category", "")
89
+ return f"Brainstorm {category} ideas about {topic}. Provide a diverse list of options."
90
+
91
+ elif task_type == "content_creation":
92
+ content_type = kwargs.get("content_type", "")
93
+ topic = kwargs.get("topic", "")
94
+ audience = kwargs.get("audience", "")
95
+ return f"Create a {content_type} about {topic} for {audience}. Make it engaging and relevant."
96
+
97
+ elif task_type == "email_draft":
98
+ email_type = kwargs.get("email_type", "")
99
+ context = kwargs.get("context", "")
100
+ return f"Write a professional {email_type} email with the following context:\n\n{context}"
101
+
102
+ elif task_type == "document_edit":
103
+ text = kwargs.get("text", "")
104
+ edit_type = kwargs.get("edit_type", "")
105
+ return f"Improve the following text for {edit_type}:\n\n{text}"
106
+
107
+ elif task_type == "explain":
108
+ topic = kwargs.get("topic", "")
109
+ level = kwargs.get("level", "")
110
+ return f"Explain {topic} in a way that's easy to understand for a {level} audience."
111
+
112
+ elif task_type == "classify":
113
+ text = kwargs.get("text", "")
114
+ categories = kwargs.get("categories", "")
115
+ return f"Classify the following text into one of these categories: {categories}\n\nText: {text}\n\nCategory:"
116
+
117
+ elif task_type == "data_extract":
118
+ text = kwargs.get("text", "")
119
+ data_points = kwargs.get("data_points", "")
120
+ return f"Extract the following information from the text: {data_points}\n\nText: {text}\n\nExtracted information:"
121
+
122
+ else:
123
+ return kwargs.get("prompt", "")
124
+
125
+ def generate_text(prompt, max_length=1024, temperature=0.7, top_p=0.95):
126
+ """Generate text using the Gemma model"""
127
+ global global_model, global_tokenizer, model_loaded
128
+
129
+ if not model_loaded or global_model is None or global_tokenizer is None:
130
+ return "⚠️ Model not loaded. Please authenticate with your Hugging Face token."
131
+
132
+ if not prompt:
133
+ return "Please enter a prompt to generate text."
134
+
135
+ try:
136
+ inputs = global_tokenizer(prompt, return_tensors="pt").to(global_model.device)
137
+
138
+ # Generate text
139
+ outputs = global_model.generate(
140
+ **inputs,
141
+ max_length=max_length,
142
+ temperature=temperature,
143
+ top_p=top_p,
144
+ do_sample=True,
145
+ pad_token_id=global_tokenizer.eos_token_id,
146
+ )
147
+
148
+ # Decode and return the generated text
149
+ generated_text = global_tokenizer.decode(outputs[0], skip_special_tokens=True)
150
+ return generated_text
151
+ except Exception as e:
152
+ return f"Error generating text: {str(e)}"
153
+
154
+ # Create parameters UI component
155
+ def create_parameter_ui():
156
+ with gr.Row():
157
+ max_length = gr.Slider(
158
+ minimum=128,
159
+ maximum=2048,
160
+ value=1024,
161
+ step=64,
162
+ label="Maximum Length"
163
+ )
164
+ temperature = gr.Slider(
165
+ minimum=0.1,
166
+ maximum=1.5,
167
+ value=0.7,
168
+ step=0.1,
169
+ label="Temperature"
170
+ )
171
+ top_p = gr.Slider(
172
+ minimum=0.5,
173
+ maximum=1.0,
174
+ value=0.95,
175
+ step=0.05,
176
+ label="Top-p"
177
+ )
178
+ return [max_length, temperature, top_p]
179
+
180
+ # Create Gradio interface
181
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
182
+ gr.Markdown(
183
+ """
184
+ # 🤖 Gemma Capabilities Demo
185
+
186
+ This interactive demo showcases Google's Gemma model capabilities across different tasks.
187
+ """
188
+ )
189
+
190
+ # Authentication Section
191
+ with gr.Box():
192
+ gr.Markdown("## 🔑 Authentication")
193
+
194
+ with gr.Row():
195
+ with gr.Column(scale=3):
196
+ hf_token = gr.Textbox(
197
+ label="Hugging Face Token",
198
+ placeholder="Enter your token here...",
199
+ type="password",
200
+ value=DEFAULT_HF_TOKEN,
201
+ info="Get your token from https://huggingface.co/settings/tokens"
202
+ )
203
+
204
+ with gr.Column(scale=1):
205
+ auth_button = gr.Button("Authenticate")
206
+
207
+ auth_status = gr.Markdown("Please authenticate to use the model.")
208
+
209
+ auth_button.click(
210
+ fn=load_model,
211
+ inputs=[hf_token],
212
+ outputs=[auth_status]
213
+ )
214
+
215
+ gr.Markdown(
216
+ """
217
+ ### How to get a token:
218
+ 1. Go to [Hugging Face Token Settings](https://huggingface.co/settings/tokens)
219
+ 2. Create a new token with read access
220
+ 3. Make sure you've accepted the [Gemma model license](https://huggingface.co/google/gemma-3-4b-pt)
221
+ """
222
+ )
223
+
224
+ # Main content - only show when authenticated
225
+ with gr.Tabs():
226
+ # Text Generation Tab
227
+ with gr.TabItem("Text Generation"):
228
+ gr.Markdown(
229
+ """
230
+ ## Creative Text Generation
231
+
232
+ Generate stories, poems, and other creative content. Choose a style and topic or enter your own prompt.
233
+ """
234
+ )
235
+
236
+ with gr.Row():
237
+ with gr.Column():
238
+ text_gen_type = gr.Radio(
239
+ ["Creative Writing", "Informational Writing", "Custom Prompt"],
240
+ label="Writing Type",
241
+ value="Creative Writing"
242
+ )
243
+
244
+ # Creative writing options
245
+ with gr.Group(visible=True) as creative_options:
246
+ style = gr.Dropdown(
247
+ ["short story", "poem", "script", "song lyrics", "joke"],
248
+ label="Style",
249
+ value="short story"
250
+ )
251
+ creative_topic = gr.Textbox(
252
+ label="Topic",
253
+ placeholder="Enter a topic...",
254
+ value="a robot discovering emotions"
255
+ )
256
+
257
+ # Informational writing options
258
+ with gr.Group(visible=False) as info_options:
259
+ format_type = gr.Dropdown(
260
+ ["article", "summary", "explanation", "report"],
261
+ label="Format",
262
+ value="article"
263
+ )
264
+ info_topic = gr.Textbox(
265
+ label="Topic",
266
+ placeholder="Enter a topic...",
267
+ value="artificial intelligence"
268
+ )
269
+
270
+ # Custom prompt
271
+ with gr.Group(visible=False) as custom_prompt_group:
272
+ custom_prompt = gr.Textbox(
273
+ label="Custom Prompt",
274
+ placeholder="Enter your custom prompt...",
275
+ lines=3
276
+ )
277
+
278
+ # Show/hide options based on selection
279
+ def update_text_gen_visibility(choice):
280
+ return {
281
+ creative_options: choice == "Creative Writing",
282
+ info_options: choice == "Informational Writing",
283
+ custom_prompt_group: choice == "Custom Prompt"
284
+ }
285
+
286
+ text_gen_type.change(
287
+ update_text_gen_visibility,
288
+ inputs=text_gen_type,
289
+ outputs=[creative_options, info_options, custom_prompt_group]
290
+ )
291
+
292
+ # Generation parameters
293
+ text_gen_params = create_parameter_ui()
294
+
295
+ generate_text_btn = gr.Button("Generate")
296
+
297
+ with gr.Column():
298
+ text_output = gr.Textbox(
299
+ label="Generated Text",
300
+ lines=20
301
+ )
302
+
303
+ # Handle text generation
304
+ def text_generation_handler(
305
+ gen_type, style, creative_topic, format_type, info_topic,
306
+ custom_prompt, max_length, temperature, top_p
307
+ ):
308
+ if gen_type == "Creative Writing":
309
+ style = safe_value(style, "short story")
310
+ creative_topic = safe_value(creative_topic, "a story")
311
+ prompt = generate_prompt("creative", style=style, topic=creative_topic)
312
+ elif gen_type == "Informational Writing":
313
+ format_type = safe_value(format_type, "article")
314
+ info_topic = safe_value(info_topic, "a topic")
315
+ prompt = generate_prompt("informational", format_type=format_type, topic=info_topic)
316
+ else:
317
+ prompt = safe_value(custom_prompt, "Write something interesting")
318
+
319
+ return generate_text(prompt, max_length, temperature, top_p)
320
+
321
+ generate_text_btn.click(
322
+ text_generation_handler,
323
+ inputs=[
324
+ text_gen_type, style, creative_topic, format_type, info_topic,
325
+ custom_prompt, *text_gen_params
326
+ ],
327
+ outputs=text_output
328
+ )
329
+
330
+ # Examples for text generation
331
+ gr.Examples(
332
+ [
333
+ ["Creative Writing", "short story", "a robot learning to paint", "article", "artificial intelligence", "", 1024, 0.7, 0.95],
334
+ ["Creative Writing", "poem", "the beauty of mathematics", "article", "artificial intelligence", "", 768, 0.8, 0.95],
335
+ ["Informational Writing", "short story", "a robot discovering emotions", "article", "quantum computing", "", 1024, 0.5, 0.95],
336
+ ["Custom Prompt", "short story", "a robot discovering emotions", "article", "artificial intelligence", "Write a marketing email for a new smartphone with innovative AI features", 1024, 0.7, 0.95]
337
+ ],
338
+ fn=text_generation_handler,
339
+ inputs=[
340
+ text_gen_type, style, creative_topic, format_type, info_topic,
341
+ custom_prompt, *text_gen_params
342
+ ],
343
+ outputs=text_output,
344
+ label="Examples"
345
+ )
346
+
347
+ # Brainstorming Tab
348
+ with gr.TabItem("Brainstorming"):
349
+ gr.Markdown(
350
+ """
351
+ ## Brainstorming Ideas
352
+
353
+ Generate creative ideas for projects, solutions, or any topic you're interested in.
354
+ """
355
+ )
356
+
357
+ with gr.Row():
358
+ with gr.Column():
359
+ brainstorm_category = gr.Dropdown(
360
+ ["project", "business", "creative", "solution", "content", "feature", "product"],
361
+ label="Category",
362
+ value="project"
363
+ )
364
+ brainstorm_topic = gr.Textbox(
365
+ label="Topic or Problem",
366
+ placeholder="What would you like ideas for?",
367
+ value="sustainable technology"
368
+ )
369
+ brainstorm_params = create_parameter_ui()
370
+ brainstorm_btn = gr.Button("Generate Ideas")
371
+
372
+ with gr.Column():
373
+ brainstorm_output = gr.Textbox(
374
+ label="Generated Ideas",
375
+ lines=20
376
+ )
377
+
378
+ def brainstorm_handler(category, topic, max_length, temperature, top_p):
379
+ category = safe_value(category, "project")
380
+ topic = safe_value(topic, "innovative ideas")
381
+ prompt = generate_prompt("brainstorm", category=category, topic=topic)
382
+ return generate_text(prompt, max_length, temperature, top_p)
383
+
384
+ brainstorm_btn.click(
385
+ brainstorm_handler,
386
+ inputs=[brainstorm_category, brainstorm_topic, *brainstorm_params],
387
+ outputs=brainstorm_output
388
+ )
389
+
390
+ # Examples for brainstorming
391
+ gr.Examples(
392
+ [
393
+ ["project", "educational app for children", 1024, 0.8, 0.95],
394
+ ["business", "eco-friendly food packaging", 1024, 0.8, 0.95],
395
+ ["solution", "reducing urban traffic congestion", 1024, 0.8, 0.95],
396
+ ],
397
+ fn=brainstorm_handler,
398
+ inputs=[brainstorm_category, brainstorm_topic, *brainstorm_params],
399
+ outputs=brainstorm_output,
400
+ label="Examples"
401
+ )
402
+
403
+ # Content Creation Tab
404
+ with gr.TabItem("Content Creation"):
405
+ gr.Markdown(
406
+ """
407
+ ## Content Creation
408
+
409
+ Generate various types of content such as blog posts, social media updates, marketing copy, etc.
410
+ """
411
+ )
412
+
413
+ with gr.Row():
414
+ with gr.Column():
415
+ content_type = gr.Dropdown(
416
+ ["blog post", "social media post", "marketing copy", "product description", "press release", "newsletter"],
417
+ label="Content Type",
418
+ value="blog post"
419
+ )
420
+ content_topic = gr.Textbox(
421
+ label="Topic",
422
+ placeholder="What is your content about?",
423
+ value="the future of artificial intelligence"
424
+ )
425
+ content_audience = gr.Textbox(
426
+ label="Target Audience",
427
+ placeholder="Who is your audience?",
428
+ value="tech enthusiasts"
429
+ )
430
+ content_params = create_parameter_ui()
431
+ content_btn = gr.Button("Generate Content")
432
+
433
+ with gr.Column():
434
+ content_output = gr.Textbox(
435
+ label="Generated Content",
436
+ lines=20
437
+ )
438
+
439
+ def content_creation_handler(content_type, topic, audience, max_length, temperature, top_p):
440
+ content_type = safe_value(content_type, "blog post")
441
+ topic = safe_value(topic, "interesting topic")
442
+ audience = safe_value(audience, "general audience")
443
+ prompt = generate_prompt("content_creation", content_type=content_type, topic=topic, audience=audience)
444
+ return generate_text(prompt, max_length, temperature, top_p)
445
+
446
+ content_btn.click(
447
+ content_creation_handler,
448
+ inputs=[content_type, content_topic, content_audience, *content_params],
449
+ outputs=content_output
450
+ )
451
+
452
+ # Examples for content creation
453
+ gr.Examples(
454
+ [
455
+ ["blog post", "sustainable living tips", "environmentally conscious consumers", 1536, 0.7, 0.95],
456
+ ["social media post", "product launch announcement", "existing customers", 512, 0.7, 0.95],
457
+ ["marketing copy", "new fitness app", "health-focused individuals", 1024, 0.7, 0.95],
458
+ ],
459
+ fn=content_creation_handler,
460
+ inputs=[content_type, content_topic, content_audience, *content_params],
461
+ outputs=content_output,
462
+ label="Examples"
463
+ )
464
+
465
+ # Email Drafting Tab
466
+ with gr.TabItem("Email Drafting"):
467
+ gr.Markdown(
468
+ """
469
+ ## Email Drafting
470
+
471
+ Generate professional email drafts for various purposes.
472
+ """
473
+ )
474
+
475
+ with gr.Row():
476
+ with gr.Column():
477
+ email_type = gr.Dropdown(
478
+ ["job application", "customer support", "business proposal", "networking", "follow-up", "thank you", "meeting request"],
479
+ label="Email Type",
480
+ value="job application"
481
+ )
482
+ email_context = gr.Textbox(
483
+ label="Context and Details",
484
+ placeholder="Provide necessary context for the email...",
485
+ lines=5,
486
+ value="Applying for a software developer position at Tech Solutions Inc. I have 3 years of experience with Python and JavaScript."
487
+ )
488
+ email_params = create_parameter_ui()
489
+ email_btn = gr.Button("Generate Email")
490
+
491
+ with gr.Column():
492
+ email_output = gr.Textbox(
493
+ label="Generated Email",
494
+ lines=20
495
+ )
496
+
497
+ def email_draft_handler(email_type, context, max_length, temperature, top_p):
498
+ email_type = safe_value(email_type, "professional")
499
+ context = safe_value(context, "general communication")
500
+ prompt = generate_prompt("email_draft", email_type=email_type, context=context)
501
+ return generate_text(prompt, max_length, temperature, top_p)
502
+
503
+ email_btn.click(
504
+ email_draft_handler,
505
+ inputs=[email_type, email_context, *email_params],
506
+ outputs=email_output
507
+ )
508
+
509
+ # Examples for email drafting
510
+ gr.Examples(
511
+ [
512
+ ["job application", "Applying for a marketing specialist position at ABC Marketing. I have 5 years of experience in digital marketing.", 1024, 0.7, 0.95],
513
+ ["business proposal", "Proposing a collaboration between our companies for a joint product development effort.", 1024, 0.7, 0.95],
514
+ ["follow-up", "Following up after our meeting last Thursday about the project timeline and resources.", 1024, 0.7, 0.95],
515
+ ],
516
+ fn=email_draft_handler,
517
+ inputs=[email_type, email_context, *email_params],
518
+ outputs=email_output,
519
+ label="Examples"
520
+ )
521
+
522
+ # Document Editing Tab
523
+ with gr.TabItem("Document Editing"):
524
+ gr.Markdown(
525
+ """
526
+ ## Document Editing
527
+
528
+ Improve the clarity, grammar, and style of your writing.
529
+ """
530
+ )
531
+
532
+ with gr.Row():
533
+ with gr.Column():
534
+ edit_text = gr.Textbox(
535
+ label="Text to Edit",
536
+ placeholder="Paste your text here...",
537
+ lines=10,
538
+ value="The company have been experiencing rapid growth over the past few years and is expecting to continue this trend in the coming years. They believe that it's success is due to the quality of their products and the dedicated team."
539
+ )
540
+ edit_type = gr.Dropdown(
541
+ ["grammar and clarity", "conciseness", "formal tone", "casual tone", "simplification", "academic style", "persuasive style"],
542
+ label="Edit Type",
543
+ value="grammar and clarity"
544
+ )
545
+ edit_params = create_parameter_ui()
546
+ edit_btn = gr.Button("Edit Document")
547
+
548
+ with gr.Column():
549
+ edit_output = gr.Textbox(
550
+ label="Edited Text",
551
+ lines=10
552
+ )
553
+
554
+ def document_edit_handler(text, edit_type, max_length, temperature, top_p):
555
+ text = safe_value(text, "Please provide text to edit.")
556
+ edit_type = safe_value(edit_type, "grammar and clarity")
557
+ prompt = generate_prompt("document_edit", text=text, edit_type=edit_type)
558
+ return generate_text(prompt, max_length, temperature, top_p)
559
+
560
+ edit_btn.click(
561
+ document_edit_handler,
562
+ inputs=[edit_text, edit_type, *edit_params],
563
+ outputs=edit_output
564
+ )
565
+
566
+ # Learning & Explanation Tab
567
+ with gr.TabItem("Learning & Explanation"):
568
+ gr.Markdown(
569
+ """
570
+ ## Learning & Explanation
571
+
572
+ Get easy-to-understand explanations of complex topics.
573
+ """
574
+ )
575
+
576
+ with gr.Row():
577
+ with gr.Column():
578
+ explain_topic = gr.Textbox(
579
+ label="Topic to Explain",
580
+ placeholder="What topic would you like explained?",
581
+ value="quantum computing"
582
+ )
583
+ explain_level = gr.Dropdown(
584
+ ["beginner", "child", "teenager", "college student", "professional", "expert"],
585
+ label="Audience Level",
586
+ value="beginner"
587
+ )
588
+ explain_params = create_parameter_ui()
589
+ explain_btn = gr.Button("Generate Explanation")
590
+
591
+ with gr.Column():
592
+ explain_output = gr.Textbox(
593
+ label="Explanation",
594
+ lines=20
595
+ )
596
+
597
+ def explanation_handler(topic, level, max_length, temperature, top_p):
598
+ topic = safe_value(topic, "an interesting concept")
599
+ level = safe_value(level, "beginner")
600
+ prompt = generate_prompt("explain", topic=topic, level=level)
601
+ return generate_text(prompt, max_length, temperature, top_p)
602
+
603
+ explain_btn.click(
604
+ explanation_handler,
605
+ inputs=[explain_topic, explain_level, *explain_params],
606
+ outputs=explain_output
607
+ )
608
+
609
+ # Examples for explanation
610
+ gr.Examples(
611
+ [
612
+ ["blockchain technology", "beginner", 1024, 0.7, 0.95],
613
+ ["photosynthesis", "child", 1024, 0.7, 0.95],
614
+ ["machine learning", "college student", 1024, 0.7, 0.95],
615
+ ],
616
+ fn=explanation_handler,
617
+ inputs=[explain_topic, explain_level, *explain_params],
618
+ outputs=explain_output,
619
+ label="Examples"
620
+ )
621
+
622
+ # Classification & Categorization Tab
623
+ with gr.TabItem("Classification"):
624
+ gr.Markdown(
625
+ """
626
+ ## Classification & Categorization
627
+
628
+ Classify text into different categories or themes.
629
+ """
630
+ )
631
+
632
+ with gr.Row():
633
+ with gr.Column():
634
+ classify_text = gr.Textbox(
635
+ label="Text to Classify",
636
+ placeholder="Enter the text you want to classify...",
637
+ lines=8,
638
+ value="The latest smartphone features a powerful processor, excellent camera, and impressive battery life, making it a top choice for tech enthusiasts."
639
+ )
640
+ classify_categories = gr.Textbox(
641
+ label="Categories (comma-separated)",
642
+ placeholder="List categories separated by commas...",
643
+ value="technology, health, finance, entertainment, education, sports"
644
+ )
645
+ classify_params = create_parameter_ui()
646
+ classify_btn = gr.Button("Classify Text")
647
+
648
+ with gr.Column():
649
+ classify_output = gr.Textbox(
650
+ label="Classification Result",
651
+ lines=5
652
+ )
653
+
654
+ def classification_handler(text, categories, max_length, temperature, top_p):
655
+ text = safe_value(text, "Please provide text to classify.")
656
+ categories = safe_value(categories, "general, specific, other")
657
+ prompt = generate_prompt("classify", text=text, categories=categories)
658
+ return generate_text(prompt, max_length, temperature, top_p)
659
+
660
+ classify_btn.click(
661
+ classification_handler,
662
+ inputs=[classify_text, classify_categories, *classify_params],
663
+ outputs=classify_output
664
+ )
665
+
666
+ # Examples for classification
667
+ gr.Examples(
668
+ [
669
+ ["The stock market saw significant gains today as tech companies reported strong quarterly earnings.", "technology, health, finance, entertainment, education, sports", 256, 0.1, 0.95],
670
+ ["The team scored in the final minutes to secure their victory in the championship game.", "technology, health, finance, entertainment, education, sports", 256, 0.1, 0.95],
671
+ ["The new educational app helps students master complex math concepts through interactive exercises.", "technology, health, finance, entertainment, education, sports", 256, 0.1, 0.95],
672
+ ],
673
+ fn=classification_handler,
674
+ inputs=[classify_text, classify_categories, *classify_params],
675
+ outputs=classify_output,
676
+ label="Examples"
677
+ )
678
+
679
+ # Data Extraction Tab
680
+ with gr.TabItem("Data Extraction"):
681
+ gr.Markdown(
682
+ """
683
+ ## Data Extraction
684
+
685
+ Extract specific data points from text.
686
+ """
687
+ )
688
+
689
+ with gr.Row():
690
+ with gr.Column():
691
+ extract_text = gr.Textbox(
692
+ label="Text to Process",
693
+ placeholder="Enter the text containing data to extract...",
694
+ lines=10,
695
+ value="John Smith, born on May 15, 1985, is a software engineer at Tech Solutions Inc. He can be reached at [email protected] or (555) 123-4567. John graduated from MIT in 2007 with a degree in Computer Science."
696
+ )
697
+ extract_data_points = gr.Textbox(
698
+ label="Data Points to Extract (comma-separated)",
699
+ placeholder="Specify what data to extract...",
700
+ value="name, email, phone number, birth date, company, education"
701
+ )
702
+ extract_params = create_parameter_ui()
703
+ extract_btn = gr.Button("Extract Data")
704
+
705
+ with gr.Column():
706
+ extract_output = gr.Textbox(
707
+ label="Extracted Data",
708
+ lines=10
709
+ )
710
+
711
+ def data_extraction_handler(text, data_points, max_length, temperature, top_p):
712
+ text = safe_value(text, "Please provide text with data to extract.")
713
+ data_points = safe_value(data_points, "key information")
714
+ prompt = generate_prompt("data_extract", text=text, data_points=data_points)
715
+ return generate_text(prompt, max_length, temperature, top_p)
716
+
717
+ extract_btn.click(
718
+ data_extraction_handler,
719
+ inputs=[extract_text, extract_data_points, *extract_params],
720
+ outputs=extract_output
721
+ )
722
+
723
+ # Examples for data extraction
724
+ gr.Examples(
725
+ [
726
+ ["Sarah Johnson is the CEO of Green Innovations, founded in 2012. The company reported $8.5 million in revenue for 2023. Contact her at [email protected].", "name, position, company, founding year, revenue, contact", 768, 0.3, 0.95],
727
+ ["The new iPhone 15 Pro features a 6.1-inch display, A17 Pro chip, 48MP camera, and starts at $999 for the 128GB model.", "product name, screen size, processor, camera, price, storage capacity", 768, 0.3, 0.95],
728
+ ],
729
+ fn=data_extraction_handler,
730
+ inputs=[extract_text, extract_data_points, *extract_params],
731
+ outputs=extract_output,
732
+ label="Examples"
733
+ )
734
+
735
+ # Text Comprehension Tab
736
+ with gr.TabItem("Text Comprehension"):
737
+ gr.Markdown(
738
+ """
739
+ ## Text Comprehension
740
+
741
+ Test Gemma's ability to understand and process text. Try summarization, Q&A, or translation.
742
+ """
743
+ )
744
+
745
+ with gr.Tabs():
746
+ # Summarization
747
+ with gr.TabItem("Summarization"):
748
+ with gr.Row():
749
+ with gr.Column():
750
+ summarize_text = gr.Textbox(
751
+ label="Text to Summarize",
752
+ placeholder="Paste text here...",
753
+ lines=10
754
+ )
755
+ summarize_params = create_parameter_ui()
756
+ summarize_btn = gr.Button("Summarize")
757
+
758
+ with gr.Column():
759
+ summary_output = gr.Textbox(
760
+ label="Summary",
761
+ lines=10
762
+ )
763
+
764
+ def summarize_handler(text, max_length, temperature, top_p):
765
+ text = safe_value(text, "Please provide text to summarize.")
766
+ prompt = generate_prompt("summarize", text=text)
767
+ return generate_text(prompt, max_length, temperature, top_p)
768
+
769
+ summarize_btn.click(
770
+ summarize_handler,
771
+ inputs=[summarize_text, *summarize_params],
772
+ outputs=summary_output
773
+ )
774
+
775
+ # Question Answering
776
+ with gr.TabItem("Question Answering"):
777
+ with gr.Row():
778
+ with gr.Column():
779
+ qa_text = gr.Textbox(
780
+ label="Context Text",
781
+ placeholder="Paste text here...",
782
+ lines=10
783
+ )
784
+ qa_question = gr.Textbox(
785
+ label="Question",
786
+ placeholder="Ask a question about the text..."
787
+ )
788
+ qa_params = create_parameter_ui()
789
+ qa_btn = gr.Button("Answer")
790
+
791
+ with gr.Column():
792
+ qa_output = gr.Textbox(
793
+ label="Answer",
794
+ lines=10
795
+ )
796
+
797
+ def qa_handler(text, question, max_length, temperature, top_p):
798
+ text = safe_value(text, "Please provide context text.")
799
+ question = safe_value(question, "Please provide a question.")
800
+ prompt = generate_prompt("qa", text=text, question=question)
801
+ return generate_text(prompt, max_length, temperature, top_p)
802
+
803
+ qa_btn.click(
804
+ qa_handler,
805
+ inputs=[qa_text, qa_question, *qa_params],
806
+ outputs=qa_output
807
+ )
808
+
809
+ # Translation
810
+ with gr.TabItem("Translation"):
811
+ with gr.Row():
812
+ with gr.Column():
813
+ translate_text = gr.Textbox(
814
+ label="Text to Translate",
815
+ placeholder="Enter text to translate...",
816
+ lines=5
817
+ )
818
+ target_lang = gr.Dropdown(
819
+ ["French", "Spanish", "German", "Japanese", "Chinese", "Russian", "Arabic", "Hindi"],
820
+ label="Target Language",
821
+ value="French"
822
+ )
823
+ translate_params = create_parameter_ui()
824
+ translate_btn = gr.Button("Translate")
825
+
826
+ with gr.Column():
827
+ translation_output = gr.Textbox(
828
+ label="Translation",
829
+ lines=5
830
+ )
831
+
832
+ def translate_handler(text, lang, max_length, temperature, top_p):
833
+ text = safe_value(text, "Please provide text to translate.")
834
+ lang = safe_value(lang, "French")
835
+ prompt = generate_prompt("translate", text=text, target_lang=lang)
836
+ return generate_text(prompt, max_length, temperature, top_p)
837
+
838
+ translate_btn.click(
839
+ translate_handler,
840
+ inputs=[translate_text, target_lang, *translate_params],
841
+ outputs=translation_output
842
+ )
843
+
844
+ # Code Capabilities Tab
845
+ with gr.TabItem("Code Capabilities"):
846
+ gr.Markdown(
847
+ """
848
+ ## Code Generation and Understanding
849
+
850
+ Test Gemma's ability to generate, explain, and debug code in various programming languages.
851
+ """
852
+ )
853
+
854
+ with gr.Tabs():
855
+ # Code Generation
856
+ with gr.TabItem("Code Generation"):
857
+ with gr.Row():
858
+ with gr.Column():
859
+ code_language = gr.Dropdown(
860
+ ["Python", "JavaScript", "Java", "C++", "HTML/CSS", "SQL", "Bash"],
861
+ label="Programming Language",
862
+ value="Python"
863
+ )
864
+ code_task = gr.Textbox(
865
+ label="Coding Task",
866
+ placeholder="Describe what you want the code to do...",
867
+ value="Create a function to find prime numbers up to n"
868
+ )
869
+ code_gen_params = create_parameter_ui()
870
+ code_gen_btn = gr.Button("Generate Code")
871
+
872
+ with gr.Column():
873
+ code_output = gr.Code(
874
+ label="Generated Code",
875
+ language="python"
876
+ )
877
+
878
+ def code_gen_handler(language, task, max_length, temperature, top_p):
879
+ language = safe_value(language, "Python")
880
+ task = safe_value(task, "write a hello world program")
881
+ prompt = generate_prompt("code_generate", language=language, task=task)
882
+ result = generate_text(prompt, max_length, temperature, top_p)
883
+ return result
884
+
885
+ # Update language in code output component
886
+ def update_code_language(lang):
887
+ lang_map = {
888
+ "Python": "python",
889
+ "JavaScript": "javascript",
890
+ "Java": "java",
891
+ "C++": "cpp",
892
+ "HTML/CSS": "html",
893
+ "SQL": "sql",
894
+ "Bash": "bash"
895
+ }
896
+ return gr.Code.update(language=lang_map.get(lang, "python"))
897
+
898
+ code_language.change(update_code_language, inputs=code_language, outputs=code_output)
899
+
900
+ code_gen_btn.click(
901
+ code_gen_handler,
902
+ inputs=[code_language, code_task, *code_gen_params],
903
+ outputs=code_output
904
+ )
905
+
906
+ # Code Explanation
907
+ with gr.TabItem("Code Explanation"):
908
+ with gr.Row():
909
+ with gr.Column():
910
+ code_to_explain = gr.Code(
911
+ label="Code to Explain",
912
+ language="python",
913
+ value="def quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pivot]\n right = [x for x in arr if x > pivot]\n return quicksort(left) + middle + quicksort(right)"
914
+ )
915
+ explain_code_params = create_parameter_ui()
916
+ explain_code_btn = gr.Button("Explain Code")
917
+
918
+ with gr.Column():
919
+ code_explanation = gr.Textbox(
920
+ label="Explanation",
921
+ lines=10
922
+ )
923
+
924
+ def explain_code_handler(code, max_length, temperature, top_p):
925
+ code = safe_value(code, "print('Hello, world!')")
926
+ prompt = generate_prompt("code_explain", code=code)
927
+ return generate_text(prompt, max_length, temperature, top_p)
928
+
929
+ explain_code_btn.click(
930
+ explain_code_handler,
931
+ inputs=[code_to_explain, *explain_code_params],
932
+ outputs=code_explanation
933
+ )
934
+
935
+ # Code Debugging
936
+ with gr.TabItem("Code Debugging"):
937
+ with gr.Row():
938
+ with gr.Column():
939
+ code_to_debug = gr.Code(
940
+ label="Code to Debug",
941
+ language="python",
942
+ value="def fibonacci(n):\n if n <= 0:\n return []\n elif n == 1:\n return [0]\n elif n == 2:\n return [0, 1]\n \n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[i-1] - fib[i-2]) # Bug is here (should be +)\n \n return fib\n\nprint(fibonacci(10))"
943
+ )
944
+ debug_code_params = create_parameter_ui()
945
+ debug_code_btn = gr.Button("Debug Code")
946
+
947
+ with gr.Column():
948
+ debug_result = gr.Textbox(
949
+ label="Debugging Result",
950
+ lines=10
951
+ )
952
+
953
+ def debug_code_handler(code, max_length, temperature, top_p):
954
+ code = safe_value(code, "print('Hello, world!')")
955
+ prompt = generate_prompt("code_debug", code=code)
956
+ return generate_text(prompt, max_length, temperature, top_p)
957
+
958
+ debug_code_btn.click(
959
+ debug_code_handler,
960
+ inputs=[code_to_debug, *debug_code_params],
961
+ outputs=debug_result
962
+ )
963
+
964
+ gr.Markdown(
965
+ """
966
+ ## About Gemma
967
+
968
+ Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models.
969
+ It's designed to be efficient and accessible for various applications.
970
+
971
+ [Learn more about Gemma](https://huggingface.co/google/gemma-3-4b-pt)
972
+ """
973
+ )
974
+
975
+ # Load default token if available
976
+ if DEFAULT_HF_TOKEN:
977
+ demo.load(fn=load_model, inputs=[hf_token], outputs=[auth_status])
978
+
979
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ torch>=2.0.0
3
+ transformers>=4.34.0
4
+ accelerate>=0.23.0
5
+ sentencepiece>=0.1.99