broadfield-dev commited on
Commit
8eceaa6
·
verified ·
1 Parent(s): 14140d0

Create component_events.py

Browse files
Files changed (1) hide show
  1. component_events.py +1204 -0
component_events.py ADDED
@@ -0,0 +1,1204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains all of the events that can be triggered in a gr.Blocks() app, with the exception
2
+ of the on-page-load event, which is defined in gr.Blocks().load()."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import dataclasses
7
+ from collections.abc import Callable, Sequence, Set
8
+ from functools import partial, wraps
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Literal,
13
+ Union,
14
+ cast,
15
+ )
16
+
17
+ from gradio_client.documentation import document
18
+ from jinja2 import Template
19
+
20
+ from gradio.data_classes import FileData, FileDataDict
21
+
22
+ if TYPE_CHECKING:
23
+ from gradio.blocks import Block, BlockContext, Component
24
+ from gradio.components import Timer
25
+
26
+ from gradio_client.utils import python_type_to_json_schema
27
+
28
+ from gradio.context import get_blocks_context
29
+ from gradio.utils import get_cancelled_fn_indices, get_function_params, get_return_types
30
+
31
+
32
+ def set_cancel_events(
33
+ triggers: Sequence[EventListenerMethod],
34
+ cancels: None | dict[str, Any] | list[dict[str, Any]],
35
+ ):
36
+ if not cancels:
37
+ return
38
+
39
+ root_block = get_blocks_context()
40
+ if root_block is None:
41
+ raise AttributeError("Cannot cancel outside of a gradio.Blocks context.")
42
+
43
+ if not isinstance(cancels, list):
44
+ cancels = [cancels]
45
+
46
+ regular_cancels: list[dict[str, Any]] = []
47
+ timers_to_cancel: list[Component] = []
48
+ for cancel in cancels:
49
+ associated_timer = getattr(cancel, "associated_timer", None)
50
+ if associated_timer:
51
+ timers_to_cancel.append(associated_timer)
52
+ else:
53
+ regular_cancels.append(cancel)
54
+
55
+ if timers_to_cancel:
56
+ from gradio.components import Timer
57
+
58
+ root_block.set_event_trigger(
59
+ triggers,
60
+ fn=lambda: (
61
+ [Timer(active=False) for _ in timers_to_cancel]
62
+ if len(timers_to_cancel) > 1
63
+ else Timer(active=False)
64
+ ),
65
+ inputs=None,
66
+ outputs=timers_to_cancel,
67
+ show_api=False,
68
+ )
69
+
70
+ if regular_cancels:
71
+ fn_indices_to_cancel = get_cancelled_fn_indices(regular_cancels)
72
+ root_block.set_event_trigger(
73
+ triggers,
74
+ fn=None,
75
+ inputs=None,
76
+ outputs=None,
77
+ queue=False,
78
+ preprocess=False,
79
+ show_api=False,
80
+ cancels=fn_indices_to_cancel,
81
+ is_cancel_function=True,
82
+ )
83
+
84
+
85
+ @document()
86
+ class Dependency(dict):
87
+ def __init__(
88
+ self, trigger, key_vals, dep_index, fn, associated_timer: Timer | None = None
89
+ ):
90
+ """
91
+ The Dependency object is usualy not created directly but is returned when an event listener is set up. It contains the configuration
92
+ data for the event listener, and can be used to set up additional event listeners that depend on the completion of the current event
93
+ listener using .then() and .success().
94
+
95
+ Demos: chatbot_consecutive, blocks_chained_events
96
+ """
97
+
98
+ super().__init__(key_vals)
99
+ self.fn = fn
100
+ self.associated_timer = associated_timer
101
+ self.then = partial(
102
+ EventListener(
103
+ "then",
104
+ trigger_after=dep_index,
105
+ trigger_only_on_success=False,
106
+ has_trigger=False,
107
+ ).listener,
108
+ trigger,
109
+ )
110
+ """
111
+ Triggered after directly preceding event is completed, regardless of success or failure.
112
+ """
113
+ self.success = partial(
114
+ EventListener(
115
+ "success",
116
+ trigger_after=dep_index,
117
+ trigger_only_on_success=True,
118
+ has_trigger=False,
119
+ ).listener,
120
+ trigger,
121
+ )
122
+ """
123
+ Triggered after directly preceding event is completed, if it was successful.
124
+ """
125
+
126
+ def __call__(self, *args, **kwargs):
127
+ return self.fn(*args, **kwargs)
128
+
129
+
130
+ @document()
131
+ class EventData:
132
+ """
133
+ When gr.EventData or one of its subclasses is added as a type hint to an argument of a prediction function, a gr.EventData object will automatically be passed as the value of that argument.
134
+ The attributes of this object contains information about the event that triggered the listener. The gr.EventData object itself contains a `.target` attribute that refers to the component
135
+ that triggered the event, while subclasses of gr.EventData contains additional attributes that are different for each class.
136
+
137
+ Example:
138
+ import gradio as gr
139
+ with gr.Blocks() as demo:
140
+ table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])
141
+ gallery = gr.Gallery([("cat.jpg", "Cat"), ("dog.jpg", "Dog")])
142
+ textbox = gr.Textbox("Hello World!")
143
+ statement = gr.Textbox()
144
+ def on_select(value, evt: gr.EventData):
145
+ return f"The {evt.target} component was selected, and its value was {value}."
146
+ table.select(on_select, table, statement)
147
+ gallery.select(on_select, gallery, statement)
148
+ textbox.select(on_select, textbox, statement)
149
+ demo.launch()
150
+ Demos: gallery_selections, tictactoe
151
+ """
152
+
153
+ def __init__(self, target: Block | None, _data: Any):
154
+ """
155
+ Parameters:
156
+ target: The component object that triggered the event. Can be used to distinguish multiple components bound to the same listener.
157
+ """
158
+ self.target = target
159
+ self._data = _data
160
+
161
+
162
+ @document()
163
+ class SelectData(EventData):
164
+ """
165
+ The gr.SelectData class is a subclass of gr.EventData that specifically carries information about the `.select()` event. When gr.SelectData
166
+ is added as a type hint to an argument of an event listener method, a gr.SelectData object will automatically be passed as the value of that argument.
167
+ The attributes of this object contains information about the event that triggered the listener.
168
+
169
+ Example:
170
+ import gradio as gr
171
+ with gr.Blocks() as demo:
172
+ table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])
173
+ gallery = gr.Gallery([("cat.jpg", "Cat"), ("dog.jpg", "Dog")])
174
+ textbox = gr.Textbox("Hello World!")
175
+ statement = gr.Textbox()
176
+ def on_select(evt: gr.SelectData):
177
+ return f"You selected {evt.value} at {evt.index} from {evt.target}"
178
+ table.select(on_select, table, statement)
179
+ gallery.select(on_select, gallery, statement)
180
+ textbox.select(on_select, textbox, statement)
181
+ demo.launch()
182
+ Demos: gallery_selections, tictactoe
183
+ """
184
+
185
+ def __init__(self, target: Block | None, data: Any):
186
+ super().__init__(target, data)
187
+ self.index: Any = data["index"]
188
+ """
189
+ The index of the selected item. Is a tuple if the component is two dimensional or selection is a range.
190
+ """
191
+ self.value: Any = data["value"]
192
+ """
193
+ The value of the selected item.
194
+ """
195
+ self.row_value: Any = data.get("row_value")
196
+ """
197
+ The value of the entire row that the selected item belongs to, as a 1-D list. Only implemented for the `Dataframe` component, returns None for other components.
198
+ """
199
+ self.col_value: Any = data.get("col_value")
200
+ """
201
+ The value of the entire row that the selected item belongs to, as a 1-D list. Only implemented for the `Dataframe` component, returns None for other components.
202
+ """
203
+ self.selected: bool = data.get("selected", True)
204
+ """
205
+ True if the item was selected, False if deselected.
206
+ """
207
+
208
+
209
+ @document()
210
+ class KeyUpData(EventData):
211
+ """
212
+ The gr.KeyUpData class is a subclass of gr.EventData that specifically carries information about the `.key_up()` event. When gr.KeyUpData
213
+ is added as a type hint to an argument of an event listener method, a gr.KeyUpData object will automatically be passed as the value of that argument.
214
+ The attributes of this object contains information about the event that triggered the listener.
215
+
216
+ Example:
217
+ import gradio as gr
218
+ def test(value, key_up_data: gr.KeyUpData):
219
+ return {
220
+ "component value": value,
221
+ "input value": key_up_data.input_value,
222
+ "key": key_up_data.key
223
+ }
224
+ with gr.Blocks() as demo:
225
+ d = gr.Dropdown(["abc", "def"], allow_custom_value=True)
226
+ t = gr.JSON()
227
+ d.key_up(test, d, t)
228
+ demo.launch()
229
+ Demos: dropdown_key_up
230
+ """
231
+
232
+ def __init__(self, target: Block | None, data: Any):
233
+ super().__init__(target, data)
234
+ self.key: str = data["key"]
235
+ """
236
+ The key that was pressed.
237
+ """
238
+ self.input_value: str = data["input_value"]
239
+ """
240
+ The displayed value in the input textbox after the key was pressed. This may be different than the `value`
241
+ attribute of the component itself, as the `value` attribute of some components (e.g. Dropdown) are not updated
242
+ until the user presses Enter.
243
+ """
244
+
245
+
246
+ @document()
247
+ class DeletedFileData(EventData):
248
+ """
249
+ The gr.DeletedFileData class is a subclass of gr.EventData that specifically carries information about the `.delete()` event. When gr.DeletedFileData
250
+ is added as a type hint to an argument of an event listener method, a gr.DeletedFileData object will automatically be passed as the value of that argument.
251
+ The attributes of this object contains information about the event that triggered the listener.
252
+ Example:
253
+ import gradio as gr
254
+ def test(delete_data: gr.DeletedFileData):
255
+ return delete_data.file.path
256
+ with gr.Blocks() as demo:
257
+ files = gr.File(file_count="multiple")
258
+ deleted_file = gr.File()
259
+ files.delete(test, None, deleted_file)
260
+ demo.launch()
261
+ Demos: file_component_events
262
+ """
263
+
264
+ def __init__(self, target: Block | None, data: FileDataDict):
265
+ super().__init__(target, data)
266
+ self.file: FileData = FileData(**data) # type: ignore
267
+ """
268
+ The file that was deleted, as a FileData object.
269
+ """
270
+
271
+
272
+ @document()
273
+ class LikeData(EventData):
274
+ """
275
+ The gr.LikeData class is a subclass of gr.EventData that specifically carries information about the `.like()` event. When gr.LikeData
276
+ is added as a type hint to an argument of an event listener method, a gr.LikeData object will automatically be passed as the value of that argument.
277
+ The attributes of this object contains information about the event that triggered the listener.
278
+ Example:
279
+ import gradio as gr
280
+ def test(value, like_data: gr.LikeData):
281
+ return {
282
+ "chatbot_value": value,
283
+ "liked_message": like_data.value,
284
+ "liked_index": like_data.index,
285
+ "liked_or_disliked": like_data.liked
286
+ }
287
+ with gr.Blocks() as demo:
288
+ c = gr.Chatbot([("abc", "def")])
289
+ t = gr.JSON()
290
+ c.like(test, c, t)
291
+ demo.launch()
292
+ Demos: chatbot_core_components_simple
293
+ """
294
+
295
+ def __init__(self, target: Block | None, data: Any):
296
+ super().__init__(target, data)
297
+ self.index: int | tuple[int, int] = data["index"]
298
+ """
299
+ The index of the liked/disliked item. Is a tuple if the component is two dimensional.
300
+ """
301
+ self.value: Any = data["value"]
302
+ """
303
+ The value of the liked/disliked item.
304
+ """
305
+ self.liked: bool | str = data.get("liked", True)
306
+ """
307
+ True if the item was liked, False if disliked, or string value if any other feedback.
308
+ """
309
+
310
+
311
+ @document()
312
+ class RetryData(EventData):
313
+ """
314
+ The gr.RetryData class is a subclass of gr.Event data that specifically carries information about the `.retry()` event. When gr.RetryData
315
+ is added as a type hint to an argument of an event listener method, a gr.RetryData object will automatically be passed as the value of that argument.
316
+ The attributes of this object contains information about the event that triggered the listener.
317
+ Example:
318
+ import gradio as gr
319
+
320
+ def retry(retry_data: gr.RetryData, history: list[gr.MessageDict]):
321
+ history_up_to_retry = history[:retry_data.index]
322
+ new_response = ""
323
+ for token in api.chat_completion(history):
324
+ new_response += token
325
+ yield history + [new_response]
326
+
327
+ with gr.Blocks() as demo:
328
+ chatbot = gr.Chatbot()
329
+ chatbot.retry(retry, chatbot, chatbot)
330
+ demo.launch()
331
+ """
332
+
333
+ def __init__(self, target: Block | None, data: Any):
334
+ super().__init__(target, data)
335
+ self.index: int | tuple[int, int] = data["index"]
336
+ """
337
+ The index of the user message that should be retried.
338
+ """
339
+ self.value: Any = data["value"]
340
+ """
341
+ The value of the user message that should be retried.
342
+ """
343
+
344
+
345
+ @document()
346
+ class UndoData(EventData):
347
+ """
348
+ The gr.UndoData class is a subclass of gr.Event data that specifically carries information about the `.undo()` event. When gr.UndoData
349
+ is added as a type hint to an argument of an event listener method, a gr.UndoData object will automatically be passed as the value of that argument.
350
+ The attributes of this object contains information about the event that triggered the listener.
351
+ Example:
352
+ import gradio as gr
353
+
354
+ def undo(retry_data: gr.UndoData, history: list[gr.MessageDict]):
355
+ history_up_to_retry = history[:retry_data.index]
356
+ return history_up_to_retry
357
+
358
+ with gr.Blocks() as demo:
359
+ chatbot = gr.Chatbot()
360
+ chatbot.undo(undo, chatbot, chatbot)
361
+ demo.launch()
362
+ """
363
+
364
+ def __init__(self, target: Block | None, data: Any):
365
+ super().__init__(target, data)
366
+ self.index: int | tuple[int, int] = data["index"]
367
+ """
368
+ The index of the user message that should be undone.
369
+ """
370
+ self.value: Any = data["value"]
371
+ """
372
+ The value of the user message that should be undone.
373
+ """
374
+
375
+
376
+ @document()
377
+ class EditData(EventData):
378
+ """
379
+ The gr.EditData class is a subclass of gr.Event data that specifically carries information about the `.edit()` event. When gr.EditData
380
+ is added as a type hint to an argument of an event listener method, a gr.EditData object will automatically be passed as the value of that argument.
381
+ The attributes of this object contains information about the event that triggered the listener.
382
+ Example:
383
+ import gradio as gr
384
+
385
+ def edit(edit_data: gr.EditData, history: list[gr.MessageDict]):
386
+ history_up_to_edit = history[:edit_data.index]
387
+ history_up_to_edit[-1] = edit_data.value
388
+ return history_up_to_edit
389
+
390
+ with gr.Blocks() as demo:
391
+ chatbot = gr.Chatbot()
392
+ chatbot.undo(edit, chatbot, chatbot)
393
+ demo.launch()
394
+ """
395
+
396
+ def __init__(self, target: Block | None, data: Any):
397
+ super().__init__(target, data)
398
+ self.index: int | tuple[int, int] = data["index"]
399
+ """
400
+ The index of the message that was edited.
401
+ """
402
+ self.previous_value: Any = data["previous_value"]
403
+ """
404
+ The previous content of the message that was edited.
405
+ """
406
+ self.value: Any = data["value"]
407
+ """
408
+ The new content of the message that was edited.
409
+ """
410
+
411
+
412
+ @document()
413
+ class DownloadData(EventData):
414
+ """
415
+ The gr.DownloadData class is a subclass of gr.EventData that specifically carries information about the `.download()` event. When gr.DownloadData
416
+ is added as a type hint to an argument of an event listener method, a gr.DownloadData object will automatically be passed as the value of that argument.
417
+ The attributes of this object contains information about the event that triggered the listener.
418
+ Example:
419
+ import gradio as gr
420
+ def on_download(download_data: gr.DownloadData):
421
+ return f"Downloaded file: {download_data.file.path}"
422
+ with gr.Blocks() as demo:
423
+ files = gr.File()
424
+ textbox = gr.Textbox()
425
+ files.download(on_download, None, textbox)
426
+ demo.launch()
427
+ """
428
+
429
+ def __init__(self, target: Block | None, data: FileDataDict):
430
+ super().__init__(target, data)
431
+ self.file: FileData = FileData(**data) # type: ignore
432
+ """
433
+ The file that was downloaded, as a FileData object.
434
+ """
435
+
436
+
437
+ @document()
438
+ class CopyData(EventData):
439
+ """
440
+ The gr.CopyData class is a subclass of gr.EventData that specifically carries information about the `.copy()` event. When gr.CopyData
441
+ is added as a type hint to an argument of an event listener method, a gr.CopyData object will automatically be passed as the value of that argument.
442
+ The attributes of this object contains information about the event that triggered the listener.
443
+ Example:
444
+ import gradio as gr
445
+ def on_copy(copy_data: gr.CopyData):
446
+ return f"Copied text: {copy_data.value}"
447
+ with gr.Blocks() as demo:
448
+ textbox = gr.Textbox("Hello World!")
449
+ copied = gr.Textbox()
450
+ textbox.copy(on_copy, None, copied)
451
+ demo.launch()
452
+ """
453
+
454
+ def __init__(self, target: Block | None, data: Any):
455
+ super().__init__(target, data)
456
+ self.value: Any = data["value"]
457
+ """
458
+ The value that was copied.
459
+ """
460
+
461
+
462
+ @dataclasses.dataclass
463
+ class EventListenerMethod:
464
+ block: Block | None
465
+ event_name: str
466
+
467
+
468
+ if TYPE_CHECKING:
469
+ EventListenerCallable = Callable[
470
+ [
471
+ Union[Callable[..., Any], None],
472
+ Union[Component, Sequence[Component], None],
473
+ Union[Block, Sequence[Block], Sequence[Component], Component, None],
474
+ Union[str, None, Literal[False]],
475
+ bool,
476
+ Literal["full", "minimal", "hidden"],
477
+ Union[Component, Sequence[Component], None],
478
+ Union[bool, None],
479
+ bool,
480
+ int,
481
+ bool,
482
+ bool,
483
+ Union[dict[str, Any], list[dict[str, Any]], None],
484
+ Union[float, None],
485
+ Union[Literal["once", "multiple", "always_last"], None],
486
+ Union[str, None],
487
+ Union[int, None, Literal["default"]],
488
+ Union[str, None],
489
+ bool,
490
+ ],
491
+ Dependency,
492
+ ]
493
+
494
+
495
+ class EventListener(str):
496
+ def __new__(cls, event_name, *_args, **_kwargs):
497
+ return super().__new__(cls, event_name)
498
+
499
+ def __init__(
500
+ self,
501
+ event_name: str,
502
+ has_trigger: bool = True,
503
+ config_data: Callable[..., dict[str, Any]] = lambda: {},
504
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
505
+ callback: Callable | None = None,
506
+ trigger_after: int | None = None,
507
+ trigger_only_on_success: bool = False,
508
+ doc: str = "",
509
+ connection: Literal["sse", "stream"] = "sse",
510
+ event_specific_args: list[dict[str, str]] | None = None,
511
+ ):
512
+ super().__init__()
513
+ self.has_trigger = has_trigger
514
+ self.config_data = config_data
515
+ self.event_name = event_name
516
+ self.show_progress = show_progress
517
+ self.trigger_after = trigger_after
518
+ self.trigger_only_on_success = trigger_only_on_success
519
+ self.callback = callback
520
+ self.doc = doc
521
+ self.connection = connection
522
+ self.event_specific_args = event_specific_args or []
523
+ self.listener = self._setup(
524
+ event_name,
525
+ has_trigger,
526
+ show_progress,
527
+ callback,
528
+ trigger_after,
529
+ trigger_only_on_success,
530
+ self.event_specific_args,
531
+ self.connection,
532
+ )
533
+ if doc and self.listener.__doc__:
534
+ self.listener.__doc__ = doc + self.listener.__doc__
535
+
536
+ def set_doc(self, component: str):
537
+ if self.listener.__doc__:
538
+ doc = Template(self.listener.__doc__).render(component=component)
539
+ self.listener.__doc__ = doc
540
+
541
+ def copy(self):
542
+ return EventListener(
543
+ self.event_name,
544
+ self.has_trigger,
545
+ self.config_data,
546
+ self.show_progress, # type: ignore
547
+ self.callback,
548
+ self.trigger_after,
549
+ self.trigger_only_on_success,
550
+ self.doc,
551
+ self.connection, # type: ignore
552
+ self.event_specific_args,
553
+ )
554
+
555
+ @staticmethod
556
+ def _setup(
557
+ _event_name: str,
558
+ _has_trigger: bool,
559
+ _show_progress: Literal["full", "minimal", "hidden"],
560
+ _callback: Callable | None,
561
+ _trigger_after: int | None,
562
+ _trigger_only_on_success: bool,
563
+ _event_specific_args: list[dict[str, str]],
564
+ _connection: Literal["sse", "stream"] = "sse",
565
+ ):
566
+ def event_trigger(
567
+ block: Block | None,
568
+ fn: Callable | None | Literal["decorator"] = "decorator",
569
+ inputs: Component
570
+ | BlockContext
571
+ | Sequence[Component | BlockContext]
572
+ | Set[Component | BlockContext]
573
+ | None = None,
574
+ outputs: Component
575
+ | BlockContext
576
+ | Sequence[Component | BlockContext]
577
+ | Set[Component | BlockContext]
578
+ | None = None,
579
+ api_name: str | None | Literal[False] = None,
580
+ scroll_to_output: bool = False,
581
+ show_progress: Literal["full", "minimal", "hidden"] = _show_progress,
582
+ show_progress_on: Component | Sequence[Component] | None = None,
583
+ queue: bool = True,
584
+ batch: bool = False,
585
+ max_batch_size: int = 4,
586
+ preprocess: bool = True,
587
+ postprocess: bool = True,
588
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
589
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
590
+ js: str | Literal[True] | None = None,
591
+ concurrency_limit: int | None | Literal["default"] = "default",
592
+ concurrency_id: str | None = None,
593
+ show_api: bool = True,
594
+ time_limit: int | None = None,
595
+ stream_every: float = 0.5,
596
+ like_user_message: bool = False,
597
+ key: int | str | tuple[int | str, ...] | None = None,
598
+ ) -> Dependency:
599
+ """
600
+ Parameters:
601
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
602
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
603
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
604
+ api_name: defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event.
605
+ scroll_to_output: If True, will scroll to output component on completion
606
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
607
+ show_progress_on: Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components.
608
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
609
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
610
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
611
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
612
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
613
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
614
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
615
+ js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
616
+ concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
617
+ concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
618
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
619
+ key: A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical.
620
+ """
621
+
622
+ if fn == "decorator":
623
+
624
+ def wrapper(func):
625
+ event_trigger(
626
+ block=block,
627
+ fn=func,
628
+ inputs=inputs,
629
+ outputs=outputs,
630
+ api_name=api_name,
631
+ scroll_to_output=scroll_to_output,
632
+ show_progress=show_progress,
633
+ show_progress_on=show_progress_on,
634
+ queue=queue,
635
+ batch=batch,
636
+ max_batch_size=max_batch_size,
637
+ preprocess=preprocess,
638
+ postprocess=postprocess,
639
+ cancels=cancels,
640
+ trigger_mode=trigger_mode,
641
+ js=js,
642
+ concurrency_limit=concurrency_limit,
643
+ concurrency_id=concurrency_id,
644
+ show_api=show_api,
645
+ key=key,
646
+ )
647
+
648
+ @wraps(func)
649
+ def inner(*args, **kwargs):
650
+ return func(*args, **kwargs)
651
+
652
+ return inner
653
+
654
+ return Dependency(None, {}, None, wrapper)
655
+
656
+ from gradio.components.base import StreamingInput
657
+
658
+ if isinstance(block, StreamingInput) and "stream" in block.events:
659
+ block.check_streamable() # type: ignore
660
+ if isinstance(show_progress, bool):
661
+ show_progress = "full" if show_progress else "hidden"
662
+
663
+ root_block = get_blocks_context()
664
+ if root_block is None:
665
+ raise AttributeError(
666
+ f"Cannot call {_event_name} outside of a gradio.Blocks context."
667
+ )
668
+
669
+ event_target = EventListenerMethod(
670
+ block if _has_trigger else None, _event_name
671
+ )
672
+
673
+ dep, dep_index = root_block.set_event_trigger(
674
+ [event_target],
675
+ fn,
676
+ inputs,
677
+ outputs,
678
+ preprocess=preprocess,
679
+ postprocess=postprocess,
680
+ scroll_to_output=scroll_to_output,
681
+ show_progress=show_progress,
682
+ show_progress_on=show_progress_on,
683
+ api_name=api_name,
684
+ js=js,
685
+ concurrency_limit=concurrency_limit,
686
+ concurrency_id=concurrency_id,
687
+ queue=queue,
688
+ batch=batch,
689
+ max_batch_size=max_batch_size,
690
+ trigger_after=_trigger_after,
691
+ trigger_only_on_success=_trigger_only_on_success,
692
+ trigger_mode=trigger_mode,
693
+ show_api=show_api,
694
+ connection=_connection,
695
+ time_limit=time_limit,
696
+ stream_every=stream_every,
697
+ like_user_message=like_user_message,
698
+ event_specific_args=[
699
+ d["name"]
700
+ for d in _event_specific_args
701
+ if d.get("component_prop", "true") != "false"
702
+ ]
703
+ if _event_specific_args
704
+ else None,
705
+ key=key,
706
+ )
707
+ set_cancel_events(
708
+ [event_target],
709
+ cancels,
710
+ )
711
+ if _callback:
712
+ _callback(block)
713
+ return Dependency(block, dep.get_config(), dep_index, fn)
714
+
715
+ event_trigger.event_name = _event_name # type: ignore
716
+ event_trigger.has_trigger = _has_trigger # type: ignore
717
+ event_trigger.callback = _callback # type: ignore
718
+ event_trigger.connection = _connection # type: ignore
719
+ event_specific_args = (
720
+ [
721
+ d["name"]
722
+ for d in _event_specific_args
723
+ if d.get("component_prop", "true") != "false"
724
+ ]
725
+ if _event_specific_args
726
+ else None
727
+ )
728
+ event_trigger.event_specific_args = event_specific_args # type: ignore
729
+ return event_trigger
730
+
731
+
732
+ @document()
733
+ def on(
734
+ triggers: Sequence[EventListenerCallable] | EventListenerCallable | None = None,
735
+ fn: Callable[..., Any] | None | Literal["decorator"] = "decorator",
736
+ inputs: Component
737
+ | BlockContext
738
+ | Sequence[Component | BlockContext]
739
+ | Set[Component | BlockContext]
740
+ | None = None,
741
+ outputs: Component
742
+ | BlockContext
743
+ | Sequence[Component | BlockContext]
744
+ | Set[Component | BlockContext]
745
+ | None = None,
746
+ *,
747
+ api_name: str | None | Literal[False] = None,
748
+ scroll_to_output: bool = False,
749
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
750
+ show_progress_on: Component | Sequence[Component] | None = None,
751
+ queue: bool = True,
752
+ batch: bool = False,
753
+ max_batch_size: int = 4,
754
+ preprocess: bool = True,
755
+ postprocess: bool = True,
756
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
757
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
758
+ js: str | Literal[True] | None = None,
759
+ concurrency_limit: int | None | Literal["default"] = "default",
760
+ concurrency_id: str | None = None,
761
+ show_api: bool = True,
762
+ time_limit: int | None = None,
763
+ stream_every: float = 0.5,
764
+ key: int | str | tuple[int | str, ...] | None = None,
765
+ ) -> Dependency:
766
+ """
767
+ Sets up an event listener that triggers a function when the specified event(s) occur. This is especially
768
+ useful when the same function should be triggered by multiple events. Only a single API endpoint is generated
769
+ for all events in the triggers list.
770
+
771
+ Parameters:
772
+ triggers: List of triggers to listen to, e.g. [btn.click, number.change]. If None, will run on app load and changes to any inputs.
773
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
774
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
775
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
776
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
777
+ scroll_to_output: If True, will scroll to output component on completion
778
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all,
779
+ show_progress_on: Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components.
780
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
781
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
782
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
783
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
784
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
785
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
786
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
787
+ js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs', return should be a list of values for output components.
788
+ concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
789
+ concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
790
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
791
+ time_limit: The time limit for the function to run. Parameter only used for the `.stream()` event.
792
+ stream_every: The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.
793
+ Example:
794
+ import gradio as gr
795
+ with gr.Blocks() as demo:
796
+ with gr.Row():
797
+ input = gr.Textbox()
798
+ button = gr.Button("Submit")
799
+ output = gr.Textbox()
800
+ gr.on(
801
+ triggers=[button.click, input.submit],
802
+ fn=lambda x: x,
803
+ inputs=[input],
804
+ outputs=[output]
805
+ )
806
+ demo.launch()
807
+ """
808
+ from gradio.blocks import Block
809
+
810
+ if not isinstance(triggers, Sequence) and triggers is not None:
811
+ triggers = [triggers]
812
+ triggers_typed = cast(Sequence[EventListener], triggers)
813
+
814
+ if isinstance(inputs, Block):
815
+ inputs = [inputs]
816
+
817
+ if fn == "decorator":
818
+
819
+ def wrapper(func):
820
+ on(
821
+ triggers,
822
+ fn=func,
823
+ inputs=inputs,
824
+ outputs=outputs,
825
+ api_name=api_name,
826
+ scroll_to_output=scroll_to_output,
827
+ show_progress=show_progress,
828
+ show_progress_on=show_progress_on,
829
+ queue=queue,
830
+ batch=batch,
831
+ max_batch_size=max_batch_size,
832
+ preprocess=preprocess,
833
+ postprocess=postprocess,
834
+ cancels=cancels,
835
+ js=js,
836
+ concurrency_limit=concurrency_limit,
837
+ concurrency_id=concurrency_id,
838
+ show_api=show_api,
839
+ trigger_mode=trigger_mode,
840
+ time_limit=time_limit,
841
+ stream_every=stream_every,
842
+ key=key,
843
+ )
844
+
845
+ @wraps(func)
846
+ def inner(*args, **kwargs):
847
+ return func(*args, **kwargs)
848
+
849
+ return inner
850
+
851
+ return Dependency(None, {}, None, wrapper)
852
+
853
+ root_block = get_blocks_context()
854
+ if root_block is None:
855
+ raise Exception("Cannot call on() outside of a gradio.Blocks context.")
856
+ if triggers is None:
857
+ methods = (
858
+ [EventListenerMethod(input, "change") for input in inputs]
859
+ if inputs is not None
860
+ else []
861
+ ) + [EventListenerMethod(root_block, "load")] # type: ignore
862
+ else:
863
+ methods = [
864
+ EventListenerMethod(t.__self__ if t.has_trigger else None, t.event_name) # type: ignore
865
+ for t in triggers_typed
866
+ ]
867
+ if triggers:
868
+ for trigger in triggers:
869
+ if trigger.callback: # type: ignore
870
+ trigger.callback(trigger.__self__) # type: ignore
871
+
872
+ dep, dep_index = root_block.set_event_trigger(
873
+ methods,
874
+ fn,
875
+ inputs,
876
+ outputs,
877
+ preprocess=preprocess,
878
+ postprocess=postprocess,
879
+ scroll_to_output=scroll_to_output,
880
+ show_progress=show_progress,
881
+ show_progress_on=show_progress_on,
882
+ api_name=api_name,
883
+ js=js,
884
+ concurrency_limit=concurrency_limit,
885
+ concurrency_id=concurrency_id,
886
+ queue=queue,
887
+ batch=batch,
888
+ max_batch_size=max_batch_size,
889
+ show_api=show_api,
890
+ trigger_mode=trigger_mode,
891
+ connection="stream"
892
+ if any(t.connection == "stream" for t in (triggers_typed or []))
893
+ else "sse",
894
+ event_specific_args=[
895
+ a
896
+ for t in (triggers_typed or [])
897
+ for a in cast(list[str], t.event_specific_args or [])
898
+ ],
899
+ time_limit=time_limit,
900
+ stream_every=stream_every,
901
+ key=key,
902
+ )
903
+ set_cancel_events(methods, cancels)
904
+ return Dependency(None, dep.get_config(), dep_index, fn)
905
+
906
+
907
+ @document()
908
+ def api(
909
+ fn: Callable | Literal["decorator"] = "decorator",
910
+ *,
911
+ api_name: str | None | Literal[False] = None,
912
+ queue: bool = True,
913
+ batch: bool = False,
914
+ max_batch_size: int = 4,
915
+ concurrency_limit: int | None | Literal["default"] = "default",
916
+ concurrency_id: str | None = None,
917
+ show_api: bool = True,
918
+ time_limit: int | None = None,
919
+ stream_every: float = 0.5,
920
+ ) -> Dependency:
921
+ """
922
+ Sets up an API or MCP endpoint for a generic function without needing define events listeners or components. Derives its typing from type hints in the provided function's signature rather than the components.
923
+
924
+ Parameters:
925
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. The function should be fully typed, and the type hints will be used to derive the typing information for the API/MCP endpoint.
926
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
927
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
928
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
929
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
930
+ concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
931
+ concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
932
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
933
+ time_limit: The time limit for the function to run. Parameter only used for the `.stream()` event.
934
+ stream_every: The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.
935
+ Example:
936
+ import gradio as gr
937
+ with gr.Blocks() as demo:
938
+ with gr.Row():
939
+ input = gr.Textbox()
940
+ button = gr.Button("Submit")
941
+ output = gr.Textbox()
942
+ def fn(a: int, b: int, c: list[str]) -> tuple[int, str]:
943
+ return a + b, c[a:b]
944
+ gr.api(fn, api_name="add_and_slice")
945
+ _, url, _ = demo.launch()
946
+
947
+ from gradio_client import Client
948
+ client = Client(url)
949
+ result = client.predict(
950
+ a=3,
951
+ b=5,
952
+ c=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
953
+ api_name="/add_and_slice"
954
+ )
955
+ print(result)
956
+ """
957
+ if fn == "decorator":
958
+
959
+ def wrapper(func):
960
+ api(
961
+ fn=func,
962
+ api_name=api_name,
963
+ queue=queue,
964
+ batch=batch,
965
+ max_batch_size=max_batch_size,
966
+ concurrency_limit=concurrency_limit,
967
+ concurrency_id=concurrency_id,
968
+ show_api=show_api,
969
+ time_limit=time_limit,
970
+ stream_every=stream_every,
971
+ )
972
+
973
+ @wraps(func)
974
+ def inner(*args, **kwargs):
975
+ return func(*args, **kwargs)
976
+
977
+ return inner
978
+
979
+ return Dependency(None, {}, None, wrapper)
980
+
981
+ root_block = get_blocks_context()
982
+ if root_block is None:
983
+ raise Exception("Cannot call api() outside of a gradio.Blocks context.")
984
+
985
+ from gradio.components.api_component import Api
986
+
987
+ fn_params = get_function_params(fn)
988
+ return_types = get_return_types(fn)
989
+
990
+ def ordinal(n):
991
+ return f"{n}{'th' if 10 <= n % 100 <= 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')}"
992
+
993
+ if any(param[3] is None for param in fn_params):
994
+ raise ValueError(
995
+ "API endpoints must have type hints. Please specify a type hint for all parameters."
996
+ )
997
+ inputs = [
998
+ Api(
999
+ default_value if has_default else None,
1000
+ python_type_to_json_schema(_type),
1001
+ ordinal(i + 1),
1002
+ )
1003
+ for i, (_, has_default, default_value, _type) in enumerate(fn_params)
1004
+ ]
1005
+ outputs = [
1006
+ Api(None, python_type_to_json_schema(type), ordinal(i + 1))
1007
+ for i, type in enumerate(return_types)
1008
+ ]
1009
+
1010
+ dep, dep_index = root_block.set_event_trigger(
1011
+ [],
1012
+ fn,
1013
+ inputs,
1014
+ outputs,
1015
+ preprocess=False,
1016
+ postprocess=False,
1017
+ scroll_to_output=False,
1018
+ show_progress="hidden",
1019
+ api_name=api_name,
1020
+ js=None,
1021
+ concurrency_limit=concurrency_limit,
1022
+ concurrency_id=concurrency_id,
1023
+ queue=queue,
1024
+ batch=batch,
1025
+ max_batch_size=max_batch_size,
1026
+ show_api=show_api,
1027
+ trigger_mode=None,
1028
+ time_limit=time_limit,
1029
+ stream_every=stream_every,
1030
+ )
1031
+ return Dependency(None, dep.get_config(), dep_index, fn)
1032
+
1033
+
1034
+ class Events:
1035
+ change = EventListener(
1036
+ "change",
1037
+ doc="Triggered when the value of the {{ component }} changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.",
1038
+ )
1039
+ input = EventListener(
1040
+ "input",
1041
+ doc="This listener is triggered when the user changes the value of the {{ component }}.",
1042
+ )
1043
+ click = EventListener("click", doc="Triggered when the {{ component }} is clicked.")
1044
+ double_click = EventListener(
1045
+ "double_click", doc="Triggered when the {{ component }} is double clicked."
1046
+ )
1047
+ submit = EventListener(
1048
+ "submit",
1049
+ doc="This listener is triggered when the user presses the Enter key while the {{ component }} is focused.",
1050
+ )
1051
+ stop = EventListener(
1052
+ "stop",
1053
+ doc="This listener is triggered when the user clicks on the stop button or icon.",
1054
+ )
1055
+ edit = EventListener(
1056
+ "edit",
1057
+ doc="This listener is triggered when the user edits the {{ component }} (e.g. image) using the built-in editor.",
1058
+ callback=lambda block: setattr(block, "editable", "user")
1059
+ if getattr(block, "editable", None) is None
1060
+ else None,
1061
+ )
1062
+ clear = EventListener(
1063
+ "clear",
1064
+ doc="This listener is triggered when the user clears the {{ component }} using the clear button for the component.",
1065
+ )
1066
+ play = EventListener(
1067
+ "play",
1068
+ doc="This listener is triggered when the user plays the media in the {{ component }}.",
1069
+ )
1070
+ pause = EventListener(
1071
+ "pause",
1072
+ doc="This listener is triggered when the media in the {{ component }} stops for any reason.",
1073
+ )
1074
+ stop = EventListener(
1075
+ "stop",
1076
+ doc="This listener is triggered when the user reaches the end of the media playing in the {{ component }}.",
1077
+ )
1078
+ end = EventListener(
1079
+ "end",
1080
+ doc="This listener is triggered when the user reaches the end of the media playing in the {{ component }}.",
1081
+ )
1082
+ start_recording = EventListener(
1083
+ "start_recording",
1084
+ doc="This listener is triggered when the user starts recording with the {{ component }}.",
1085
+ )
1086
+ pause_recording = EventListener(
1087
+ "pause_recording",
1088
+ doc="This listener is triggered when the user pauses recording with the {{ component }}.",
1089
+ )
1090
+ stop_recording = EventListener(
1091
+ "stop_recording",
1092
+ doc="This listener is triggered when the user stops recording with the {{ component }}.",
1093
+ )
1094
+ focus = EventListener(
1095
+ "focus", doc="This listener is triggered when the {{ component }} is focused."
1096
+ )
1097
+ blur = EventListener(
1098
+ "blur",
1099
+ doc="This listener is triggered when the {{ component }} is unfocused/blurred.",
1100
+ )
1101
+ upload = EventListener(
1102
+ "upload",
1103
+ doc="This listener is triggered when the user uploads a file into the {{ component }}.",
1104
+ )
1105
+ release = EventListener(
1106
+ "release",
1107
+ doc="This listener is triggered when the user releases the mouse on this {{ component }}.",
1108
+ )
1109
+ select = EventListener(
1110
+ "select",
1111
+ callback=lambda block: setattr(block, "_selectable", True),
1112
+ doc="Event listener for when the user selects or deselects the {{ component }}. Uses event data gradio.SelectData to carry `value` referring to the label of the {{ component }}, and `selected` to refer to state of the {{ component }}. See EventData documentation on how to use this event data",
1113
+ )
1114
+ stream = EventListener(
1115
+ "stream",
1116
+ config_data=lambda: {"streamable": False},
1117
+ callback=lambda block: setattr(block, "streaming", True),
1118
+ doc="This listener is triggered when the user streams the {{ component }}.",
1119
+ connection="stream",
1120
+ show_progress="minimal",
1121
+ event_specific_args=[
1122
+ {
1123
+ "name": "stream_every",
1124
+ "type": "float = 0.5",
1125
+ "doc": "The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.",
1126
+ },
1127
+ {
1128
+ "name": "time_limit",
1129
+ "type": "float | None = None",
1130
+ "doc": "The time limit for the function to run. Parameter only used for the `.stream()` event.",
1131
+ "component_prop": "false",
1132
+ },
1133
+ ],
1134
+ )
1135
+ like = EventListener(
1136
+ "like",
1137
+ config_data=lambda: {"likeable": False},
1138
+ callback=lambda block: setattr(block, "likeable", True),
1139
+ event_specific_args=[
1140
+ {
1141
+ "name": "like_user_message",
1142
+ "type": "bool = False",
1143
+ "doc": "Whether to display the like buttons for user messages in the chatbot.",
1144
+ }
1145
+ ],
1146
+ doc="This listener is triggered when the user likes/dislikes from within the {{ component }}. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.",
1147
+ )
1148
+ example_select = EventListener(
1149
+ "example_select",
1150
+ doc="This listener is triggered when the user clicks on an example from within the {{ component }}. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.",
1151
+ )
1152
+ option_select = EventListener(
1153
+ "option_select",
1154
+ doc="This listener is triggered when the user clicks on an option from within the {{ component }}. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.",
1155
+ )
1156
+ load = EventListener(
1157
+ "load",
1158
+ doc="This listener is triggered when the {{ component }} initially loads in the browser.",
1159
+ )
1160
+ key_up = EventListener(
1161
+ "key_up",
1162
+ doc="This listener is triggered when the user presses a key while the {{ component }} is focused.",
1163
+ )
1164
+ apply = EventListener(
1165
+ "apply",
1166
+ doc="This listener is triggered when the user applies changes to the {{ component }} through an integrated UI action.",
1167
+ )
1168
+ delete = EventListener(
1169
+ "delete",
1170
+ doc="This listener is triggered when the user deletes and item from the {{ component }}. Uses event data gradio.DeletedFileData to carry `value` referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event data",
1171
+ )
1172
+ tick = EventListener(
1173
+ "tick",
1174
+ doc="This listener is triggered at regular intervals defined by the {{ component }}.",
1175
+ show_progress="hidden",
1176
+ )
1177
+ undo = EventListener(
1178
+ "undo",
1179
+ doc="This listener is triggered when the user clicks the undo button in the chatbot message.",
1180
+ callback=lambda block: setattr(block, "_undoable", True),
1181
+ config_data=lambda: {"_undoable": False},
1182
+ )
1183
+ retry = EventListener(
1184
+ "retry",
1185
+ doc="This listener is triggered when the user clicks the retry button in the chatbot message.",
1186
+ callback=lambda block: setattr(block, "_retryable", True),
1187
+ config_data=lambda: {"_retryable": False},
1188
+ )
1189
+ expand = EventListener(
1190
+ "expand",
1191
+ doc="This listener is triggered when the {{ component }} is expanded.",
1192
+ )
1193
+ collapse = EventListener(
1194
+ "collapse",
1195
+ doc="This listener is triggered when the {{ component }} is collapsed.",
1196
+ )
1197
+ download = EventListener(
1198
+ "download",
1199
+ doc="This listener is triggered when the user downloads a file from the {{ component }}. Uses event data gradio.DownloadData to carry information about the downloaded file as a FileData object. See EventData documentation on how to use this event data",
1200
+ )
1201
+ copy = EventListener(
1202
+ "copy",
1203
+ doc="This listener is triggered when the user copies content from the {{ component }}. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data",
1204
+ )