emmajoanne commited on
Commit
289c551
1 Parent(s): 71fd223

Upload 4 files

Browse files
Files changed (4) hide show
  1. blocks.py +1670 -0
  2. extras.py +258 -0
  3. paths.py +61 -0
  4. sd_models.py +489 -0
blocks.py ADDED
@@ -0,0 +1,1670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import getpass
5
+ import inspect
6
+ import json
7
+ import os
8
+ import pkgutil
9
+ import random
10
+ import sys
11
+ import time
12
+ import warnings
13
+ import webbrowser
14
+ from abc import abstractmethod
15
+ from types import ModuleType
16
+ from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Set, Tuple, Type
17
+
18
+ import anyio
19
+ import requests
20
+ from anyio import CapacityLimiter
21
+ from typing_extensions import Literal
22
+
23
+ from gradio import (
24
+ components,
25
+ encryptor,
26
+ external,
27
+ networking,
28
+ queueing,
29
+ routes,
30
+ strings,
31
+ utils,
32
+ )
33
+ from gradio.context import Context
34
+ from gradio.deprecation import check_deprecated_parameters
35
+ from gradio.documentation import document, set_documentation_group
36
+ from gradio.exceptions import DuplicateBlockError, InvalidApiName
37
+ from gradio.helpers import create_tracker, skip, special_args
38
+ from gradio.tunneling import CURRENT_TUNNELS
39
+ from gradio.utils import (
40
+ TupleNoPrint,
41
+ check_function_inputs_match,
42
+ component_or_layout_class,
43
+ delete_none,
44
+ get_cancel_function,
45
+ get_continuous_fn,
46
+ )
47
+
48
+ set_documentation_group("blocks")
49
+
50
+
51
+ if TYPE_CHECKING: # Only import for type checking (is False at runtime).
52
+ import comet_ml
53
+ from fastapi.applications import FastAPI
54
+
55
+ from gradio.components import Component
56
+
57
+
58
+ class Block:
59
+ def __init__(
60
+ self,
61
+ *,
62
+ render: bool = True,
63
+ elem_id: str | None = None,
64
+ visible: bool = True,
65
+ root_url: str | None = None, # URL that is prepended to all file paths
66
+ _skip_init_processing: bool = False, # Used for loading from Spaces
67
+ **kwargs,
68
+ ):
69
+ self._id = Context.id
70
+ Context.id += 1
71
+ self.visible = visible
72
+ self.elem_id = elem_id
73
+ self.root_url = root_url
74
+ self._skip_init_processing = _skip_init_processing
75
+ self._style = {}
76
+ self.parent: BlockContext | None = None
77
+
78
+ if render:
79
+ self.render()
80
+ check_deprecated_parameters(self.__class__.__name__, **kwargs)
81
+
82
+ def render(self):
83
+ """
84
+ Adds self into appropriate BlockContext
85
+ """
86
+ if Context.root_block is not None and self._id in Context.root_block.blocks:
87
+ raise DuplicateBlockError(
88
+ f"A block with id: {self._id} has already been rendered in the current Blocks."
89
+ )
90
+ if Context.block is not None:
91
+ Context.block.add(self)
92
+ if Context.root_block is not None:
93
+ Context.root_block.blocks[self._id] = self
94
+ if isinstance(self, components.TempFileManager):
95
+ Context.root_block.temp_file_sets.append(self.temp_files)
96
+ return self
97
+
98
+ def unrender(self):
99
+ """
100
+ Removes self from BlockContext if it has been rendered (otherwise does nothing).
101
+ Removes self from the layout and collection of blocks, but does not delete any event triggers.
102
+ """
103
+ if Context.block is not None:
104
+ try:
105
+ Context.block.children.remove(self)
106
+ except ValueError:
107
+ pass
108
+ if Context.root_block is not None:
109
+ try:
110
+ del Context.root_block.blocks[self._id]
111
+ except KeyError:
112
+ pass
113
+ return self
114
+
115
+ def get_block_name(self) -> str:
116
+ """
117
+ Gets block's class name.
118
+
119
+ If it is template component it gets the parent's class name.
120
+
121
+ @return: class name
122
+ """
123
+ return (
124
+ self.__class__.__base__.__name__.lower()
125
+ if hasattr(self, "is_template")
126
+ else self.__class__.__name__.lower()
127
+ )
128
+
129
+ def get_expected_parent(self) -> Type[BlockContext] | None:
130
+ return None
131
+
132
+ def set_event_trigger(
133
+ self,
134
+ event_name: str,
135
+ fn: Callable | None,
136
+ inputs: Component | List[Component] | Set[Component] | None,
137
+ outputs: Component | List[Component] | None,
138
+ preprocess: bool = True,
139
+ postprocess: bool = True,
140
+ scroll_to_output: bool = False,
141
+ show_progress: bool = True,
142
+ api_name: str | None = None,
143
+ js: str | None = None,
144
+ no_target: bool = False,
145
+ queue: bool | None = None,
146
+ batch: bool = False,
147
+ max_batch_size: int = 4,
148
+ cancels: List[int] | None = None,
149
+ every: float | None = None,
150
+ ) -> Dict[str, Any]:
151
+ """
152
+ Adds an event to the component's dependencies.
153
+ Parameters:
154
+ event_name: event name
155
+ fn: Callable function
156
+ inputs: input list
157
+ outputs: output list
158
+ preprocess: whether to run the preprocess methods of components
159
+ postprocess: whether to run the postprocess methods of components
160
+ scroll_to_output: whether to scroll to output of dependency on trigger
161
+ show_progress: whether to show progress animation while running.
162
+ api_name: Defining this parameter exposes the endpoint in the api docs
163
+ 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
164
+ no_target: if True, sets "targets" to [], used for Blocks "load" event
165
+ batch: whether this function takes in a batch of inputs
166
+ max_batch_size: the maximum batch size to send to the function
167
+ 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.
168
+ Returns: None
169
+ """
170
+ # Support for singular parameter
171
+ if isinstance(inputs, set):
172
+ inputs_as_dict = True
173
+ inputs = sorted(inputs, key=lambda x: x._id)
174
+ else:
175
+ inputs_as_dict = False
176
+ if inputs is None:
177
+ inputs = []
178
+ elif not isinstance(inputs, list):
179
+ inputs = [inputs]
180
+
181
+ if isinstance(outputs, set):
182
+ outputs = sorted(outputs, key=lambda x: x._id)
183
+ else:
184
+ if outputs is None:
185
+ outputs = []
186
+ elif not isinstance(outputs, list):
187
+ outputs = [outputs]
188
+
189
+ if fn is not None and not cancels:
190
+ check_function_inputs_match(fn, inputs, inputs_as_dict)
191
+
192
+ if Context.root_block is None:
193
+ raise AttributeError(
194
+ f"{event_name}() and other events can only be called within a Blocks context."
195
+ )
196
+ if every is not None and every <= 0:
197
+ raise ValueError("Parameter every must be positive or None")
198
+ if every and batch:
199
+ raise ValueError(
200
+ f"Cannot run {event_name} event in a batch and every {every} seconds. "
201
+ "Either batch is True or every is non-zero but not both."
202
+ )
203
+
204
+ if every and fn:
205
+ fn = get_continuous_fn(fn, every)
206
+ elif every:
207
+ raise ValueError("Cannot set a value for `every` without a `fn`.")
208
+
209
+ Context.root_block.fns.append(
210
+ BlockFunction(fn, inputs, outputs, preprocess, postprocess, inputs_as_dict)
211
+ )
212
+ if api_name is not None:
213
+ api_name_ = utils.append_unique_suffix(
214
+ api_name, [dep["api_name"] for dep in Context.root_block.dependencies]
215
+ )
216
+ if not (api_name == api_name_):
217
+ warnings.warn(
218
+ "api_name {} already exists, using {}".format(api_name, api_name_)
219
+ )
220
+ api_name = api_name_
221
+
222
+ dependency = {
223
+ "targets": [self._id] if not no_target else [],
224
+ "trigger": event_name,
225
+ "inputs": [block._id for block in inputs],
226
+ "outputs": [block._id for block in outputs],
227
+ "backend_fn": fn is not None,
228
+ "js": js,
229
+ "queue": False if fn is None else queue,
230
+ "api_name": api_name,
231
+ "scroll_to_output": scroll_to_output,
232
+ "show_progress": show_progress,
233
+ "every": every,
234
+ "batch": batch,
235
+ "max_batch_size": max_batch_size,
236
+ "cancels": cancels or [],
237
+ }
238
+ Context.root_block.dependencies.append(dependency)
239
+ return dependency
240
+
241
+ def get_config(self):
242
+ return {
243
+ "visible": self.visible,
244
+ "elem_id": self.elem_id,
245
+ "style": self._style,
246
+ "root_url": self.root_url,
247
+ }
248
+
249
+ @staticmethod
250
+ @abstractmethod
251
+ def update(**kwargs) -> Dict:
252
+ return {}
253
+
254
+ @classmethod
255
+ def get_specific_update(cls, generic_update: Dict[str, Any]) -> Dict:
256
+ del generic_update["__type__"]
257
+ specific_update = cls.update(**generic_update)
258
+ return specific_update
259
+
260
+
261
+ class BlockContext(Block):
262
+ def __init__(
263
+ self,
264
+ visible: bool = True,
265
+ render: bool = True,
266
+ **kwargs,
267
+ ):
268
+ """
269
+ Parameters:
270
+ visible: If False, this will be hidden but included in the Blocks config file (its visibility can later be updated).
271
+ render: If False, this will not be included in the Blocks config file at all.
272
+ """
273
+ self.children: List[Block] = []
274
+ super().__init__(visible=visible, render=render, **kwargs)
275
+
276
+ def __enter__(self):
277
+ self.parent = Context.block
278
+ Context.block = self
279
+ return self
280
+
281
+ def add(self, child: Block):
282
+ child.parent = self
283
+ self.children.append(child)
284
+
285
+ def fill_expected_parents(self):
286
+ children = []
287
+ pseudo_parent = None
288
+ for child in self.children:
289
+ expected_parent = child.get_expected_parent()
290
+ if not expected_parent or isinstance(self, expected_parent):
291
+ pseudo_parent = None
292
+ children.append(child)
293
+ else:
294
+ if pseudo_parent is not None and isinstance(
295
+ pseudo_parent, expected_parent
296
+ ):
297
+ pseudo_parent.children.append(child)
298
+ else:
299
+ pseudo_parent = expected_parent(render=False)
300
+ children.append(pseudo_parent)
301
+ pseudo_parent.children = [child]
302
+ if Context.root_block:
303
+ Context.root_block.blocks[pseudo_parent._id] = pseudo_parent
304
+ child.parent = pseudo_parent
305
+ self.children = children
306
+
307
+ def __exit__(self, *args):
308
+ if getattr(self, "allow_expected_parents", True):
309
+ self.fill_expected_parents()
310
+ Context.block = self.parent
311
+
312
+ def postprocess(self, y):
313
+ """
314
+ Any postprocessing needed to be performed on a block context.
315
+ """
316
+ return y
317
+
318
+
319
+ class BlockFunction:
320
+ def __init__(
321
+ self,
322
+ fn: Callable | None,
323
+ inputs: List[Component],
324
+ outputs: List[Component],
325
+ preprocess: bool,
326
+ postprocess: bool,
327
+ inputs_as_dict: bool,
328
+ ):
329
+ self.fn = fn
330
+ self.inputs = inputs
331
+ self.outputs = outputs
332
+ self.preprocess = preprocess
333
+ self.postprocess = postprocess
334
+ self.total_runtime = 0
335
+ self.total_runs = 0
336
+ self.inputs_as_dict = inputs_as_dict
337
+
338
+ def __str__(self):
339
+ return str(
340
+ {
341
+ "fn": getattr(self.fn, "__name__", "fn")
342
+ if self.fn is not None
343
+ else None,
344
+ "preprocess": self.preprocess,
345
+ "postprocess": self.postprocess,
346
+ }
347
+ )
348
+
349
+ def __repr__(self):
350
+ return str(self)
351
+
352
+
353
+ class class_or_instancemethod(classmethod):
354
+ def __get__(self, instance, type_):
355
+ descr_get = super().__get__ if instance is None else self.__func__.__get__
356
+ return descr_get(instance, type_)
357
+
358
+
359
+ def postprocess_update_dict(block: Block, update_dict: Dict, postprocess: bool = True):
360
+ """
361
+ Converts a dictionary of updates into a format that can be sent to the frontend.
362
+ E.g. {"__type__": "generic_update", "value": "2", "interactive": False}
363
+ Into -> {"__type__": "update", "value": 2.0, "mode": "static"}
364
+
365
+ Parameters:
366
+ block: The Block that is being updated with this update dictionary.
367
+ update_dict: The original update dictionary
368
+ postprocess: Whether to postprocess the "value" key of the update dictionary.
369
+ """
370
+ if update_dict.get("__type__", "") == "generic_update":
371
+ update_dict = block.get_specific_update(update_dict)
372
+ if update_dict.get("value") is components._Keywords.NO_VALUE:
373
+ update_dict.pop("value")
374
+ prediction_value = delete_none(update_dict, skip_value=True)
375
+ if "value" in prediction_value and postprocess:
376
+ assert isinstance(
377
+ block, components.IOComponent
378
+ ), f"Component {block.__class__} does not support value"
379
+ prediction_value["value"] = block.postprocess(prediction_value["value"])
380
+ return prediction_value
381
+
382
+
383
+ def convert_component_dict_to_list(
384
+ outputs_ids: List[int], predictions: Dict
385
+ ) -> List | Dict:
386
+ """
387
+ Converts a dictionary of component updates into a list of updates in the order of
388
+ the outputs_ids and including every output component. Leaves other types of dictionaries unchanged.
389
+ E.g. {"textbox": "hello", "number": {"__type__": "generic_update", "value": "2"}}
390
+ Into -> ["hello", {"__type__": "generic_update"}, {"__type__": "generic_update", "value": "2"}]
391
+ """
392
+ keys_are_blocks = [isinstance(key, Block) for key in predictions.keys()]
393
+ if all(keys_are_blocks):
394
+ reordered_predictions = [skip() for _ in outputs_ids]
395
+ for component, value in predictions.items():
396
+ if component._id not in outputs_ids:
397
+ raise ValueError(
398
+ f"Returned component {component} not specified as output of function."
399
+ )
400
+ output_index = outputs_ids.index(component._id)
401
+ reordered_predictions[output_index] = value
402
+ predictions = utils.resolve_singleton(reordered_predictions)
403
+ elif any(keys_are_blocks):
404
+ raise ValueError(
405
+ "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."
406
+ )
407
+ return predictions
408
+
409
+
410
+ @document("load")
411
+ class Blocks(BlockContext):
412
+ """
413
+ Blocks is Gradio's low-level API that allows you to create more custom web
414
+ applications and demos than Interfaces (yet still entirely in Python).
415
+
416
+
417
+ Compared to the Interface class, Blocks offers more flexibility and control over:
418
+ (1) the layout of components (2) the events that
419
+ trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs,
420
+ which can trigger the next level of outputs). Blocks also offers ways to group
421
+ together related demos such as with tabs.
422
+
423
+
424
+ The basic usage of Blocks is as follows: create a Blocks object, then use it as a
425
+ context (with the "with" statement), and then define layouts, components, or events
426
+ within the Blocks context. Finally, call the launch() method to launch the demo.
427
+
428
+ Example:
429
+ import gradio as gr
430
+ def update(name):
431
+ return f"Welcome to Gradio, {name}!"
432
+
433
+ with gr.Blocks() as demo:
434
+ gr.Markdown("Start typing below and then click **Run** to see the output.")
435
+ with gr.Row():
436
+ inp = gr.Textbox(placeholder="What is your name?")
437
+ out = gr.Textbox()
438
+ btn = gr.Button("Run")
439
+ btn.click(fn=update, inputs=inp, outputs=out)
440
+
441
+ demo.launch()
442
+ Demos: blocks_hello, blocks_flipper, blocks_speech_text_sentiment, generate_english_german, sound_alert
443
+ Guides: blocks_and_event_listeners, controlling_layout, state_in_blocks, custom_CSS_and_JS, custom_interpretations_with_blocks, using_blocks_like_functions
444
+ """
445
+
446
+ def __init__(
447
+ self,
448
+ theme: str = "default",
449
+ analytics_enabled: bool | None = None,
450
+ mode: str = "blocks",
451
+ title: str = "Gradio",
452
+ css: str | None = None,
453
+ **kwargs,
454
+ ):
455
+ """
456
+ Parameters:
457
+ theme: which theme to use - right now, only "default" is supported.
458
+ analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
459
+ mode: a human-friendly name for the kind of Blocks or Interface being created.
460
+ title: The tab title to display when this is opened in a browser window.
461
+ css: custom css or path to custom css file to apply to entire Blocks
462
+ """
463
+ # Cleanup shared parameters with Interface #TODO: is this part still necessary after Interface with Blocks?
464
+ self.limiter = None
465
+ self.save_to = None
466
+ self.theme = theme
467
+ self.encrypt = False
468
+ self.share = False
469
+ self.enable_queue = None
470
+ self.max_threads = 40
471
+ self.show_error = True
472
+ if css is not None and os.path.exists(css):
473
+ with open(css) as css_file:
474
+ self.css = css_file.read()
475
+ else:
476
+ self.css = css
477
+
478
+ # For analytics_enabled and allow_flagging: (1) first check for
479
+ # parameter, (2) check for env variable, (3) default to True/"manual"
480
+ self.analytics_enabled = (
481
+ analytics_enabled
482
+ if analytics_enabled is not None
483
+ else os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True"
484
+ )
485
+
486
+ super().__init__(render=False, **kwargs)
487
+ self.blocks: Dict[int, Block] = {}
488
+ self.fns: List[BlockFunction] = []
489
+ self.dependencies = []
490
+ self.mode = mode
491
+
492
+ self.is_running = False
493
+ self.local_url = None
494
+ self.share_url = None
495
+ self.width = None
496
+ self.height = None
497
+ self.api_open = True
498
+
499
+ self.ip_address = ""
500
+ self.is_space = True if os.getenv("SYSTEM") == "spaces" else False
501
+ self.favicon_path = None
502
+ self.auth = None
503
+ self.dev_mode = True
504
+ self.app_id = random.getrandbits(64)
505
+ self.temp_file_sets = []
506
+ self.title = title
507
+ self.show_api = True
508
+
509
+ # Only used when an Interface is loaded from a config
510
+ self.predict = None
511
+ self.input_components = None
512
+ self.output_components = None
513
+ self.__name__ = None
514
+ self.api_mode = None
515
+ self.progress_tracking = None
516
+
517
+ if self.analytics_enabled:
518
+ self.ip_address = utils.get_local_ip_address()
519
+ data = {
520
+ "mode": self.mode,
521
+ "ip_address": self.ip_address,
522
+ "custom_css": self.css is not None,
523
+ "theme": self.theme,
524
+ "version": (pkgutil.get_data(__name__, "version.txt") or b"")
525
+ .decode("ascii")
526
+ .strip(),
527
+ }
528
+ utils.initiated_analytics(data)
529
+
530
+ @classmethod
531
+ def from_config(
532
+ cls, config: dict, fns: List[Callable], root_url: str | None = None
533
+ ) -> Blocks:
534
+ """
535
+ Factory method that creates a Blocks from a config and list of functions.
536
+
537
+ Parameters:
538
+ config: a dictionary containing the configuration of the Blocks.
539
+ fns: a list of functions that are used in the Blocks. Must be in the same order as the dependencies in the config.
540
+ root_url: an optional root url to use for the components in the Blocks. Allows serving files from an external URL.
541
+ """
542
+ config = copy.deepcopy(config)
543
+ components_config = config["components"]
544
+ original_mapping: Dict[int, Block] = {}
545
+
546
+ def get_block_instance(id: int) -> Block:
547
+ for block_config in components_config:
548
+ if block_config["id"] == id:
549
+ break
550
+ else:
551
+ raise ValueError("Cannot find block with id {}".format(id))
552
+ cls = component_or_layout_class(block_config["type"])
553
+ block_config["props"].pop("type", None)
554
+ block_config["props"].pop("name", None)
555
+ style = block_config["props"].pop("style", None)
556
+ if block_config["props"].get("root_url") is None and root_url:
557
+ block_config["props"]["root_url"] = root_url + "/"
558
+ # Any component has already processed its initial value, so we skip that step here
559
+ block = cls(**block_config["props"], _skip_init_processing=True)
560
+ if style and isinstance(block, components.IOComponent):
561
+ block.style(**style)
562
+ return block
563
+
564
+ def iterate_over_children(children_list):
565
+ for child_config in children_list:
566
+ id = child_config["id"]
567
+ block = get_block_instance(id)
568
+
569
+ original_mapping[id] = block
570
+
571
+ children = child_config.get("children")
572
+ if children is not None:
573
+ assert isinstance(
574
+ block, BlockContext
575
+ ), f"Invalid config, Block with id {id} has children but is not a BlockContext."
576
+ with block:
577
+ iterate_over_children(children)
578
+
579
+ with Blocks(theme=config["theme"], css=config["theme"]) as blocks:
580
+ # ID 0 should be the root Blocks component
581
+ original_mapping[0] = Context.root_block or blocks
582
+
583
+ iterate_over_children(config["layout"]["children"])
584
+
585
+ first_dependency = None
586
+
587
+ # add the event triggers
588
+ for dependency, fn in zip(config["dependencies"], fns):
589
+ # We used to add a "fake_event" to the config to cache examples
590
+ # without removing it. This was causing bugs in calling gr.Interface.load
591
+ # We fixed the issue by removing "fake_event" from the config in examples.py
592
+ # but we still need to skip these events when loading the config to support
593
+ # older demos
594
+ if dependency["trigger"] == "fake_event":
595
+ continue
596
+ targets = dependency.pop("targets")
597
+ trigger = dependency.pop("trigger")
598
+ dependency.pop("backend_fn")
599
+ dependency.pop("documentation", None)
600
+ dependency["inputs"] = [
601
+ original_mapping[i] for i in dependency["inputs"]
602
+ ]
603
+ dependency["outputs"] = [
604
+ original_mapping[o] for o in dependency["outputs"]
605
+ ]
606
+ dependency.pop("status_tracker", None)
607
+ dependency["preprocess"] = False
608
+ dependency["postprocess"] = False
609
+
610
+ for target in targets:
611
+ dependency = original_mapping[target].set_event_trigger(
612
+ event_name=trigger, fn=fn, **dependency
613
+ )
614
+ if first_dependency is None:
615
+ first_dependency = dependency
616
+
617
+ # Allows some use of Interface-specific methods with loaded Spaces
618
+ if first_dependency and Context.root_block:
619
+ blocks.predict = [fns[0]]
620
+ blocks.input_components = [
621
+ Context.root_block.blocks[i] for i in first_dependency["inputs"]
622
+ ]
623
+ blocks.output_components = [
624
+ Context.root_block.blocks[o] for o in first_dependency["outputs"]
625
+ ]
626
+ blocks.__name__ = "Interface"
627
+ blocks.api_mode = True
628
+
629
+ return blocks
630
+
631
+ def __str__(self):
632
+ return self.__repr__()
633
+
634
+ def __repr__(self):
635
+ num_backend_fns = len([d for d in self.dependencies if d["backend_fn"]])
636
+ repr = f"Gradio Blocks instance: {num_backend_fns} backend functions"
637
+ repr += "\n" + "-" * len(repr)
638
+ for d, dependency in enumerate(self.dependencies):
639
+ if dependency["backend_fn"]:
640
+ repr += f"\nfn_index={d}"
641
+ repr += "\n inputs:"
642
+ for input_id in dependency["inputs"]:
643
+ block = self.blocks[input_id]
644
+ repr += "\n |-{}".format(str(block))
645
+ repr += "\n outputs:"
646
+ for output_id in dependency["outputs"]:
647
+ block = self.blocks[output_id]
648
+ repr += "\n |-{}".format(str(block))
649
+ return repr
650
+
651
+ def render(self):
652
+ if Context.root_block is not None:
653
+ if self._id in Context.root_block.blocks:
654
+ raise DuplicateBlockError(
655
+ f"A block with id: {self._id} has already been rendered in the current Blocks."
656
+ )
657
+ if not set(Context.root_block.blocks).isdisjoint(self.blocks):
658
+ raise DuplicateBlockError(
659
+ "At least one block in this Blocks has already been rendered."
660
+ )
661
+
662
+ Context.root_block.blocks.update(self.blocks)
663
+ Context.root_block.fns.extend(self.fns)
664
+ dependency_offset = len(Context.root_block.dependencies)
665
+ for i, dependency in enumerate(self.dependencies):
666
+ api_name = dependency["api_name"]
667
+ if api_name is not None:
668
+ api_name_ = utils.append_unique_suffix(
669
+ api_name,
670
+ [dep["api_name"] for dep in Context.root_block.dependencies],
671
+ )
672
+ if not (api_name == api_name_):
673
+ warnings.warn(
674
+ "api_name {} already exists, using {}".format(
675
+ api_name, api_name_
676
+ )
677
+ )
678
+ dependency["api_name"] = api_name_
679
+ dependency["cancels"] = [
680
+ c + dependency_offset for c in dependency["cancels"]
681
+ ]
682
+ # Recreate the cancel function so that it has the latest
683
+ # dependency fn indices. This is necessary to properly cancel
684
+ # events in the backend
685
+ if dependency["cancels"]:
686
+ updated_cancels = [
687
+ Context.root_block.dependencies[i]
688
+ for i in dependency["cancels"]
689
+ ]
690
+ new_fn = BlockFunction(
691
+ get_cancel_function(updated_cancels)[0],
692
+ [],
693
+ [],
694
+ False,
695
+ True,
696
+ False,
697
+ )
698
+ Context.root_block.fns[dependency_offset + i] = new_fn
699
+ Context.root_block.dependencies.append(dependency)
700
+ Context.root_block.temp_file_sets.extend(self.temp_file_sets)
701
+
702
+ if Context.block is not None:
703
+ Context.block.children.extend(self.children)
704
+ return self
705
+
706
+ def is_callable(self, fn_index: int = 0) -> bool:
707
+ """Checks if a particular Blocks function is callable (i.e. not stateful or a generator)."""
708
+ block_fn = self.fns[fn_index]
709
+ dependency = self.dependencies[fn_index]
710
+
711
+ if inspect.isasyncgenfunction(block_fn.fn):
712
+ return False
713
+ if inspect.isgeneratorfunction(block_fn.fn):
714
+ return False
715
+ for input_id in dependency["inputs"]:
716
+ block = self.blocks[input_id]
717
+ if getattr(block, "stateful", False):
718
+ return False
719
+ for output_id in dependency["outputs"]:
720
+ block = self.blocks[output_id]
721
+ if getattr(block, "stateful", False):
722
+ return False
723
+
724
+ return True
725
+
726
+ def __call__(self, *inputs, fn_index: int = 0, api_name: str | None = None):
727
+ """
728
+ Allows Blocks objects to be called as functions. Supply the parameters to the
729
+ function as positional arguments. To choose which function to call, use the
730
+ fn_index parameter, which must be a keyword argument.
731
+
732
+ Parameters:
733
+ *inputs: the parameters to pass to the function
734
+ fn_index: the index of the function to call (defaults to 0, which for Interfaces, is the default prediction function)
735
+ api_name: The api_name of the dependency to call. Will take precedence over fn_index.
736
+ """
737
+ if api_name is not None:
738
+ inferred_fn_index = next(
739
+ (
740
+ i
741
+ for i, d in enumerate(self.dependencies)
742
+ if d.get("api_name") == api_name
743
+ ),
744
+ None,
745
+ )
746
+ if inferred_fn_index is None:
747
+ raise InvalidApiName(f"Cannot find a function with api_name {api_name}")
748
+ fn_index = inferred_fn_index
749
+ if not (self.is_callable(fn_index)):
750
+ raise ValueError(
751
+ "This function is not callable because it is either stateful or is a generator. Please use the .launch() method instead to create an interactive user interface."
752
+ )
753
+
754
+ inputs = list(inputs)
755
+ processed_inputs = self.serialize_data(fn_index, inputs)
756
+ batch = self.dependencies[fn_index]["batch"]
757
+ if batch:
758
+ processed_inputs = [[inp] for inp in processed_inputs]
759
+
760
+ outputs = utils.synchronize_async(
761
+ self.process_api,
762
+ fn_index=fn_index,
763
+ inputs=processed_inputs,
764
+ request=None,
765
+ state={},
766
+ )
767
+ outputs = outputs["data"]
768
+
769
+ if batch:
770
+ outputs = [out[0] for out in outputs]
771
+
772
+ processed_outputs = self.deserialize_data(fn_index, outputs)
773
+ processed_outputs = utils.resolve_singleton(processed_outputs)
774
+
775
+ return processed_outputs
776
+
777
+ async def call_function(
778
+ self,
779
+ fn_index: int,
780
+ processed_input: List[Any],
781
+ iterator: Iterator[Any] | None = None,
782
+ requests: routes.Request | List[routes.Request] | None = None,
783
+ event_id: str | None = None,
784
+ ):
785
+ """
786
+ Calls function with given index and preprocessed input, and measures process time.
787
+ Parameters:
788
+ fn_index: index of function to call
789
+ processed_input: preprocessed input to pass to function
790
+ iterator: iterator to use if function is a generator
791
+ requests: requests to pass to function
792
+ event_id: id of event in queue
793
+ """
794
+ block_fn = self.fns[fn_index]
795
+ assert block_fn.fn, f"function with index {fn_index} not defined."
796
+ is_generating = False
797
+
798
+ if block_fn.inputs_as_dict:
799
+ processed_input = [
800
+ {
801
+ input_component: data
802
+ for input_component, data in zip(block_fn.inputs, processed_input)
803
+ }
804
+ ]
805
+
806
+ if isinstance(requests, list):
807
+ request = requests[0]
808
+ else:
809
+ request = requests
810
+ processed_input, progress_index = special_args(
811
+ block_fn.fn,
812
+ processed_input,
813
+ request,
814
+ )
815
+ progress_tracker = (
816
+ processed_input[progress_index] if progress_index is not None else None
817
+ )
818
+
819
+ start = time.time()
820
+
821
+ if iterator is None: # If not a generator function that has already run
822
+ if progress_tracker is not None and progress_index is not None:
823
+ progress_tracker, fn = create_tracker(
824
+ self, event_id, block_fn.fn, progress_tracker.track_tqdm
825
+ )
826
+ processed_input[progress_index] = progress_tracker
827
+ else:
828
+ fn = block_fn.fn
829
+
830
+ if inspect.iscoroutinefunction(fn):
831
+ prediction = await fn(*processed_input)
832
+ else:
833
+ prediction = await anyio.to_thread.run_sync(
834
+ fn, *processed_input, limiter=self.limiter
835
+ )
836
+ else:
837
+ prediction = None
838
+
839
+ if inspect.isasyncgenfunction(block_fn.fn):
840
+ raise ValueError("Gradio does not support async generators.")
841
+ if inspect.isgeneratorfunction(block_fn.fn):
842
+ if not self.enable_queue:
843
+ raise ValueError("Need to enable queue to use generators.")
844
+ try:
845
+ if iterator is None:
846
+ iterator = prediction
847
+ prediction = await anyio.to_thread.run_sync(
848
+ utils.async_iteration, iterator, limiter=self.limiter
849
+ )
850
+ is_generating = True
851
+ except StopAsyncIteration:
852
+ n_outputs = len(self.dependencies[fn_index].get("outputs"))
853
+ prediction = (
854
+ components._Keywords.FINISHED_ITERATING
855
+ if n_outputs == 1
856
+ else (components._Keywords.FINISHED_ITERATING,) * n_outputs
857
+ )
858
+ iterator = None
859
+
860
+ duration = time.time() - start
861
+
862
+ return {
863
+ "prediction": prediction,
864
+ "duration": duration,
865
+ "is_generating": is_generating,
866
+ "iterator": iterator,
867
+ }
868
+
869
+ def serialize_data(self, fn_index: int, inputs: List[Any]) -> List[Any]:
870
+ dependency = self.dependencies[fn_index]
871
+ processed_input = []
872
+
873
+ for i, input_id in enumerate(dependency["inputs"]):
874
+ block = self.blocks[input_id]
875
+ assert isinstance(
876
+ block, components.IOComponent
877
+ ), f"{block.__class__} Component with id {input_id} not a valid input component."
878
+ serialized_input = block.serialize(inputs[i])
879
+ processed_input.append(serialized_input)
880
+
881
+ return processed_input
882
+
883
+ def deserialize_data(self, fn_index: int, outputs: List[Any]) -> List[Any]:
884
+ dependency = self.dependencies[fn_index]
885
+ predictions = []
886
+
887
+ for o, output_id in enumerate(dependency["outputs"]):
888
+ block = self.blocks[output_id]
889
+ assert isinstance(
890
+ block, components.IOComponent
891
+ ), f"{block.__class__} Component with id {output_id} not a valid output component."
892
+ deserialized = block.deserialize(outputs[o])
893
+ predictions.append(deserialized)
894
+
895
+ return predictions
896
+
897
+ def preprocess_data(self, fn_index: int, inputs: List[Any], state: Dict[int, Any]):
898
+ block_fn = self.fns[fn_index]
899
+ dependency = self.dependencies[fn_index]
900
+
901
+ if block_fn.preprocess:
902
+ processed_input = []
903
+ for i, input_id in enumerate(dependency["inputs"]):
904
+ block = self.blocks[input_id]
905
+ assert isinstance(
906
+ block, components.Component
907
+ ), f"{block.__class__} Component with id {input_id} not a valid input component."
908
+ if getattr(block, "stateful", False):
909
+ processed_input.append(state.get(input_id))
910
+ else:
911
+ processed_input.append(block.preprocess(inputs[i]))
912
+ else:
913
+ processed_input = inputs
914
+ return processed_input
915
+
916
+ def postprocess_data(
917
+ self, fn_index: int, predictions: List | Dict, state: Dict[int, Any]
918
+ ):
919
+ block_fn = self.fns[fn_index]
920
+ dependency = self.dependencies[fn_index]
921
+ batch = dependency["batch"]
922
+
923
+ if type(predictions) is dict and len(predictions) > 0:
924
+ predictions = convert_component_dict_to_list(
925
+ dependency["outputs"], predictions
926
+ )
927
+
928
+ if len(dependency["outputs"]) == 1 and not (batch):
929
+ predictions = [
930
+ predictions,
931
+ ]
932
+
933
+ output = []
934
+ for i, output_id in enumerate(dependency["outputs"]):
935
+ if predictions[i] is components._Keywords.FINISHED_ITERATING:
936
+ output.append(None)
937
+ continue
938
+ block = self.blocks[output_id]
939
+ if getattr(block, "stateful", False):
940
+ if not utils.is_update(predictions[i]):
941
+ state[output_id] = predictions[i]
942
+ output.append(None)
943
+ else:
944
+ prediction_value = predictions[i]
945
+ if utils.is_update(prediction_value):
946
+ assert isinstance(prediction_value, dict)
947
+ prediction_value = postprocess_update_dict(
948
+ block=block,
949
+ update_dict=prediction_value,
950
+ postprocess=block_fn.postprocess,
951
+ )
952
+ elif block_fn.postprocess:
953
+ assert isinstance(
954
+ block, components.Component
955
+ ), f"{block.__class__} Component with id {output_id} not a valid output component."
956
+ prediction_value = block.postprocess(prediction_value)
957
+ output.append(prediction_value)
958
+ return output
959
+
960
+ async def process_api(
961
+ self,
962
+ fn_index: int,
963
+ inputs: List[Any],
964
+ state: Dict[int, Any],
965
+ request: routes.Request | List[routes.Request] | None = None,
966
+ iterators: Dict[int, Any] | None = None,
967
+ event_id: str | None = None,
968
+ ) -> Dict[str, Any]:
969
+ """
970
+ Processes API calls from the frontend. First preprocesses the data,
971
+ then runs the relevant function, then postprocesses the output.
972
+ Parameters:
973
+ fn_index: Index of function to run.
974
+ inputs: input data received from the frontend
975
+ username: name of user if authentication is set up (not used)
976
+ state: data stored from stateful components for session (key is input block id)
977
+ iterators: the in-progress iterators for each generator function (key is function index)
978
+ Returns: None
979
+ """
980
+ block_fn = self.fns[fn_index]
981
+ batch = self.dependencies[fn_index]["batch"]
982
+
983
+ if batch:
984
+ max_batch_size = self.dependencies[fn_index]["max_batch_size"]
985
+ batch_sizes = [len(inp) for inp in inputs]
986
+ batch_size = batch_sizes[0]
987
+ if inspect.isasyncgenfunction(block_fn.fn) or inspect.isgeneratorfunction(
988
+ block_fn.fn
989
+ ):
990
+ raise ValueError("Gradio does not support generators in batch mode.")
991
+ if not all(x == batch_size for x in batch_sizes):
992
+ raise ValueError(
993
+ f"All inputs to a batch function must have the same length but instead have sizes: {batch_sizes}."
994
+ )
995
+ if batch_size > max_batch_size:
996
+ raise ValueError(
997
+ f"Batch size ({batch_size}) exceeds the max_batch_size for this function ({max_batch_size})"
998
+ )
999
+
1000
+ inputs = [
1001
+ self.preprocess_data(fn_index, list(i), state) for i in zip(*inputs)
1002
+ ]
1003
+ result = await self.call_function(
1004
+ fn_index, list(zip(*inputs)), None, request
1005
+ )
1006
+ preds = result["prediction"]
1007
+ data = [
1008
+ self.postprocess_data(fn_index, list(o), state) for o in zip(*preds)
1009
+ ]
1010
+ data = list(zip(*data))
1011
+ is_generating, iterator = None, None
1012
+ else:
1013
+ inputs = self.preprocess_data(fn_index, inputs, state)
1014
+ iterator = iterators.get(fn_index, None) if iterators else None
1015
+ result = await self.call_function(
1016
+ fn_index, inputs, iterator, request, event_id
1017
+ )
1018
+ data = self.postprocess_data(fn_index, result["prediction"], state)
1019
+ is_generating, iterator = result["is_generating"], result["iterator"]
1020
+
1021
+ block_fn.total_runtime += result["duration"]
1022
+ block_fn.total_runs += 1
1023
+
1024
+ return {
1025
+ "data": data,
1026
+ "is_generating": is_generating,
1027
+ "iterator": iterator,
1028
+ "duration": result["duration"],
1029
+ "average_duration": block_fn.total_runtime / block_fn.total_runs,
1030
+ }
1031
+
1032
+ async def create_limiter(self):
1033
+ self.limiter = (
1034
+ None
1035
+ if self.max_threads == 40
1036
+ else CapacityLimiter(total_tokens=self.max_threads)
1037
+ )
1038
+
1039
+ def get_config(self):
1040
+ return {"type": "column"}
1041
+
1042
+ def get_config_file(self):
1043
+ config = {
1044
+ "version": routes.VERSION,
1045
+ "mode": self.mode,
1046
+ "dev_mode": self.dev_mode,
1047
+ "components": [],
1048
+ "theme": self.theme,
1049
+ "css": self.css,
1050
+ "title": self.title or "Gradio",
1051
+ "is_space": self.is_space,
1052
+ "enable_queue": getattr(self, "enable_queue", False), # launch attributes
1053
+ "show_error": getattr(self, "show_error", False),
1054
+ "show_api": self.show_api,
1055
+ "is_colab": utils.colab_check(),
1056
+ }
1057
+
1058
+ def getLayout(block):
1059
+ if not isinstance(block, BlockContext):
1060
+ return {"id": block._id}
1061
+ children_layout = []
1062
+ for child in block.children:
1063
+ children_layout.append(getLayout(child))
1064
+ return {"id": block._id, "children": children_layout}
1065
+
1066
+ config["layout"] = getLayout(self)
1067
+
1068
+ for _id, block in self.blocks.items():
1069
+ config["components"].append(
1070
+ {
1071
+ "id": _id,
1072
+ "type": (block.get_block_name()),
1073
+ "props": utils.delete_none(block.get_config())
1074
+ if hasattr(block, "get_config")
1075
+ else {},
1076
+ }
1077
+ )
1078
+ config["dependencies"] = self.dependencies
1079
+ return config
1080
+
1081
+ def __enter__(self):
1082
+ if Context.block is None:
1083
+ Context.root_block = self
1084
+ self.parent = Context.block
1085
+ Context.block = self
1086
+ return self
1087
+
1088
+ def __exit__(self, *args):
1089
+ super().fill_expected_parents()
1090
+ Context.block = self.parent
1091
+ # Configure the load events before root_block is reset
1092
+ self.attach_load_events()
1093
+ if self.parent is None:
1094
+ Context.root_block = None
1095
+ else:
1096
+ self.parent.children.extend(self.children)
1097
+ self.config = self.get_config_file()
1098
+ self.app = routes.App.create_app(self)
1099
+ self.progress_tracking = any(
1100
+ block_fn.fn is not None and special_args(block_fn.fn)[1] is not None
1101
+ for block_fn in self.fns
1102
+ )
1103
+
1104
+ @class_or_instancemethod
1105
+ def load(
1106
+ self_or_cls,
1107
+ fn: Callable | None = None,
1108
+ inputs: List[Component] | None = None,
1109
+ outputs: List[Component] | None = None,
1110
+ api_name: str | None = None,
1111
+ scroll_to_output: bool = False,
1112
+ show_progress: bool = True,
1113
+ queue=None,
1114
+ batch: bool = False,
1115
+ max_batch_size: int = 4,
1116
+ preprocess: bool = True,
1117
+ postprocess: bool = True,
1118
+ every: float | None = None,
1119
+ _js: str | None = None,
1120
+ *,
1121
+ name: str | None = None,
1122
+ src: str | None = None,
1123
+ api_key: str | None = None,
1124
+ alias: str | None = None,
1125
+ **kwargs,
1126
+ ) -> Blocks | Dict[str, Any] | None:
1127
+ """
1128
+ For reverse compatibility reasons, this is both a class method and an instance
1129
+ method, the two of which, confusingly, do two completely different things.
1130
+
1131
+
1132
+ Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Equivalent to gradio.Interface.load()
1133
+
1134
+
1135
+ Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.
1136
+ Parameters:
1137
+ name: Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
1138
+ src: Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
1139
+ api_key: Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens
1140
+ alias: Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
1141
+ fn: Instance Method - the function to wrap an interface around. 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.
1142
+ inputs: Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
1143
+ outputs: Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
1144
+ api_name: Instance Method - Defining this parameter exposes the endpoint in the api docs
1145
+ scroll_to_output: Instance Method - If True, will scroll to output component on completion
1146
+ show_progress: Instance Method - If True, will show progress animation while pending
1147
+ queue: Instance Method - If True, will place the request on the queue, if the queue exists
1148
+ batch: Instance Method - 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.
1149
+ max_batch_size: Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
1150
+ preprocess: Instance Method - 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).
1151
+ postprocess: Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser.
1152
+ every: Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled.
1153
+ Example:
1154
+ import gradio as gr
1155
+ import datetime
1156
+ with gr.Blocks() as demo:
1157
+ def get_time():
1158
+ return datetime.datetime.now().time()
1159
+ dt = gr.Textbox(label="Current time")
1160
+ demo.load(get_time, inputs=None, outputs=dt)
1161
+ demo.launch()
1162
+ """
1163
+ # _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.
1164
+ if isinstance(self_or_cls, type):
1165
+ if name is None:
1166
+ raise ValueError(
1167
+ "Blocks.load() requires passing parameters as keyword arguments"
1168
+ )
1169
+ return external.load_blocks_from_repo(name, src, api_key, alias, **kwargs)
1170
+ else:
1171
+ return self_or_cls.set_event_trigger(
1172
+ event_name="load",
1173
+ fn=fn,
1174
+ inputs=inputs,
1175
+ outputs=outputs,
1176
+ api_name=api_name,
1177
+ preprocess=preprocess,
1178
+ postprocess=postprocess,
1179
+ scroll_to_output=scroll_to_output,
1180
+ show_progress=show_progress,
1181
+ js=_js,
1182
+ queue=queue,
1183
+ batch=batch,
1184
+ max_batch_size=max_batch_size,
1185
+ every=every,
1186
+ no_target=True,
1187
+ )
1188
+
1189
+ def clear(self):
1190
+ """Resets the layout of the Blocks object."""
1191
+ self.blocks = {}
1192
+ self.fns = []
1193
+ self.dependencies = []
1194
+ self.children = []
1195
+ return self
1196
+
1197
+ @document()
1198
+ def queue(
1199
+ self,
1200
+ concurrency_count: int = 1,
1201
+ status_update_rate: float | Literal["auto"] = "auto",
1202
+ client_position_to_load_data: int | None = None,
1203
+ default_enabled: bool | None = None,
1204
+ api_open: bool = True,
1205
+ max_size: int | None = None,
1206
+ ):
1207
+ """
1208
+ You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.
1209
+ Parameters:
1210
+ concurrency_count: Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue.
1211
+ status_update_rate: If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
1212
+ client_position_to_load_data: DEPRECATED. This parameter is deprecated and has no effect.
1213
+ default_enabled: Deprecated and has no effect.
1214
+ api_open: If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
1215
+ max_size: The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
1216
+ Example:
1217
+ demo = gr.Interface(gr.Textbox(), gr.Image(), image_generator)
1218
+ demo.queue(concurrency_count=3)
1219
+ demo.launch()
1220
+ """
1221
+ if default_enabled is not None:
1222
+ warnings.warn(
1223
+ "The default_enabled parameter of queue has no effect and will be removed "
1224
+ "in a future version of gradio."
1225
+ )
1226
+ self.enable_queue = True
1227
+ self.api_open = api_open
1228
+ if client_position_to_load_data is not None:
1229
+ warnings.warn("The client_position_to_load_data parameter is deprecated.")
1230
+ self._queue = queueing.Queue(
1231
+ live_updates=status_update_rate == "auto",
1232
+ concurrency_count=concurrency_count,
1233
+ update_intervals=status_update_rate if status_update_rate != "auto" else 1,
1234
+ max_size=max_size,
1235
+ blocks_dependencies=self.dependencies,
1236
+ )
1237
+ self.config = self.get_config_file()
1238
+ return self
1239
+
1240
+ def launch(
1241
+ self,
1242
+ inline: bool | None = None,
1243
+ inbrowser: bool = False,
1244
+ share: bool | None = None,
1245
+ debug: bool = False,
1246
+ enable_queue: bool | None = None,
1247
+ max_threads: int = 40,
1248
+ auth: Callable | Tuple[str, str] | List[Tuple[str, str]] | None = None,
1249
+ auth_message: str | None = None,
1250
+ prevent_thread_lock: bool = False,
1251
+ show_error: bool = False,
1252
+ server_name: str | None = None,
1253
+ server_port: int | None = None,
1254
+ show_tips: bool = False,
1255
+ height: int = 500,
1256
+ width: int | str = "100%",
1257
+ encrypt: bool = False,
1258
+ favicon_path: str | None = None,
1259
+ ssl_keyfile: str | None = None,
1260
+ ssl_certfile: str | None = None,
1261
+ ssl_keyfile_password: str | None = None,
1262
+ quiet: bool = False,
1263
+ show_api: bool = True,
1264
+ _frontend: bool = True,
1265
+ ) -> Tuple[FastAPI, str, str]:
1266
+ """
1267
+ Launches a simple web server that serves the demo. Can also be used to create a
1268
+ public link used by anyone to access the demo from their browser by setting share=True.
1269
+
1270
+ Parameters:
1271
+ inline: whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.
1272
+ inbrowser: whether to automatically launch the interface in a new tab on the default browser.
1273
+ share: whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
1274
+ debug: if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
1275
+ auth: If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login.
1276
+ auth_message: If provided, HTML message provided on login page.
1277
+ prevent_thread_lock: If True, the interface will block the main thread while the server is running.
1278
+ show_error: If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log
1279
+ server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
1280
+ server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
1281
+ show_tips: if True, will occasionally show tips about new Gradio features
1282
+ enable_queue: DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
1283
+ max_threads: the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue.
1284
+ width: The width in pixels of the iframe element containing the interface (used if inline=True)
1285
+ height: The height in pixels of the iframe element containing the interface (used if inline=True)
1286
+ encrypt: If True, flagged data will be encrypted by key provided by creator at launch
1287
+ favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
1288
+ ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
1289
+ ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
1290
+ ssl_keyfile_password: If a password is provided, will use this with the ssl certificate for https.
1291
+ quiet: If True, suppresses most print statements.
1292
+ show_api: If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api.
1293
+ Returns:
1294
+ app: FastAPI app object that is running the demo
1295
+ local_url: Locally accessible link to the demo
1296
+ share_url: Publicly accessible link to the demo (if share=True, otherwise None)
1297
+ Example:
1298
+ import gradio as gr
1299
+ def reverse(text):
1300
+ return text[::-1]
1301
+ demo = gr.Interface(reverse, "text", "text")
1302
+ demo.launch(share=True, auth=("username", "password"))
1303
+ """
1304
+ self.dev_mode = False
1305
+ if (
1306
+ auth
1307
+ and not callable(auth)
1308
+ and not isinstance(auth[0], tuple)
1309
+ and not isinstance(auth[0], list)
1310
+ ):
1311
+ self.auth = [auth]
1312
+ else:
1313
+ self.auth = auth
1314
+ self.auth_message = auth_message
1315
+ self.show_tips = show_tips
1316
+ self.show_error = show_error
1317
+ self.height = height
1318
+ self.width = width
1319
+ self.favicon_path = favicon_path
1320
+
1321
+ if enable_queue is not None:
1322
+ self.enable_queue = enable_queue
1323
+ warnings.warn(
1324
+ "The `enable_queue` parameter has been deprecated. Please use the `.queue()` method instead.",
1325
+ DeprecationWarning,
1326
+ )
1327
+
1328
+ if self.is_space:
1329
+ self.enable_queue = self.enable_queue is not False
1330
+ else:
1331
+ self.enable_queue = self.enable_queue is True
1332
+ if self.enable_queue and not hasattr(self, "_queue"):
1333
+ self.queue()
1334
+ self.show_api = self.api_open if self.enable_queue else show_api
1335
+
1336
+ if not self.enable_queue and self.progress_tracking:
1337
+ raise ValueError("Progress tracking requires queuing to be enabled.")
1338
+
1339
+ for dep in self.dependencies:
1340
+ for i in dep["cancels"]:
1341
+ if not self.queue_enabled_for_fn(i):
1342
+ raise ValueError(
1343
+ "In order to cancel an event, the queue for that event must be enabled! "
1344
+ "You may get this error by either 1) passing a function that uses the yield keyword "
1345
+ "into an interface without enabling the queue or 2) defining an event that cancels "
1346
+ "another event without enabling the queue. Both can be solved by calling .queue() "
1347
+ "before .launch()"
1348
+ )
1349
+ if dep["batch"] and (
1350
+ dep["queue"] is False
1351
+ or (dep["queue"] is None and not self.enable_queue)
1352
+ ):
1353
+ raise ValueError("In order to use batching, the queue must be enabled.")
1354
+
1355
+ self.config = self.get_config_file()
1356
+ self.encrypt = encrypt
1357
+ self.max_threads = max(
1358
+ self._queue.max_thread_count if self.enable_queue else 0, max_threads
1359
+ )
1360
+ if self.encrypt:
1361
+ self.encryption_key = encryptor.get_key(
1362
+ getpass.getpass("Enter key for encryption: ")
1363
+ )
1364
+
1365
+ if self.is_running:
1366
+ assert isinstance(
1367
+ self.local_url, str
1368
+ ), f"Invalid local_url: {self.local_url}"
1369
+ if not (quiet):
1370
+ print(
1371
+ "Rerunning server... use `close()` to stop if you need to change `launch()` parameters.\n----"
1372
+ )
1373
+ else:
1374
+ server_name, server_port, local_url, app, server = networking.start_server(
1375
+ self,
1376
+ server_name,
1377
+ server_port,
1378
+ ssl_keyfile,
1379
+ ssl_certfile,
1380
+ ssl_keyfile_password,
1381
+ )
1382
+ self.server_name = server_name
1383
+ self.local_url = local_url
1384
+ self.server_port = server_port
1385
+ self.server_app = app
1386
+ self.server = server
1387
+ self.is_running = True
1388
+ self.is_colab = utils.colab_check()
1389
+ self.protocol = (
1390
+ "https"
1391
+ if self.local_url.startswith("https") or self.is_colab
1392
+ else "http"
1393
+ )
1394
+
1395
+ if self.enable_queue:
1396
+ self._queue.set_url(self.local_url)
1397
+
1398
+ # Cannot run async functions in background other than app's scope.
1399
+ # Workaround by triggering the app endpoint
1400
+ requests.get(f"{self.local_url}startup-events")
1401
+
1402
+ if self.enable_queue:
1403
+ if self.encrypt:
1404
+ raise ValueError("Cannot queue with encryption enabled.")
1405
+ utils.launch_counter()
1406
+
1407
+ self.share = (
1408
+ share
1409
+ if share is not None
1410
+ else True
1411
+ if self.is_colab and self.enable_queue
1412
+ else False
1413
+ )
1414
+
1415
+ # If running in a colab or not able to access localhost,
1416
+ # a shareable link must be created.
1417
+ if _frontend and (not networking.url_ok(self.local_url)) and (not self.share):
1418
+ raise ValueError(
1419
+ "When localhost is not accessible, a shareable link must be created. Please set share=True."
1420
+ )
1421
+
1422
+ if self.is_colab:
1423
+ if not quiet:
1424
+ if debug:
1425
+ print(strings.en["COLAB_DEBUG_TRUE"])
1426
+ else:
1427
+ print(strings.en["COLAB_DEBUG_FALSE"])
1428
+ if not self.share:
1429
+ print(strings.en["COLAB_WARNING"].format(self.server_port))
1430
+ if self.enable_queue and not self.share:
1431
+ raise ValueError(
1432
+ "When using queueing in Colab, a shareable link must be created. Please set share=True."
1433
+ )
1434
+ else:
1435
+ if not self.share:
1436
+ print(f'Running on local URL: https://{self.server_name}')
1437
+
1438
+ if self.share:
1439
+ if self.is_space:
1440
+ raise RuntimeError("Share is not supported when you are in Spaces")
1441
+ try:
1442
+ if self.share_url is None:
1443
+ self.share_url = networking.setup_tunnel(
1444
+ self.server_name, self.server_port
1445
+ )
1446
+ print(strings.en["SHARE_LINK_DISPLAY"].format(self.share_url))
1447
+ if not (quiet):
1448
+ print('\u2714 Connected')
1449
+ except RuntimeError:
1450
+ if self.analytics_enabled:
1451
+ utils.error_analytics(self.ip_address, "Not able to set up tunnel")
1452
+ self.share_url = None
1453
+ self.share = False
1454
+ print(strings.en["COULD_NOT_GET_SHARE_LINK"])
1455
+ else:
1456
+ if not (quiet):
1457
+ print('\u2714 Connected')
1458
+ self.share_url = None
1459
+
1460
+ if inbrowser:
1461
+ link = self.share_url if self.share and self.share_url else self.local_url
1462
+ webbrowser.open(link)
1463
+
1464
+ # Check if running in a Python notebook in which case, display inline
1465
+ if inline is None:
1466
+ inline = utils.ipython_check() and (self.auth is None)
1467
+ if inline:
1468
+ if self.auth is not None:
1469
+ print(
1470
+ "Warning: authentication is not supported inline. Please"
1471
+ "click the link to access the interface in a new tab."
1472
+ )
1473
+ try:
1474
+ from IPython.display import HTML, Javascript, display # type: ignore
1475
+
1476
+ if self.share and self.share_url:
1477
+ while not networking.url_ok(self.share_url):
1478
+ time.sleep(0.25)
1479
+ display(
1480
+ HTML(
1481
+ f'<div><iframe src="{self.share_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
1482
+ )
1483
+ )
1484
+ elif self.is_colab:
1485
+ # modified from /usr/local/lib/python3.7/dist-packages/google/colab/output/_util.py within Colab environment
1486
+ code = """(async (port, path, width, height, cache, element) => {
1487
+ if (!google.colab.kernel.accessAllowed && !cache) {
1488
+ return;
1489
+ }
1490
+ element.appendChild(document.createTextNode(''));
1491
+ const url = await google.colab.kernel.proxyPort(port, {cache});
1492
+
1493
+ const external_link = document.createElement('div');
1494
+ external_link.innerHTML = `
1495
+ <div style="font-family: monospace; margin-bottom: 0.5rem">
1496
+ Running on <a href=${new URL(path, url).toString()} target="_blank">
1497
+ https://localhost:${port}${path}
1498
+ </a>
1499
+ </div>
1500
+ `;
1501
+ element.appendChild(external_link);
1502
+
1503
+ const iframe = document.createElement('iframe');
1504
+ iframe.src = new URL(path, url).toString();
1505
+ iframe.height = height;
1506
+ iframe.allow = "autoplay; camera; microphone; clipboard-read; clipboard-write;"
1507
+ iframe.width = width;
1508
+ iframe.style.border = 0;
1509
+ element.appendChild(iframe);
1510
+ })""" + "({port}, {path}, {width}, {height}, {cache}, window.element)".format(
1511
+ port=json.dumps(self.server_port),
1512
+ path=json.dumps("/"),
1513
+ width=json.dumps(self.width),
1514
+ height=json.dumps(self.height),
1515
+ cache=json.dumps(False),
1516
+ )
1517
+
1518
+ display(Javascript(code))
1519
+ else:
1520
+ display(
1521
+ HTML(
1522
+ f'<div><iframe src="{self.local_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
1523
+ )
1524
+ )
1525
+ except ImportError:
1526
+ pass
1527
+
1528
+ if getattr(self, "analytics_enabled", False):
1529
+ data = {
1530
+ "launch_method": "browser" if inbrowser else "inline",
1531
+ "is_google_colab": self.is_colab,
1532
+ "is_sharing_on": self.share,
1533
+ "share_url": self.share_url,
1534
+ "ip_address": self.ip_address,
1535
+ "enable_queue": self.enable_queue,
1536
+ "show_tips": self.show_tips,
1537
+ "server_name": server_name,
1538
+ "server_port": server_port,
1539
+ "is_spaces": self.is_space,
1540
+ "mode": self.mode,
1541
+ }
1542
+ utils.launch_analytics(data)
1543
+
1544
+ utils.show_tip(self)
1545
+
1546
+ # Block main thread if debug==True
1547
+ if debug or int(os.getenv("GRADIO_DEBUG", 0)) == 1:
1548
+ self.block_thread()
1549
+ # Block main thread if running in a script to stop script from exiting
1550
+ is_in_interactive_mode = bool(getattr(sys, "ps1", sys.flags.interactive))
1551
+
1552
+ if not prevent_thread_lock and not is_in_interactive_mode:
1553
+ self.block_thread()
1554
+
1555
+ return TupleNoPrint((self.server_app, self.local_url, self.share_url))
1556
+
1557
+ def integrate(
1558
+ self,
1559
+ comet_ml: comet_ml.Experiment | None = None,
1560
+ wandb: ModuleType | None = None,
1561
+ mlflow: ModuleType | None = None,
1562
+ ) -> None:
1563
+ """
1564
+ A catch-all method for integrating with other libraries. This method should be run after launch()
1565
+ Parameters:
1566
+ comet_ml: If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
1567
+ wandb: If the wandb module is provided, will integrate with it and appear on WandB dashboard
1568
+ mlflow: If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard
1569
+ """
1570
+ analytics_integration = ""
1571
+ if comet_ml is not None:
1572
+ analytics_integration = "CometML"
1573
+ comet_ml.log_other("Created from", "Gradio")
1574
+ if self.share_url is not None:
1575
+ comet_ml.log_text("gradio: " + self.share_url)
1576
+ comet_ml.end()
1577
+ elif self.local_url:
1578
+ comet_ml.log_text("gradio: " + self.local_url)
1579
+ comet_ml.end()
1580
+ else:
1581
+ raise ValueError("Please run `launch()` first.")
1582
+ if wandb is not None:
1583
+ analytics_integration = "WandB"
1584
+ if self.share_url is not None:
1585
+ wandb.log(
1586
+ {
1587
+ "Gradio panel": wandb.Html(
1588
+ '<iframe src="'
1589
+ + self.share_url
1590
+ + '" width="'
1591
+ + str(self.width)
1592
+ + '" height="'
1593
+ + str(self.height)
1594
+ + '" frameBorder="0"></iframe>'
1595
+ )
1596
+ }
1597
+ )
1598
+ else:
1599
+ print(
1600
+ "The WandB integration requires you to "
1601
+ "`launch(share=True)` first."
1602
+ )
1603
+ if mlflow is not None:
1604
+ analytics_integration = "MLFlow"
1605
+ if self.share_url is not None:
1606
+ mlflow.log_param("Gradio Interface Share Link", self.share_url)
1607
+ else:
1608
+ mlflow.log_param("Gradio Interface Local Link", self.local_url)
1609
+ if self.analytics_enabled and analytics_integration:
1610
+ data = {"integration": analytics_integration}
1611
+ utils.integration_analytics(data)
1612
+
1613
+ def close(self, verbose: bool = True) -> None:
1614
+ """
1615
+ Closes the Interface that was launched and frees the port.
1616
+ """
1617
+ try:
1618
+ if self.enable_queue:
1619
+ self._queue.close()
1620
+ self.server.close()
1621
+ self.is_running = False
1622
+ if verbose:
1623
+ print("Closing server running on port: {}".format(self.server_port))
1624
+ except (AttributeError, OSError): # can't close if not running
1625
+ pass
1626
+
1627
+ def block_thread(
1628
+ self,
1629
+ ) -> None:
1630
+ """Block main thread until interrupted by user."""
1631
+ try:
1632
+ while True:
1633
+ time.sleep(0.1)
1634
+ except (KeyboardInterrupt, OSError):
1635
+ print("Keyboard interruption in main thread... closing server.")
1636
+ self.server.close()
1637
+ for tunnel in CURRENT_TUNNELS:
1638
+ tunnel.kill()
1639
+
1640
+ def attach_load_events(self):
1641
+ """Add a load event for every component whose initial value should be randomized."""
1642
+ if Context.root_block:
1643
+ for component in Context.root_block.blocks.values():
1644
+ if (
1645
+ isinstance(component, components.IOComponent)
1646
+ and component.load_event_to_attach
1647
+ ):
1648
+ load_fn, every = component.load_event_to_attach
1649
+ # Use set_event_trigger to avoid ambiguity between load class/instance method
1650
+ self.set_event_trigger(
1651
+ "load",
1652
+ load_fn,
1653
+ None,
1654
+ component,
1655
+ no_target=True,
1656
+ queue=False,
1657
+ every=every,
1658
+ )
1659
+
1660
+ def startup_events(self):
1661
+ """Events that should be run when the app containing this block starts up."""
1662
+
1663
+ if self.enable_queue:
1664
+ utils.run_coro_in_background(self._queue.start, (self.progress_tracking,))
1665
+ utils.run_coro_in_background(self.create_limiter)
1666
+
1667
+ def queue_enabled_for_fn(self, fn_index: int):
1668
+ if self.dependencies[fn_index]["queue"] is None:
1669
+ return self.enable_queue
1670
+ return self.dependencies[fn_index]["queue"]
extras.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shutil
4
+
5
+
6
+ import torch
7
+ import tqdm
8
+
9
+ from modules import shared, images, sd_models, sd_vae, sd_models_config
10
+ from modules.ui_common import plaintext_to_html
11
+ import gradio as gr
12
+ import safetensors.torch
13
+
14
+
15
+ def run_pnginfo(image):
16
+ if image is None:
17
+ return '', '', ''
18
+
19
+ geninfo, items = images.read_info_from_image(image)
20
+ items = {**{'parameters': geninfo}, **items}
21
+
22
+ info = ''
23
+ for key, text in items.items():
24
+ info += f"""
25
+ <div>
26
+ <p><b>{plaintext_to_html(str(key))}</b></p>
27
+ <p>{plaintext_to_html(str(text))}</p>
28
+ </div>
29
+ """.strip()+"\n"
30
+
31
+ if len(info) == 0:
32
+ message = "Nothing found in the image."
33
+ info = f"<div><p>{message}<p></div>"
34
+
35
+ return '', geninfo, info
36
+
37
+
38
+ def create_config(ckpt_result, config_source, a, b, c):
39
+ def config(x):
40
+ res = sd_models_config.find_checkpoint_config_near_filename(x) if x else None
41
+ return res if res != shared.sd_default_config else None
42
+
43
+ if config_source == 0:
44
+ cfg = config(a) or config(b) or config(c)
45
+ elif config_source == 1:
46
+ cfg = config(b)
47
+ elif config_source == 2:
48
+ cfg = config(c)
49
+ else:
50
+ cfg = None
51
+
52
+ if cfg is None:
53
+ return
54
+
55
+ filename, _ = os.path.splitext(ckpt_result)
56
+ checkpoint_filename = filename + ".yaml"
57
+
58
+ print("Copying config:")
59
+ print(" from:", cfg)
60
+ print(" to:", checkpoint_filename)
61
+ shutil.copyfile(cfg, checkpoint_filename)
62
+
63
+
64
+ checkpoint_dict_skip_on_merge = ["cond_stage_model.transformer.text_model.embeddings.position_ids"]
65
+
66
+
67
+ def to_half(tensor, enable):
68
+ if enable and tensor.dtype == torch.float:
69
+ return tensor.half()
70
+
71
+ return tensor
72
+
73
+
74
+ def run_modelmerger(id_task, primary_model_name, secondary_model_name, tertiary_model_name, interp_method, multiplier, save_as_half, custom_name, checkpoint_format, config_source, bake_in_vae, discard_weights):
75
+ shared.state.begin()
76
+ shared.state.job = 'model-merge'
77
+
78
+ def fail(message):
79
+ shared.state.textinfo = message
80
+ shared.state.end()
81
+ return [*[gr.update() for _ in range(4)], message]
82
+
83
+ def weighted_sum(theta0, theta1, alpha):
84
+ return ((1 - alpha) * theta0) + (alpha * theta1)
85
+
86
+ def get_difference(theta1, theta2):
87
+ return theta1 - theta2
88
+
89
+ def add_difference(theta0, theta1_2_diff, alpha):
90
+ return theta0 + (alpha * theta1_2_diff)
91
+
92
+ def filename_weighted_sum():
93
+ a = primary_model_info.model_name
94
+ b = secondary_model_info.model_name
95
+ Ma = round(1 - multiplier, 2)
96
+ Mb = round(multiplier, 2)
97
+
98
+ return f"{Ma}({a}) + {Mb}({b})"
99
+
100
+ def filename_add_difference():
101
+ a = primary_model_info.model_name
102
+ b = secondary_model_info.model_name
103
+ c = tertiary_model_info.model_name
104
+ M = round(multiplier, 2)
105
+
106
+ return f"{a} + {M}({b} - {c})"
107
+
108
+ def filename_nothing():
109
+ return primary_model_info.model_name
110
+
111
+ theta_funcs = {
112
+ "Weighted sum": (filename_weighted_sum, None, weighted_sum),
113
+ "Add difference": (filename_add_difference, get_difference, add_difference),
114
+ "No interpolation": (filename_nothing, None, None),
115
+ }
116
+ filename_generator, theta_func1, theta_func2 = theta_funcs[interp_method]
117
+ shared.state.job_count = (1 if theta_func1 else 0) + (1 if theta_func2 else 0)
118
+
119
+ if not primary_model_name:
120
+ return fail("Failed: Merging requires a primary model.")
121
+
122
+ primary_model_info = sd_models.checkpoints_list[primary_model_name]
123
+
124
+ if theta_func2 and not secondary_model_name:
125
+ return fail("Failed: Merging requires a secondary model.")
126
+
127
+ secondary_model_info = sd_models.checkpoints_list[secondary_model_name] if theta_func2 else None
128
+
129
+ if theta_func1 and not tertiary_model_name:
130
+ return fail(f"Failed: Interpolation method ({interp_method}) requires a tertiary model.")
131
+
132
+ tertiary_model_info = sd_models.checkpoints_list[tertiary_model_name] if theta_func1 else None
133
+
134
+ result_is_inpainting_model = False
135
+ result_is_instruct_pix2pix_model = False
136
+
137
+ if theta_func2:
138
+ shared.state.textinfo = f"Loading B"
139
+ print(f"Loading {secondary_model_info.filename}...")
140
+ theta_1 = sd_models.read_state_dict(secondary_model_info.filename, map_location='cpu')
141
+ else:
142
+ theta_1 = None
143
+
144
+ if theta_func1:
145
+ shared.state.textinfo = f"Loading C"
146
+ print(f"Loading {tertiary_model_info.filename}...")
147
+ theta_2 = sd_models.read_state_dict(tertiary_model_info.filename, map_location='cpu')
148
+
149
+ shared.state.textinfo = 'Merging B and C'
150
+ shared.state.sampling_steps = len(theta_1.keys())
151
+ for key in tqdm.tqdm(theta_1.keys()):
152
+ if key in checkpoint_dict_skip_on_merge:
153
+ continue
154
+
155
+ if 'model' in key:
156
+ if key in theta_2:
157
+ t2 = theta_2.get(key, torch.zeros_like(theta_1[key]))
158
+ theta_1[key] = theta_func1(theta_1[key], t2)
159
+ else:
160
+ theta_1[key] = torch.zeros_like(theta_1[key])
161
+
162
+ shared.state.sampling_step += 1
163
+ del theta_2
164
+
165
+ shared.state.nextjob()
166
+
167
+ shared.state.textinfo = f"Loading {primary_model_info.filename}..."
168
+ print(f"Loading {primary_model_info.filename}...")
169
+ theta_0 = sd_models.read_state_dict(primary_model_info.filename, map_location='cpu')
170
+
171
+ print("Merging...")
172
+ shared.state.textinfo = 'Merging A and B'
173
+ shared.state.sampling_steps = len(theta_0.keys())
174
+ for key in tqdm.tqdm(theta_0.keys()):
175
+ if theta_1 and 'model' in key and key in theta_1:
176
+
177
+ if key in checkpoint_dict_skip_on_merge:
178
+ continue
179
+
180
+ a = theta_0[key]
181
+ b = theta_1[key]
182
+
183
+ # this enables merging an inpainting model (A) with another one (B);
184
+ # where normal model would have 4 channels, for latenst space, inpainting model would
185
+ # have another 4 channels for unmasked picture's latent space, plus one channel for mask, for a total of 9
186
+ if a.shape != b.shape and a.shape[0:1] + a.shape[2:] == b.shape[0:1] + b.shape[2:]:
187
+ if a.shape[1] == 4 and b.shape[1] == 9:
188
+ raise RuntimeError("When merging inpainting model with a normal one, A must be the inpainting model.")
189
+ if a.shape[1] == 4 and b.shape[1] == 8:
190
+ raise RuntimeError("When merging instruct-pix2pix model with a normal one, A must be the instruct-pix2pix model.")
191
+
192
+ if a.shape[1] == 8 and b.shape[1] == 4:#If we have an Instruct-Pix2Pix model...
193
+ theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier)#Merge only the vectors the models have in common. Otherwise we get an error due to dimension mismatch.
194
+ result_is_instruct_pix2pix_model = True
195
+ else:
196
+ assert a.shape[1] == 9 and b.shape[1] == 4, f"Bad dimensions for merged layer {key}: A={a.shape}, B={b.shape}"
197
+ theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier)
198
+ result_is_inpainting_model = True
199
+ else:
200
+ theta_0[key] = theta_func2(a, b, multiplier)
201
+
202
+ theta_0[key] = to_half(theta_0[key], save_as_half)
203
+
204
+ shared.state.sampling_step += 1
205
+
206
+ del theta_1
207
+
208
+ bake_in_vae_filename = sd_vae.vae_dict.get(bake_in_vae, None)
209
+ if bake_in_vae_filename is not None:
210
+ print(f"Baking in VAE from {bake_in_vae_filename}")
211
+ shared.state.textinfo = 'Baking in VAE'
212
+ vae_dict = sd_vae.load_vae_dict(bake_in_vae_filename, map_location='cpu')
213
+
214
+ for key in vae_dict.keys():
215
+ theta_0_key = 'first_stage_model.' + key
216
+ if theta_0_key in theta_0:
217
+ theta_0[theta_0_key] = to_half(vae_dict[key], save_as_half)
218
+
219
+ del vae_dict
220
+
221
+ if save_as_half and not theta_func2:
222
+ for key in theta_0.keys():
223
+ theta_0[key] = to_half(theta_0[key], save_as_half)
224
+
225
+ if discard_weights:
226
+ regex = re.compile(discard_weights)
227
+ for key in list(theta_0):
228
+ if re.search(regex, key):
229
+ theta_0.pop(key, None)
230
+
231
+ ckpt_dir = shared.cmd_opts.ckpt_dir or sd_models.model_path
232
+
233
+ filename = filename_generator() if custom_name == '' else custom_name
234
+ filename += ".inpainting" if result_is_inpainting_model else ""
235
+ filename += ".instruct-pix2pix" if result_is_instruct_pix2pix_model else ""
236
+ filename += "." + checkpoint_format
237
+
238
+ output_modelname = os.path.join(ckpt_dir, filename)
239
+
240
+ shared.state.nextjob()
241
+ shared.state.textinfo = "Saving"
242
+ print(f"Saving to {output_modelname}...")
243
+
244
+ _, extension = os.path.splitext(output_modelname)
245
+ if extension.lower() == ".safetensors":
246
+ safetensors.torch.save_file(theta_0, output_modelname, metadata={"format": "pt"})
247
+ else:
248
+ torch.save(theta_0, output_modelname)
249
+
250
+ sd_models.list_models()
251
+
252
+ create_config(output_modelname, config_source, primary_model_info, secondary_model_info, tertiary_model_info)
253
+
254
+ print(f"Checkpoint saved to {output_modelname}.")
255
+ shared.state.textinfo = "Checkpoint saved"
256
+ shared.state.end()
257
+
258
+ return [*[gr.Dropdown.update(choices=sd_models.checkpoint_tiles()) for _ in range(4)], "Checkpoint saved to " + output_modelname]
paths.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import modules.safe
5
+
6
+ script_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
7
+
8
+ # Parse the --data-dir flag first so we can use it as a base for our other argument default values
9
+ parser = argparse.ArgumentParser(add_help=False)
10
+ parser.add_argument("--data-dir", type=str, default=os.path.dirname(os.path.dirname(os.path.realpath(__file__))), help="base path where all user data is stored",)
11
+ cmd_opts_pre = parser.parse_known_args()[0]
12
+ data_path = cmd_opts_pre.data_dir
13
+ models_path = os.path.join(data_path, "models")
14
+
15
+ # data_path = cmd_opts_pre.data
16
+ sys.path.insert(0, script_path)
17
+
18
+ # search for directory of stable diffusion in following places
19
+ sd_path = None
20
+ possible_sd_paths = [os.path.join(script_path, '/content/gdrive/MyDrive/sd/stablediffusion'), '.', os.path.dirname(script_path)]
21
+ for possible_sd_path in possible_sd_paths:
22
+ if os.path.exists(os.path.join(possible_sd_path, 'ldm/models/diffusion/ddpm.py')):
23
+ sd_path = os.path.abspath(possible_sd_path)
24
+ break
25
+
26
+ assert sd_path is not None, "Couldn't find Stable Diffusion in any of: " + str(possible_sd_paths)
27
+
28
+ path_dirs = [
29
+ (sd_path, 'ldm', 'Stable Diffusion', []),
30
+ (os.path.join(sd_path, 'src/taming-transformers'), 'taming', 'Taming Transformers', []),
31
+ (os.path.join(sd_path, 'src/codeformer'), 'inference_codeformer.py', 'CodeFormer', []),
32
+ (os.path.join(sd_path, 'src/blip'), 'models/blip.py', 'BLIP', []),
33
+ (os.path.join(sd_path, 'src/k-diffusion'), 'k_diffusion/sampling.py', 'k_diffusion', ["atstart"]),
34
+ ]
35
+
36
+ paths = {}
37
+
38
+ for d, must_exist, what, options in path_dirs:
39
+ must_exist_path = os.path.abspath(os.path.join(script_path, d, must_exist))
40
+ if not os.path.exists(must_exist_path):
41
+ print(f"Warning: {what} not found at path {must_exist_path}", file=sys.stderr)
42
+ else:
43
+ d = os.path.abspath(d)
44
+ if "atstart" in options:
45
+ sys.path.insert(0, d)
46
+ else:
47
+ sys.path.append(d)
48
+ paths[what] = d
49
+
50
+ class Prioritize:
51
+ def __init__(self, name):
52
+ self.name = name
53
+ self.path = None
54
+
55
+ def __enter__(self):
56
+ self.path = sys.path.copy()
57
+ sys.path = [paths[self.name]] + sys.path
58
+
59
+ def __exit__(self, exc_type, exc_val, exc_tb):
60
+ sys.path = self.path
61
+ self.path = None
sd_models.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import os.path
3
+ import sys
4
+ import gc
5
+ import torch
6
+ import re
7
+ import safetensors.torch
8
+ from omegaconf import OmegaConf
9
+ from os import mkdir
10
+ from urllib import request
11
+ import ldm.modules.midas as midas
12
+
13
+ from ldm.util import instantiate_from_config
14
+
15
+ from modules import paths, shared, modelloader, devices, script_callbacks, sd_vae, sd_disable_initialization, errors, hashes, sd_models_config
16
+ from modules.paths import models_path
17
+ from modules.sd_hijack_inpainting import do_inpainting_hijack
18
+ from modules.timer import Timer
19
+
20
+ model_dir = "Stable-diffusion"
21
+ model_path = os.path.abspath(os.path.join(paths.models_path, model_dir))
22
+
23
+ checkpoints_list = {}
24
+ checkpoint_alisases = {}
25
+ checkpoints_loaded = collections.OrderedDict()
26
+
27
+
28
+ class CheckpointInfo:
29
+ def __init__(self, filename):
30
+ self.filename = filename
31
+ abspath = os.path.abspath(filename)
32
+
33
+ if shared.cmd_opts.ckpt_dir is not None and abspath.startswith(shared.cmd_opts.ckpt_dir):
34
+ name = abspath.replace(shared.cmd_opts.ckpt_dir, '')
35
+ elif abspath.startswith(model_path):
36
+ name = abspath.replace(model_path, '')
37
+ else:
38
+ name = os.path.basename(filename)
39
+
40
+ if name.startswith("\\") or name.startswith("/"):
41
+ name = name[1:]
42
+
43
+ self.name = name
44
+ self.name_for_extra = os.path.splitext(os.path.basename(filename))[0]
45
+ self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0]
46
+ self.hash = model_hash(filename)
47
+
48
+ self.sha256 = hashes.sha256_from_cache(self.filename, "checkpoint/" + name)
49
+ self.shorthash = self.sha256[0:10] if self.sha256 else None
50
+
51
+ self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]'
52
+
53
+ self.ids = [self.hash, self.model_name, self.title, name, f'{name} [{self.hash}]'] + ([self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]'] if self.shorthash else [])
54
+
55
+ def register(self):
56
+ checkpoints_list[self.title] = self
57
+ for id in self.ids:
58
+ checkpoint_alisases[id] = self
59
+
60
+ def calculate_shorthash(self):
61
+ self.sha256 = hashes.sha256(self.filename, "checkpoint/" + self.name)
62
+ if self.sha256 is None:
63
+ return
64
+
65
+ self.shorthash = self.sha256[0:10]
66
+
67
+ if self.shorthash not in self.ids:
68
+ self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]']
69
+
70
+ checkpoints_list.pop(self.title)
71
+ self.title = f'{self.name} [{self.shorthash}]'
72
+ self.register()
73
+
74
+ return self.shorthash
75
+
76
+
77
+ try:
78
+ # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.
79
+
80
+ from transformers import logging, CLIPModel
81
+
82
+ logging.set_verbosity_error()
83
+ except Exception:
84
+ pass
85
+
86
+
87
+ def setup_model():
88
+ if not os.path.exists(model_path):
89
+ os.makedirs(model_path)
90
+
91
+ list_models()
92
+ enable_midas_autodownload()
93
+
94
+
95
+ def checkpoint_tiles():
96
+ def convert(name):
97
+ return int(name) if name.isdigit() else name.lower()
98
+
99
+ def alphanumeric_key(key):
100
+ return [convert(c) for c in re.split('([0-9]+)', key)]
101
+
102
+ return sorted([x.title for x in checkpoints_list.values()], key=alphanumeric_key)
103
+
104
+
105
+ def list_models():
106
+ checkpoints_list.clear()
107
+ checkpoint_alisases.clear()
108
+ model_list = modelloader.load_models(model_path=model_path, command_path=shared.cmd_opts.ckpt_dir, ext_filter=[".ckpt", ".safetensors"], ext_blacklist=[".vae.safetensors"])
109
+
110
+ cmd_ckpt = shared.cmd_opts.ckpt
111
+ if os.path.exists(cmd_ckpt):
112
+ checkpoint_info = CheckpointInfo(cmd_ckpt)
113
+ checkpoint_info.register()
114
+
115
+ shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title
116
+ elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file:
117
+ print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr)
118
+
119
+ for filename in model_list:
120
+ checkpoint_info = CheckpointInfo(filename)
121
+ checkpoint_info.register()
122
+
123
+
124
+ def get_closet_checkpoint_match(search_string):
125
+ checkpoint_info = checkpoint_alisases.get(search_string, None)
126
+ if checkpoint_info is not None:
127
+ return checkpoint_info
128
+
129
+ found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title))
130
+ if found:
131
+ return found[0]
132
+
133
+ return None
134
+
135
+
136
+ def model_hash(filename):
137
+ """old hash that only looks at a small part of the file and is prone to collisions"""
138
+
139
+ try:
140
+ with open(filename, "rb") as file:
141
+ import hashlib
142
+ m = hashlib.sha256()
143
+
144
+ file.seek(0x100000)
145
+ m.update(file.read(0x10000))
146
+ return m.hexdigest()[0:8]
147
+ except FileNotFoundError:
148
+ return 'NOFILE'
149
+
150
+
151
+ def select_checkpoint():
152
+ model_checkpoint = shared.opts.sd_model_checkpoint
153
+
154
+ checkpoint_info = checkpoint_alisases.get(model_checkpoint, None)
155
+ if checkpoint_info is not None:
156
+ return checkpoint_info
157
+
158
+ if len(checkpoints_list) == 0:
159
+ print("No checkpoints found. When searching for checkpoints, looked at:", file=sys.stderr)
160
+ if shared.cmd_opts.ckpt is not None:
161
+ print(f" - file {os.path.abspath(shared.cmd_opts.ckpt)}", file=sys.stderr)
162
+ print(f" - directory {model_path}", file=sys.stderr)
163
+ if shared.cmd_opts.ckpt_dir is not None:
164
+ print(f" - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}", file=sys.stderr)
165
+ print("Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations. The program will exit.", file=sys.stderr)
166
+ exit(1)
167
+
168
+ checkpoint_info = next(iter(checkpoints_list.values()))
169
+ if model_checkpoint is not None:
170
+ print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr)
171
+
172
+ return checkpoint_info
173
+
174
+
175
+ chckpoint_dict_replacements = {
176
+ 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.',
177
+ 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.',
178
+ 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.',
179
+ }
180
+
181
+
182
+ def transform_checkpoint_dict_key(k):
183
+ for text, replacement in chckpoint_dict_replacements.items():
184
+ if k.startswith(text):
185
+ k = replacement + k[len(text):]
186
+
187
+ return k
188
+
189
+
190
+ def get_state_dict_from_checkpoint(pl_sd):
191
+ pl_sd = pl_sd.pop("state_dict", pl_sd)
192
+ pl_sd.pop("state_dict", None)
193
+
194
+ sd = {}
195
+ for k, v in pl_sd.items():
196
+ new_key = transform_checkpoint_dict_key(k)
197
+
198
+ if new_key is not None:
199
+ sd[new_key] = v
200
+
201
+ pl_sd.clear()
202
+ pl_sd.update(sd)
203
+
204
+ return pl_sd
205
+
206
+
207
+ def read_state_dict(checkpoint_file, print_global_state=False, map_location=None):
208
+ _, extension = os.path.splitext(checkpoint_file)
209
+ if extension.lower() == ".safetensors":
210
+ device = map_location or shared.weight_load_location or devices.get_optimal_device_name()
211
+ pl_sd = safetensors.torch.load_file(checkpoint_file, device=device)
212
+ else:
213
+ pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location)
214
+
215
+ if print_global_state and "global_step" in pl_sd:
216
+ print(f"Global Step: {pl_sd['global_step']}")
217
+
218
+ sd = get_state_dict_from_checkpoint(pl_sd)
219
+ return sd
220
+
221
+
222
+ def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer):
223
+ sd_model_hash = checkpoint_info.calculate_shorthash()
224
+ timer.record("calculate hash")
225
+
226
+ if checkpoint_info in checkpoints_loaded:
227
+ # use checkpoint cache
228
+ print(f"Loading weights [{sd_model_hash}] from cache")
229
+ return checkpoints_loaded[checkpoint_info]
230
+
231
+ print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}")
232
+ res = read_state_dict(checkpoint_info.filename)
233
+ timer.record("load weights from disk")
234
+
235
+ return res
236
+
237
+
238
+ def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer):
239
+ sd_model_hash = checkpoint_info.calculate_shorthash()
240
+ timer.record("calculate hash")
241
+
242
+ shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title
243
+
244
+ if state_dict is None:
245
+ state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
246
+
247
+ model.load_state_dict(state_dict, strict=False)
248
+ del state_dict
249
+ timer.record("apply weights to model")
250
+
251
+ if shared.opts.sd_checkpoint_cache > 0:
252
+ # cache newly loaded model
253
+ checkpoints_loaded[checkpoint_info] = model.state_dict().copy()
254
+
255
+ if shared.cmd_opts.opt_channelslast:
256
+ model.to(memory_format=torch.channels_last)
257
+ timer.record("apply channels_last")
258
+
259
+ if not shared.cmd_opts.no_half:
260
+ vae = model.first_stage_model
261
+ depth_model = getattr(model, 'depth_model', None)
262
+
263
+ # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16
264
+ if shared.cmd_opts.no_half_vae:
265
+ model.first_stage_model = None
266
+ # with --upcast-sampling, don't convert the depth model weights to float16
267
+ if shared.cmd_opts.upcast_sampling and depth_model:
268
+ model.depth_model = None
269
+
270
+ model.half()
271
+ model.first_stage_model = vae
272
+ if depth_model:
273
+ model.depth_model = depth_model
274
+
275
+ timer.record("apply half()")
276
+
277
+ devices.dtype = torch.float32 if shared.cmd_opts.no_half else torch.float16
278
+ devices.dtype_vae = torch.float32 if shared.cmd_opts.no_half or shared.cmd_opts.no_half_vae else torch.float16
279
+ devices.dtype_unet = model.model.diffusion_model.dtype
280
+ devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16
281
+
282
+ model.first_stage_model.to(devices.dtype_vae)
283
+ timer.record("apply dtype to VAE")
284
+
285
+ # clean up cache if limit is reached
286
+ while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache:
287
+ checkpoints_loaded.popitem(last=False)
288
+
289
+ model.sd_model_hash = sd_model_hash
290
+ model.sd_model_checkpoint = checkpoint_info.filename
291
+ model.sd_checkpoint_info = checkpoint_info
292
+ shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256
293
+
294
+ model.logvar = model.logvar.to(devices.device) # fix for training
295
+
296
+ sd_vae.delete_base_vae()
297
+ sd_vae.clear_loaded_vae()
298
+ vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename)
299
+ sd_vae.load_vae(model, vae_file, vae_source)
300
+ timer.record("load VAE")
301
+
302
+
303
+ def enable_midas_autodownload():
304
+ """
305
+ Gives the ldm.modules.midas.api.load_model function automatic downloading.
306
+
307
+ When the 512-depth-ema model, and other future models like it, is loaded,
308
+ it calls midas.api.load_model to load the associated midas depth model.
309
+ This function applies a wrapper to download the model to the correct
310
+ location automatically.
311
+ """
312
+
313
+ midas_path = os.path.join(paths.models_path, 'midas')
314
+
315
+ # stable-diffusion-stability-ai hard-codes the midas model path to
316
+ # a location that differs from where other scripts using this model look.
317
+ # HACK: Overriding the path here.
318
+ for k, v in midas.api.ISL_PATHS.items():
319
+ file_name = os.path.basename(v)
320
+ midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name)
321
+
322
+ midas_urls = {
323
+ "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
324
+ "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt",
325
+ "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt",
326
+ "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt",
327
+ }
328
+
329
+ midas.api.load_model_inner = midas.api.load_model
330
+
331
+ def load_model_wrapper(model_type):
332
+ path = midas.api.ISL_PATHS[model_type]
333
+ if not os.path.exists(path):
334
+ if not os.path.exists(midas_path):
335
+ mkdir(midas_path)
336
+
337
+ print(f"Downloading midas model weights for {model_type} to {path}")
338
+ request.urlretrieve(midas_urls[model_type], path)
339
+ print(f"{model_type} downloaded")
340
+
341
+ return midas.api.load_model_inner(model_type)
342
+
343
+ midas.api.load_model = load_model_wrapper
344
+
345
+
346
+ def repair_config(sd_config):
347
+
348
+ if not hasattr(sd_config.model.params, "use_ema"):
349
+ sd_config.model.params.use_ema = False
350
+
351
+ if shared.cmd_opts.no_half:
352
+ sd_config.model.params.unet_config.params.use_fp16 = False
353
+ elif shared.cmd_opts.upcast_sampling:
354
+ sd_config.model.params.unet_config.params.use_fp16 = True
355
+
356
+
357
+ sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight'
358
+ sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight'
359
+
360
+ def load_model(checkpoint_info=None, already_loaded_state_dict=None, time_taken_to_load_state_dict=None):
361
+ from modules import lowvram, sd_hijack
362
+ checkpoint_info = checkpoint_info or select_checkpoint()
363
+
364
+ if shared.sd_model:
365
+ sd_hijack.model_hijack.undo_hijack(shared.sd_model)
366
+ shared.sd_model = None
367
+ gc.collect()
368
+ devices.torch_gc()
369
+
370
+ do_inpainting_hijack()
371
+
372
+ timer = Timer()
373
+
374
+ if already_loaded_state_dict is not None:
375
+ state_dict = already_loaded_state_dict
376
+ else:
377
+ state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
378
+
379
+ checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
380
+ clip_is_included_into_sd = sd1_clip_weight in state_dict or sd2_clip_weight in state_dict
381
+
382
+ timer.record("find config")
383
+
384
+ sd_config = OmegaConf.load(checkpoint_config)
385
+ repair_config(sd_config)
386
+
387
+ timer.record("load config")
388
+
389
+ print(f"Creating model from config: {checkpoint_config}")
390
+
391
+ sd_model = None
392
+ try:
393
+ with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd):
394
+ sd_model = instantiate_from_config(sd_config.model)
395
+ except Exception as e:
396
+ pass
397
+
398
+ if sd_model is None:
399
+ print('Failed to create model quickly; will retry using slow method.', file=sys.stderr)
400
+ sd_model = instantiate_from_config(sd_config.model)
401
+
402
+ sd_model.used_config = checkpoint_config
403
+
404
+ timer.record("create model")
405
+
406
+ load_model_weights(sd_model, checkpoint_info, state_dict, timer)
407
+
408
+ if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
409
+ lowvram.setup_for_low_vram(sd_model, shared.cmd_opts.medvram)
410
+ else:
411
+ sd_model.to(shared.device)
412
+
413
+ timer.record("move model to device")
414
+
415
+ sd_hijack.model_hijack.hijack(sd_model)
416
+
417
+ timer.record("hijack")
418
+
419
+ sd_model.eval()
420
+ shared.sd_model = sd_model
421
+
422
+ sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True) # Reload embeddings after model load as they may or may not fit the model
423
+
424
+ timer.record("load textual inversion embeddings")
425
+
426
+ script_callbacks.model_loaded_callback(sd_model)
427
+
428
+ timer.record("scripts callbacks")
429
+
430
+ print(f"Model loaded in {timer.summary()}.")
431
+
432
+ return sd_model
433
+
434
+
435
+ def reload_model_weights(sd_model=None, info=None):
436
+ from modules import lowvram, devices, sd_hijack
437
+ checkpoint_info = info or select_checkpoint()
438
+
439
+ if not sd_model:
440
+ sd_model = shared.sd_model
441
+
442
+ if sd_model is None: # previous model load failed
443
+ current_checkpoint_info = None
444
+ else:
445
+ current_checkpoint_info = sd_model.sd_checkpoint_info
446
+ if sd_model.sd_model_checkpoint == checkpoint_info.filename:
447
+ return
448
+
449
+ if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
450
+ lowvram.send_everything_to_cpu()
451
+ else:
452
+ sd_model.to(devices.cpu)
453
+
454
+ sd_hijack.model_hijack.undo_hijack(sd_model)
455
+
456
+ timer = Timer()
457
+
458
+ state_dict = get_checkpoint_state_dict(checkpoint_info, timer)
459
+
460
+ checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info)
461
+
462
+ timer.record("find config")
463
+
464
+ if sd_model is None or checkpoint_config != sd_model.used_config:
465
+ del sd_model
466
+ checkpoints_loaded.clear()
467
+ load_model(checkpoint_info, already_loaded_state_dict=state_dict, time_taken_to_load_state_dict=timer.records["load weights from disk"])
468
+ return shared.sd_model
469
+
470
+ try:
471
+ load_model_weights(sd_model, checkpoint_info, state_dict, timer)
472
+ except Exception as e:
473
+ print("Failed to load checkpoint, restoring previous")
474
+ load_model_weights(sd_model, current_checkpoint_info, None, timer)
475
+ raise
476
+ finally:
477
+ sd_hijack.model_hijack.hijack(sd_model)
478
+ timer.record("hijack")
479
+
480
+ script_callbacks.model_loaded_callback(sd_model)
481
+ timer.record("script callbacks")
482
+
483
+ if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
484
+ sd_model.to(devices.device)
485
+ timer.record("move model to device")
486
+
487
+ print(f"Weights loaded in {timer.summary()}.")
488
+
489
+ return sd_model