0
# Utilities and Helpers
1
2
Support functions and classes for progress tracking, notifications, examples, state management, and integration with external systems to enhance Gradio application functionality.
3
4
## Capabilities
5
6
### Progress Tracking
7
8
Classes and functions for tracking progress of long-running operations with visual indicators and user feedback.
9
10
```python { .api }
11
class Progress:
12
def __init__(self, track_tqdm=False):
13
"""
14
Progress tracking for long-running iterators.
15
16
Parameters:
17
- track_tqdm: Whether to automatically track tqdm progress bars
18
"""
19
20
def __call__(self, progress, desc=None, total=None, unit="steps"):
21
"""
22
Update progress indicator.
23
24
Parameters:
25
- progress: Progress value (0-1 for percentage, or current/total)
26
- desc: Description of current operation
27
- total: Total number of steps (if not using 0-1 scale)
28
- unit: Unit name for progress display
29
"""
30
31
def tqdm(self, iterable, *args, **kwargs):
32
"""
33
Wrap iterable with progress tracking.
34
35
Parameters:
36
- iterable: Iterable to track progress for
37
- Additional tqdm arguments for customization
38
39
Returns:
40
- Progress-wrapped iterable
41
"""
42
43
def update(self, n=1):
44
"""Increment progress by n steps."""
45
46
def close(self):
47
"""Close progress indicator."""
48
```
49
50
Usage examples:
51
52
```python
53
import gradio as gr
54
import time
55
56
def long_task(progress=gr.Progress()):
57
progress(0, desc="Starting...")
58
59
for i in progress.tqdm(range(100), desc="Processing"):
60
time.sleep(0.1) # Simulate work
61
62
progress(1.0, desc="Complete!")
63
return "Task finished!"
64
65
def manual_progress(progress=gr.Progress()):
66
total_steps = 50
67
68
for i in range(total_steps):
69
# Update with fraction
70
progress(i / total_steps, desc=f"Step {i+1}/{total_steps}")
71
time.sleep(0.1)
72
73
return "Manual progress complete!"
74
75
# Use in interface
76
gr.Interface(
77
fn=long_task,
78
inputs=None,
79
outputs="text"
80
)
81
```
82
83
### Notification System
84
85
Functions for displaying user notifications including informational messages, warnings, success indicators, and error alerts.
86
87
```python { .api }
88
def Info(message):
89
"""
90
Display information notification.
91
92
Parameters:
93
- message: Information message to display
94
"""
95
96
def Warning(message):
97
"""
98
Display warning notification.
99
100
Parameters:
101
- message: Warning message to display
102
"""
103
104
def Success(message):
105
"""
106
Display success notification.
107
108
Parameters:
109
- message: Success message to display
110
"""
111
112
class Error(Exception):
113
"""
114
Gradio-specific error exception for user-facing error messages.
115
116
Parameters:
117
- message: Error message to display to user
118
"""
119
120
def __init__(self, message):
121
self.message = message
122
super().__init__(message)
123
```
124
125
Usage examples:
126
127
```python
128
import gradio as gr
129
130
def process_data(data):
131
if not data:
132
gr.Warning("No data provided, using defaults")
133
data = "default_value"
134
135
try:
136
result = complex_operation(data)
137
gr.Success("Data processed successfully!")
138
return result
139
except ValueError as e:
140
gr.Error(f"Invalid data format: {e}")
141
return None
142
except Exception as e:
143
gr.Info("Processing failed, but this is recoverable")
144
return fallback_processing(data)
145
146
def validate_input(text):
147
if len(text) < 5:
148
raise gr.Error("Input must be at least 5 characters long")
149
150
gr.Info("Input validation passed")
151
return text.upper()
152
```
153
154
### Examples Management
155
156
Class for managing and displaying example datasets with interactive selection and automatic input population.
157
158
```python { .api }
159
class Examples:
160
def __init__(
161
self,
162
examples,
163
inputs,
164
outputs=None,
165
fn=None,
166
cache_examples=None,
167
examples_per_page=10,
168
label="Examples",
169
elem_id=None,
170
run_on_click=False,
171
preprocess=True,
172
postprocess=True,
173
api_name="load_example",
174
batch=False,
175
**kwargs
176
):
177
"""
178
Example data management and display system.
179
180
Parameters:
181
- examples: List of example inputs (one per row)
182
- inputs: List of input components that examples correspond to
183
- outputs: List of output components to populate (optional)
184
- fn: Function to run when example is selected
185
- cache_examples: Whether to cache example outputs
186
- examples_per_page: Number of examples to show per page
187
- label: Label for examples section
188
- run_on_click: Whether to run function when example clicked
189
- preprocess: Whether to preprocess example data
190
- postprocess: Whether to postprocess example outputs
191
- api_name: API endpoint name for examples
192
- batch: Whether to process examples in batches
193
"""
194
195
def create(self):
196
"""Create examples component."""
197
198
def load_from_cache(self, example_id):
199
"""Load cached example result."""
200
201
def cache(self):
202
"""Cache all example results."""
203
```
204
205
Usage examples:
206
207
```python
208
import gradio as gr
209
210
def text_classifier(text):
211
# Simple sentiment classification
212
if "good" in text.lower() or "great" in text.lower():
213
return "Positive"
214
elif "bad" in text.lower() or "terrible" in text.lower():
215
return "Negative"
216
else:
217
return "Neutral"
218
219
with gr.Blocks() as demo:
220
text_input = gr.Textbox(label="Text to classify")
221
classification_output = gr.Textbox(label="Classification")
222
submit_btn = gr.Button("Classify")
223
224
# Add examples
225
examples = gr.Examples(
226
examples=[
227
["This movie is really great!"],
228
["I had a terrible experience."],
229
["The weather is okay today."],
230
["Absolutely fantastic service!"],
231
["Not good at all, very disappointing."]
232
],
233
inputs=text_input,
234
outputs=classification_output,
235
fn=text_classifier,
236
cache_examples=True,
237
run_on_click=True
238
)
239
240
submit_btn.click(text_classifier, text_input, classification_output)
241
```
242
243
### Component Update Functions
244
245
Helper functions for dynamically updating component properties and managing component state during runtime.
246
247
```python { .api }
248
def update(
249
value=None,
250
visible=None,
251
interactive=None,
252
label=None,
253
info=None,
254
elem_id=None,
255
elem_classes=None,
256
**kwargs
257
):
258
"""
259
Component property update utility for dynamic interface changes.
260
261
Parameters:
262
- value: New component value
263
- visible: Whether component should be visible
264
- interactive: Whether component should be interactive
265
- label: New component label
266
- info: New info text
267
- elem_id: New element ID
268
- elem_classes: New CSS classes
269
- Additional component-specific properties
270
271
Returns:
272
- Update dictionary for component modification
273
"""
274
275
def skip():
276
"""
277
Processing skip flag for conditional execution.
278
279
Returns:
280
- Special value indicating to skip this output
281
"""
282
```
283
284
Usage examples:
285
286
```python
287
import gradio as gr
288
289
def toggle_component(visible):
290
if visible:
291
return gr.update(visible=False, value="Hidden!")
292
else:
293
return gr.update(visible=True, value="Visible!")
294
295
def conditional_processing(input_text, should_process):
296
if not should_process:
297
return gr.skip() # Don't update output
298
299
return input_text.upper()
300
301
def dynamic_update(choice):
302
if choice == "text":
303
return gr.update(
304
label="Text Input",
305
placeholder="Enter text here...",
306
visible=True,
307
interactive=True
308
)
309
elif choice == "number":
310
return gr.update(
311
label="Number Input",
312
placeholder="Enter number...",
313
visible=True,
314
interactive=True
315
)
316
else:
317
return gr.update(visible=False)
318
319
with gr.Blocks() as demo:
320
choice = gr.Radio(["text", "number", "hidden"], label="Input Type")
321
dynamic_input = gr.Textbox(label="Dynamic Input")
322
toggle_btn = gr.Button("Toggle Visibility")
323
324
choice.change(dynamic_update, choice, dynamic_input)
325
toggle_btn.click(toggle_component, dynamic_input, dynamic_input)
326
```
327
328
### Rendering and Display Functions
329
330
Functions for component rendering, display management, and interface control.
331
332
```python { .api }
333
def render(component):
334
"""
335
Component rendering and display function.
336
337
Parameters:
338
- component: Component to render
339
340
Returns:
341
- Rendered component
342
"""
343
```
344
345
### File and Data Utilities
346
347
Utility classes and functions for handling file operations, data processing, and system integration.
348
349
```python { .api }
350
class FileSize:
351
def __init__(self, size_bytes):
352
"""
353
File size utility class with formatting.
354
355
Parameters:
356
- size_bytes: File size in bytes
357
"""
358
359
def human_readable(self):
360
"""Convert to human-readable format (KB, MB, GB)."""
361
362
def to_mb(self):
363
"""Convert to megabytes."""
364
365
def to_gb(self):
366
"""Convert to gigabytes."""
367
368
# Configuration constants
369
NO_RELOAD = object() # Flag to disable automatic reload functionality
370
IS_WASM = False # WebAssembly environment detection flag
371
372
def get_package_version():
373
"""
374
Package version retrieval utility.
375
376
Returns:
377
- Current Gradio version string
378
"""
379
380
def set_static_paths(paths):
381
"""
382
Static file path configuration for custom assets.
383
384
Parameters:
385
- paths: List of paths to serve as static files
386
"""
387
```
388
389
Usage examples:
390
391
```python
392
import gradio as gr
393
394
def file_info(file):
395
if file is None:
396
return "No file uploaded"
397
398
# Get file size
399
size = gr.FileSize(file.size)
400
401
return f"""
402
File: {file.orig_name}
403
Size: {size.human_readable()}
404
Path: {file.path}
405
"""
406
407
def check_environment():
408
version = gr.get_package_version()
409
is_wasm = gr.IS_WASM
410
411
return f"Gradio version: {version}, WASM: {is_wasm}"
412
413
# Configure static file serving
414
gr.set_static_paths(["/path/to/custom/assets"])
415
416
with gr.Blocks() as demo:
417
file_input = gr.File(label="Upload File")
418
file_info_output = gr.Textbox(label="File Information")
419
env_info_output = gr.Textbox(label="Environment")
420
421
file_input.change(file_info, file_input, file_info_output)
422
423
# Show environment info on load
424
demo.load(check_environment, outputs=env_info_output)
425
```
426
427
### State Management Utilities
428
429
Advanced state management helpers for complex applications with persistent data and session handling.
430
431
```python { .api }
432
class BrowserState:
433
def __init__(self, value=None, **kwargs):
434
"""
435
Browser-specific state management for client-side persistence.
436
437
Parameters:
438
- value: Initial state value
439
"""
440
441
def close_all():
442
"""Close all running Gradio interfaces and clean up resources."""
443
```
444
445
Usage examples:
446
447
```python
448
import gradio as gr
449
450
def increment_session_counter(count):
451
return count + 1
452
453
def reset_session_counter():
454
return 0
455
456
def save_to_browser(data):
457
# Browser state persists across page reloads
458
return data
459
460
with gr.Blocks() as demo:
461
# Session state (resets on page reload)
462
session_count = gr.State(0)
463
464
# Browser state (persists across reloads)
465
persistent_data = gr.BrowserState("")
466
467
count_display = gr.Number(label="Session Count")
468
increment_btn = gr.Button("Increment")
469
reset_btn = gr.Button("Reset")
470
471
persistent_input = gr.Textbox(label="Persistent Data")
472
save_btn = gr.Button("Save to Browser")
473
474
increment_btn.click(
475
increment_session_counter,
476
session_count,
477
[session_count, count_display]
478
)
479
480
reset_btn.click(
481
reset_session_counter,
482
outputs=[session_count, count_display]
483
)
484
485
save_btn.click(
486
save_to_browser,
487
persistent_input,
488
persistent_data
489
)
490
```
491
492
### Internationalization Support
493
494
Internationalization and localization utilities for multi-language interfaces.
495
496
```python { .api }
497
class I18n:
498
def __init__(self, locale="en", translations=None):
499
"""
500
Internationalization and localization support.
501
502
Parameters:
503
- locale: Default locale code (e.g., "en", "es", "fr")
504
- translations: Dictionary of translations
505
"""
506
507
def t(self, key, **kwargs):
508
"""
509
Translate text key with optional parameters.
510
511
Parameters:
512
- key: Translation key
513
- kwargs: Variables for string formatting
514
515
Returns:
516
- Translated string
517
"""
518
519
def set_locale(self, locale):
520
"""Change current locale."""
521
522
def load_translations(self, translations):
523
"""Load translation dictionary."""
524
```
525
526
Usage example:
527
528
```python
529
import gradio as gr
530
531
# Set up internationalization
532
i18n = gr.I18n("en", {
533
"en": {
534
"welcome": "Welcome to the app!",
535
"submit": "Submit",
536
"result": "Result: {value}"
537
},
538
"es": {
539
"welcome": "¡Bienvenido a la aplicación!",
540
"submit": "Enviar",
541
"result": "Resultado: {value}"
542
}
543
})
544
545
def process_with_i18n(text, locale):
546
i18n.set_locale(locale)
547
548
result = text.upper()
549
return i18n.t("result", value=result)
550
551
with gr.Blocks() as demo:
552
gr.Markdown(i18n.t("welcome"))
553
554
text_input = gr.Textbox()
555
locale_choice = gr.Radio(["en", "es"], value="en", label="Language")
556
submit_btn = gr.Button(i18n.t("submit"))
557
output = gr.Textbox()
558
559
submit_btn.click(process_with_i18n, [text_input, locale_choice], output)
560
```
561
562
## Integration Utilities
563
564
### Development and Debugging
565
566
Tools for development, debugging, and development environment integration.
567
568
```python { .api }
569
def load_ipython_extension(ipython):
570
"""
571
Jupyter notebook integration for IPython environments.
572
573
Parameters:
574
- ipython: IPython instance for magic command registration
575
"""
576
```
577
578
Usage in Jupyter notebooks:
579
580
```python
581
# Load Gradio IPython extension
582
%load_ext gradio
583
584
# Use Gradio magic commands
585
%%gradio
586
def my_function(x):
587
return x * 2
588
589
gr.Interface(my_function, "number", "number")
590
```
591
592
### Performance Optimization
593
594
Utilities for optimizing performance and resource usage in production environments.
595
596
```python
597
# Disable auto-reload for production
598
demo = gr.Blocks()
599
demo.queue(default_concurrency_limit=10)
600
601
# Configure static file caching
602
gr.set_static_paths(["/static"], cache_headers=True)
603
604
# Use NO_RELOAD flag
605
if gr.NO_RELOAD:
606
# Production configuration
607
demo.launch(server_name="0.0.0.0", server_port=7860)
608
else:
609
# Development configuration
610
demo.launch(share=True, debug=True)
611
```