/
blocks.py
2354 lines (2135 loc) 路 99.9 KB
/
blocks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import copy
import hashlib
import inspect
import json
import os
import random
import secrets
import string
import sys
import tempfile
import threading
import time
import warnings
import webbrowser
from collections import defaultdict
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Literal, Sequence, cast
from urllib.parse import urlparse, urlunparse
import anyio
import httpx
from anyio import CapacityLimiter
from gradio_client import utils as client_utils
from gradio_client.documentation import document, set_documentation_group
from gradio import (
analytics,
components,
networking,
processing_utils,
queueing,
routes,
strings,
themes,
utils,
wasm_utils,
)
from gradio.blocks_events import BlocksEvents, BlocksMeta
from gradio.context import Context
from gradio.data_classes import FileData, GradioModel, GradioRootModel
from gradio.events import (
EventData,
EventListener,
EventListenerMethod,
)
from gradio.exceptions import (
DuplicateBlockError,
InvalidApiNameError,
InvalidBlockError,
InvalidComponentError,
)
from gradio.helpers import create_tracker, skip, special_args
from gradio.state_holder import SessionState
from gradio.themes import Default as DefaultTheme
from gradio.themes import ThemeClass as Theme
from gradio.tunneling import (
BINARY_FILENAME,
BINARY_FOLDER,
BINARY_PATH,
BINARY_URL,
CURRENT_TUNNELS,
)
from gradio.utils import (
TupleNoPrint,
check_function_inputs_match,
component_or_layout_class,
get_cancel_function,
get_continuous_fn,
get_package_version,
)
try:
import spaces # type: ignore
except Exception:
spaces = None
set_documentation_group("blocks")
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
from fastapi.applications import FastAPI
from gradio.components.base import Component
BUILT_IN_THEMES: dict[str, Theme] = {
t.name: t
for t in [
themes.Base(),
themes.Default(),
themes.Monochrome(),
themes.Soft(),
themes.Glass(),
]
}
class Block:
def __init__(
self,
*,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
render: bool = True,
visible: bool = True,
proxy_url: str | None = None,
):
self._id = Context.id
Context.id += 1
self.visible = visible
self.elem_id = elem_id
self.elem_classes = (
[elem_classes] if isinstance(elem_classes, str) else elem_classes
)
self.proxy_url = proxy_url
self.share_token = secrets.token_urlsafe(32)
self.parent: BlockContext | None = None
self.is_rendered: bool = False
self._constructor_args: list[dict]
self.state_session_capacity = 10000
self.temp_files: set[str] = set()
self.GRADIO_CACHE = str(
Path(
os.environ.get("GRADIO_TEMP_DIR")
or str(Path(tempfile.gettempdir()) / "gradio")
).resolve()
)
if render:
self.render()
@property
def skip_api(self):
return False
@property
def constructor_args(self) -> dict[str, Any]:
"""Get the arguments passed to the component's initializer.
Only set classes whose metaclass is ComponentMeta
"""
# the _constructor_args list is appended based on the mro of the class
# so the first entry is for the bottom of the hierarchy
return self._constructor_args[0] if self._constructor_args else {}
@property
def events(
self,
) -> list[EventListener]:
return getattr(self, "EVENTS", [])
def render(self):
"""
Adds self into appropriate BlockContext
"""
if Context.root_block is not None and self._id in Context.root_block.blocks:
raise DuplicateBlockError(
f"A block with id: {self._id} has already been rendered in the current Blocks."
)
if Context.block is not None:
Context.block.add(self)
if Context.root_block is not None:
Context.root_block.blocks[self._id] = self
self.is_rendered = True
if isinstance(self, components.Component):
Context.root_block.temp_file_sets.append(self.temp_files)
return self
def unrender(self):
"""
Removes self from BlockContext if it has been rendered (otherwise does nothing).
Removes self from the layout and collection of blocks, but does not delete any event triggers.
"""
if Context.block is not None:
try:
Context.block.children.remove(self)
except ValueError:
pass
if Context.root_block is not None:
try:
del Context.root_block.blocks[self._id]
self.is_rendered = False
except KeyError:
pass
return self
def get_block_name(self) -> str:
"""
Gets block's class name.
If it is template component it gets the parent's class name.
@return: class name
"""
return (
self.__class__.__base__.__name__.lower()
if hasattr(self, "is_template")
else self.__class__.__name__.lower()
)
def get_expected_parent(self) -> type[BlockContext] | None:
return None
def get_config(self):
config = {}
signature = inspect.signature(self.__class__.__init__)
for parameter in signature.parameters.values():
if hasattr(self, parameter.name):
value = getattr(self, parameter.name)
config[parameter.name] = utils.convert_to_dict_if_dataclass(value)
for e in self.events:
to_add = e.config_data()
if to_add:
config = {**to_add, **config}
config.pop("render", None)
config = {**config, "proxy_url": self.proxy_url, "name": self.get_block_name()}
if (_selectable := getattr(self, "_selectable", None)) is not None:
config["_selectable"] = _selectable
return config
@classmethod
def recover_kwargs(
cls, props: dict[str, Any], additional_keys: list[str] | None = None
):
"""
Recovers kwargs from a dict of props.
"""
additional_keys = additional_keys or []
signature = inspect.signature(cls.__init__)
kwargs = {}
for parameter in signature.parameters.values():
if parameter.name in props and parameter.name not in additional_keys:
kwargs[parameter.name] = props[parameter.name]
return kwargs
def move_resource_to_block_cache(
self, url_or_file_path: str | Path | None
) -> str | None:
"""Moves a file or downloads a file from a url to a block's cache directory, adds
to to the block's temp_files, and returns the path to the file in cache. This
ensures that the file is accessible to the Block and can be served to users.
"""
if url_or_file_path is None:
return None
if isinstance(url_or_file_path, Path):
url_or_file_path = str(url_or_file_path)
if client_utils.is_http_url_like(url_or_file_path):
temp_file_path = processing_utils.save_url_to_cache(
url_or_file_path, cache_dir=self.GRADIO_CACHE
)
self.temp_files.add(temp_file_path)
else:
url_or_file_path = str(utils.abspath(url_or_file_path))
if not utils.is_in_or_equal(url_or_file_path, self.GRADIO_CACHE):
temp_file_path = processing_utils.save_file_to_cache(
url_or_file_path, cache_dir=self.GRADIO_CACHE
)
else:
temp_file_path = url_or_file_path
self.temp_files.add(temp_file_path)
return temp_file_path
class BlockContext(Block):
def __init__(
self,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
visible: bool = True,
render: bool = True,
):
"""
Parameters:
elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
elem_classes: An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.
visible: If False, this will be hidden but included in the Blocks config file (its visibility can later be updated).
render: If False, this will not be included in the Blocks config file at all.
"""
self.children: list[Block] = []
Block.__init__(
self,
elem_id=elem_id,
elem_classes=elem_classes,
visible=visible,
render=render,
)
TEMPLATE_DIR = "./templates/"
FRONTEND_DIR = "../../frontend/"
@property
def skip_api(self):
return True
@classmethod
def get_component_class_id(cls) -> str:
module_name = cls.__module__
module_path = sys.modules[module_name].__file__
module_hash = hashlib.md5(f"{cls.__name__}_{module_path}".encode()).hexdigest()
return module_hash
@property
def component_class_id(self):
return self.get_component_class_id()
def add_child(self, child: Block):
self.children.append(child)
def __enter__(self):
self.parent = Context.block
Context.block = self
return self
def add(self, child: Block):
child.parent = self
self.children.append(child)
def fill_expected_parents(self):
children = []
pseudo_parent = None
for child in self.children:
expected_parent = child.get_expected_parent()
if not expected_parent or isinstance(self, expected_parent):
pseudo_parent = None
children.append(child)
else:
if pseudo_parent is not None and isinstance(
pseudo_parent, expected_parent
):
pseudo_parent.add_child(child)
else:
pseudo_parent = expected_parent(render=False)
pseudo_parent.parent = self
children.append(pseudo_parent)
pseudo_parent.add_child(child)
if Context.root_block:
Context.root_block.blocks[pseudo_parent._id] = pseudo_parent
child.parent = pseudo_parent
self.children = children
def __exit__(self, exc_type: type[BaseException] | None = None, *args):
Context.block = self.parent
if exc_type is not None:
return
if getattr(self, "allow_expected_parents", True):
self.fill_expected_parents()
def postprocess(self, y):
"""
Any postprocessing needed to be performed on a block context.
"""
return y
class BlockFunction:
def __init__(
self,
fn: Callable | None,
inputs: list[Component],
outputs: list[Component],
preprocess: bool,
postprocess: bool,
inputs_as_dict: bool,
batch: bool = False,
max_batch_size: int = 4,
concurrency_limit: int | None | Literal["default"] = "default",
concurrency_id: str | None = None,
tracks_progress: bool = False,
):
self.fn = fn
self.inputs = inputs
self.outputs = outputs
self.preprocess = preprocess
self.postprocess = postprocess
self.tracks_progress = tracks_progress
self.concurrency_limit: int | None | Literal["default"] = concurrency_limit
self.concurrency_id = concurrency_id or str(id(fn))
self.batch = batch
self.max_batch_size = max_batch_size
self.total_runtime = 0
self.total_runs = 0
self.inputs_as_dict = inputs_as_dict
self.name = getattr(fn, "__name__", "fn") if fn is not None else None
self.spaces_auto_wrap()
def spaces_auto_wrap(self):
if spaces is None:
return
if utils.get_space() is None:
return
self.fn = spaces.gradio_auto_wrap(self.fn)
def __str__(self):
return str(
{
"fn": self.name,
"preprocess": self.preprocess,
"postprocess": self.postprocess,
}
)
def __repr__(self):
return str(self)
def postprocess_update_dict(
block: Component | BlockContext, update_dict: dict, postprocess: bool = True
):
"""
Converts a dictionary of updates into a format that can be sent to the frontend to update the component.
E.g. {"value": "2", "visible": True, "invalid_arg": "hello"}
Into -> {"__type__": "update", "value": 2.0, "visible": True}
Parameters:
block: The Block that is being updated with this update dictionary.
update_dict: The original update dictionary
postprocess: Whether to postprocess the "value" key of the update dictionary.
"""
value = update_dict.pop("value", components._Keywords.NO_VALUE)
update_dict = {k: getattr(block, k) for k in update_dict if hasattr(block, k)}
if value is not components._Keywords.NO_VALUE:
if postprocess:
update_dict["value"] = block.postprocess(value)
if isinstance(update_dict["value"], (GradioModel, GradioRootModel)):
update_dict["value"] = update_dict["value"].model_dump()
else:
update_dict["value"] = value
update_dict["__type__"] = "update"
return update_dict
def convert_component_dict_to_list(
outputs_ids: list[int], predictions: dict
) -> list | dict:
"""
Converts a dictionary of component updates into a list of updates in the order of
the outputs_ids and including every output component. Leaves other types of dictionaries unchanged.
E.g. {"textbox": "hello", "number": {"__type__": "generic_update", "value": "2"}}
Into -> ["hello", {"__type__": "generic_update"}, {"__type__": "generic_update", "value": "2"}]
"""
keys_are_blocks = [isinstance(key, Block) for key in predictions]
if all(keys_are_blocks):
reordered_predictions = [skip() for _ in outputs_ids]
for component, value in predictions.items():
if component._id not in outputs_ids:
raise ValueError(
f"Returned component {component} not specified as output of function."
)
output_index = outputs_ids.index(component._id)
reordered_predictions[output_index] = value
predictions = utils.resolve_singleton(reordered_predictions)
elif any(keys_are_blocks):
raise ValueError(
"Returned dictionary included some keys as Components. Either all keys must be Components to assign Component values, or return a List of values to assign output values in order."
)
return predictions
@document("launch", "queue", "integrate", "load")
class Blocks(BlockContext, BlocksEvents, metaclass=BlocksMeta):
"""
Blocks is Gradio's low-level API that allows you to create more custom web
applications and demos than Interfaces (yet still entirely in Python).
Compared to the Interface class, Blocks offers more flexibility and control over:
(1) the layout of components (2) the events that
trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs,
which can trigger the next level of outputs). Blocks also offers ways to group
together related demos such as with tabs.
The basic usage of Blocks is as follows: create a Blocks object, then use it as a
context (with the "with" statement), and then define layouts, components, or events
within the Blocks context. Finally, call the launch() method to launch the demo.
Example:
import gradio as gr
def update(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown("Start typing below and then click **Run** to see the output.")
with gr.Row():
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
btn = gr.Button("Run")
btn.click(fn=update, inputs=inp, outputs=out)
demo.launch()
Demos: blocks_hello, blocks_flipper, blocks_speech_text_sentiment, generate_english_german
Guides: blocks-and-event-listeners, controlling-layout, state-in-blocks, custom-CSS-and-JS, using-blocks-like-functions
"""
def __init__(
self,
theme: Theme | str | None = None,
analytics_enabled: bool | None = None,
mode: str = "blocks",
title: str = "Gradio",
css: str | None = None,
js: str | None = None,
head: str | None = None,
**kwargs,
):
"""
Parameters:
theme: A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
mode: A human-friendly name for the kind of Blocks or Interface being created. Used internally for analytics.
title: The tab title to display when this is opened in a browser window.
css: Custom css as a string or path to a css file. This css will be included in the demo webpage.
js: Custom js or path to js file to run when demo is first loaded. This javascript will be included in the demo webpage.
head: Custom html to insert into the head of the demo webpage. This can be used to add custom meta tags, scripts, stylesheets, etc. to the page.
"""
self.limiter = None
if theme is None:
theme = DefaultTheme()
elif isinstance(theme, str):
if theme.lower() in BUILT_IN_THEMES:
theme = BUILT_IN_THEMES[theme.lower()]
else:
try:
theme = Theme.from_hub(theme)
except Exception as e:
warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
theme = DefaultTheme()
if not isinstance(theme, Theme):
warnings.warn("Theme should be a class loaded from gradio.themes")
theme = DefaultTheme()
self.theme: Theme = theme
self.theme_css = theme._get_theme_css()
self.stylesheets = theme._stylesheets
self.encrypt = False
self.share = False
self.enable_queue = True
self.max_threads = 40
self.pending_streams = defaultdict(dict)
self.show_error = True
self.head = head
if css is not None and os.path.exists(css):
with open(css) as css_file:
self.css = css_file.read()
else:
self.css = css
if js is not None and os.path.exists(js):
with open(js) as js_file:
self.js = js_file.read()
else:
self.js = js
# For analytics_enabled and allow_flagging: (1) first check for
# parameter, (2) check for env variable, (3) default to True/"manual"
self.analytics_enabled = (
analytics_enabled
if analytics_enabled is not None
else analytics.analytics_enabled()
)
if self.analytics_enabled:
if not wasm_utils.IS_WASM:
t = threading.Thread(target=analytics.version_check)
t.start()
else:
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "True"
super().__init__(render=False, **kwargs)
self.blocks: dict[int, Component | Block] = {}
self.fns: list[BlockFunction] = []
self.dependencies = []
self.mode = mode
self.is_running = False
self.local_url = None
self.share_url = None
self.width = None
self.height = None
self.api_open = utils.get_space() is None
self.space_id = utils.get_space()
self.favicon_path = None
self.auth = None
self.dev_mode = bool(os.getenv("GRADIO_WATCH_DIRS", False))
self.app_id = random.getrandbits(64)
self.temp_file_sets = []
self.title = title
self.show_api = not wasm_utils.IS_WASM
# Only used when an Interface is loaded from a config
self.predict = None
self.input_components = None
self.output_components = None
self.__name__ = None
self.api_mode = None
self.progress_tracking = None
self.ssl_verify = True
self.allowed_paths = []
self.blocked_paths = []
self.root_path = os.environ.get("GRADIO_ROOT_PATH", "")
self.proxy_urls = set()
if self.analytics_enabled:
is_custom_theme = not any(
self.theme.to_dict() == built_in_theme.to_dict()
for built_in_theme in BUILT_IN_THEMES.values()
)
data = {
"mode": self.mode,
"custom_css": self.css is not None,
"theme": self.theme.name,
"is_custom_theme": is_custom_theme,
"version": get_package_version(),
}
analytics.initiated_analytics(data)
self.queue()
def get_component(self, id: int) -> Component | BlockContext:
comp = self.blocks[id]
assert isinstance(comp, (components.Component, BlockContext)), f"{comp}"
return comp
@property
def _is_running_in_reload_thread(self):
from gradio.cli.commands.reload import reload_thread
return getattr(reload_thread, "running_reload", False)
@classmethod
def from_config(
cls,
config: dict,
fns: list[Callable],
proxy_url: str,
) -> Blocks:
"""
Factory method that creates a Blocks from a config and list of functions. Used
internally by the gradio.external.load() method.
Parameters:
config: a dictionary containing the configuration of the Blocks.
fns: a list of functions that are used in the Blocks. Must be in the same order as the dependencies in the config.
proxy_url: an external url to use as a root URL when serving files for components in the Blocks.
"""
config = copy.deepcopy(config)
components_config = config["components"]
theme = config.get("theme", "default")
original_mapping: dict[int, Block] = {}
proxy_urls = {proxy_url}
def get_block_instance(id: int) -> Block:
for block_config in components_config:
if block_config["id"] == id:
break
else:
raise ValueError(f"Cannot find block with id {id}")
cls = component_or_layout_class(block_config["type"])
# If a Gradio app B is loaded into a Gradio app A, and B itself loads a
# Gradio app C, then the proxy_urls of the components in A need to be the
# URL of C, not B. The else clause below handles this case.
if block_config["props"].get("proxy_url") is None:
block_config["props"]["proxy_url"] = f"{proxy_url}/"
postprocessed_value = block_config["props"].pop("value", None)
constructor_args = cls.recover_kwargs(block_config["props"])
block = cls(**constructor_args)
if postprocessed_value is not None:
block.value = postprocessed_value # type: ignore
block_proxy_url = block_config["props"]["proxy_url"]
block.proxy_url = block_proxy_url
proxy_urls.add(block_proxy_url)
if (
_selectable := block_config["props"].pop("_selectable", None)
) is not None:
block._selectable = _selectable # type: ignore
return block
def iterate_over_children(children_list):
for child_config in children_list:
id = child_config["id"]
block = get_block_instance(id)
original_mapping[id] = block
children = child_config.get("children")
if children is not None:
if not isinstance(block, BlockContext):
raise ValueError(
f"Invalid config, Block with id {id} has children but is not a BlockContext."
)
with block:
iterate_over_children(children)
derived_fields = ["types"]
with Blocks(theme=theme) as blocks:
# ID 0 should be the root Blocks component
original_mapping[0] = Context.root_block or blocks
iterate_over_children(config["layout"]["children"])
first_dependency = None
# add the event triggers
for dependency, fn in zip(config["dependencies"], fns):
# We used to add a "fake_event" to the config to cache examples
# without removing it. This was causing bugs in calling gr.load
# We fixed the issue by removing "fake_event" from the config in examples.py
# but we still need to skip these events when loading the config to support
# older demos
if "trigger" in dependency and dependency["trigger"] == "fake_event":
continue
for field in derived_fields:
dependency.pop(field, None)
# older versions had a separate trigger field, but now it is part of the
# targets field
_targets = dependency.pop("targets")
trigger = dependency.pop("trigger", None)
targets = [
getattr(
original_mapping[
target if isinstance(target, int) else target[0]
],
trigger if isinstance(target, int) else target[1],
)
for target in _targets
]
dependency.pop("backend_fn")
dependency.pop("documentation", None)
dependency["inputs"] = [
original_mapping[i] for i in dependency["inputs"]
]
dependency["outputs"] = [
original_mapping[o] for o in dependency["outputs"]
]
dependency.pop("status_tracker", None)
dependency["preprocess"] = False
dependency["postprocess"] = False
targets = [
EventListenerMethod(
t.__self__ if t.has_trigger else None, t.event_name
)
for t in targets
]
dependency = blocks.set_event_trigger(
targets=targets, fn=fn, **dependency
)[0]
if first_dependency is None:
first_dependency = dependency
# Allows some use of Interface-specific methods with loaded Spaces
if first_dependency and Context.root_block:
blocks.predict = [fns[0]]
blocks.input_components = [
Context.root_block.blocks[i] for i in first_dependency["inputs"]
]
blocks.output_components = [
Context.root_block.blocks[o] for o in first_dependency["outputs"]
]
blocks.__name__ = "Interface"
blocks.api_mode = True
blocks.proxy_urls = proxy_urls
return blocks
def __str__(self):
return self.__repr__()
def __repr__(self):
num_backend_fns = len([d for d in self.dependencies if d["backend_fn"]])
repr = f"Gradio Blocks instance: {num_backend_fns} backend functions"
repr += f"\n{'-' * len(repr)}"
for d, dependency in enumerate(self.dependencies):
if dependency["backend_fn"]:
repr += f"\nfn_index={d}"
repr += "\n inputs:"
for input_id in dependency["inputs"]:
block = self.blocks[input_id]
repr += f"\n |-{block}"
repr += "\n outputs:"
for output_id in dependency["outputs"]:
block = self.blocks[output_id]
repr += f"\n |-{block}"
return repr
@property
def expects_oauth(self):
"""Return whether the app expects user to authenticate via OAuth."""
return any(
isinstance(block, (components.LoginButton, components.LogoutButton))
for block in self.blocks.values()
)
def set_event_trigger(
self,
targets: Sequence[EventListenerMethod],
fn: Callable | None,
inputs: Component | list[Component] | set[Component] | None,
outputs: Component | list[Component] | None,
preprocess: bool = True,
postprocess: bool = True,
scroll_to_output: bool = False,
show_progress: Literal["full", "minimal", "hidden"] = "full",
api_name: str | None | Literal[False] = None,
js: str | None = None,
no_target: bool = False,
queue: bool | None = None,
batch: bool = False,
max_batch_size: int = 4,
cancels: list[int] | None = None,
every: float | None = None,
collects_event_data: bool | None = None,
trigger_after: int | None = None,
trigger_only_on_success: bool = False,
trigger_mode: Literal["once", "multiple", "always_last"] | None = "once",
concurrency_limit: int | None | Literal["default"] = "default",
concurrency_id: str | None = None,
show_api: bool = True,
) -> tuple[dict[str, Any], int]:
"""
Adds an event to the component's dependencies.
Parameters:
targets: a list of EventListenerMethod objects that define the event trigger
fn: Callable function
inputs: input list
outputs: output list
preprocess: whether to run the preprocess methods of components
postprocess: whether to run the postprocess methods of components
scroll_to_output: whether to scroll to output of dependency on trigger
show_progress: whether to show progress animation while running.
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.
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
no_target: if True, sets "targets" to [], used for Blocks "load" event
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.
batch: whether this function takes in a batch of inputs
max_batch_size: the maximum batch size to send to the function
cancels: a list of other events to cancel when this event 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.
every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
collects_event_data: whether to collect event data for this event
trigger_after: if set, this event will be triggered after 'trigger_after' function index
trigger_only_on_success: if True, this event will only be triggered if the previous event was successful (only applies if `trigger_after` is set)
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()` event) would allow a second submission after the pending event is complete.
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 `queue()`, which itself is 1 by default).
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.
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 to use this event. If fn is None, show_api will automatically be set to False.
Returns: dependency information, dependency index
"""
# Support for singular parameter
_targets = [
(
target.block._id if target.block and not no_target else None,
target.event_name,
)
for target in targets
]
if isinstance(inputs, set):
inputs_as_dict = True
inputs = sorted(inputs, key=lambda x: x._id)
else:
inputs_as_dict = False
if inputs is None:
inputs = []
elif not isinstance(inputs, list):
inputs = [inputs]
if isinstance(outputs, set):
outputs = sorted(outputs, key=lambda x: x._id)
else:
if outputs is None:
outputs = []
elif not isinstance(outputs, list):
outputs = [outputs]
if fn is not None and not cancels:
check_function_inputs_match(fn, inputs, inputs_as_dict)
if every is not None and every <= 0:
raise ValueError("Parameter every must be positive or None")
if every and batch:
raise ValueError(
f"Cannot run event in a batch and every {every} seconds. "
"Either batch is True or every is non-zero but not both."
)
if every and fn:
fn = get_continuous_fn(fn, every)
elif every:
raise ValueError("Cannot set a value for `every` without a `fn`.")
if every and concurrency_limit is not None:
if concurrency_limit == "default":
concurrency_limit = None
else:
raise ValueError(
"Cannot set a value for `concurrency_limit` with `every`."
)
if _targets[0][1] == "change" and trigger_mode is None:
trigger_mode = "always_last"
elif trigger_mode is None:
trigger_mode = "once"
elif trigger_mode not in ["once", "multiple", "always_last"]:
raise ValueError(
f"Invalid value for parameter `trigger_mode`: {trigger_mode}. Please choose from: {['once', 'multiple', 'always_last']}"
)
_, progress_index, event_data_index = (
special_args(fn) if fn else (None, None, None)
)
self.fns.append(
BlockFunction(
fn,
inputs,
outputs,
preprocess,
postprocess,
inputs_as_dict=inputs_as_dict,
concurrency_limit=concurrency_limit,
concurrency_id=concurrency_id,
batch=batch,
max_batch_size=max_batch_size,
tracks_progress=progress_index is not None,
)
)
# If api_name is None or empty string, use the function name
if api_name is None or isinstance(api_name, str) and api_name.strip() == "":
if fn is not None:
if not hasattr(fn, "__name__"):
if hasattr(fn, "__class__") and hasattr(fn.__class__, "__name__"):
name = fn.__class__.__name__
else:
name = "unnamed"
else:
name = fn.__name__
api_name = "".join(
[s for s in name if s not in set(string.punctuation) - {"-", "_"}]
)
elif js is not None:
api_name = "js_fn"
show_api = False
else:
api_name = "unnamed"
show_api = False
if api_name is not False:
api_name = utils.append_unique_suffix(
api_name, [dep["api_name"] for dep in self.dependencies]
)
else:
show_api = False
# The `show_api` parameter is False if: (1) the user explicitly sets it (2) the user sets `api_name` to False
# or (3) the user sets `fn` to None (there's no backend function)
if collects_event_data is None:
collects_event_data = event_data_index is not None
dependency = {
"targets": _targets,
"inputs": [block._id for block in inputs],
"outputs": [block._id for block in outputs],
"backend_fn": fn is not None,
"js": js,
"queue": False if fn is None else queue,
"api_name": api_name,
"scroll_to_output": False if utils.get_space() else scroll_to_output,
"show_progress": show_progress,
"every": every,
"batch": batch,
"max_batch_size": max_batch_size,
"cancels": cancels or [],
"types": {
"continuous": bool(every),
"generator": inspect.isgeneratorfunction(fn)
or inspect.isasyncgenfunction(fn)
or bool(every),
},
"collects_event_data": collects_event_data,
"trigger_after": trigger_after,
"trigger_only_on_success": trigger_only_on_success,
"trigger_mode": trigger_mode,
"show_api": show_api,
}
self.dependencies.append(dependency)
return dependency, len(self.dependencies) - 1
def render(self):
if Context.root_block is not None:
if self._id in Context.root_block.blocks:
raise DuplicateBlockError(
f"A block with id: {self._id} has already been rendered in the current Blocks."
)
overlapping_ids = set(Context.root_block.blocks).intersection(self.blocks)
for id in overlapping_ids:
# State components are allowed to be reused between Blocks