akashmadisetty commited on
Commit
9b95875
·
1 Parent(s): d6791a6
Files changed (3) hide show
  1. app.py +0 -0
  2. app_2.py +1322 -0
  3. requirements.txt +2 -1
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
app_2.py ADDED
@@ -0,0 +1,1322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM
5
+ import random
6
+ from gradio.themes.utils import colors, sizes
7
+ from gradio.themes import Base, Soft
8
+
9
+ # Create custom themes for light and dark mode
10
+ class GemmaLightTheme(Soft):
11
+ def __init__(self):
12
+ super().__init__(
13
+ primary_hue=colors.blue,
14
+ secondary_hue=colors.indigo,
15
+ neutral_hue=colors.gray,
16
+ spacing_size=sizes.spacing_md,
17
+ radius_size=sizes.radius_md,
18
+ text_size=sizes.text_md,
19
+ )
20
+
21
+ class GemmaDarkTheme(Soft):
22
+ def __init__(self):
23
+ super().__init__(
24
+ primary_hue=colors.blue,
25
+ secondary_hue=colors.indigo,
26
+ neutral_hue=colors.gray,
27
+ spacing_size=sizes.spacing_md,
28
+ radius_size=sizes.radius_md,
29
+ text_size=sizes.text_md,
30
+ )
31
+ self.name = "gemma_dark"
32
+ # Make it dark
33
+ self.background_fill_primary = "#1F1F2E"
34
+ self.background_fill_secondary = "#2A2A3C"
35
+ self.border_color_primary = "#3A3A4C"
36
+ self.border_color_secondary = "#4A4A5C"
37
+ self.color_accent_soft = "#3B5FA3"
38
+ self.color_accent = "#4B82C4"
39
+ self.text_color = "#FFFFFF"
40
+ self.text_color_subdued = "#CCCCCC"
41
+ self.shadow_spread = "8px"
42
+ self.shadow_inset = "0px 1px 2px 0px rgba(0, 0, 0, 0.1) inset"
43
+
44
+ # Helper function to handle empty values
45
+ def safe_value(value, default):
46
+ """Return default if value is empty or None"""
47
+ if value is None or value == "":
48
+ return default
49
+ return value
50
+
51
+ # Get Hugging Face token from environment variable (as fallback)
52
+ DEFAULT_HF_TOKEN = os.environ.get("HUGGINGFACE_TOKEN", None)
53
+
54
+ # Create global variables for model and tokenizer
55
+ global_model = None
56
+ global_tokenizer = None
57
+ model_loaded = False
58
+
59
+ def load_model(hf_token):
60
+ """Load the model with the provided token"""
61
+ global global_model, global_tokenizer, model_loaded
62
+
63
+ if not hf_token:
64
+ model_loaded = False
65
+ return "⚠️ Please enter your Hugging Face token to use the model."
66
+
67
+ try:
68
+ # Try different model versions from smallest to largest
69
+ model_options = [
70
+ "google/gemma-2b-it", # Try an instruction-tuned 2B model first (smallest)
71
+ "google/gemma-2b", # Try base 2B model next
72
+ "google/gemma-7b-it", # Try 7B instruction-tuned model
73
+ "google/gemma-7b", # Try base 7B model
74
+ ]
75
+
76
+ print(f"Attempting to load models with token starting with: {hf_token[:5]}...")
77
+
78
+ # Try to load models in order until one works
79
+ for model_name in model_options:
80
+ try:
81
+ print(f"Attempting to load model: {model_name}")
82
+
83
+ # Load tokenizer
84
+ print("Loading tokenizer...")
85
+ global_tokenizer = AutoTokenizer.from_pretrained(
86
+ model_name,
87
+ token=hf_token
88
+ )
89
+ print("Tokenizer loaded successfully")
90
+
91
+ # Load model with minimal configuration
92
+ print(f"Loading model {model_name}...")
93
+ global_model = AutoModelForCausalLM.from_pretrained(
94
+ model_name,
95
+ torch_dtype=torch.float16,
96
+ device_map="auto",
97
+ token=hf_token
98
+ )
99
+ print(f"Model {model_name} loaded successfully!")
100
+
101
+ model_loaded = True
102
+ return f"✅ Model {model_name} loaded successfully!"
103
+ except Exception as specific_e:
104
+ print(f"Failed to load {model_name}: {specific_e}")
105
+ import traceback
106
+ traceback.print_exc()
107
+ continue
108
+
109
+ # If we get here, all model options failed - try one more option with no token
110
+ try:
111
+ print("Trying a public model with no token requirement...")
112
+ model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
113
+ global_tokenizer = AutoTokenizer.from_pretrained(model_name)
114
+ global_model = AutoModelForCausalLM.from_pretrained(
115
+ model_name,
116
+ torch_dtype=torch.float16,
117
+ device_map="auto"
118
+ )
119
+ model_loaded = True
120
+ return f"✅ Fallback model {model_name} loaded successfully! Note: This is not Gemma but a fallback model."
121
+ except Exception as fallback_e:
122
+ print(f"Failed to load fallback model: {fallback_e}")
123
+
124
+ # If we get here, all model options failed
125
+ model_loaded = False
126
+ return "❌ Could not load any model version. Please check your token and try again."
127
+
128
+ except Exception as e:
129
+ model_loaded = False
130
+ error_msg = str(e)
131
+ print(f"Error in load_model: {error_msg}")
132
+ import traceback
133
+ traceback.print_exc()
134
+
135
+ if "401 Client Error" in error_msg:
136
+ return "❌ Authentication failed. Please check your token and make sure you've accepted the model license on Hugging Face."
137
+ else:
138
+ return f"❌ Error loading model: {error_msg}"
139
+
140
+ def generate_prompt(task_type, **kwargs):
141
+ """Generate appropriate prompts based on task type and parameters"""
142
+ if task_type == "creative":
143
+ style = kwargs.get("style", "")
144
+ topic = kwargs.get("topic", "")
145
+ return f"Write a {style} about {topic}. Be creative and engaging."
146
+
147
+ elif task_type == "informational":
148
+ format_type = kwargs.get("format_type", "")
149
+ topic = kwargs.get("topic", "")
150
+ return f"Write an {format_type} about {topic}. Be clear, factual, and informative."
151
+
152
+ elif task_type == "summarize":
153
+ text = kwargs.get("text", "")
154
+ return f"Summarize the following text in a concise way:\n\n{text}"
155
+
156
+ elif task_type == "translate":
157
+ text = kwargs.get("text", "")
158
+ target_lang = kwargs.get("target_lang", "")
159
+ return f"Translate the following text to {target_lang}:\n\n{text}"
160
+
161
+ elif task_type == "qa":
162
+ text = kwargs.get("text", "")
163
+ question = kwargs.get("question", "")
164
+ return f"Based on the following text:\n\n{text}\n\nAnswer this question: {question}"
165
+
166
+ elif task_type == "code_generate":
167
+ language = kwargs.get("language", "")
168
+ task = kwargs.get("task", "")
169
+ return f"Write {language} code to {task}. Include helpful comments."
170
+
171
+ elif task_type == "code_explain":
172
+ code = kwargs.get("code", "")
173
+ return f"Explain what the following code does in simple terms:\n\n```\n{code}\n```"
174
+
175
+ elif task_type == "code_debug":
176
+ code = kwargs.get("code", "")
177
+ return f"The following code has an issue. Identify and fix the problem:\n\n```\n{code}\n```"
178
+
179
+ elif task_type == "brainstorm":
180
+ topic = kwargs.get("topic", "")
181
+ category = kwargs.get("category", "")
182
+ return f"Brainstorm {category} ideas about {topic}. Provide a diverse list of options."
183
+
184
+ elif task_type == "content_creation":
185
+ content_type = kwargs.get("content_type", "")
186
+ topic = kwargs.get("topic", "")
187
+ audience = kwargs.get("audience", "")
188
+ return f"Create a {content_type} about {topic} for {audience}. Make it engaging and relevant."
189
+
190
+ elif task_type == "email_draft":
191
+ email_type = kwargs.get("email_type", "")
192
+ context = kwargs.get("context", "")
193
+ return f"Write a professional {email_type} email with the following context:\n\n{context}"
194
+
195
+ elif task_type == "document_edit":
196
+ text = kwargs.get("text", "")
197
+ edit_type = kwargs.get("edit_type", "")
198
+ return f"Improve the following text for {edit_type}:\n\n{text}"
199
+
200
+ elif task_type == "explain":
201
+ topic = kwargs.get("topic", "")
202
+ level = kwargs.get("level", "")
203
+ return f"Explain {topic} in a way that's easy to understand for a {level} audience."
204
+
205
+ elif task_type == "classify":
206
+ text = kwargs.get("text", "")
207
+ categories = kwargs.get("categories", "")
208
+ return f"Classify the following text into one of these categories: {categories}\n\nText: {text}\n\nCategory:"
209
+
210
+ elif task_type == "data_extract":
211
+ text = kwargs.get("text", "")
212
+ data_points = kwargs.get("data_points", "")
213
+ return f"Extract the following information from the text: {data_points}\n\nText: {text}\n\nExtracted information:"
214
+
215
+ else:
216
+ return kwargs.get("prompt", "")
217
+
218
+ def generate_text(prompt, max_length=1024, temperature=0.7, top_p=0.95):
219
+ """Generate text using the Gemma model"""
220
+ global global_model, global_tokenizer, model_loaded
221
+
222
+ print(f"Generating text with params: max_length={max_length}, temp={temperature}, top_p={top_p}")
223
+ print(f"Prompt: {prompt[:100]}...")
224
+
225
+ if not model_loaded or global_model is None or global_tokenizer is None:
226
+ print("Model not loaded")
227
+ return "⚠️ Model not loaded. Please authenticate with your Hugging Face token."
228
+
229
+ if not prompt:
230
+ return "Please enter a prompt to generate text."
231
+
232
+ try:
233
+ # Keep generation simple to avoid errors
234
+ inputs = global_tokenizer(prompt, return_tensors="pt").to(global_model.device)
235
+ print(f"Input token length: {len(inputs.input_ids[0])}")
236
+
237
+ # Use even simpler generation parameters
238
+ generation_args = {
239
+ "input_ids": inputs.input_ids,
240
+ "max_length": min(2048, max_length + len(inputs.input_ids[0])),
241
+ "do_sample": True,
242
+ }
243
+
244
+ # Only add temperature if not too low (can cause issues)
245
+ if temperature >= 0.3:
246
+ generation_args["temperature"] = temperature
247
+
248
+ print(f"Generation args: {generation_args}")
249
+
250
+ # Generate text
251
+ outputs = global_model.generate(**generation_args)
252
+
253
+ # Decode and return the generated text
254
+ generated_text = global_tokenizer.decode(outputs[0], skip_special_tokens=True)
255
+ print(f"Generated text length: {len(generated_text)}")
256
+ return generated_text
257
+ except Exception as e:
258
+ error_msg = str(e)
259
+ print(f"Generation error: {error_msg}")
260
+ print(f"Error type: {type(e)}")
261
+ import traceback
262
+ traceback.print_exc()
263
+
264
+ if "probability tensor" in error_msg:
265
+ return "Error: There was a problem with the generation parameters. Try using simpler parameters or a different prompt."
266
+ else:
267
+ return f"Error generating text: {error_msg}"
268
+
269
+ # Create parameters UI component
270
+ def create_parameter_ui():
271
+ with gr.Row(equal_height=True):
272
+ with gr.Column(scale=1):
273
+ max_length = gr.Slider(
274
+ minimum=128,
275
+ maximum=2048,
276
+ value=1024,
277
+ step=64,
278
+ label="Maximum Length",
279
+ info="Control the maximum length of generated text",
280
+ elem_id="max_length_slider"
281
+ )
282
+ with gr.Column(scale=1):
283
+ temperature = gr.Slider(
284
+ minimum=0.3,
285
+ maximum=1.5,
286
+ value=0.8,
287
+ step=0.1,
288
+ label="Temperature",
289
+ info="Higher values create more creative but potentially less coherent outputs",
290
+ elem_id="temperature_slider"
291
+ )
292
+ with gr.Column(scale=1):
293
+ top_p = gr.Slider(
294
+ minimum=0.5,
295
+ maximum=0.99,
296
+ value=0.9,
297
+ step=0.05,
298
+ label="Top-p",
299
+ info="Controls diversity of generated text",
300
+ elem_id="top_p_slider"
301
+ )
302
+ return [max_length, temperature, top_p]
303
+
304
+ # Create Gradio interface
305
+ with gr.Blocks(theme=GemmaLightTheme()) as demo:
306
+ # Header with theme toggle
307
+ with gr.Row(equal_height=True):
308
+ with gr.Column(scale=6):
309
+ gr.Markdown(
310
+ """
311
+ # 🤖 Gemma Capabilities Demo
312
+
313
+ This interactive demo showcases Google's Gemma model capabilities across different tasks.
314
+ """
315
+ )
316
+
317
+ with gr.Column(scale=1, min_width=150):
318
+ theme_toggle = gr.Radio(
319
+ ["Light", "Dark"],
320
+ value="Light",
321
+ label="Theme",
322
+ info="Switch between light and dark mode",
323
+ elem_id="theme_toggle"
324
+ )
325
+
326
+ # Add CSS for themes and set up JavaScript for theme toggle
327
+ gr.HTML("""
328
+ <style>
329
+ /* Dark theme styles */
330
+ .dark-theme {
331
+ --background-fill-primary: #1F1F2E !important;
332
+ --background-fill-secondary: #2A2A3C !important;
333
+ --border-color-primary: #3A3A4C !important;
334
+ --border-color-secondary: #4A4A5C !important;
335
+ --color-accent: #4B82C4 !important;
336
+ --color-accent-soft: #3B5FA3 !important;
337
+ --color-text: #FFFFFF !important;
338
+ --color-subtext: #CCCCCC !important;
339
+ }
340
+ </style>
341
+
342
+ <script>
343
+ // This script will run after the page loads
344
+ (function() {
345
+ // Function to check the theme toggle and apply the appropriate theme
346
+ function applyTheme() {
347
+ const themeToggle = document.getElementById('theme_toggle');
348
+ if (!themeToggle) return;
349
+
350
+ const inputs = themeToggle.querySelectorAll('input');
351
+ for (let input of inputs) {
352
+ if (input.checked && input.value === 'Dark') {
353
+ document.body.classList.add('dark-theme');
354
+ return;
355
+ }
356
+ }
357
+
358
+ // If we get here, light theme is selected or no selection
359
+ document.body.classList.remove('dark-theme');
360
+ }
361
+
362
+ // Set up a mutation observer to watch for changes to the radio buttons
363
+ function setupObserver() {
364
+ const themeToggle = document.getElementById('theme_toggle');
365
+ if (!themeToggle) {
366
+ // Try again in a bit if the element isn't ready yet
367
+ setTimeout(setupObserver, 100);
368
+ return;
369
+ }
370
+
371
+ // Apply theme initially
372
+ applyTheme();
373
+
374
+ // Watch for changes
375
+ const observer = new MutationObserver(function(mutations) {
376
+ mutations.forEach(function(mutation) {
377
+ if (mutation.type === 'attributes' || mutation.type === 'childList') {
378
+ applyTheme();
379
+ }
380
+ });
381
+ });
382
+
383
+ observer.observe(themeToggle, {
384
+ attributes: true,
385
+ childList: true,
386
+ subtree: true
387
+ });
388
+
389
+ // Also add click listeners to ensure theme changes on click
390
+ const inputs = themeToggle.querySelectorAll('input');
391
+ inputs.forEach(input => {
392
+ input.addEventListener('change', applyTheme);
393
+ });
394
+ }
395
+
396
+ // Start the setup when the document is ready
397
+ if (document.readyState === 'loading') {
398
+ document.addEventListener('DOMContentLoaded', setupObserver);
399
+ } else {
400
+ setupObserver();
401
+ }
402
+ })();
403
+ </script>
404
+ """)
405
+
406
+ # Authentication Section
407
+ with gr.Group(elem_id="auth_box"):
408
+ gr.Markdown("## 🔑 Authentication", elem_id="auth_heading")
409
+
410
+ with gr.Row(equal_height=True):
411
+ with gr.Column(scale=3):
412
+ hf_token = gr.Textbox(
413
+ label="Hugging Face Token",
414
+ placeholder="Enter your token here...",
415
+ type="password",
416
+ value=DEFAULT_HF_TOKEN,
417
+ info="Get your token from https://huggingface.co/settings/tokens",
418
+ elem_id="hf_token_input"
419
+ )
420
+
421
+ with gr.Column(scale=1):
422
+ auth_button = gr.Button("Authenticate", variant="primary", elem_id="auth_button")
423
+
424
+ auth_status = gr.Markdown("Please authenticate to use the model.", elem_id="auth_status")
425
+
426
+ def authenticate(token):
427
+ return "⏳ Loading model... Please wait, this may take a minute."
428
+
429
+ def auth_complete(token):
430
+ result = load_model(token)
431
+ return result
432
+
433
+ # Two-step authentication to show loading message
434
+ auth_button.click(
435
+ fn=authenticate,
436
+ inputs=[hf_token],
437
+ outputs=[auth_status],
438
+ queue=False
439
+ ).then(
440
+ fn=auth_complete,
441
+ inputs=[hf_token],
442
+ outputs=[auth_status]
443
+ )
444
+
445
+ gr.Markdown(
446
+ """
447
+ ### How to get a token:
448
+ 1. Go to [Hugging Face Token Settings](https://huggingface.co/settings/tokens)
449
+ 2. Create a new token with read access
450
+ 3. Make sure you've accepted the [Gemma model license](https://huggingface.co/google/gemma-3-4b-pt)
451
+ """
452
+ )
453
+
454
+ # Main content - only show when authenticated
455
+ with gr.Tabs(elem_id="main_tabs") as tabs:
456
+ # Text Generation Tab
457
+ with gr.TabItem("Text Generation", id="tab_text_gen"):
458
+ gr.Markdown(
459
+ """
460
+ ## ✏️ Creative Text Generation
461
+
462
+ Generate stories, poems, and other creative content. Choose a style and topic or enter your own prompt.
463
+ """
464
+ )
465
+
466
+ with gr.Group(elem_id="text_gen_box"):
467
+ with gr.Row(equal_height=True):
468
+ with gr.Column(scale=1):
469
+ text_gen_type = gr.Radio(
470
+ ["Creative Writing", "Informational Writing", "Custom Prompt"],
471
+ label="Writing Type",
472
+ value="Creative Writing",
473
+ elem_id="text_gen_type"
474
+ )
475
+
476
+ # Creative writing options
477
+ with gr.Group(visible=True, elem_id="creative_options") as creative_options:
478
+ style = gr.Dropdown(
479
+ ["short story", "poem", "script", "song lyrics", "joke"],
480
+ label="Style",
481
+ value="short story",
482
+ elem_id="creative_style"
483
+ )
484
+ creative_topic = gr.Textbox(
485
+ label="Topic",
486
+ placeholder="Enter a topic...",
487
+ value="a robot discovering emotions",
488
+ elem_id="creative_topic"
489
+ )
490
+
491
+ # Informational writing options
492
+ with gr.Group(visible=False, elem_id="info_options") as info_options:
493
+ format_type = gr.Dropdown(
494
+ ["article", "summary", "explanation", "report"],
495
+ label="Format",
496
+ value="article",
497
+ elem_id="info_format"
498
+ )
499
+ info_topic = gr.Textbox(
500
+ label="Topic",
501
+ placeholder="Enter a topic...",
502
+ value="artificial intelligence",
503
+ elem_id="info_topic"
504
+ )
505
+
506
+ # Custom prompt
507
+ with gr.Group(visible=False, elem_id="custom_prompt_group") as custom_prompt_group:
508
+ custom_prompt = gr.Textbox(
509
+ label="Custom Prompt",
510
+ placeholder="Enter your custom prompt...",
511
+ lines=3,
512
+ elem_id="custom_prompt"
513
+ )
514
+
515
+ # Show/hide options based on selection
516
+ def update_text_gen_visibility(choice):
517
+ return {
518
+ creative_options: choice == "Creative Writing",
519
+ info_options: choice == "Informational Writing",
520
+ custom_prompt_group: choice == "Custom Prompt"
521
+ }
522
+
523
+ text_gen_type.change(
524
+ update_text_gen_visibility,
525
+ inputs=text_gen_type,
526
+ outputs=[creative_options, info_options, custom_prompt_group]
527
+ )
528
+
529
+ # Generation parameters
530
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="text_gen_params"):
531
+ text_gen_params = create_parameter_ui()
532
+
533
+ generate_text_btn = gr.Button("Generate", variant="primary", size="lg", elem_id="generate_text_btn")
534
+
535
+ with gr.Column(scale=1):
536
+ text_output = gr.Textbox(
537
+ label="Generated Text",
538
+ lines=20,
539
+ elem_id="text_output"
540
+ )
541
+
542
+ # Handle text generation
543
+ def text_generation_handler(
544
+ gen_type, style, creative_topic, format_type, info_topic,
545
+ custom_prompt, max_length, temperature, top_p
546
+ ):
547
+ if gen_type == "Creative Writing":
548
+ style = safe_value(style, "short story")
549
+ creative_topic = safe_value(creative_topic, "a story")
550
+ prompt = generate_prompt("creative", style=style, topic=creative_topic)
551
+ elif gen_type == "Informational Writing":
552
+ format_type = safe_value(format_type, "article")
553
+ info_topic = safe_value(info_topic, "a topic")
554
+ prompt = generate_prompt("informational", format_type=format_type, topic=info_topic)
555
+ else:
556
+ prompt = safe_value(custom_prompt, "Write something interesting")
557
+
558
+ return generate_text(prompt, max_length, temperature, top_p)
559
+
560
+ generate_text_btn.click(
561
+ text_generation_handler,
562
+ inputs=[
563
+ text_gen_type, style, creative_topic, format_type, info_topic,
564
+ custom_prompt, *text_gen_params
565
+ ],
566
+ outputs=text_output
567
+ )
568
+
569
+ # Examples for text generation
570
+ gr.Examples(
571
+ [
572
+ ["Creative Writing", "short story", "a robot learning to paint", "article", "artificial intelligence", "", 1024, 0.8, 0.9],
573
+ ["Creative Writing", "poem", "the beauty of mathematics", "article", "artificial intelligence", "", 768, 0.8, 0.9],
574
+ ["Informational Writing", "short story", "a robot discovering emotions", "article", "quantum computing", "", 1024, 0.7, 0.9],
575
+ ["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.8, 0.9]
576
+ ],
577
+ fn=text_generation_handler,
578
+ inputs=[
579
+ text_gen_type, style, creative_topic, format_type, info_topic,
580
+ custom_prompt, *text_gen_params
581
+ ],
582
+ outputs=text_output,
583
+ label="Examples"
584
+ )
585
+
586
+ # Brainstorming Tab
587
+ with gr.TabItem("Brainstorming", id="tab_brainstorm"):
588
+ gr.Markdown(
589
+ """
590
+ ## 🧠 Brainstorming Ideas
591
+
592
+ Generate creative ideas for projects, solutions, or any topic you're interested in.
593
+ """
594
+ )
595
+
596
+ with gr.Group(elem_id="brainstorm_box"):
597
+ with gr.Row(equal_height=True):
598
+ with gr.Column(scale=1):
599
+ brainstorm_category = gr.Dropdown(
600
+ ["project", "business", "creative", "solution", "content", "feature", "product"],
601
+ label="Category",
602
+ value="project",
603
+ elem_id="brainstorm_category"
604
+ )
605
+ brainstorm_topic = gr.Textbox(
606
+ label="Topic or Problem",
607
+ placeholder="What would you like ideas for?",
608
+ value="sustainable technology",
609
+ elem_id="brainstorm_topic"
610
+ )
611
+
612
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="brainstorm_params"):
613
+ brainstorm_params = create_parameter_ui()
614
+
615
+ brainstorm_btn = gr.Button("Generate Ideas", variant="primary", size="lg", elem_id="brainstorm_btn")
616
+
617
+ with gr.Column(scale=1):
618
+ brainstorm_output = gr.Textbox(
619
+ label="Generated Ideas",
620
+ lines=20,
621
+ elem_id="brainstorm_output"
622
+ )
623
+
624
+ def brainstorm_handler(category, topic, max_length, temperature, top_p):
625
+ category = safe_value(category, "project")
626
+ topic = safe_value(topic, "innovative ideas")
627
+ prompt = generate_prompt("brainstorm", category=category, topic=topic)
628
+ return generate_text(prompt, max_length, temperature, top_p)
629
+
630
+ brainstorm_btn.click(
631
+ brainstorm_handler,
632
+ inputs=[brainstorm_category, brainstorm_topic, *brainstorm_params],
633
+ outputs=brainstorm_output
634
+ )
635
+
636
+ # Examples for brainstorming
637
+ gr.Examples(
638
+ [
639
+ ["project", "educational app for children", 1024, 0.8, 0.9],
640
+ ["business", "eco-friendly food packaging", 1024, 0.8, 0.9],
641
+ ["solution", "reducing urban traffic congestion", 1024, 0.8, 0.9],
642
+ ],
643
+ fn=brainstorm_handler,
644
+ inputs=[brainstorm_category, brainstorm_topic, *brainstorm_params],
645
+ outputs=brainstorm_output,
646
+ label="Examples"
647
+ )
648
+
649
+ # Content Creation Tab
650
+ with gr.TabItem("Content Creation", id="tab_content"):
651
+ gr.Markdown(
652
+ """
653
+ ## 📝 Content Creation
654
+
655
+ Generate various types of content such as blog posts, social media updates, marketing copy, etc.
656
+ """
657
+ )
658
+
659
+ with gr.Group(elem_id="content_box"):
660
+ with gr.Row(equal_height=True):
661
+ with gr.Column(scale=1):
662
+ content_type = gr.Dropdown(
663
+ ["blog post", "social media post", "marketing copy", "product description", "press release", "newsletter"],
664
+ label="Content Type",
665
+ value="blog post",
666
+ elem_id="content_type"
667
+ )
668
+ content_topic = gr.Textbox(
669
+ label="Topic",
670
+ placeholder="What is your content about?",
671
+ value="the future of artificial intelligence",
672
+ elem_id="content_topic"
673
+ )
674
+ content_audience = gr.Textbox(
675
+ label="Target Audience",
676
+ placeholder="Who is your audience?",
677
+ value="tech enthusiasts",
678
+ elem_id="content_audience"
679
+ )
680
+
681
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="content_params"):
682
+ content_params = create_parameter_ui()
683
+
684
+ content_btn = gr.Button("Generate Content", variant="primary", size="lg", elem_id="content_btn")
685
+
686
+ with gr.Column(scale=1):
687
+ content_output = gr.Textbox(
688
+ label="Generated Content",
689
+ lines=20,
690
+ elem_id="content_output"
691
+ )
692
+
693
+ def content_creation_handler(content_type, topic, audience, max_length, temperature, top_p):
694
+ content_type = safe_value(content_type, "blog post")
695
+ topic = safe_value(topic, "interesting topic")
696
+ audience = safe_value(audience, "general audience")
697
+ prompt = generate_prompt("content_creation", content_type=content_type, topic=topic, audience=audience)
698
+ return generate_text(prompt, max_length, temperature, top_p)
699
+
700
+ content_btn.click(
701
+ content_creation_handler,
702
+ inputs=[content_type, content_topic, content_audience, *content_params],
703
+ outputs=content_output
704
+ )
705
+
706
+ # Examples for content creation
707
+ gr.Examples(
708
+ [
709
+ ["blog post", "sustainable living tips", "environmentally conscious consumers", 1536, 0.8, 0.9],
710
+ ["social media post", "product launch announcement", "existing customers", 512, 0.8, 0.9],
711
+ ["marketing copy", "new fitness app", "health-focused individuals", 1024, 0.8, 0.9],
712
+ ],
713
+ fn=content_creation_handler,
714
+ inputs=[content_type, content_topic, content_audience, *content_params],
715
+ outputs=content_output,
716
+ label="Examples"
717
+ )
718
+
719
+ # Email Drafting Tab
720
+ with gr.TabItem("Email Drafting", id="tab_email"):
721
+ gr.Markdown(
722
+ """
723
+ ## ✉️ Email Drafting
724
+
725
+ Generate professional email drafts for various purposes.
726
+ """
727
+ )
728
+
729
+ with gr.Group(elem_id="email_box"):
730
+ with gr.Row(equal_height=True):
731
+ with gr.Column(scale=1):
732
+ email_type = gr.Dropdown(
733
+ ["job application", "customer support", "business proposal", "networking", "follow-up", "thank you", "meeting request"],
734
+ label="Email Type",
735
+ value="job application",
736
+ elem_id="email_type"
737
+ )
738
+ email_context = gr.Textbox(
739
+ label="Context and Details",
740
+ placeholder="Provide necessary context for the email...",
741
+ lines=5,
742
+ value="Applying for a software developer position at Tech Solutions Inc. I have 3 years of experience with Python and JavaScript.",
743
+ elem_id="email_context"
744
+ )
745
+
746
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="email_params"):
747
+ email_params = create_parameter_ui()
748
+
749
+ email_btn = gr.Button("Generate Email", variant="primary", size="lg", elem_id="email_btn")
750
+
751
+ with gr.Column(scale=1):
752
+ email_output = gr.Textbox(
753
+ label="Generated Email",
754
+ lines=20,
755
+ elem_id="email_output"
756
+ )
757
+
758
+ def email_draft_handler(email_type, context, max_length, temperature, top_p):
759
+ email_type = safe_value(email_type, "professional")
760
+ context = safe_value(context, "general communication")
761
+ prompt = generate_prompt("email_draft", email_type=email_type, context=context)
762
+ return generate_text(prompt, max_length, temperature, top_p)
763
+
764
+ email_btn.click(
765
+ email_draft_handler,
766
+ inputs=[email_type, email_context, *email_params],
767
+ outputs=email_output
768
+ )
769
+
770
+ # Examples for email drafting
771
+ gr.Examples(
772
+ [
773
+ ["job application", "Applying for a marketing specialist position at ABC Marketing. I have 5 years of experience in digital marketing.", 1024, 0.8, 0.9],
774
+ ["business proposal", "Proposing a collaboration between our companies for a joint product development effort.", 1024, 0.8, 0.9],
775
+ ["follow-up", "Following up after our meeting last Thursday about the project timeline and resources.", 1024, 0.8, 0.9],
776
+ ],
777
+ fn=email_draft_handler,
778
+ inputs=[email_type, email_context, *email_params],
779
+ outputs=email_output,
780
+ label="Examples"
781
+ )
782
+
783
+ # Document Editing Tab
784
+ with gr.TabItem("Document Editing", id="tab_edit"):
785
+ gr.Markdown(
786
+ """
787
+ ## ✂️ Document Editing
788
+
789
+ Improve the clarity, grammar, and style of your writing.
790
+ """
791
+ )
792
+
793
+ with gr.Group(elem_id="edit_box"):
794
+ with gr.Row(equal_height=True):
795
+ with gr.Column(scale=1):
796
+ edit_text = gr.Textbox(
797
+ label="Text to Edit",
798
+ placeholder="Paste your text here...",
799
+ lines=10,
800
+ 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.",
801
+ elem_id="edit_text"
802
+ )
803
+ edit_type = gr.Dropdown(
804
+ ["grammar and clarity", "conciseness", "formal tone", "casual tone", "simplification", "academic style", "persuasive style"],
805
+ label="Edit Type",
806
+ value="grammar and clarity",
807
+ elem_id="edit_type"
808
+ )
809
+
810
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="edit_params"):
811
+ edit_params = create_parameter_ui()
812
+
813
+ edit_btn = gr.Button("Edit Document", variant="primary", size="lg", elem_id="edit_btn")
814
+
815
+ with gr.Column(scale=1):
816
+ edit_output = gr.Textbox(
817
+ label="Edited Text",
818
+ lines=10,
819
+ elem_id="edit_output"
820
+ )
821
+
822
+ def document_edit_handler(text, edit_type, max_length, temperature, top_p):
823
+ text = safe_value(text, "Please provide text to edit.")
824
+ edit_type = safe_value(edit_type, "grammar and clarity")
825
+ prompt = generate_prompt("document_edit", text=text, edit_type=edit_type)
826
+ return generate_text(prompt, max_length, temperature, top_p)
827
+
828
+ edit_btn.click(
829
+ document_edit_handler,
830
+ inputs=[edit_text, edit_type, *edit_params],
831
+ outputs=edit_output
832
+ )
833
+
834
+ # Learning & Explanation Tab
835
+ with gr.TabItem("Learning & Explanation", id="tab_explain"):
836
+ gr.Markdown(
837
+ """
838
+ ## 🎓 Learning & Explanation
839
+
840
+ Get easy-to-understand explanations of complex topics.
841
+ """
842
+ )
843
+
844
+ with gr.Group(elem_id="explain_box"):
845
+ with gr.Row(equal_height=True):
846
+ with gr.Column(scale=1):
847
+ explain_topic = gr.Textbox(
848
+ label="Topic to Explain",
849
+ placeholder="What topic would you like explained?",
850
+ value="quantum computing",
851
+ elem_id="explain_topic"
852
+ )
853
+ explain_level = gr.Dropdown(
854
+ ["beginner", "child", "teenager", "college student", "professional", "expert"],
855
+ label="Audience Level",
856
+ value="beginner",
857
+ elem_id="explain_level"
858
+ )
859
+
860
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="explain_params"):
861
+ explain_params = create_parameter_ui()
862
+
863
+ explain_btn = gr.Button("Generate Explanation", variant="primary", size="lg", elem_id="explain_btn")
864
+
865
+ with gr.Column(scale=1):
866
+ explain_output = gr.Textbox(
867
+ label="Explanation",
868
+ lines=20,
869
+ elem_id="explain_output"
870
+ )
871
+
872
+ def explanation_handler(topic, level, max_length, temperature, top_p):
873
+ topic = safe_value(topic, "an interesting concept")
874
+ level = safe_value(level, "beginner")
875
+ prompt = generate_prompt("explain", topic=topic, level=level)
876
+ return generate_text(prompt, max_length, temperature, top_p)
877
+
878
+ explain_btn.click(
879
+ explanation_handler,
880
+ inputs=[explain_topic, explain_level, *explain_params],
881
+ outputs=explain_output
882
+ )
883
+
884
+ # Examples for explanation
885
+ gr.Examples(
886
+ [
887
+ ["blockchain technology", "beginner", 1024, 0.8, 0.9],
888
+ ["photosynthesis", "child", 1024, 0.8, 0.9],
889
+ ["machine learning", "college student", 1024, 0.8, 0.9],
890
+ ],
891
+ fn=explanation_handler,
892
+ inputs=[explain_topic, explain_level, *explain_params],
893
+ outputs=explain_output,
894
+ label="Examples"
895
+ )
896
+
897
+ # Classification & Categorization Tab
898
+ with gr.TabItem("Classification", id="tab_classify"):
899
+ gr.Markdown(
900
+ """
901
+ ## ���️ Classification & Categorization
902
+
903
+ Classify text into different categories or themes.
904
+ """
905
+ )
906
+
907
+ with gr.Group(elem_id="classify_box"):
908
+ with gr.Row(equal_height=True):
909
+ with gr.Column(scale=1):
910
+ classify_text = gr.Textbox(
911
+ label="Text to Classify",
912
+ placeholder="Enter the text you want to classify...",
913
+ lines=8,
914
+ value="The latest smartphone features a powerful processor, excellent camera, and impressive battery life, making it a top choice for tech enthusiasts.",
915
+ elem_id="classify_text"
916
+ )
917
+ classify_categories = gr.Textbox(
918
+ label="Categories (comma-separated)",
919
+ placeholder="List categories separated by commas...",
920
+ value="technology, health, finance, entertainment, education, sports",
921
+ elem_id="classify_categories"
922
+ )
923
+
924
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="classify_params"):
925
+ classify_params = create_parameter_ui()
926
+
927
+ classify_btn = gr.Button("Classify Text", variant="primary", size="lg", elem_id="classify_btn")
928
+
929
+ with gr.Column(scale=1):
930
+ classify_output = gr.Textbox(
931
+ label="Classification Result",
932
+ lines=5,
933
+ elem_id="classify_output"
934
+ )
935
+
936
+ def classification_handler(text, categories, max_length, temperature, top_p):
937
+ text = safe_value(text, "Please provide text to classify.")
938
+ categories = safe_value(categories, "general, specific, other")
939
+ prompt = generate_prompt("classify", text=text, categories=categories)
940
+ return generate_text(prompt, max_length, temperature, top_p)
941
+
942
+ classify_btn.click(
943
+ classification_handler,
944
+ inputs=[classify_text, classify_categories, *classify_params],
945
+ outputs=classify_output
946
+ )
947
+
948
+ # Examples for classification
949
+ gr.Examples(
950
+ [
951
+ ["The stock market saw significant gains today as tech companies reported strong quarterly earnings.", "technology, health, finance, entertainment, education, sports", 256, 0.5, 0.9],
952
+ ["The team scored in the final minutes to secure their victory in the championship game.", "technology, health, finance, entertainment, education, sports", 256, 0.5, 0.9],
953
+ ["The new educational app helps students master complex math concepts through interactive exercises.", "technology, health, finance, entertainment, education, sports", 256, 0.5, 0.9],
954
+ ],
955
+ fn=classification_handler,
956
+ inputs=[classify_text, classify_categories, *classify_params],
957
+ outputs=classify_output,
958
+ label="Examples"
959
+ )
960
+
961
+ # Data Extraction Tab
962
+ with gr.TabItem("Data Extraction", id="tab_extract"):
963
+ gr.Markdown(
964
+ """
965
+ ## 📊 Data Extraction
966
+
967
+ Extract specific data points from text.
968
+ """
969
+ )
970
+
971
+ with gr.Group(elem_id="extract_box"):
972
+ with gr.Row(equal_height=True):
973
+ with gr.Column(scale=1):
974
+ extract_text = gr.Textbox(
975
+ label="Text to Process",
976
+ placeholder="Enter the text containing data to extract...",
977
+ lines=10,
978
+ 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.",
979
+ elem_id="extract_text"
980
+ )
981
+ extract_data_points = gr.Textbox(
982
+ label="Data Points to Extract (comma-separated)",
983
+ placeholder="Specify what data to extract...",
984
+ value="name, email, phone number, birth date, company, education",
985
+ elem_id="extract_data_points"
986
+ )
987
+
988
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="extract_params"):
989
+ extract_params = create_parameter_ui()
990
+
991
+ extract_btn = gr.Button("Extract Data", variant="primary", size="lg", elem_id="extract_btn")
992
+
993
+ with gr.Column(scale=1):
994
+ extract_output = gr.Textbox(
995
+ label="Extracted Data",
996
+ lines=10,
997
+ elem_id="extract_output"
998
+ )
999
+
1000
+ def data_extraction_handler(text, data_points, max_length, temperature, top_p):
1001
+ text = safe_value(text, "Please provide text with data to extract.")
1002
+ data_points = safe_value(data_points, "key information")
1003
+ prompt = generate_prompt("data_extract", text=text, data_points=data_points)
1004
+ return generate_text(prompt, max_length, temperature, top_p)
1005
+
1006
+ extract_btn.click(
1007
+ data_extraction_handler,
1008
+ inputs=[extract_text, extract_data_points, *extract_params],
1009
+ outputs=extract_output
1010
+ )
1011
+
1012
+ # Examples for data extraction
1013
+ gr.Examples(
1014
+ [
1015
+ ["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.5, 0.9],
1016
+ ["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.5, 0.9],
1017
+ ],
1018
+ fn=data_extraction_handler,
1019
+ inputs=[extract_text, extract_data_points, *extract_params],
1020
+ outputs=extract_output,
1021
+ label="Examples"
1022
+ )
1023
+
1024
+ # Text Comprehension Tab
1025
+ with gr.TabItem("Text Comprehension", id="tab_comprehension"):
1026
+ gr.Markdown(
1027
+ """
1028
+ ## 📚 Text Comprehension
1029
+
1030
+ Test Gemma's ability to understand and process text. Try summarization, Q&A, or translation.
1031
+ """
1032
+ )
1033
+
1034
+ with gr.Tabs() as comprehension_tabs:
1035
+ # Summarization
1036
+ with gr.TabItem("Summarization", id="subtab_summarize"):
1037
+ with gr.Group(elem_id="summarize_box"):
1038
+ with gr.Row(equal_height=True):
1039
+ with gr.Column(scale=1):
1040
+ summarize_text = gr.Textbox(
1041
+ label="Text to Summarize",
1042
+ placeholder="Paste text here...",
1043
+ lines=10,
1044
+ elem_id="summarize_text"
1045
+ )
1046
+
1047
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="summarize_params"):
1048
+ summarize_params = create_parameter_ui()
1049
+
1050
+ summarize_btn = gr.Button("Summarize", variant="primary", size="lg", elem_id="summarize_btn")
1051
+
1052
+ with gr.Column(scale=1):
1053
+ summary_output = gr.Textbox(
1054
+ label="Summary",
1055
+ lines=10,
1056
+ elem_id="summary_output"
1057
+ )
1058
+
1059
+ # Question Answering
1060
+ with gr.TabItem("Question Answering", id="subtab_qa"):
1061
+ with gr.Group(elem_id="qa_box"):
1062
+ with gr.Row(equal_height=True):
1063
+ with gr.Column(scale=1):
1064
+ qa_text = gr.Textbox(
1065
+ label="Context Text",
1066
+ placeholder="Paste text here...",
1067
+ lines=10,
1068
+ elem_id="qa_text"
1069
+ )
1070
+ qa_question = gr.Textbox(
1071
+ label="Question",
1072
+ placeholder="Ask a question about the text...",
1073
+ elem_id="qa_question"
1074
+ )
1075
+
1076
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="qa_params"):
1077
+ qa_params = create_parameter_ui()
1078
+
1079
+ qa_btn = gr.Button("Answer", variant="primary", size="lg", elem_id="qa_btn")
1080
+
1081
+ with gr.Column(scale=1):
1082
+ qa_output = gr.Textbox(
1083
+ label="Answer",
1084
+ lines=10,
1085
+ elem_id="qa_output"
1086
+ )
1087
+
1088
+ # Translation
1089
+ with gr.TabItem("Translation", id="subtab_translate"):
1090
+ with gr.Group(elem_id="translate_box"):
1091
+ with gr.Row(equal_height=True):
1092
+ with gr.Column(scale=1):
1093
+ translate_text = gr.Textbox(
1094
+ label="Text to Translate",
1095
+ placeholder="Enter text to translate...",
1096
+ lines=5,
1097
+ elem_id="translate_text"
1098
+ )
1099
+ target_lang = gr.Dropdown(
1100
+ ["French", "Spanish", "German", "Japanese", "Chinese", "Russian", "Arabic", "Hindi"],
1101
+ label="Target Language",
1102
+ value="French",
1103
+ elem_id="target_lang"
1104
+ )
1105
+
1106
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="translate_params"):
1107
+ translate_params = create_parameter_ui()
1108
+
1109
+ translate_btn = gr.Button("Translate", variant="primary", size="lg", elem_id="translate_btn")
1110
+
1111
+ with gr.Column(scale=1):
1112
+ translation_output = gr.Textbox(
1113
+ label="Translation",
1114
+ lines=5,
1115
+ elem_id="translation_output"
1116
+ )
1117
+
1118
+ # Code Capabilities Tab
1119
+ with gr.TabItem("Code Capabilities", id="tab_code"):
1120
+ gr.Markdown(
1121
+ """
1122
+ ## 💻 Code Generation and Understanding
1123
+
1124
+ Test Gemma's ability to generate, explain, and debug code in various programming languages.
1125
+ """
1126
+ )
1127
+
1128
+ with gr.Tabs() as code_tabs:
1129
+ # Code Generation
1130
+ with gr.TabItem("Code Generation", id="subtab_code_gen"):
1131
+ with gr.Group(elem_id="code_gen_box"):
1132
+ with gr.Row(equal_height=True):
1133
+ with gr.Column(scale=1):
1134
+ code_language = gr.Dropdown(
1135
+ ["Python", "JavaScript", "Java", "C++", "HTML/CSS", "SQL", "Bash"],
1136
+ label="Programming Language",
1137
+ value="Python",
1138
+ elem_id="code_language"
1139
+ )
1140
+ code_task = gr.Textbox(
1141
+ label="Coding Task",
1142
+ placeholder="Describe what you want the code to do...",
1143
+ value="Create a function to find prime numbers up to n",
1144
+ elem_id="code_task"
1145
+ )
1146
+
1147
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="code_gen_params"):
1148
+ code_gen_params = create_parameter_ui()
1149
+
1150
+ code_gen_btn = gr.Button("Generate Code", variant="primary", size="lg", elem_id="code_gen_btn")
1151
+
1152
+ with gr.Column(scale=1):
1153
+ code_output = gr.Code(
1154
+ label="Generated Code",
1155
+ language="python",
1156
+ elem_id="code_output"
1157
+ )
1158
+
1159
+ def code_gen_handler(language, task, max_length, temperature, top_p):
1160
+ language = safe_value(language, "Python")
1161
+ task = safe_value(task, "write a hello world program")
1162
+ prompt = generate_prompt("code_generate", language=language, task=task)
1163
+ result = generate_text(prompt, max_length, temperature, top_p)
1164
+ return result
1165
+
1166
+ # Update language in code output component
1167
+ def update_code_language(lang):
1168
+ lang_map = {
1169
+ "Python": "python",
1170
+ "JavaScript": "javascript",
1171
+ "Java": "java",
1172
+ "C++": "cpp",
1173
+ "HTML/CSS": "html",
1174
+ "SQL": "sql",
1175
+ "Bash": "bash"
1176
+ }
1177
+ return gr.Code.update(language=lang_map.get(lang, "python"))
1178
+
1179
+ code_language.change(update_code_language, inputs=code_language, outputs=code_output)
1180
+
1181
+ code_gen_btn.click(
1182
+ code_gen_handler,
1183
+ inputs=[code_language, code_task, *code_gen_params],
1184
+ outputs=code_output
1185
+ )
1186
+
1187
+ # Code Explanation
1188
+ with gr.TabItem("Code Explanation", id="subtab_code_explain"):
1189
+ with gr.Group(elem_id="code_explain_box"):
1190
+ with gr.Row(equal_height=True):
1191
+ with gr.Column(scale=1):
1192
+ code_to_explain = gr.Code(
1193
+ label="Code to Explain",
1194
+ language="python",
1195
+ 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)",
1196
+ elem_id="code_to_explain"
1197
+ )
1198
+
1199
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="explain_code_params"):
1200
+ explain_code_params = create_parameter_ui()
1201
+
1202
+ explain_code_btn = gr.Button("Explain Code", variant="primary", size="lg", elem_id="explain_code_btn")
1203
+
1204
+ with gr.Column(scale=1):
1205
+ code_explanation = gr.Textbox(
1206
+ label="Explanation",
1207
+ lines=10,
1208
+ elem_id="code_explanation"
1209
+ )
1210
+
1211
+ def explain_code_handler(code, max_length, temperature, top_p):
1212
+ code = safe_value(code, "print('Hello, world!')")
1213
+ prompt = generate_prompt("code_explain", code=code)
1214
+ return generate_text(prompt, max_length, temperature, top_p)
1215
+
1216
+ explain_code_btn.click(
1217
+ explain_code_handler,
1218
+ inputs=[code_to_explain, *explain_code_params],
1219
+ outputs=code_explanation
1220
+ )
1221
+
1222
+ # Code Debugging
1223
+ with gr.TabItem("Code Debugging", id="subtab_code_debug"):
1224
+ with gr.Group(elem_id="code_debug_box"):
1225
+ with gr.Row(equal_height=True):
1226
+ with gr.Column(scale=1):
1227
+ code_to_debug = gr.Code(
1228
+ label="Code to Debug",
1229
+ language="python",
1230
+ 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))",
1231
+ elem_id="code_to_debug"
1232
+ )
1233
+
1234
+ with gr.Accordion("Advanced Parameters", open=False, elem_id="debug_code_params"):
1235
+ debug_code_params = create_parameter_ui()
1236
+
1237
+ debug_code_btn = gr.Button("Debug Code", variant="primary", size="lg", elem_id="debug_code_btn")
1238
+
1239
+ with gr.Column(scale=1):
1240
+ debug_result = gr.Textbox(
1241
+ label="Debugging Result",
1242
+ lines=10,
1243
+ elem_id="debug_result"
1244
+ )
1245
+
1246
+ def debug_code_handler(code, max_length, temperature, top_p):
1247
+ code = safe_value(code, "print('Hello, world!')")
1248
+ prompt = generate_prompt("code_debug", code=code)
1249
+ return generate_text(prompt, max_length, temperature, top_p)
1250
+
1251
+ debug_code_btn.click(
1252
+ debug_code_handler,
1253
+ inputs=[code_to_debug, *debug_code_params],
1254
+ outputs=debug_result
1255
+ )
1256
+
1257
+ # Footer
1258
+ with gr.Group(elem_id="footer"):
1259
+ gr.Markdown(
1260
+ """
1261
+ ## About Gemma
1262
+
1263
+ 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.
1264
+ It's designed to be efficient and accessible for various applications.
1265
+
1266
+ [Learn more about Gemma](https://huggingface.co/google/gemma-3-4b-pt)
1267
+
1268
+ <div style="text-align: center; margin-top: 20px; padding: 10px;">
1269
+ <p>© 2023 Gemma Capabilities Demo | Made with ❤️ using Gradio</p>
1270
+ </div>
1271
+ """
1272
+ )
1273
+
1274
+ # Add CSS for better styling
1275
+ demo.load(js="""
1276
+ () => {
1277
+ // Add custom CSS for better styling
1278
+ const style = document.createElement('style');
1279
+ style.textContent = `
1280
+ .tabs {
1281
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1);
1282
+ border-radius: 10px;
1283
+ overflow: hidden;
1284
+ }
1285
+
1286
+ /* Make buttons more noticeable */
1287
+ button.primary {
1288
+ transition: transform 0.2s, box-shadow 0.2s;
1289
+ }
1290
+
1291
+ button.primary:hover {
1292
+ transform: translateY(-2px);
1293
+ box-shadow: 0 4px 8px rgba(0,0,0,0.2);
1294
+ }
1295
+
1296
+ /* Add hover effect to tabs */
1297
+ .tab-nav button {
1298
+ transition: background-color 0.3s;
1299
+ }
1300
+
1301
+ /* Make textboxes more readable */
1302
+ textarea, .input-box {
1303
+ font-size: 16px !important;
1304
+ }
1305
+
1306
+ /* Improve box styling */
1307
+ .container {
1308
+ border-radius: 10px;
1309
+ overflow: hidden;
1310
+ }
1311
+ `;
1312
+ document.head.appendChild(style);
1313
+ }
1314
+ """)
1315
+
1316
+ # Load default token if available
1317
+ if DEFAULT_HF_TOKEN:
1318
+ demo.load(lambda x: authenticate(DEFAULT_HF_TOKEN), outputs=auth_status).then(
1319
+ lambda x: auth_complete(DEFAULT_HF_TOKEN), outputs=auth_status
1320
+ )
1321
+
1322
+ demo.launch(share=False)
requirements.txt CHANGED
@@ -2,4 +2,5 @@ gradio>=4.0.0
2
  torch>=2.0.0
3
  transformers>=4.34.0
4
  accelerate>=0.23.0
5
- sentencepiece>=0.1.99
 
 
2
  torch>=2.0.0
3
  transformers>=4.34.0
4
  accelerate>=0.23.0
5
+ sentencepiece>=0.1.99
6
+ bitsandbytes