freddyaboulton HF staff commited on
Commit
372a6e6
1 Parent(s): ec011d9

Upload folder using huggingface_hub

Browse files
Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.9
3
+
4
+ WORKDIR /code
5
+
6
+ COPY --link --chown=1000 . .
7
+
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ ENV PYTHONUNBUFFERED=1 GRADIO_ALLOW_FLAGGING=never GRADIO_NUM_PORTS=1 GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860 SYSTEM=spaces
11
+
12
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,10 +1,10 @@
 
1
  ---
2
- title: Gradio Coolimage
3
- emoji: 📈
4
- colorFrom: yellow
5
- colorTo: indigo
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+
2
  ---
3
+ tags: [gradio-custom-component, gradio-template-Image]
4
+ title: gradio_coolimage V0.0.1
5
+ colorFrom: green
6
+ colorTo: yellow
7
  sdk: docker
8
  pinned: false
9
+ license: apache-2.0
10
  ---
 
 
__init__.py ADDED
File without changes
app.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from gradio_coolimage import CoolImage
4
+
5
+
6
+ example = CoolImage().example_inputs()
7
+
8
+ demo = gr.Interface(
9
+ lambda x:x,
10
+ CoolImage(), # interactive version of your component
11
+ CoolImage(), # static version of your component
12
+ # examples=[[example]], # uncomment this line to view the "example version" of your component
13
+ )
14
+
15
+
16
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ https://gradio-builds.s3.amazonaws.com/4.0/attempt-05/gradio-4.0.0-py3-none-any.whl
2
+ https://gradio-builds.s3.amazonaws.com/4.0/attempt-05/gradio_client-0.7.0b0-py3-none-any.whl
3
+ gradio_coolimage-0.0.1-py3-none-any.whl
src/.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .eggs/
2
+ dist/
3
+ *.pyc
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+ __tmp/*
8
+ *.pyi
9
+ node_modules
src/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # gradio_coolimage
3
+ A Custom Gradio component.
4
+
5
+ ## Example usage
6
+
7
+ ```python
8
+ import gradio as gr
9
+ from gradio_coolimage import CoolImage
10
+ ```
src/backend/gradio_coolimage/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ from .coolimage import CoolImage
3
+
4
+ __all__ = ['CoolImage']
src/backend/gradio_coolimage/coolimage.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Image() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import numpy as np
10
+ import PIL
11
+ import PIL.ImageOps
12
+ from gradio_client import utils as client_utils
13
+ from gradio_client.documentation import document, set_documentation_group
14
+ from PIL import Image as _Image # using _ to minimize namespace pollution
15
+
16
+ from gradio import processing_utils, utils
17
+ from gradio.components.base import Component, StreamingInput
18
+ from gradio.data_classes import FileData
19
+ from gradio.events import Events
20
+
21
+ set_documentation_group("component")
22
+ _Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
23
+
24
+
25
+ @document()
26
+ class CoolImage(StreamingInput, Component):
27
+ """
28
+ Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
29
+ Preprocessing: passes the uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a {dict} with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
30
+ Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} or {pathlib.Path} filepath to an image and displays the image.
31
+ Examples-format: a {str} local filepath or URL to an image.
32
+ Demos: image_mod, image_mod_default_image
33
+ Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary_app, create-your-own-friends-with-a-gan
34
+ """
35
+
36
+ EVENTS = [
37
+ Events.edit,
38
+ Events.clear,
39
+ Events.change,
40
+ Events.stream,
41
+ Events.select,
42
+ Events.upload,
43
+ ]
44
+ data_model = FileData
45
+
46
+ def __init__(
47
+ self,
48
+ value: str | _Image.Image | np.ndarray | None = None,
49
+ *,
50
+ shape: tuple[int, int] | None = None,
51
+ height: int | None = None,
52
+ width: int | None = None,
53
+ image_mode: Literal[
54
+ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F"
55
+ ] = "RGB",
56
+ invert_colors: bool = False,
57
+ source: Literal["upload", "webcam", "canvas"] = "upload",
58
+ tool: Literal["editor", "select", "sketch", "color-sketch"] | None = None,
59
+ type: Literal["numpy", "pil", "filepath"] = "numpy",
60
+ label: str | None = None,
61
+ every: float | None = None,
62
+ show_label: bool | None = None,
63
+ show_download_button: bool = True,
64
+ container: bool = True,
65
+ scale: int | None = None,
66
+ min_width: int = 160,
67
+ interactive: bool | None = None,
68
+ visible: bool = True,
69
+ streaming: bool = False,
70
+ elem_id: str | None = None,
71
+ elem_classes: list[str] | str | None = None,
72
+ render: bool = True,
73
+ root_url: str | None = None,
74
+ _skip_init_processing: bool = False,
75
+ mirror_webcam: bool = True,
76
+ brush_radius: float | None = None,
77
+ brush_color: str = "#000000",
78
+ mask_opacity: float = 0.7,
79
+ show_share_button: bool | None = None,
80
+ ):
81
+ """
82
+ Parameters:
83
+ value: A PIL CoolImage, numpy array, path or URL for the default value that CoolImage component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
84
+ shape: (width, height) shape to crop and resize image when passed to function. If None, matches input image size. Pass None for either width or height to only crop and resize the other.
85
+ height: Height of the displayed image in pixels.
86
+ width: Width of the displayed image in pixels.
87
+ image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.
88
+ invert_colors: whether to invert the image as a preprocessing step.
89
+ source: Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
90
+ tool: Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively.
91
+ type: The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image.
92
+ label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
93
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
94
+ show_label: if True, will display label.
95
+ show_download_button: If True, will display button to download image.
96
+ container: If True, will place the component in a container - providing some extra padding around the border.
97
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
98
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
99
+ interactive: if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.
100
+ visible: If False, component will be hidden.
101
+ streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.
102
+ elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
103
+ elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
104
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
105
+ root_url: The remote URL that of the Gradio app that this component belongs to. Used in `gr.load()`. Should not be set manually.
106
+ mirror_webcam: If True webcam will be mirrored. Default is True.
107
+ brush_radius: Size of the brush for Sketch. Default is None which chooses a sensible default
108
+ brush_color: Color of the brush for Sketch as hex string. Default is "#000000".
109
+ mask_opacity: Opacity of mask drawn on image, as a value between 0 and 1.
110
+ show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
111
+ """
112
+ self.brush_radius = brush_radius
113
+ self.brush_color = brush_color
114
+ self.mask_opacity = mask_opacity
115
+ self.mirror_webcam = mirror_webcam
116
+ valid_types = ["numpy", "pil", "filepath"]
117
+ if type not in valid_types:
118
+ raise ValueError(
119
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
120
+ )
121
+ self.type = type
122
+ self.shape = shape
123
+ self.height = height
124
+ self.width = width
125
+ self.image_mode = image_mode
126
+ valid_sources = ["upload", "webcam", "canvas"]
127
+ if source not in valid_sources:
128
+ raise ValueError(
129
+ f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}"
130
+ )
131
+ self.source = source
132
+ if tool is None:
133
+ self.tool = "sketch" if source == "canvas" else "editor"
134
+ else:
135
+ self.tool = tool
136
+ self.invert_colors = invert_colors
137
+ self.streaming = streaming
138
+ self.show_download_button = show_download_button
139
+ if streaming and source != "webcam":
140
+ raise ValueError("CoolImage streaming only available if source is 'webcam'.")
141
+ self.show_share_button = (
142
+ (utils.get_space() is not None)
143
+ if show_share_button is None
144
+ else show_share_button
145
+ )
146
+ super().__init__(
147
+ label=label,
148
+ every=every,
149
+ show_label=show_label,
150
+ container=container,
151
+ scale=scale,
152
+ min_width=min_width,
153
+ interactive=interactive,
154
+ visible=visible,
155
+ elem_id=elem_id,
156
+ elem_classes=elem_classes,
157
+ render=render,
158
+ root_url=root_url,
159
+ _skip_init_processing=_skip_init_processing,
160
+ value=value,
161
+ )
162
+
163
+ def _format_image(
164
+ self, im: _Image.Image | None
165
+ ) -> np.ndarray | _Image.Image | str | None:
166
+ """Helper method to format an image based on self.type"""
167
+ if im is None:
168
+ return im
169
+ fmt = im.format
170
+ if self.type == "pil":
171
+ return im
172
+ elif self.type == "numpy":
173
+ return np.array(im)
174
+ elif self.type == "filepath":
175
+ path = processing_utils.save_pil_to_cache(
176
+ im, cache_dir=self.GRADIO_CACHE, format=fmt or "png" # type: ignore
177
+ )
178
+ return path
179
+ else:
180
+ raise ValueError(
181
+ "Unknown type: "
182
+ + str(self.type)
183
+ + ". Please choose from: 'numpy', 'pil', 'filepath'."
184
+ )
185
+
186
+ def preprocess(
187
+ self, x: str | dict[str, str]
188
+ ) -> np.ndarray | _Image.Image | str | dict | None:
189
+ """
190
+ Parameters:
191
+ x: base64 url data, or (if tool == "sketch") a dict of image and mask base64 url data
192
+ Returns:
193
+ image in requested format, or (if tool == "sketch") a dict of image and mask in requested format
194
+ """
195
+ if x is None:
196
+ return x
197
+
198
+ mask = ""
199
+ if self.tool == "sketch" and self.source in ["upload", "webcam"]:
200
+ assert isinstance(x, dict)
201
+ x, mask = x["image"], x["mask"]
202
+
203
+ if isinstance(x, str):
204
+ im = processing_utils.decode_base64_to_image(x)
205
+ else:
206
+ im = _Image.open(x["name"])
207
+ with warnings.catch_warnings():
208
+ warnings.simplefilter("ignore")
209
+ im = im.convert(self.image_mode)
210
+ if self.shape is not None:
211
+ im = processing_utils.resize_and_crop(im, self.shape)
212
+ if self.invert_colors:
213
+ im = PIL.ImageOps.invert(im)
214
+ if (
215
+ self.source == "webcam"
216
+ and self.mirror_webcam is True
217
+ and self.tool != "color-sketch"
218
+ ):
219
+ im = PIL.ImageOps.mirror(im)
220
+
221
+ if self.tool == "sketch" and self.source in ["upload", "webcam"]:
222
+ mask_im = processing_utils.decode_base64_to_image(mask)
223
+
224
+ if mask_im.mode == "RGBA": # whiten any opaque pixels in the mask
225
+ alpha_data = mask_im.getchannel("A").convert("L")
226
+ mask_im = _Image.merge("RGB", [alpha_data, alpha_data, alpha_data])
227
+ return {
228
+ "image": self._format_image(im),
229
+ "mask": self._format_image(mask_im),
230
+ }
231
+
232
+ return self._format_image(im)
233
+
234
+ def postprocess(
235
+ self, y: np.ndarray | _Image.Image | str | Path | None
236
+ ) -> FileData | None:
237
+ """
238
+ Parameters:
239
+ y: image as a numpy array, PIL CoolImage, string/Path filepath, or string URL
240
+ Returns:
241
+ base64 url data
242
+ """
243
+ if y is None:
244
+ return None
245
+ if isinstance(y, np.ndarray):
246
+ path = processing_utils.save_img_array_to_cache(
247
+ y, cache_dir=self.GRADIO_CACHE
248
+ )
249
+ elif isinstance(y, _Image.Image):
250
+ path = processing_utils.save_pil_to_cache(y, cache_dir=self.GRADIO_CACHE)
251
+ elif isinstance(y, (str, Path)):
252
+ path = y if isinstance(y, str) else str(y)
253
+ else:
254
+ raise ValueError("Cannot process this value as an CoolImage")
255
+ return FileData(name=path, data=None, is_file=True)
256
+
257
+ def check_streamable(self):
258
+ if self.source != "webcam" and self.streaming:
259
+ raise ValueError("CoolImage streaming only available if source is 'webcam'.")
260
+
261
+ def as_example(self, input_data: str | Path | None) -> str:
262
+ if input_data is None:
263
+ return ""
264
+ input_data = str(input_data)
265
+ # If an externally hosted image or a URL, don't convert to absolute path
266
+ if self.root_url or client_utils.is_http_url_like(input_data):
267
+ return input_data
268
+ return str(utils.abspath(input_data))
269
+
270
+ def example_inputs(self) -> Any:
271
+ return "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
src/backend/gradio_coolimage/coolimage.pyi ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Image() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import numpy as np
10
+ import PIL
11
+ import PIL.ImageOps
12
+ from gradio_client import utils as client_utils
13
+ from gradio_client.documentation import document, set_documentation_group
14
+ from PIL import Image as _Image # using _ to minimize namespace pollution
15
+
16
+ from gradio import processing_utils, utils
17
+ from gradio.components.base import Component, StreamingInput, _Keywords
18
+ from gradio.data_classes import FileData
19
+ from gradio.events import Events
20
+
21
+ set_documentation_group("component")
22
+ _Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
23
+
24
+ from gradio.events import Dependency
25
+
26
+ @document()
27
+ class CoolImage(StreamingInput, Component):
28
+ """
29
+ Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
30
+ Preprocessing: passes the uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a {dict} with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
31
+ Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} or {pathlib.Path} filepath to an image and displays the image.
32
+ Examples-format: a {str} local filepath or URL to an image.
33
+ Demos: image_mod, image_mod_default_image
34
+ Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary_app, create-your-own-friends-with-a-gan
35
+ """
36
+
37
+ EVENTS = [
38
+ Events.edit,
39
+ Events.clear,
40
+ Events.change,
41
+ Events.stream,
42
+ Events.select,
43
+ Events.upload,
44
+ ]
45
+ data_model = FileData
46
+
47
+ def __init__(
48
+ self,
49
+ value: str | _Image.Image | np.ndarray | None = None,
50
+ *,
51
+ shape: tuple[int, int] | None = None,
52
+ height: int | None = None,
53
+ width: int | None = None,
54
+ image_mode: Literal[
55
+ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F"
56
+ ] = "RGB",
57
+ invert_colors: bool = False,
58
+ source: Literal["upload", "webcam", "canvas"] = "upload",
59
+ tool: Literal["editor", "select", "sketch", "color-sketch"] | None = None,
60
+ type: Literal["numpy", "pil", "filepath"] = "numpy",
61
+ label: str | None = None,
62
+ every: float | None = None,
63
+ show_label: bool | None = None,
64
+ show_download_button: bool = True,
65
+ container: bool = True,
66
+ scale: int | None = None,
67
+ min_width: int = 160,
68
+ interactive: bool | None = None,
69
+ visible: bool = True,
70
+ streaming: bool = False,
71
+ elem_id: str | None = None,
72
+ elem_classes: list[str] | str | None = None,
73
+ render: bool = True,
74
+ root_url: str | None = None,
75
+ _skip_init_processing: bool = False,
76
+ mirror_webcam: bool = True,
77
+ brush_radius: float | None = None,
78
+ brush_color: str = "#000000",
79
+ mask_opacity: float = 0.7,
80
+ show_share_button: bool | None = None,
81
+ ):
82
+ """
83
+ Parameters:
84
+ value: A PIL CoolImage, numpy array, path or URL for the default value that CoolImage component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
85
+ shape: (width, height) shape to crop and resize image when passed to function. If None, matches input image size. Pass None for either width or height to only crop and resize the other.
86
+ height: Height of the displayed image in pixels.
87
+ width: Width of the displayed image in pixels.
88
+ image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.
89
+ invert_colors: whether to invert the image as a preprocessing step.
90
+ source: Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
91
+ tool: Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively.
92
+ type: The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image.
93
+ label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
94
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
95
+ show_label: if True, will display label.
96
+ show_download_button: If True, will display button to download image.
97
+ container: If True, will place the component in a container - providing some extra padding around the border.
98
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
99
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
100
+ interactive: if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.
101
+ visible: If False, component will be hidden.
102
+ streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.
103
+ elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
104
+ elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
105
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
106
+ root_url: The remote URL that of the Gradio app that this component belongs to. Used in `gr.load()`. Should not be set manually.
107
+ mirror_webcam: If True webcam will be mirrored. Default is True.
108
+ brush_radius: Size of the brush for Sketch. Default is None which chooses a sensible default
109
+ brush_color: Color of the brush for Sketch as hex string. Default is "#000000".
110
+ mask_opacity: Opacity of mask drawn on image, as a value between 0 and 1.
111
+ show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
112
+ """
113
+ self.brush_radius = brush_radius
114
+ self.brush_color = brush_color
115
+ self.mask_opacity = mask_opacity
116
+ self.mirror_webcam = mirror_webcam
117
+ valid_types = ["numpy", "pil", "filepath"]
118
+ if type not in valid_types:
119
+ raise ValueError(
120
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
121
+ )
122
+ self.type = type
123
+ self.shape = shape
124
+ self.height = height
125
+ self.width = width
126
+ self.image_mode = image_mode
127
+ valid_sources = ["upload", "webcam", "canvas"]
128
+ if source not in valid_sources:
129
+ raise ValueError(
130
+ f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}"
131
+ )
132
+ self.source = source
133
+ if tool is None:
134
+ self.tool = "sketch" if source == "canvas" else "editor"
135
+ else:
136
+ self.tool = tool
137
+ self.invert_colors = invert_colors
138
+ self.streaming = streaming
139
+ self.show_download_button = show_download_button
140
+ if streaming and source != "webcam":
141
+ raise ValueError("CoolImage streaming only available if source is 'webcam'.")
142
+ self.show_share_button = (
143
+ (utils.get_space() is not None)
144
+ if show_share_button is None
145
+ else show_share_button
146
+ )
147
+ super().__init__(
148
+ label=label,
149
+ every=every,
150
+ show_label=show_label,
151
+ container=container,
152
+ scale=scale,
153
+ min_width=min_width,
154
+ interactive=interactive,
155
+ visible=visible,
156
+ elem_id=elem_id,
157
+ elem_classes=elem_classes,
158
+ render=render,
159
+ root_url=root_url,
160
+ _skip_init_processing=_skip_init_processing,
161
+ value=value,
162
+ )
163
+
164
+ def _format_image(
165
+ self, im: _Image.Image | None
166
+ ) -> np.ndarray | _Image.Image | str | None:
167
+ """Helper method to format an image based on self.type"""
168
+ if im is None:
169
+ return im
170
+ fmt = im.format
171
+ if self.type == "pil":
172
+ return im
173
+ elif self.type == "numpy":
174
+ return np.array(im)
175
+ elif self.type == "filepath":
176
+ path = processing_utils.save_pil_to_cache(
177
+ im, cache_dir=self.GRADIO_CACHE, format=fmt or "png" # type: ignore
178
+ )
179
+ return path
180
+ else:
181
+ raise ValueError(
182
+ "Unknown type: "
183
+ + str(self.type)
184
+ + ". Please choose from: 'numpy', 'pil', 'filepath'."
185
+ )
186
+
187
+ def preprocess(
188
+ self, x: str | dict[str, str]
189
+ ) -> np.ndarray | _Image.Image | str | dict | None:
190
+ """
191
+ Parameters:
192
+ x: base64 url data, or (if tool == "sketch") a dict of image and mask base64 url data
193
+ Returns:
194
+ image in requested format, or (if tool == "sketch") a dict of image and mask in requested format
195
+ """
196
+ if x is None:
197
+ return x
198
+
199
+ mask = ""
200
+ if self.tool == "sketch" and self.source in ["upload", "webcam"]:
201
+ assert isinstance(x, dict)
202
+ x, mask = x["image"], x["mask"]
203
+
204
+ if isinstance(x, str):
205
+ im = processing_utils.decode_base64_to_image(x)
206
+ else:
207
+ im = _Image.open(x["name"])
208
+ with warnings.catch_warnings():
209
+ warnings.simplefilter("ignore")
210
+ im = im.convert(self.image_mode)
211
+ if self.shape is not None:
212
+ im = processing_utils.resize_and_crop(im, self.shape)
213
+ if self.invert_colors:
214
+ im = PIL.ImageOps.invert(im)
215
+ if (
216
+ self.source == "webcam"
217
+ and self.mirror_webcam is True
218
+ and self.tool != "color-sketch"
219
+ ):
220
+ im = PIL.ImageOps.mirror(im)
221
+
222
+ if self.tool == "sketch" and self.source in ["upload", "webcam"]:
223
+ mask_im = processing_utils.decode_base64_to_image(mask)
224
+
225
+ if mask_im.mode == "RGBA": # whiten any opaque pixels in the mask
226
+ alpha_data = mask_im.getchannel("A").convert("L")
227
+ mask_im = _Image.merge("RGB", [alpha_data, alpha_data, alpha_data])
228
+ return {
229
+ "image": self._format_image(im),
230
+ "mask": self._format_image(mask_im),
231
+ }
232
+
233
+ return self._format_image(im)
234
+
235
+ def postprocess(
236
+ self, y: np.ndarray | _Image.Image | str | Path | None
237
+ ) -> FileData | None:
238
+ """
239
+ Parameters:
240
+ y: image as a numpy array, PIL CoolImage, string/Path filepath, or string URL
241
+ Returns:
242
+ base64 url data
243
+ """
244
+ if y is None:
245
+ return None
246
+ if isinstance(y, np.ndarray):
247
+ path = processing_utils.save_img_array_to_cache(
248
+ y, cache_dir=self.GRADIO_CACHE
249
+ )
250
+ elif isinstance(y, _Image.Image):
251
+ path = processing_utils.save_pil_to_cache(y, cache_dir=self.GRADIO_CACHE)
252
+ elif isinstance(y, (str, Path)):
253
+ path = y if isinstance(y, str) else str(y)
254
+ else:
255
+ raise ValueError("Cannot process this value as an CoolImage")
256
+ return FileData(name=path, data=None, is_file=True)
257
+
258
+ def check_streamable(self):
259
+ if self.source != "webcam" and self.streaming:
260
+ raise ValueError("CoolImage streaming only available if source is 'webcam'.")
261
+
262
+ def as_example(self, input_data: str | Path | None) -> str:
263
+ if input_data is None:
264
+ return ""
265
+ input_data = str(input_data)
266
+ # If an externally hosted image or a URL, don't convert to absolute path
267
+ if self.root_url or client_utils.is_http_url_like(input_data):
268
+ return input_data
269
+ return str(utils.abspath(input_data))
270
+
271
+ def example_inputs(self) -> Any:
272
+ return "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
273
+
274
+
275
+ def edit(self,
276
+ fn: Callable | None,
277
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
278
+ outputs: Component | Sequence[Component] | None = None,
279
+ api_name: str | None | Literal[False] = None,
280
+ status_tracker: None = None,
281
+ scroll_to_output: bool = False,
282
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
283
+ queue: bool | None = None,
284
+ batch: bool = False,
285
+ max_batch_size: int = 4,
286
+ preprocess: bool = True,
287
+ postprocess: bool = True,
288
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
289
+ every: float | None = None,
290
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
291
+ _js: str | None = None,) -> Dependency:
292
+ """
293
+ Parameters:
294
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
295
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
296
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
297
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
298
+ scroll_to_output: If True, will scroll to output component on completion
299
+ show_progress: If True, will show progress animation while pending
300
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
301
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
302
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
303
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
304
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
305
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
306
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
307
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
308
+ """
309
+ ...
310
+
311
+ def clear(self,
312
+ fn: Callable | None,
313
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
314
+ outputs: Component | Sequence[Component] | None = None,
315
+ api_name: str | None | Literal[False] = None,
316
+ status_tracker: None = None,
317
+ scroll_to_output: bool = False,
318
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
319
+ queue: bool | None = None,
320
+ batch: bool = False,
321
+ max_batch_size: int = 4,
322
+ preprocess: bool = True,
323
+ postprocess: bool = True,
324
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
325
+ every: float | None = None,
326
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
327
+ _js: str | None = None,) -> Dependency:
328
+ """
329
+ Parameters:
330
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
331
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
332
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
333
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
334
+ scroll_to_output: If True, will scroll to output component on completion
335
+ show_progress: If True, will show progress animation while pending
336
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
337
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
338
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
339
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
340
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
341
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
342
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
343
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
344
+ """
345
+ ...
346
+
347
+ def change(self,
348
+ fn: Callable | None,
349
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
350
+ outputs: Component | Sequence[Component] | None = None,
351
+ api_name: str | None | Literal[False] = None,
352
+ status_tracker: None = None,
353
+ scroll_to_output: bool = False,
354
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
355
+ queue: bool | None = None,
356
+ batch: bool = False,
357
+ max_batch_size: int = 4,
358
+ preprocess: bool = True,
359
+ postprocess: bool = True,
360
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
361
+ every: float | None = None,
362
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
363
+ _js: str | None = None,) -> Dependency:
364
+ """
365
+ Parameters:
366
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
367
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
368
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
369
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
370
+ scroll_to_output: If True, will scroll to output component on completion
371
+ show_progress: If True, will show progress animation while pending
372
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
373
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
374
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
375
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
376
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
377
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
378
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
379
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
380
+ """
381
+ ...
382
+
383
+ def stream(self,
384
+ fn: Callable | None,
385
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
386
+ outputs: Component | Sequence[Component] | None = None,
387
+ api_name: str | None | Literal[False] = None,
388
+ status_tracker: None = None,
389
+ scroll_to_output: bool = False,
390
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
391
+ queue: bool | None = None,
392
+ batch: bool = False,
393
+ max_batch_size: int = 4,
394
+ preprocess: bool = True,
395
+ postprocess: bool = True,
396
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
397
+ every: float | None = None,
398
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
399
+ _js: str | None = None,) -> Dependency:
400
+ """
401
+ Parameters:
402
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
403
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
404
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
405
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
406
+ scroll_to_output: If True, will scroll to output component on completion
407
+ show_progress: If True, will show progress animation while pending
408
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
409
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
410
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
411
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
412
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
413
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
414
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
415
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
416
+ """
417
+ ...
418
+
419
+ def select(self,
420
+ fn: Callable | None,
421
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
422
+ outputs: Component | Sequence[Component] | None = None,
423
+ api_name: str | None | Literal[False] = None,
424
+ status_tracker: None = None,
425
+ scroll_to_output: bool = False,
426
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
427
+ queue: bool | None = None,
428
+ batch: bool = False,
429
+ max_batch_size: int = 4,
430
+ preprocess: bool = True,
431
+ postprocess: bool = True,
432
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
433
+ every: float | None = None,
434
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
435
+ _js: str | None = None,) -> Dependency:
436
+ """
437
+ Parameters:
438
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
439
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
440
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
441
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
442
+ scroll_to_output: If True, will scroll to output component on completion
443
+ show_progress: If True, will show progress animation while pending
444
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
445
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
446
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
447
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
448
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
449
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
450
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
451
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
452
+ """
453
+ ...
454
+
455
+ def upload(self,
456
+ fn: Callable | None,
457
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
458
+ outputs: Component | Sequence[Component] | None = None,
459
+ api_name: str | None | Literal[False] = None,
460
+ status_tracker: None = None,
461
+ scroll_to_output: bool = False,
462
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
463
+ queue: bool | None = None,
464
+ batch: bool = False,
465
+ max_batch_size: int = 4,
466
+ preprocess: bool = True,
467
+ postprocess: bool = True,
468
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
469
+ every: float | None = None,
470
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
471
+ _js: str | None = None,) -> Dependency:
472
+ """
473
+ Parameters:
474
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
475
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
476
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
477
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
478
+ scroll_to_output: If True, will scroll to output component on completion
479
+ show_progress: If True, will show progress animation while pending
480
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
481
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
482
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
483
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
484
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
485
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
486
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
487
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
488
+ """
489
+ ...
src/backend/gradio_coolimage/templates/component/__vite-browser-external-2447137e.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ const e = {};
2
+ export {
3
+ e as default
4
+ };
src/backend/gradio_coolimage/templates/component/index.js ADDED
The diff for this file is too large to render. See raw diff
 
src/backend/gradio_coolimage/templates/component/style.css ADDED
@@ -0,0 +1 @@
 
 
1
+ .block.svelte-1t38q2d{position:relative;margin:0;box-shadow:var(--block-shadow);border-width:var(--block-border-width);border-color:var(--block-border-color);border-radius:var(--block-radius);background:var(--block-background-fill);width:100%;line-height:var(--line-sm)}.block.border_focus.svelte-1t38q2d{border-color:var(--color-accent)}.padded.svelte-1t38q2d{padding:var(--block-padding)}.hidden.svelte-1t38q2d{display:none}.hide-container.svelte-1t38q2d{margin:0;box-shadow:none;--block-border-width:0;background:transparent;padding:0;overflow:visible}div.svelte-1hnfib2{margin-bottom:var(--spacing-lg);color:var(--block-info-text-color);font-weight:var(--block-info-text-weight);font-size:var(--block-info-text-size);line-height:var(--line-sm)}span.has-info.svelte-22c38v{margin-bottom:var(--spacing-xs)}span.svelte-22c38v:not(.has-info){margin-bottom:var(--spacing-lg)}span.svelte-22c38v{display:inline-block;position:relative;z-index:var(--layer-4);border:solid var(--block-title-border-width) var(--block-title-border-color);border-radius:var(--block-title-radius);background:var(--block-title-background-fill);padding:var(--block-title-padding);color:var(--block-title-text-color);font-weight:var(--block-title-text-weight);font-size:var(--block-title-text-size);line-height:var(--line-sm)}.hide.svelte-22c38v{margin:0;height:0}label.svelte-9gxdi0{display:inline-flex;align-items:center;z-index:var(--layer-2);box-shadow:var(--block-label-shadow);border:var(--block-label-border-width) solid var(--border-color-primary);border-top:none;border-left:none;border-radius:var(--block-label-radius);background:var(--block-label-background-fill);padding:var(--block-label-padding);pointer-events:none;color:var(--block-label-text-color);font-weight:var(--block-label-text-weight);font-size:var(--block-label-text-size);line-height:var(--line-sm)}.gr-group label.svelte-9gxdi0{border-top-left-radius:0}label.float.svelte-9gxdi0{position:absolute;top:var(--block-label-margin);left:var(--block-label-margin)}label.svelte-9gxdi0:not(.float){position:static;margin-top:var(--block-label-margin);margin-left:var(--block-label-margin)}.hide.svelte-9gxdi0{height:0}span.svelte-9gxdi0{opacity:.8;margin-right:var(--size-2);width:calc(var(--block-label-text-size) - 1px);height:calc(var(--block-label-text-size) - 1px)}.hide-label.svelte-9gxdi0{box-shadow:none;border-width:0;background:transparent;overflow:visible}button.svelte-lkmj4t{display:flex;justify-content:center;align-items:center;gap:1px;z-index:var(--layer-1);box-shadow:var(--shadow-drop);border:1px solid var(--button-secondary-border-color);border-radius:var(--radius-sm);background:var(--background-fill-primary);padding:2px;color:var(--block-label-text-color)}button.svelte-lkmj4t:hover{cursor:pointer;border:2px solid var(--button-secondary-border-color-hover);padding:1px;color:var(--block-label-text-color)}span.svelte-lkmj4t{padding:0 1px;font-size:10px}div.svelte-lkmj4t{padding:2px;width:14px;height:14px}.pending.svelte-lkmj4t{animation:svelte-lkmj4t-flash .5s infinite}@keyframes svelte-lkmj4t-flash{0%{opacity:.5}50%{opacity:1}to{opacity:.5}}.empty.svelte-3w3rth{display:flex;justify-content:center;align-items:center;margin-top:calc(0px - var(--size-6));height:var(--size-full)}.icon.svelte-3w3rth{opacity:.5;height:var(--size-5);color:var(--body-text-color)}.small.svelte-3w3rth{min-height:calc(var(--size-32) - 20px)}.large.svelte-3w3rth{min-height:calc(var(--size-64) - 20px)}.unpadded_box.svelte-3w3rth{margin-top:0}.small_parent.svelte-3w3rth{min-height:100%!important}.dropdown-arrow.svelte-1in5nh4{fill:var(--body-text-color);margin-right:var(--size-2);width:var(--size-5)}.wrap.svelte-8ytugg{display:flex;flex-direction:column;justify-content:center;min-height:var(--size-60);color:var(--block-label-text-color);line-height:var(--line-md)}.or.svelte-8ytugg{color:var(--body-text-color-subdued)}@media (--screen-md){.wrap.svelte-8ytugg{font-size:var(--text-lg)}}button.svelte-2w9i1r{cursor:pointer;width:var(--size-full);height:var(--size-full)}.center.svelte-2w9i1r{display:flex;justify-content:center}.flex.svelte-2w9i1r{display:flex;justify-content:center;align-items:center}input.svelte-2w9i1r{display:none}div.svelte-1wj0ocy{display:flex;top:var(--size-2);right:var(--size-2);justify-content:flex-end;gap:var(--spacing-sm);z-index:var(--layer-1)}.not-absolute.svelte-1wj0ocy{margin:var(--size-1)}img.svelte-v9w493{width:var(--size-full);height:var(--size-full);object-fit:contain}.selectable.svelte-v9w493{cursor:crosshair}.icon-buttons.svelte-v9w493{display:flex;position:absolute;top:6px;right:6px;gap:var(--size-1)}canvas.svelte-14l85k0{display:block;position:absolute;top:0;right:0;bottom:0;left:0;margin:auto}.lr.svelte-14l85k0{border-right:1px solid var(--border-color-primary);border-left:1px solid var(--border-color-primary)}.tb.svelte-14l85k0{border-top:1px solid var(--border-color-primary);border-bottom:1px solid var(--border-color-primary)}canvas.svelte-14l85k0:hover{cursor:none}.wrap.svelte-14l85k0{position:relative;width:var(--size-full);height:var(--size-full);touch-action:none}.start-prompt.svelte-14l85k0{display:flex;position:absolute;top:0;right:0;bottom:0;left:0;justify-content:center;align-items:center;z-index:var(--layer-4);touch-action:none;pointer-events:none;color:var(--body-text-color-subdued)}.wrap.svelte-ji57xm{position:relative;width:var(--size-full);height:var(--size-full);min-height:var(--size-60)}video.svelte-ji57xm{width:var(--size-full);height:var(--size-full)}button.svelte-ji57xm{display:flex;position:absolute;right:0;bottom:var(--size-2);left:0;justify-content:center;align-items:center;margin:auto;box-shadow:var(--shadow-drop-lg);border-radius:var(--radius-xl);background-color:#000000e6;width:var(--size-10);height:var(--size-10)}@media (--screen-md){button.svelte-ji57xm{bottom:var(--size-4)}}@media (--screen-xl){button.svelte-ji57xm{bottom:var(--size-8)}}.icon.svelte-ji57xm{opacity:.8;width:50%;height:50%;color:#fff}.flip.svelte-ji57xm{transform:scaleX(-1)}div.svelte-1g74h68{display:flex;position:absolute;top:var(--size-2);right:var(--size-2);justify-content:flex-end;gap:var(--spacing-sm);z-index:var(--layer-5)}.wrap.svelte-1hdlygn.svelte-1hdlygn{display:flex;position:absolute;top:var(--size-10);right:var(--size-2);flex-direction:column;justify-content:flex-end;gap:var(--spacing-sm);z-index:var(--layer-5)}.brush.svelte-1hdlygn.svelte-1hdlygn{top:0;right:0}.brush.svelte-1hdlygn input.svelte-1hdlygn{position:absolute;top:3px;right:calc(100% + 5px)}.col.svelte-1hdlygn input.svelte-1hdlygn{position:absolute;right:calc(100% + 5px);bottom:-4px}.image-container.svelte-14sn87y,img.svelte-14sn87y{width:var(--size-full);height:var(--size-full)}img.svelte-14sn87y{object-fit:contain}.selectable.svelte-14sn87y{cursor:crosshair}.absolute-img.svelte-14sn87y{position:absolute;opacity:0}.webcam.svelte-14sn87y{transform:scaleX(-1)}svg.svelte-43sxxs.svelte-43sxxs{width:var(--size-20);height:var(--size-20)}svg.svelte-43sxxs path.svelte-43sxxs{fill:var(--loader-color)}div.svelte-43sxxs.svelte-43sxxs{z-index:var(--layer-2)}.margin.svelte-43sxxs.svelte-43sxxs{margin:var(--size-4)}.wrap.svelte-14miwb5.svelte-14miwb5{display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:var(--layer-5);transition:opacity .1s ease-in-out;border-radius:var(--block-radius);background:var(--block-background-fill);padding:0 var(--size-6);max-height:var(--size-screen-h);overflow:hidden;pointer-events:none}.wrap.center.svelte-14miwb5.svelte-14miwb5{top:0;right:0;left:0}.wrap.default.svelte-14miwb5.svelte-14miwb5{top:0;right:0;bottom:0;left:0}.hide.svelte-14miwb5.svelte-14miwb5{opacity:0;pointer-events:none}.generating.svelte-14miwb5.svelte-14miwb5{animation:svelte-14miwb5-pulse 2s cubic-bezier(.4,0,.6,1) infinite;border:2px solid var(--color-accent);background:transparent}.translucent.svelte-14miwb5.svelte-14miwb5{background:none}@keyframes svelte-14miwb5-pulse{0%,to{opacity:1}50%{opacity:.5}}.loading.svelte-14miwb5.svelte-14miwb5{z-index:var(--layer-2);color:var(--body-text-color)}.eta-bar.svelte-14miwb5.svelte-14miwb5{position:absolute;top:0;right:0;bottom:0;left:0;transform-origin:left;opacity:.8;z-index:var(--layer-1);transition:10ms;background:var(--background-fill-secondary)}.progress-bar-wrap.svelte-14miwb5.svelte-14miwb5{border:1px solid var(--border-color-primary);background:var(--background-fill-primary);width:55.5%;height:var(--size-4)}.progress-bar.svelte-14miwb5.svelte-14miwb5{transform-origin:left;background-color:var(--loader-color);width:var(--size-full);height:var(--size-full)}.progress-level.svelte-14miwb5.svelte-14miwb5{display:flex;flex-direction:column;align-items:center;gap:1;z-index:var(--layer-2);width:var(--size-full)}.progress-level-inner.svelte-14miwb5.svelte-14miwb5{margin:var(--size-2) auto;color:var(--body-text-color);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text.svelte-14miwb5.svelte-14miwb5{position:absolute;top:0;right:0;z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text-center.svelte-14miwb5.svelte-14miwb5{display:flex;position:absolute;top:0;right:0;justify-content:center;align-items:center;transform:translateY(var(--size-6));z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono);text-align:center}.error.svelte-14miwb5.svelte-14miwb5{box-shadow:var(--shadow-drop);border:solid 1px var(--error-border-color);border-radius:var(--radius-full);background:var(--error-background-fill);padding-right:var(--size-4);padding-left:var(--size-4);color:var(--error-text-color);font-weight:var(--weight-semibold);font-size:var(--text-lg);line-height:var(--line-lg);font-family:var(--font)}.minimal.svelte-14miwb5 .progress-text.svelte-14miwb5{background:var(--block-background-fill)}.border.svelte-14miwb5.svelte-14miwb5{border:1px solid var(--border-color-primary)}.toast-body.svelte-solcu7{display:flex;position:relative;right:0;left:0;align-items:center;margin:var(--size-6) var(--size-4);margin:auto;border-radius:var(--container-radius);overflow:hidden;pointer-events:auto}.toast-body.error.svelte-solcu7{border:1px solid var(--color-red-700);background:var(--color-red-50)}.dark .toast-body.error.svelte-solcu7{border:1px solid var(--color-red-500);background-color:var(--color-grey-950)}.toast-body.warning.svelte-solcu7{border:1px solid var(--color-yellow-700);background:var(--color-yellow-50)}.dark .toast-body.warning.svelte-solcu7{border:1px solid var(--color-yellow-500);background-color:var(--color-grey-950)}.toast-body.info.svelte-solcu7{border:1px solid var(--color-grey-700);background:var(--color-grey-50)}.dark .toast-body.info.svelte-solcu7{border:1px solid var(--color-grey-500);background-color:var(--color-grey-950)}.toast-title.svelte-solcu7{display:flex;align-items:center;font-weight:var(--weight-bold);font-size:var(--text-lg);line-height:var(--line-sm);text-transform:capitalize}.toast-title.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-title.error.svelte-solcu7{color:var(--color-red-50)}.toast-title.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-title.warning.svelte-solcu7{color:var(--color-yellow-50)}.toast-title.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-title.info.svelte-solcu7{color:var(--color-grey-50)}.toast-close.svelte-solcu7{margin:0 var(--size-3);border-radius:var(--size-3);padding:0px var(--size-1-5);font-size:var(--size-5);line-height:var(--size-5)}.toast-close.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-close.error.svelte-solcu7{color:var(--color-red-500)}.toast-close.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-close.warning.svelte-solcu7{color:var(--color-yellow-500)}.toast-close.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-close.info.svelte-solcu7{color:var(--color-grey-500)}.toast-text.svelte-solcu7{font-size:var(--text-lg)}.toast-text.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-text.error.svelte-solcu7{color:var(--color-red-50)}.toast-text.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-text.warning.svelte-solcu7{color:var(--color-yellow-50)}.toast-text.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-text.info.svelte-solcu7{color:var(--color-grey-50)}.toast-details.svelte-solcu7{margin:var(--size-3) var(--size-3) var(--size-3) 0;width:100%}.toast-icon.svelte-solcu7{display:flex;position:absolute;position:relative;flex-shrink:0;justify-content:center;align-items:center;margin:var(--size-2);border-radius:var(--radius-full);padding:var(--size-1);padding-left:calc(var(--size-1) - 1px);width:35px;height:35px}.toast-icon.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-icon.error.svelte-solcu7{color:var(--color-red-500)}.toast-icon.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-icon.warning.svelte-solcu7{color:var(--color-yellow-500)}.toast-icon.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-icon.info.svelte-solcu7{color:var(--color-grey-500)}@keyframes svelte-solcu7-countdown{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.timer.svelte-solcu7{position:absolute;bottom:0;left:0;transform-origin:0 0;animation:svelte-solcu7-countdown 10s linear forwards;width:100%;height:var(--size-1)}.timer.error.svelte-solcu7{background:var(--color-red-700)}.dark .timer.error.svelte-solcu7{background:var(--color-red-500)}.timer.warning.svelte-solcu7{background:var(--color-yellow-700)}.dark .timer.warning.svelte-solcu7{background:var(--color-yellow-500)}.timer.info.svelte-solcu7{background:var(--color-grey-700)}.dark .timer.info.svelte-solcu7{background:var(--color-grey-500)}.toast-wrap.svelte-gatr8h{display:flex;position:fixed;top:var(--size-4);right:var(--size-4);flex-direction:column;align-items:end;gap:var(--size-2);z-index:var(--layer-top);width:calc(100% - var(--size-8))}@media (--screen-sm){.toast-wrap.svelte-gatr8h{width:calc(var(--size-96) + var(--size-10))}}
src/backend/gradio_coolimage/templates/component/wrapper-6f348d45-f837cf34.js ADDED
@@ -0,0 +1,2455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import S from "./__vite-browser-external-2447137e.js";
2
+ function z(s) {
3
+ return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s;
4
+ }
5
+ function gt(s) {
6
+ if (s.__esModule)
7
+ return s;
8
+ var e = s.default;
9
+ if (typeof e == "function") {
10
+ var t = function r() {
11
+ if (this instanceof r) {
12
+ var i = [null];
13
+ i.push.apply(i, arguments);
14
+ var n = Function.bind.apply(e, i);
15
+ return new n();
16
+ }
17
+ return e.apply(this, arguments);
18
+ };
19
+ t.prototype = e.prototype;
20
+ } else
21
+ t = {};
22
+ return Object.defineProperty(t, "__esModule", { value: !0 }), Object.keys(s).forEach(function(r) {
23
+ var i = Object.getOwnPropertyDescriptor(s, r);
24
+ Object.defineProperty(t, r, i.get ? i : {
25
+ enumerable: !0,
26
+ get: function() {
27
+ return s[r];
28
+ }
29
+ });
30
+ }), t;
31
+ }
32
+ const { Duplex: yt } = S;
33
+ function Oe(s) {
34
+ s.emit("close");
35
+ }
36
+ function vt() {
37
+ !this.destroyed && this._writableState.finished && this.destroy();
38
+ }
39
+ function Qe(s) {
40
+ this.removeListener("error", Qe), this.destroy(), this.listenerCount("error") === 0 && this.emit("error", s);
41
+ }
42
+ function St(s, e) {
43
+ let t = !0;
44
+ const r = new yt({
45
+ ...e,
46
+ autoDestroy: !1,
47
+ emitClose: !1,
48
+ objectMode: !1,
49
+ writableObjectMode: !1
50
+ });
51
+ return s.on("message", function(n, o) {
52
+ const l = !o && r._readableState.objectMode ? n.toString() : n;
53
+ r.push(l) || s.pause();
54
+ }), s.once("error", function(n) {
55
+ r.destroyed || (t = !1, r.destroy(n));
56
+ }), s.once("close", function() {
57
+ r.destroyed || r.push(null);
58
+ }), r._destroy = function(i, n) {
59
+ if (s.readyState === s.CLOSED) {
60
+ n(i), process.nextTick(Oe, r);
61
+ return;
62
+ }
63
+ let o = !1;
64
+ s.once("error", function(f) {
65
+ o = !0, n(f);
66
+ }), s.once("close", function() {
67
+ o || n(i), process.nextTick(Oe, r);
68
+ }), t && s.terminate();
69
+ }, r._final = function(i) {
70
+ if (s.readyState === s.CONNECTING) {
71
+ s.once("open", function() {
72
+ r._final(i);
73
+ });
74
+ return;
75
+ }
76
+ s._socket !== null && (s._socket._writableState.finished ? (i(), r._readableState.endEmitted && r.destroy()) : (s._socket.once("finish", function() {
77
+ i();
78
+ }), s.close()));
79
+ }, r._read = function() {
80
+ s.isPaused && s.resume();
81
+ }, r._write = function(i, n, o) {
82
+ if (s.readyState === s.CONNECTING) {
83
+ s.once("open", function() {
84
+ r._write(i, n, o);
85
+ });
86
+ return;
87
+ }
88
+ s.send(i, o);
89
+ }, r.on("end", vt), r.on("error", Qe), r;
90
+ }
91
+ var Et = St;
92
+ const Vs = /* @__PURE__ */ z(Et);
93
+ var te = { exports: {} }, U = {
94
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
95
+ EMPTY_BUFFER: Buffer.alloc(0),
96
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
97
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
98
+ kListener: Symbol("kListener"),
99
+ kStatusCode: Symbol("status-code"),
100
+ kWebSocket: Symbol("websocket"),
101
+ NOOP: () => {
102
+ }
103
+ }, bt, xt;
104
+ const { EMPTY_BUFFER: kt } = U, Se = Buffer[Symbol.species];
105
+ function wt(s, e) {
106
+ if (s.length === 0)
107
+ return kt;
108
+ if (s.length === 1)
109
+ return s[0];
110
+ const t = Buffer.allocUnsafe(e);
111
+ let r = 0;
112
+ for (let i = 0; i < s.length; i++) {
113
+ const n = s[i];
114
+ t.set(n, r), r += n.length;
115
+ }
116
+ return r < e ? new Se(t.buffer, t.byteOffset, r) : t;
117
+ }
118
+ function Je(s, e, t, r, i) {
119
+ for (let n = 0; n < i; n++)
120
+ t[r + n] = s[n] ^ e[n & 3];
121
+ }
122
+ function et(s, e) {
123
+ for (let t = 0; t < s.length; t++)
124
+ s[t] ^= e[t & 3];
125
+ }
126
+ function Ot(s) {
127
+ return s.length === s.buffer.byteLength ? s.buffer : s.buffer.slice(s.byteOffset, s.byteOffset + s.length);
128
+ }
129
+ function Ee(s) {
130
+ if (Ee.readOnly = !0, Buffer.isBuffer(s))
131
+ return s;
132
+ let e;
133
+ return s instanceof ArrayBuffer ? e = new Se(s) : ArrayBuffer.isView(s) ? e = new Se(s.buffer, s.byteOffset, s.byteLength) : (e = Buffer.from(s), Ee.readOnly = !1), e;
134
+ }
135
+ te.exports = {
136
+ concat: wt,
137
+ mask: Je,
138
+ toArrayBuffer: Ot,
139
+ toBuffer: Ee,
140
+ unmask: et
141
+ };
142
+ if (!process.env.WS_NO_BUFFER_UTIL)
143
+ try {
144
+ const s = require("bufferutil");
145
+ xt = te.exports.mask = function(e, t, r, i, n) {
146
+ n < 48 ? Je(e, t, r, i, n) : s.mask(e, t, r, i, n);
147
+ }, bt = te.exports.unmask = function(e, t) {
148
+ e.length < 32 ? et(e, t) : s.unmask(e, t);
149
+ };
150
+ } catch {
151
+ }
152
+ var ne = te.exports;
153
+ const Ce = Symbol("kDone"), ue = Symbol("kRun");
154
+ let Ct = class {
155
+ /**
156
+ * Creates a new `Limiter`.
157
+ *
158
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
159
+ * to run concurrently
160
+ */
161
+ constructor(e) {
162
+ this[Ce] = () => {
163
+ this.pending--, this[ue]();
164
+ }, this.concurrency = e || 1 / 0, this.jobs = [], this.pending = 0;
165
+ }
166
+ /**
167
+ * Adds a job to the queue.
168
+ *
169
+ * @param {Function} job The job to run
170
+ * @public
171
+ */
172
+ add(e) {
173
+ this.jobs.push(e), this[ue]();
174
+ }
175
+ /**
176
+ * Removes a job from the queue and runs it if possible.
177
+ *
178
+ * @private
179
+ */
180
+ [ue]() {
181
+ if (this.pending !== this.concurrency && this.jobs.length) {
182
+ const e = this.jobs.shift();
183
+ this.pending++, e(this[Ce]);
184
+ }
185
+ }
186
+ };
187
+ var Tt = Ct;
188
+ const W = S, Te = ne, Lt = Tt, { kStatusCode: tt } = U, Nt = Buffer[Symbol.species], Pt = Buffer.from([0, 0, 255, 255]), se = Symbol("permessage-deflate"), w = Symbol("total-length"), V = Symbol("callback"), C = Symbol("buffers"), J = Symbol("error");
189
+ let K, Rt = class {
190
+ /**
191
+ * Creates a PerMessageDeflate instance.
192
+ *
193
+ * @param {Object} [options] Configuration options
194
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
195
+ * for, or request, a custom client window size
196
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
197
+ * acknowledge disabling of client context takeover
198
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
199
+ * calls to zlib
200
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
201
+ * use of a custom server window size
202
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
203
+ * disabling of server context takeover
204
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
205
+ * messages should not be compressed if context takeover is disabled
206
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
207
+ * deflate
208
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
209
+ * inflate
210
+ * @param {Boolean} [isServer=false] Create the instance in either server or
211
+ * client mode
212
+ * @param {Number} [maxPayload=0] The maximum allowed message length
213
+ */
214
+ constructor(e, t, r) {
215
+ if (this._maxPayload = r | 0, this._options = e || {}, this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024, this._isServer = !!t, this._deflate = null, this._inflate = null, this.params = null, !K) {
216
+ const i = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
217
+ K = new Lt(i);
218
+ }
219
+ }
220
+ /**
221
+ * @type {String}
222
+ */
223
+ static get extensionName() {
224
+ return "permessage-deflate";
225
+ }
226
+ /**
227
+ * Create an extension negotiation offer.
228
+ *
229
+ * @return {Object} Extension parameters
230
+ * @public
231
+ */
232
+ offer() {
233
+ const e = {};
234
+ return this._options.serverNoContextTakeover && (e.server_no_context_takeover = !0), this._options.clientNoContextTakeover && (e.client_no_context_takeover = !0), this._options.serverMaxWindowBits && (e.server_max_window_bits = this._options.serverMaxWindowBits), this._options.clientMaxWindowBits ? e.client_max_window_bits = this._options.clientMaxWindowBits : this._options.clientMaxWindowBits == null && (e.client_max_window_bits = !0), e;
235
+ }
236
+ /**
237
+ * Accept an extension negotiation offer/response.
238
+ *
239
+ * @param {Array} configurations The extension negotiation offers/reponse
240
+ * @return {Object} Accepted configuration
241
+ * @public
242
+ */
243
+ accept(e) {
244
+ return e = this.normalizeParams(e), this.params = this._isServer ? this.acceptAsServer(e) : this.acceptAsClient(e), this.params;
245
+ }
246
+ /**
247
+ * Releases all resources used by the extension.
248
+ *
249
+ * @public
250
+ */
251
+ cleanup() {
252
+ if (this._inflate && (this._inflate.close(), this._inflate = null), this._deflate) {
253
+ const e = this._deflate[V];
254
+ this._deflate.close(), this._deflate = null, e && e(
255
+ new Error(
256
+ "The deflate stream was closed while data was being processed"
257
+ )
258
+ );
259
+ }
260
+ }
261
+ /**
262
+ * Accept an extension negotiation offer.
263
+ *
264
+ * @param {Array} offers The extension negotiation offers
265
+ * @return {Object} Accepted configuration
266
+ * @private
267
+ */
268
+ acceptAsServer(e) {
269
+ const t = this._options, r = e.find((i) => !(t.serverNoContextTakeover === !1 && i.server_no_context_takeover || i.server_max_window_bits && (t.serverMaxWindowBits === !1 || typeof t.serverMaxWindowBits == "number" && t.serverMaxWindowBits > i.server_max_window_bits) || typeof t.clientMaxWindowBits == "number" && !i.client_max_window_bits));
270
+ if (!r)
271
+ throw new Error("None of the extension offers can be accepted");
272
+ return t.serverNoContextTakeover && (r.server_no_context_takeover = !0), t.clientNoContextTakeover && (r.client_no_context_takeover = !0), typeof t.serverMaxWindowBits == "number" && (r.server_max_window_bits = t.serverMaxWindowBits), typeof t.clientMaxWindowBits == "number" ? r.client_max_window_bits = t.clientMaxWindowBits : (r.client_max_window_bits === !0 || t.clientMaxWindowBits === !1) && delete r.client_max_window_bits, r;
273
+ }
274
+ /**
275
+ * Accept the extension negotiation response.
276
+ *
277
+ * @param {Array} response The extension negotiation response
278
+ * @return {Object} Accepted configuration
279
+ * @private
280
+ */
281
+ acceptAsClient(e) {
282
+ const t = e[0];
283
+ if (this._options.clientNoContextTakeover === !1 && t.client_no_context_takeover)
284
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
285
+ if (!t.client_max_window_bits)
286
+ typeof this._options.clientMaxWindowBits == "number" && (t.client_max_window_bits = this._options.clientMaxWindowBits);
287
+ else if (this._options.clientMaxWindowBits === !1 || typeof this._options.clientMaxWindowBits == "number" && t.client_max_window_bits > this._options.clientMaxWindowBits)
288
+ throw new Error(
289
+ 'Unexpected or invalid parameter "client_max_window_bits"'
290
+ );
291
+ return t;
292
+ }
293
+ /**
294
+ * Normalize parameters.
295
+ *
296
+ * @param {Array} configurations The extension negotiation offers/reponse
297
+ * @return {Array} The offers/response with normalized parameters
298
+ * @private
299
+ */
300
+ normalizeParams(e) {
301
+ return e.forEach((t) => {
302
+ Object.keys(t).forEach((r) => {
303
+ let i = t[r];
304
+ if (i.length > 1)
305
+ throw new Error(`Parameter "${r}" must have only a single value`);
306
+ if (i = i[0], r === "client_max_window_bits") {
307
+ if (i !== !0) {
308
+ const n = +i;
309
+ if (!Number.isInteger(n) || n < 8 || n > 15)
310
+ throw new TypeError(
311
+ `Invalid value for parameter "${r}": ${i}`
312
+ );
313
+ i = n;
314
+ } else if (!this._isServer)
315
+ throw new TypeError(
316
+ `Invalid value for parameter "${r}": ${i}`
317
+ );
318
+ } else if (r === "server_max_window_bits") {
319
+ const n = +i;
320
+ if (!Number.isInteger(n) || n < 8 || n > 15)
321
+ throw new TypeError(
322
+ `Invalid value for parameter "${r}": ${i}`
323
+ );
324
+ i = n;
325
+ } else if (r === "client_no_context_takeover" || r === "server_no_context_takeover") {
326
+ if (i !== !0)
327
+ throw new TypeError(
328
+ `Invalid value for parameter "${r}": ${i}`
329
+ );
330
+ } else
331
+ throw new Error(`Unknown parameter "${r}"`);
332
+ t[r] = i;
333
+ });
334
+ }), e;
335
+ }
336
+ /**
337
+ * Decompress data. Concurrency limited.
338
+ *
339
+ * @param {Buffer} data Compressed data
340
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
341
+ * @param {Function} callback Callback
342
+ * @public
343
+ */
344
+ decompress(e, t, r) {
345
+ K.add((i) => {
346
+ this._decompress(e, t, (n, o) => {
347
+ i(), r(n, o);
348
+ });
349
+ });
350
+ }
351
+ /**
352
+ * Compress data. Concurrency limited.
353
+ *
354
+ * @param {(Buffer|String)} data Data to compress
355
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
356
+ * @param {Function} callback Callback
357
+ * @public
358
+ */
359
+ compress(e, t, r) {
360
+ K.add((i) => {
361
+ this._compress(e, t, (n, o) => {
362
+ i(), r(n, o);
363
+ });
364
+ });
365
+ }
366
+ /**
367
+ * Decompress data.
368
+ *
369
+ * @param {Buffer} data Compressed data
370
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
371
+ * @param {Function} callback Callback
372
+ * @private
373
+ */
374
+ _decompress(e, t, r) {
375
+ const i = this._isServer ? "client" : "server";
376
+ if (!this._inflate) {
377
+ const n = `${i}_max_window_bits`, o = typeof this.params[n] != "number" ? W.Z_DEFAULT_WINDOWBITS : this.params[n];
378
+ this._inflate = W.createInflateRaw({
379
+ ...this._options.zlibInflateOptions,
380
+ windowBits: o
381
+ }), this._inflate[se] = this, this._inflate[w] = 0, this._inflate[C] = [], this._inflate.on("error", Bt), this._inflate.on("data", st);
382
+ }
383
+ this._inflate[V] = r, this._inflate.write(e), t && this._inflate.write(Pt), this._inflate.flush(() => {
384
+ const n = this._inflate[J];
385
+ if (n) {
386
+ this._inflate.close(), this._inflate = null, r(n);
387
+ return;
388
+ }
389
+ const o = Te.concat(
390
+ this._inflate[C],
391
+ this._inflate[w]
392
+ );
393
+ this._inflate._readableState.endEmitted ? (this._inflate.close(), this._inflate = null) : (this._inflate[w] = 0, this._inflate[C] = [], t && this.params[`${i}_no_context_takeover`] && this._inflate.reset()), r(null, o);
394
+ });
395
+ }
396
+ /**
397
+ * Compress data.
398
+ *
399
+ * @param {(Buffer|String)} data Data to compress
400
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
401
+ * @param {Function} callback Callback
402
+ * @private
403
+ */
404
+ _compress(e, t, r) {
405
+ const i = this._isServer ? "server" : "client";
406
+ if (!this._deflate) {
407
+ const n = `${i}_max_window_bits`, o = typeof this.params[n] != "number" ? W.Z_DEFAULT_WINDOWBITS : this.params[n];
408
+ this._deflate = W.createDeflateRaw({
409
+ ...this._options.zlibDeflateOptions,
410
+ windowBits: o
411
+ }), this._deflate[w] = 0, this._deflate[C] = [], this._deflate.on("data", Ut);
412
+ }
413
+ this._deflate[V] = r, this._deflate.write(e), this._deflate.flush(W.Z_SYNC_FLUSH, () => {
414
+ if (!this._deflate)
415
+ return;
416
+ let n = Te.concat(
417
+ this._deflate[C],
418
+ this._deflate[w]
419
+ );
420
+ t && (n = new Nt(n.buffer, n.byteOffset, n.length - 4)), this._deflate[V] = null, this._deflate[w] = 0, this._deflate[C] = [], t && this.params[`${i}_no_context_takeover`] && this._deflate.reset(), r(null, n);
421
+ });
422
+ }
423
+ };
424
+ var oe = Rt;
425
+ function Ut(s) {
426
+ this[C].push(s), this[w] += s.length;
427
+ }
428
+ function st(s) {
429
+ if (this[w] += s.length, this[se]._maxPayload < 1 || this[w] <= this[se]._maxPayload) {
430
+ this[C].push(s);
431
+ return;
432
+ }
433
+ this[J] = new RangeError("Max payload size exceeded"), this[J].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH", this[J][tt] = 1009, this.removeListener("data", st), this.reset();
434
+ }
435
+ function Bt(s) {
436
+ this[se]._inflate = null, s[tt] = 1007, this[V](s);
437
+ }
438
+ var re = { exports: {} };
439
+ const $t = {}, Mt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
440
+ __proto__: null,
441
+ default: $t
442
+ }, Symbol.toStringTag, { value: "Module" })), It = /* @__PURE__ */ gt(Mt);
443
+ var Le;
444
+ const { isUtf8: Ne } = S, Dt = [
445
+ 0,
446
+ 0,
447
+ 0,
448
+ 0,
449
+ 0,
450
+ 0,
451
+ 0,
452
+ 0,
453
+ 0,
454
+ 0,
455
+ 0,
456
+ 0,
457
+ 0,
458
+ 0,
459
+ 0,
460
+ 0,
461
+ // 0 - 15
462
+ 0,
463
+ 0,
464
+ 0,
465
+ 0,
466
+ 0,
467
+ 0,
468
+ 0,
469
+ 0,
470
+ 0,
471
+ 0,
472
+ 0,
473
+ 0,
474
+ 0,
475
+ 0,
476
+ 0,
477
+ 0,
478
+ // 16 - 31
479
+ 0,
480
+ 1,
481
+ 0,
482
+ 1,
483
+ 1,
484
+ 1,
485
+ 1,
486
+ 1,
487
+ 0,
488
+ 0,
489
+ 1,
490
+ 1,
491
+ 0,
492
+ 1,
493
+ 1,
494
+ 0,
495
+ // 32 - 47
496
+ 1,
497
+ 1,
498
+ 1,
499
+ 1,
500
+ 1,
501
+ 1,
502
+ 1,
503
+ 1,
504
+ 1,
505
+ 1,
506
+ 0,
507
+ 0,
508
+ 0,
509
+ 0,
510
+ 0,
511
+ 0,
512
+ // 48 - 63
513
+ 0,
514
+ 1,
515
+ 1,
516
+ 1,
517
+ 1,
518
+ 1,
519
+ 1,
520
+ 1,
521
+ 1,
522
+ 1,
523
+ 1,
524
+ 1,
525
+ 1,
526
+ 1,
527
+ 1,
528
+ 1,
529
+ // 64 - 79
530
+ 1,
531
+ 1,
532
+ 1,
533
+ 1,
534
+ 1,
535
+ 1,
536
+ 1,
537
+ 1,
538
+ 1,
539
+ 1,
540
+ 1,
541
+ 0,
542
+ 0,
543
+ 0,
544
+ 1,
545
+ 1,
546
+ // 80 - 95
547
+ 1,
548
+ 1,
549
+ 1,
550
+ 1,
551
+ 1,
552
+ 1,
553
+ 1,
554
+ 1,
555
+ 1,
556
+ 1,
557
+ 1,
558
+ 1,
559
+ 1,
560
+ 1,
561
+ 1,
562
+ 1,
563
+ // 96 - 111
564
+ 1,
565
+ 1,
566
+ 1,
567
+ 1,
568
+ 1,
569
+ 1,
570
+ 1,
571
+ 1,
572
+ 1,
573
+ 1,
574
+ 1,
575
+ 0,
576
+ 1,
577
+ 0,
578
+ 1,
579
+ 0
580
+ // 112 - 127
581
+ ];
582
+ function Wt(s) {
583
+ return s >= 1e3 && s <= 1014 && s !== 1004 && s !== 1005 && s !== 1006 || s >= 3e3 && s <= 4999;
584
+ }
585
+ function be(s) {
586
+ const e = s.length;
587
+ let t = 0;
588
+ for (; t < e; )
589
+ if (!(s[t] & 128))
590
+ t++;
591
+ else if ((s[t] & 224) === 192) {
592
+ if (t + 1 === e || (s[t + 1] & 192) !== 128 || (s[t] & 254) === 192)
593
+ return !1;
594
+ t += 2;
595
+ } else if ((s[t] & 240) === 224) {
596
+ if (t + 2 >= e || (s[t + 1] & 192) !== 128 || (s[t + 2] & 192) !== 128 || s[t] === 224 && (s[t + 1] & 224) === 128 || // Overlong
597
+ s[t] === 237 && (s[t + 1] & 224) === 160)
598
+ return !1;
599
+ t += 3;
600
+ } else if ((s[t] & 248) === 240) {
601
+ if (t + 3 >= e || (s[t + 1] & 192) !== 128 || (s[t + 2] & 192) !== 128 || (s[t + 3] & 192) !== 128 || s[t] === 240 && (s[t + 1] & 240) === 128 || // Overlong
602
+ s[t] === 244 && s[t + 1] > 143 || s[t] > 244)
603
+ return !1;
604
+ t += 4;
605
+ } else
606
+ return !1;
607
+ return !0;
608
+ }
609
+ re.exports = {
610
+ isValidStatusCode: Wt,
611
+ isValidUTF8: be,
612
+ tokenChars: Dt
613
+ };
614
+ if (Ne)
615
+ Le = re.exports.isValidUTF8 = function(s) {
616
+ return s.length < 24 ? be(s) : Ne(s);
617
+ };
618
+ else if (!process.env.WS_NO_UTF_8_VALIDATE)
619
+ try {
620
+ const s = It;
621
+ Le = re.exports.isValidUTF8 = function(e) {
622
+ return e.length < 32 ? be(e) : s(e);
623
+ };
624
+ } catch {
625
+ }
626
+ var ae = re.exports;
627
+ const { Writable: At } = S, Pe = oe, {
628
+ BINARY_TYPES: Ft,
629
+ EMPTY_BUFFER: Re,
630
+ kStatusCode: jt,
631
+ kWebSocket: Gt
632
+ } = U, { concat: de, toArrayBuffer: Vt, unmask: Ht } = ne, { isValidStatusCode: zt, isValidUTF8: Ue } = ae, X = Buffer[Symbol.species], A = 0, Be = 1, $e = 2, Me = 3, _e = 4, Yt = 5;
633
+ let qt = class extends At {
634
+ /**
635
+ * Creates a Receiver instance.
636
+ *
637
+ * @param {Object} [options] Options object
638
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
639
+ * @param {Object} [options.extensions] An object containing the negotiated
640
+ * extensions
641
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
642
+ * client or server mode
643
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
644
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
645
+ * not to skip UTF-8 validation for text and close messages
646
+ */
647
+ constructor(e = {}) {
648
+ super(), this._binaryType = e.binaryType || Ft[0], this._extensions = e.extensions || {}, this._isServer = !!e.isServer, this._maxPayload = e.maxPayload | 0, this._skipUTF8Validation = !!e.skipUTF8Validation, this[Gt] = void 0, this._bufferedBytes = 0, this._buffers = [], this._compressed = !1, this._payloadLength = 0, this._mask = void 0, this._fragmented = 0, this._masked = !1, this._fin = !1, this._opcode = 0, this._totalPayloadLength = 0, this._messageLength = 0, this._fragments = [], this._state = A, this._loop = !1;
649
+ }
650
+ /**
651
+ * Implements `Writable.prototype._write()`.
652
+ *
653
+ * @param {Buffer} chunk The chunk of data to write
654
+ * @param {String} encoding The character encoding of `chunk`
655
+ * @param {Function} cb Callback
656
+ * @private
657
+ */
658
+ _write(e, t, r) {
659
+ if (this._opcode === 8 && this._state == A)
660
+ return r();
661
+ this._bufferedBytes += e.length, this._buffers.push(e), this.startLoop(r);
662
+ }
663
+ /**
664
+ * Consumes `n` bytes from the buffered data.
665
+ *
666
+ * @param {Number} n The number of bytes to consume
667
+ * @return {Buffer} The consumed bytes
668
+ * @private
669
+ */
670
+ consume(e) {
671
+ if (this._bufferedBytes -= e, e === this._buffers[0].length)
672
+ return this._buffers.shift();
673
+ if (e < this._buffers[0].length) {
674
+ const r = this._buffers[0];
675
+ return this._buffers[0] = new X(
676
+ r.buffer,
677
+ r.byteOffset + e,
678
+ r.length - e
679
+ ), new X(r.buffer, r.byteOffset, e);
680
+ }
681
+ const t = Buffer.allocUnsafe(e);
682
+ do {
683
+ const r = this._buffers[0], i = t.length - e;
684
+ e >= r.length ? t.set(this._buffers.shift(), i) : (t.set(new Uint8Array(r.buffer, r.byteOffset, e), i), this._buffers[0] = new X(
685
+ r.buffer,
686
+ r.byteOffset + e,
687
+ r.length - e
688
+ )), e -= r.length;
689
+ } while (e > 0);
690
+ return t;
691
+ }
692
+ /**
693
+ * Starts the parsing loop.
694
+ *
695
+ * @param {Function} cb Callback
696
+ * @private
697
+ */
698
+ startLoop(e) {
699
+ let t;
700
+ this._loop = !0;
701
+ do
702
+ switch (this._state) {
703
+ case A:
704
+ t = this.getInfo();
705
+ break;
706
+ case Be:
707
+ t = this.getPayloadLength16();
708
+ break;
709
+ case $e:
710
+ t = this.getPayloadLength64();
711
+ break;
712
+ case Me:
713
+ this.getMask();
714
+ break;
715
+ case _e:
716
+ t = this.getData(e);
717
+ break;
718
+ default:
719
+ this._loop = !1;
720
+ return;
721
+ }
722
+ while (this._loop);
723
+ e(t);
724
+ }
725
+ /**
726
+ * Reads the first two bytes of a frame.
727
+ *
728
+ * @return {(RangeError|undefined)} A possible error
729
+ * @private
730
+ */
731
+ getInfo() {
732
+ if (this._bufferedBytes < 2) {
733
+ this._loop = !1;
734
+ return;
735
+ }
736
+ const e = this.consume(2);
737
+ if (e[0] & 48)
738
+ return this._loop = !1, g(
739
+ RangeError,
740
+ "RSV2 and RSV3 must be clear",
741
+ !0,
742
+ 1002,
743
+ "WS_ERR_UNEXPECTED_RSV_2_3"
744
+ );
745
+ const t = (e[0] & 64) === 64;
746
+ if (t && !this._extensions[Pe.extensionName])
747
+ return this._loop = !1, g(
748
+ RangeError,
749
+ "RSV1 must be clear",
750
+ !0,
751
+ 1002,
752
+ "WS_ERR_UNEXPECTED_RSV_1"
753
+ );
754
+ if (this._fin = (e[0] & 128) === 128, this._opcode = e[0] & 15, this._payloadLength = e[1] & 127, this._opcode === 0) {
755
+ if (t)
756
+ return this._loop = !1, g(
757
+ RangeError,
758
+ "RSV1 must be clear",
759
+ !0,
760
+ 1002,
761
+ "WS_ERR_UNEXPECTED_RSV_1"
762
+ );
763
+ if (!this._fragmented)
764
+ return this._loop = !1, g(
765
+ RangeError,
766
+ "invalid opcode 0",
767
+ !0,
768
+ 1002,
769
+ "WS_ERR_INVALID_OPCODE"
770
+ );
771
+ this._opcode = this._fragmented;
772
+ } else if (this._opcode === 1 || this._opcode === 2) {
773
+ if (this._fragmented)
774
+ return this._loop = !1, g(
775
+ RangeError,
776
+ `invalid opcode ${this._opcode}`,
777
+ !0,
778
+ 1002,
779
+ "WS_ERR_INVALID_OPCODE"
780
+ );
781
+ this._compressed = t;
782
+ } else if (this._opcode > 7 && this._opcode < 11) {
783
+ if (!this._fin)
784
+ return this._loop = !1, g(
785
+ RangeError,
786
+ "FIN must be set",
787
+ !0,
788
+ 1002,
789
+ "WS_ERR_EXPECTED_FIN"
790
+ );
791
+ if (t)
792
+ return this._loop = !1, g(
793
+ RangeError,
794
+ "RSV1 must be clear",
795
+ !0,
796
+ 1002,
797
+ "WS_ERR_UNEXPECTED_RSV_1"
798
+ );
799
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1)
800
+ return this._loop = !1, g(
801
+ RangeError,
802
+ `invalid payload length ${this._payloadLength}`,
803
+ !0,
804
+ 1002,
805
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
806
+ );
807
+ } else
808
+ return this._loop = !1, g(
809
+ RangeError,
810
+ `invalid opcode ${this._opcode}`,
811
+ !0,
812
+ 1002,
813
+ "WS_ERR_INVALID_OPCODE"
814
+ );
815
+ if (!this._fin && !this._fragmented && (this._fragmented = this._opcode), this._masked = (e[1] & 128) === 128, this._isServer) {
816
+ if (!this._masked)
817
+ return this._loop = !1, g(
818
+ RangeError,
819
+ "MASK must be set",
820
+ !0,
821
+ 1002,
822
+ "WS_ERR_EXPECTED_MASK"
823
+ );
824
+ } else if (this._masked)
825
+ return this._loop = !1, g(
826
+ RangeError,
827
+ "MASK must be clear",
828
+ !0,
829
+ 1002,
830
+ "WS_ERR_UNEXPECTED_MASK"
831
+ );
832
+ if (this._payloadLength === 126)
833
+ this._state = Be;
834
+ else if (this._payloadLength === 127)
835
+ this._state = $e;
836
+ else
837
+ return this.haveLength();
838
+ }
839
+ /**
840
+ * Gets extended payload length (7+16).
841
+ *
842
+ * @return {(RangeError|undefined)} A possible error
843
+ * @private
844
+ */
845
+ getPayloadLength16() {
846
+ if (this._bufferedBytes < 2) {
847
+ this._loop = !1;
848
+ return;
849
+ }
850
+ return this._payloadLength = this.consume(2).readUInt16BE(0), this.haveLength();
851
+ }
852
+ /**
853
+ * Gets extended payload length (7+64).
854
+ *
855
+ * @return {(RangeError|undefined)} A possible error
856
+ * @private
857
+ */
858
+ getPayloadLength64() {
859
+ if (this._bufferedBytes < 8) {
860
+ this._loop = !1;
861
+ return;
862
+ }
863
+ const e = this.consume(8), t = e.readUInt32BE(0);
864
+ return t > Math.pow(2, 53 - 32) - 1 ? (this._loop = !1, g(
865
+ RangeError,
866
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
867
+ !1,
868
+ 1009,
869
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
870
+ )) : (this._payloadLength = t * Math.pow(2, 32) + e.readUInt32BE(4), this.haveLength());
871
+ }
872
+ /**
873
+ * Payload length has been read.
874
+ *
875
+ * @return {(RangeError|undefined)} A possible error
876
+ * @private
877
+ */
878
+ haveLength() {
879
+ if (this._payloadLength && this._opcode < 8 && (this._totalPayloadLength += this._payloadLength, this._totalPayloadLength > this._maxPayload && this._maxPayload > 0))
880
+ return this._loop = !1, g(
881
+ RangeError,
882
+ "Max payload size exceeded",
883
+ !1,
884
+ 1009,
885
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
886
+ );
887
+ this._masked ? this._state = Me : this._state = _e;
888
+ }
889
+ /**
890
+ * Reads mask bytes.
891
+ *
892
+ * @private
893
+ */
894
+ getMask() {
895
+ if (this._bufferedBytes < 4) {
896
+ this._loop = !1;
897
+ return;
898
+ }
899
+ this._mask = this.consume(4), this._state = _e;
900
+ }
901
+ /**
902
+ * Reads data bytes.
903
+ *
904
+ * @param {Function} cb Callback
905
+ * @return {(Error|RangeError|undefined)} A possible error
906
+ * @private
907
+ */
908
+ getData(e) {
909
+ let t = Re;
910
+ if (this._payloadLength) {
911
+ if (this._bufferedBytes < this._payloadLength) {
912
+ this._loop = !1;
913
+ return;
914
+ }
915
+ t = this.consume(this._payloadLength), this._masked && this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3] && Ht(t, this._mask);
916
+ }
917
+ if (this._opcode > 7)
918
+ return this.controlMessage(t);
919
+ if (this._compressed) {
920
+ this._state = Yt, this.decompress(t, e);
921
+ return;
922
+ }
923
+ return t.length && (this._messageLength = this._totalPayloadLength, this._fragments.push(t)), this.dataMessage();
924
+ }
925
+ /**
926
+ * Decompresses data.
927
+ *
928
+ * @param {Buffer} data Compressed data
929
+ * @param {Function} cb Callback
930
+ * @private
931
+ */
932
+ decompress(e, t) {
933
+ this._extensions[Pe.extensionName].decompress(e, this._fin, (i, n) => {
934
+ if (i)
935
+ return t(i);
936
+ if (n.length) {
937
+ if (this._messageLength += n.length, this._messageLength > this._maxPayload && this._maxPayload > 0)
938
+ return t(
939
+ g(
940
+ RangeError,
941
+ "Max payload size exceeded",
942
+ !1,
943
+ 1009,
944
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
945
+ )
946
+ );
947
+ this._fragments.push(n);
948
+ }
949
+ const o = this.dataMessage();
950
+ if (o)
951
+ return t(o);
952
+ this.startLoop(t);
953
+ });
954
+ }
955
+ /**
956
+ * Handles a data message.
957
+ *
958
+ * @return {(Error|undefined)} A possible error
959
+ * @private
960
+ */
961
+ dataMessage() {
962
+ if (this._fin) {
963
+ const e = this._messageLength, t = this._fragments;
964
+ if (this._totalPayloadLength = 0, this._messageLength = 0, this._fragmented = 0, this._fragments = [], this._opcode === 2) {
965
+ let r;
966
+ this._binaryType === "nodebuffer" ? r = de(t, e) : this._binaryType === "arraybuffer" ? r = Vt(de(t, e)) : r = t, this.emit("message", r, !0);
967
+ } else {
968
+ const r = de(t, e);
969
+ if (!this._skipUTF8Validation && !Ue(r))
970
+ return this._loop = !1, g(
971
+ Error,
972
+ "invalid UTF-8 sequence",
973
+ !0,
974
+ 1007,
975
+ "WS_ERR_INVALID_UTF8"
976
+ );
977
+ this.emit("message", r, !1);
978
+ }
979
+ }
980
+ this._state = A;
981
+ }
982
+ /**
983
+ * Handles a control message.
984
+ *
985
+ * @param {Buffer} data Data to handle
986
+ * @return {(Error|RangeError|undefined)} A possible error
987
+ * @private
988
+ */
989
+ controlMessage(e) {
990
+ if (this._opcode === 8)
991
+ if (this._loop = !1, e.length === 0)
992
+ this.emit("conclude", 1005, Re), this.end();
993
+ else {
994
+ const t = e.readUInt16BE(0);
995
+ if (!zt(t))
996
+ return g(
997
+ RangeError,
998
+ `invalid status code ${t}`,
999
+ !0,
1000
+ 1002,
1001
+ "WS_ERR_INVALID_CLOSE_CODE"
1002
+ );
1003
+ const r = new X(
1004
+ e.buffer,
1005
+ e.byteOffset + 2,
1006
+ e.length - 2
1007
+ );
1008
+ if (!this._skipUTF8Validation && !Ue(r))
1009
+ return g(
1010
+ Error,
1011
+ "invalid UTF-8 sequence",
1012
+ !0,
1013
+ 1007,
1014
+ "WS_ERR_INVALID_UTF8"
1015
+ );
1016
+ this.emit("conclude", t, r), this.end();
1017
+ }
1018
+ else
1019
+ this._opcode === 9 ? this.emit("ping", e) : this.emit("pong", e);
1020
+ this._state = A;
1021
+ }
1022
+ };
1023
+ var rt = qt;
1024
+ function g(s, e, t, r, i) {
1025
+ const n = new s(
1026
+ t ? `Invalid WebSocket frame: ${e}` : e
1027
+ );
1028
+ return Error.captureStackTrace(n, g), n.code = i, n[jt] = r, n;
1029
+ }
1030
+ const qs = /* @__PURE__ */ z(rt), { randomFillSync: Kt } = S, Ie = oe, { EMPTY_BUFFER: Xt } = U, { isValidStatusCode: Zt } = ae, { mask: De, toBuffer: M } = ne, x = Symbol("kByteLength"), Qt = Buffer.alloc(4);
1031
+ let Jt = class P {
1032
+ /**
1033
+ * Creates a Sender instance.
1034
+ *
1035
+ * @param {(net.Socket|tls.Socket)} socket The connection socket
1036
+ * @param {Object} [extensions] An object containing the negotiated extensions
1037
+ * @param {Function} [generateMask] The function used to generate the masking
1038
+ * key
1039
+ */
1040
+ constructor(e, t, r) {
1041
+ this._extensions = t || {}, r && (this._generateMask = r, this._maskBuffer = Buffer.alloc(4)), this._socket = e, this._firstFragment = !0, this._compress = !1, this._bufferedBytes = 0, this._deflating = !1, this._queue = [];
1042
+ }
1043
+ /**
1044
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1045
+ *
1046
+ * @param {(Buffer|String)} data The data to frame
1047
+ * @param {Object} options Options object
1048
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1049
+ * FIN bit
1050
+ * @param {Function} [options.generateMask] The function used to generate the
1051
+ * masking key
1052
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1053
+ * `data`
1054
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1055
+ * key
1056
+ * @param {Number} options.opcode The opcode
1057
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1058
+ * modified
1059
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1060
+ * RSV1 bit
1061
+ * @return {(Buffer|String)[]} The framed data
1062
+ * @public
1063
+ */
1064
+ static frame(e, t) {
1065
+ let r, i = !1, n = 2, o = !1;
1066
+ t.mask && (r = t.maskBuffer || Qt, t.generateMask ? t.generateMask(r) : Kt(r, 0, 4), o = (r[0] | r[1] | r[2] | r[3]) === 0, n = 6);
1067
+ let l;
1068
+ typeof e == "string" ? (!t.mask || o) && t[x] !== void 0 ? l = t[x] : (e = Buffer.from(e), l = e.length) : (l = e.length, i = t.mask && t.readOnly && !o);
1069
+ let f = l;
1070
+ l >= 65536 ? (n += 8, f = 127) : l > 125 && (n += 2, f = 126);
1071
+ const a = Buffer.allocUnsafe(i ? l + n : n);
1072
+ return a[0] = t.fin ? t.opcode | 128 : t.opcode, t.rsv1 && (a[0] |= 64), a[1] = f, f === 126 ? a.writeUInt16BE(l, 2) : f === 127 && (a[2] = a[3] = 0, a.writeUIntBE(l, 4, 6)), t.mask ? (a[1] |= 128, a[n - 4] = r[0], a[n - 3] = r[1], a[n - 2] = r[2], a[n - 1] = r[3], o ? [a, e] : i ? (De(e, r, a, n, l), [a]) : (De(e, r, e, 0, l), [a, e])) : [a, e];
1073
+ }
1074
+ /**
1075
+ * Sends a close message to the other peer.
1076
+ *
1077
+ * @param {Number} [code] The status code component of the body
1078
+ * @param {(String|Buffer)} [data] The message component of the body
1079
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1080
+ * @param {Function} [cb] Callback
1081
+ * @public
1082
+ */
1083
+ close(e, t, r, i) {
1084
+ let n;
1085
+ if (e === void 0)
1086
+ n = Xt;
1087
+ else {
1088
+ if (typeof e != "number" || !Zt(e))
1089
+ throw new TypeError("First argument must be a valid error code number");
1090
+ if (t === void 0 || !t.length)
1091
+ n = Buffer.allocUnsafe(2), n.writeUInt16BE(e, 0);
1092
+ else {
1093
+ const l = Buffer.byteLength(t);
1094
+ if (l > 123)
1095
+ throw new RangeError("The message must not be greater than 123 bytes");
1096
+ n = Buffer.allocUnsafe(2 + l), n.writeUInt16BE(e, 0), typeof t == "string" ? n.write(t, 2) : n.set(t, 2);
1097
+ }
1098
+ }
1099
+ const o = {
1100
+ [x]: n.length,
1101
+ fin: !0,
1102
+ generateMask: this._generateMask,
1103
+ mask: r,
1104
+ maskBuffer: this._maskBuffer,
1105
+ opcode: 8,
1106
+ readOnly: !1,
1107
+ rsv1: !1
1108
+ };
1109
+ this._deflating ? this.enqueue([this.dispatch, n, !1, o, i]) : this.sendFrame(P.frame(n, o), i);
1110
+ }
1111
+ /**
1112
+ * Sends a ping message to the other peer.
1113
+ *
1114
+ * @param {*} data The message to send
1115
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1116
+ * @param {Function} [cb] Callback
1117
+ * @public
1118
+ */
1119
+ ping(e, t, r) {
1120
+ let i, n;
1121
+ if (typeof e == "string" ? (i = Buffer.byteLength(e), n = !1) : (e = M(e), i = e.length, n = M.readOnly), i > 125)
1122
+ throw new RangeError("The data size must not be greater than 125 bytes");
1123
+ const o = {
1124
+ [x]: i,
1125
+ fin: !0,
1126
+ generateMask: this._generateMask,
1127
+ mask: t,
1128
+ maskBuffer: this._maskBuffer,
1129
+ opcode: 9,
1130
+ readOnly: n,
1131
+ rsv1: !1
1132
+ };
1133
+ this._deflating ? this.enqueue([this.dispatch, e, !1, o, r]) : this.sendFrame(P.frame(e, o), r);
1134
+ }
1135
+ /**
1136
+ * Sends a pong message to the other peer.
1137
+ *
1138
+ * @param {*} data The message to send
1139
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1140
+ * @param {Function} [cb] Callback
1141
+ * @public
1142
+ */
1143
+ pong(e, t, r) {
1144
+ let i, n;
1145
+ if (typeof e == "string" ? (i = Buffer.byteLength(e), n = !1) : (e = M(e), i = e.length, n = M.readOnly), i > 125)
1146
+ throw new RangeError("The data size must not be greater than 125 bytes");
1147
+ const o = {
1148
+ [x]: i,
1149
+ fin: !0,
1150
+ generateMask: this._generateMask,
1151
+ mask: t,
1152
+ maskBuffer: this._maskBuffer,
1153
+ opcode: 10,
1154
+ readOnly: n,
1155
+ rsv1: !1
1156
+ };
1157
+ this._deflating ? this.enqueue([this.dispatch, e, !1, o, r]) : this.sendFrame(P.frame(e, o), r);
1158
+ }
1159
+ /**
1160
+ * Sends a data message to the other peer.
1161
+ *
1162
+ * @param {*} data The message to send
1163
+ * @param {Object} options Options object
1164
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1165
+ * or text
1166
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1167
+ * compress `data`
1168
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1169
+ * last one
1170
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1171
+ * `data`
1172
+ * @param {Function} [cb] Callback
1173
+ * @public
1174
+ */
1175
+ send(e, t, r) {
1176
+ const i = this._extensions[Ie.extensionName];
1177
+ let n = t.binary ? 2 : 1, o = t.compress, l, f;
1178
+ if (typeof e == "string" ? (l = Buffer.byteLength(e), f = !1) : (e = M(e), l = e.length, f = M.readOnly), this._firstFragment ? (this._firstFragment = !1, o && i && i.params[i._isServer ? "server_no_context_takeover" : "client_no_context_takeover"] && (o = l >= i._threshold), this._compress = o) : (o = !1, n = 0), t.fin && (this._firstFragment = !0), i) {
1179
+ const a = {
1180
+ [x]: l,
1181
+ fin: t.fin,
1182
+ generateMask: this._generateMask,
1183
+ mask: t.mask,
1184
+ maskBuffer: this._maskBuffer,
1185
+ opcode: n,
1186
+ readOnly: f,
1187
+ rsv1: o
1188
+ };
1189
+ this._deflating ? this.enqueue([this.dispatch, e, this._compress, a, r]) : this.dispatch(e, this._compress, a, r);
1190
+ } else
1191
+ this.sendFrame(
1192
+ P.frame(e, {
1193
+ [x]: l,
1194
+ fin: t.fin,
1195
+ generateMask: this._generateMask,
1196
+ mask: t.mask,
1197
+ maskBuffer: this._maskBuffer,
1198
+ opcode: n,
1199
+ readOnly: f,
1200
+ rsv1: !1
1201
+ }),
1202
+ r
1203
+ );
1204
+ }
1205
+ /**
1206
+ * Dispatches a message.
1207
+ *
1208
+ * @param {(Buffer|String)} data The message to send
1209
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1210
+ * `data`
1211
+ * @param {Object} options Options object
1212
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1213
+ * FIN bit
1214
+ * @param {Function} [options.generateMask] The function used to generate the
1215
+ * masking key
1216
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1217
+ * `data`
1218
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1219
+ * key
1220
+ * @param {Number} options.opcode The opcode
1221
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1222
+ * modified
1223
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1224
+ * RSV1 bit
1225
+ * @param {Function} [cb] Callback
1226
+ * @private
1227
+ */
1228
+ dispatch(e, t, r, i) {
1229
+ if (!t) {
1230
+ this.sendFrame(P.frame(e, r), i);
1231
+ return;
1232
+ }
1233
+ const n = this._extensions[Ie.extensionName];
1234
+ this._bufferedBytes += r[x], this._deflating = !0, n.compress(e, r.fin, (o, l) => {
1235
+ if (this._socket.destroyed) {
1236
+ const f = new Error(
1237
+ "The socket was closed while data was being compressed"
1238
+ );
1239
+ typeof i == "function" && i(f);
1240
+ for (let a = 0; a < this._queue.length; a++) {
1241
+ const c = this._queue[a], h = c[c.length - 1];
1242
+ typeof h == "function" && h(f);
1243
+ }
1244
+ return;
1245
+ }
1246
+ this._bufferedBytes -= r[x], this._deflating = !1, r.readOnly = !1, this.sendFrame(P.frame(l, r), i), this.dequeue();
1247
+ });
1248
+ }
1249
+ /**
1250
+ * Executes queued send operations.
1251
+ *
1252
+ * @private
1253
+ */
1254
+ dequeue() {
1255
+ for (; !this._deflating && this._queue.length; ) {
1256
+ const e = this._queue.shift();
1257
+ this._bufferedBytes -= e[3][x], Reflect.apply(e[0], this, e.slice(1));
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Enqueues a send operation.
1262
+ *
1263
+ * @param {Array} params Send operation parameters.
1264
+ * @private
1265
+ */
1266
+ enqueue(e) {
1267
+ this._bufferedBytes += e[3][x], this._queue.push(e);
1268
+ }
1269
+ /**
1270
+ * Sends a frame.
1271
+ *
1272
+ * @param {Buffer[]} list The frame to send
1273
+ * @param {Function} [cb] Callback
1274
+ * @private
1275
+ */
1276
+ sendFrame(e, t) {
1277
+ e.length === 2 ? (this._socket.cork(), this._socket.write(e[0]), this._socket.write(e[1], t), this._socket.uncork()) : this._socket.write(e[0], t);
1278
+ }
1279
+ };
1280
+ var it = Jt;
1281
+ const Ks = /* @__PURE__ */ z(it), { kForOnEventAttribute: F, kListener: pe } = U, We = Symbol("kCode"), Ae = Symbol("kData"), Fe = Symbol("kError"), je = Symbol("kMessage"), Ge = Symbol("kReason"), I = Symbol("kTarget"), Ve = Symbol("kType"), He = Symbol("kWasClean");
1282
+ class B {
1283
+ /**
1284
+ * Create a new `Event`.
1285
+ *
1286
+ * @param {String} type The name of the event
1287
+ * @throws {TypeError} If the `type` argument is not specified
1288
+ */
1289
+ constructor(e) {
1290
+ this[I] = null, this[Ve] = e;
1291
+ }
1292
+ /**
1293
+ * @type {*}
1294
+ */
1295
+ get target() {
1296
+ return this[I];
1297
+ }
1298
+ /**
1299
+ * @type {String}
1300
+ */
1301
+ get type() {
1302
+ return this[Ve];
1303
+ }
1304
+ }
1305
+ Object.defineProperty(B.prototype, "target", { enumerable: !0 });
1306
+ Object.defineProperty(B.prototype, "type", { enumerable: !0 });
1307
+ class Y extends B {
1308
+ /**
1309
+ * Create a new `CloseEvent`.
1310
+ *
1311
+ * @param {String} type The name of the event
1312
+ * @param {Object} [options] A dictionary object that allows for setting
1313
+ * attributes via object members of the same name
1314
+ * @param {Number} [options.code=0] The status code explaining why the
1315
+ * connection was closed
1316
+ * @param {String} [options.reason=''] A human-readable string explaining why
1317
+ * the connection was closed
1318
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1319
+ * connection was cleanly closed
1320
+ */
1321
+ constructor(e, t = {}) {
1322
+ super(e), this[We] = t.code === void 0 ? 0 : t.code, this[Ge] = t.reason === void 0 ? "" : t.reason, this[He] = t.wasClean === void 0 ? !1 : t.wasClean;
1323
+ }
1324
+ /**
1325
+ * @type {Number}
1326
+ */
1327
+ get code() {
1328
+ return this[We];
1329
+ }
1330
+ /**
1331
+ * @type {String}
1332
+ */
1333
+ get reason() {
1334
+ return this[Ge];
1335
+ }
1336
+ /**
1337
+ * @type {Boolean}
1338
+ */
1339
+ get wasClean() {
1340
+ return this[He];
1341
+ }
1342
+ }
1343
+ Object.defineProperty(Y.prototype, "code", { enumerable: !0 });
1344
+ Object.defineProperty(Y.prototype, "reason", { enumerable: !0 });
1345
+ Object.defineProperty(Y.prototype, "wasClean", { enumerable: !0 });
1346
+ class le extends B {
1347
+ /**
1348
+ * Create a new `ErrorEvent`.
1349
+ *
1350
+ * @param {String} type The name of the event
1351
+ * @param {Object} [options] A dictionary object that allows for setting
1352
+ * attributes via object members of the same name
1353
+ * @param {*} [options.error=null] The error that generated this event
1354
+ * @param {String} [options.message=''] The error message
1355
+ */
1356
+ constructor(e, t = {}) {
1357
+ super(e), this[Fe] = t.error === void 0 ? null : t.error, this[je] = t.message === void 0 ? "" : t.message;
1358
+ }
1359
+ /**
1360
+ * @type {*}
1361
+ */
1362
+ get error() {
1363
+ return this[Fe];
1364
+ }
1365
+ /**
1366
+ * @type {String}
1367
+ */
1368
+ get message() {
1369
+ return this[je];
1370
+ }
1371
+ }
1372
+ Object.defineProperty(le.prototype, "error", { enumerable: !0 });
1373
+ Object.defineProperty(le.prototype, "message", { enumerable: !0 });
1374
+ class xe extends B {
1375
+ /**
1376
+ * Create a new `MessageEvent`.
1377
+ *
1378
+ * @param {String} type The name of the event
1379
+ * @param {Object} [options] A dictionary object that allows for setting
1380
+ * attributes via object members of the same name
1381
+ * @param {*} [options.data=null] The message content
1382
+ */
1383
+ constructor(e, t = {}) {
1384
+ super(e), this[Ae] = t.data === void 0 ? null : t.data;
1385
+ }
1386
+ /**
1387
+ * @type {*}
1388
+ */
1389
+ get data() {
1390
+ return this[Ae];
1391
+ }
1392
+ }
1393
+ Object.defineProperty(xe.prototype, "data", { enumerable: !0 });
1394
+ const es = {
1395
+ /**
1396
+ * Register an event listener.
1397
+ *
1398
+ * @param {String} type A string representing the event type to listen for
1399
+ * @param {(Function|Object)} handler The listener to add
1400
+ * @param {Object} [options] An options object specifies characteristics about
1401
+ * the event listener
1402
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1403
+ * listener should be invoked at most once after being added. If `true`,
1404
+ * the listener would be automatically removed when invoked.
1405
+ * @public
1406
+ */
1407
+ addEventListener(s, e, t = {}) {
1408
+ for (const i of this.listeners(s))
1409
+ if (!t[F] && i[pe] === e && !i[F])
1410
+ return;
1411
+ let r;
1412
+ if (s === "message")
1413
+ r = function(n, o) {
1414
+ const l = new xe("message", {
1415
+ data: o ? n : n.toString()
1416
+ });
1417
+ l[I] = this, Z(e, this, l);
1418
+ };
1419
+ else if (s === "close")
1420
+ r = function(n, o) {
1421
+ const l = new Y("close", {
1422
+ code: n,
1423
+ reason: o.toString(),
1424
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1425
+ });
1426
+ l[I] = this, Z(e, this, l);
1427
+ };
1428
+ else if (s === "error")
1429
+ r = function(n) {
1430
+ const o = new le("error", {
1431
+ error: n,
1432
+ message: n.message
1433
+ });
1434
+ o[I] = this, Z(e, this, o);
1435
+ };
1436
+ else if (s === "open")
1437
+ r = function() {
1438
+ const n = new B("open");
1439
+ n[I] = this, Z(e, this, n);
1440
+ };
1441
+ else
1442
+ return;
1443
+ r[F] = !!t[F], r[pe] = e, t.once ? this.once(s, r) : this.on(s, r);
1444
+ },
1445
+ /**
1446
+ * Remove an event listener.
1447
+ *
1448
+ * @param {String} type A string representing the event type to remove
1449
+ * @param {(Function|Object)} handler The listener to remove
1450
+ * @public
1451
+ */
1452
+ removeEventListener(s, e) {
1453
+ for (const t of this.listeners(s))
1454
+ if (t[pe] === e && !t[F]) {
1455
+ this.removeListener(s, t);
1456
+ break;
1457
+ }
1458
+ }
1459
+ };
1460
+ var ts = {
1461
+ CloseEvent: Y,
1462
+ ErrorEvent: le,
1463
+ Event: B,
1464
+ EventTarget: es,
1465
+ MessageEvent: xe
1466
+ };
1467
+ function Z(s, e, t) {
1468
+ typeof s == "object" && s.handleEvent ? s.handleEvent.call(s, t) : s.call(e, t);
1469
+ }
1470
+ const { tokenChars: j } = ae;
1471
+ function k(s, e, t) {
1472
+ s[e] === void 0 ? s[e] = [t] : s[e].push(t);
1473
+ }
1474
+ function ss(s) {
1475
+ const e = /* @__PURE__ */ Object.create(null);
1476
+ let t = /* @__PURE__ */ Object.create(null), r = !1, i = !1, n = !1, o, l, f = -1, a = -1, c = -1, h = 0;
1477
+ for (; h < s.length; h++)
1478
+ if (a = s.charCodeAt(h), o === void 0)
1479
+ if (c === -1 && j[a] === 1)
1480
+ f === -1 && (f = h);
1481
+ else if (h !== 0 && (a === 32 || a === 9))
1482
+ c === -1 && f !== -1 && (c = h);
1483
+ else if (a === 59 || a === 44) {
1484
+ if (f === -1)
1485
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1486
+ c === -1 && (c = h);
1487
+ const v = s.slice(f, c);
1488
+ a === 44 ? (k(e, v, t), t = /* @__PURE__ */ Object.create(null)) : o = v, f = c = -1;
1489
+ } else
1490
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1491
+ else if (l === void 0)
1492
+ if (c === -1 && j[a] === 1)
1493
+ f === -1 && (f = h);
1494
+ else if (a === 32 || a === 9)
1495
+ c === -1 && f !== -1 && (c = h);
1496
+ else if (a === 59 || a === 44) {
1497
+ if (f === -1)
1498
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1499
+ c === -1 && (c = h), k(t, s.slice(f, c), !0), a === 44 && (k(e, o, t), t = /* @__PURE__ */ Object.create(null), o = void 0), f = c = -1;
1500
+ } else if (a === 61 && f !== -1 && c === -1)
1501
+ l = s.slice(f, h), f = c = -1;
1502
+ else
1503
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1504
+ else if (i) {
1505
+ if (j[a] !== 1)
1506
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1507
+ f === -1 ? f = h : r || (r = !0), i = !1;
1508
+ } else if (n)
1509
+ if (j[a] === 1)
1510
+ f === -1 && (f = h);
1511
+ else if (a === 34 && f !== -1)
1512
+ n = !1, c = h;
1513
+ else if (a === 92)
1514
+ i = !0;
1515
+ else
1516
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1517
+ else if (a === 34 && s.charCodeAt(h - 1) === 61)
1518
+ n = !0;
1519
+ else if (c === -1 && j[a] === 1)
1520
+ f === -1 && (f = h);
1521
+ else if (f !== -1 && (a === 32 || a === 9))
1522
+ c === -1 && (c = h);
1523
+ else if (a === 59 || a === 44) {
1524
+ if (f === -1)
1525
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1526
+ c === -1 && (c = h);
1527
+ let v = s.slice(f, c);
1528
+ r && (v = v.replace(/\\/g, ""), r = !1), k(t, l, v), a === 44 && (k(e, o, t), t = /* @__PURE__ */ Object.create(null), o = void 0), l = void 0, f = c = -1;
1529
+ } else
1530
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1531
+ if (f === -1 || n || a === 32 || a === 9)
1532
+ throw new SyntaxError("Unexpected end of input");
1533
+ c === -1 && (c = h);
1534
+ const p = s.slice(f, c);
1535
+ return o === void 0 ? k(e, p, t) : (l === void 0 ? k(t, p, !0) : r ? k(t, l, p.replace(/\\/g, "")) : k(t, l, p), k(e, o, t)), e;
1536
+ }
1537
+ function rs(s) {
1538
+ return Object.keys(s).map((e) => {
1539
+ let t = s[e];
1540
+ return Array.isArray(t) || (t = [t]), t.map((r) => [e].concat(
1541
+ Object.keys(r).map((i) => {
1542
+ let n = r[i];
1543
+ return Array.isArray(n) || (n = [n]), n.map((o) => o === !0 ? i : `${i}=${o}`).join("; ");
1544
+ })
1545
+ ).join("; ")).join(", ");
1546
+ }).join(", ");
1547
+ }
1548
+ var nt = { format: rs, parse: ss };
1549
+ const is = S, ns = S, os = S, ot = S, as = S, { randomBytes: ls, createHash: fs } = S, { URL: me } = S, T = oe, hs = rt, cs = it, {
1550
+ BINARY_TYPES: ze,
1551
+ EMPTY_BUFFER: Q,
1552
+ GUID: us,
1553
+ kForOnEventAttribute: ge,
1554
+ kListener: ds,
1555
+ kStatusCode: _s,
1556
+ kWebSocket: y,
1557
+ NOOP: at
1558
+ } = U, {
1559
+ EventTarget: { addEventListener: ps, removeEventListener: ms }
1560
+ } = ts, { format: gs, parse: ys } = nt, { toBuffer: vs } = ne, Ss = 30 * 1e3, lt = Symbol("kAborted"), ye = [8, 13], O = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"], Es = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
1561
+ let m = class d extends is {
1562
+ /**
1563
+ * Create a new `WebSocket`.
1564
+ *
1565
+ * @param {(String|URL)} address The URL to which to connect
1566
+ * @param {(String|String[])} [protocols] The subprotocols
1567
+ * @param {Object} [options] Connection options
1568
+ */
1569
+ constructor(e, t, r) {
1570
+ super(), this._binaryType = ze[0], this._closeCode = 1006, this._closeFrameReceived = !1, this._closeFrameSent = !1, this._closeMessage = Q, this._closeTimer = null, this._extensions = {}, this._paused = !1, this._protocol = "", this._readyState = d.CONNECTING, this._receiver = null, this._sender = null, this._socket = null, e !== null ? (this._bufferedAmount = 0, this._isServer = !1, this._redirects = 0, t === void 0 ? t = [] : Array.isArray(t) || (typeof t == "object" && t !== null ? (r = t, t = []) : t = [t]), ht(this, e, t, r)) : this._isServer = !0;
1571
+ }
1572
+ /**
1573
+ * This deviates from the WHATWG interface since ws doesn't support the
1574
+ * required default "blob" type (instead we define a custom "nodebuffer"
1575
+ * type).
1576
+ *
1577
+ * @type {String}
1578
+ */
1579
+ get binaryType() {
1580
+ return this._binaryType;
1581
+ }
1582
+ set binaryType(e) {
1583
+ ze.includes(e) && (this._binaryType = e, this._receiver && (this._receiver._binaryType = e));
1584
+ }
1585
+ /**
1586
+ * @type {Number}
1587
+ */
1588
+ get bufferedAmount() {
1589
+ return this._socket ? this._socket._writableState.length + this._sender._bufferedBytes : this._bufferedAmount;
1590
+ }
1591
+ /**
1592
+ * @type {String}
1593
+ */
1594
+ get extensions() {
1595
+ return Object.keys(this._extensions).join();
1596
+ }
1597
+ /**
1598
+ * @type {Boolean}
1599
+ */
1600
+ get isPaused() {
1601
+ return this._paused;
1602
+ }
1603
+ /**
1604
+ * @type {Function}
1605
+ */
1606
+ /* istanbul ignore next */
1607
+ get onclose() {
1608
+ return null;
1609
+ }
1610
+ /**
1611
+ * @type {Function}
1612
+ */
1613
+ /* istanbul ignore next */
1614
+ get onerror() {
1615
+ return null;
1616
+ }
1617
+ /**
1618
+ * @type {Function}
1619
+ */
1620
+ /* istanbul ignore next */
1621
+ get onopen() {
1622
+ return null;
1623
+ }
1624
+ /**
1625
+ * @type {Function}
1626
+ */
1627
+ /* istanbul ignore next */
1628
+ get onmessage() {
1629
+ return null;
1630
+ }
1631
+ /**
1632
+ * @type {String}
1633
+ */
1634
+ get protocol() {
1635
+ return this._protocol;
1636
+ }
1637
+ /**
1638
+ * @type {Number}
1639
+ */
1640
+ get readyState() {
1641
+ return this._readyState;
1642
+ }
1643
+ /**
1644
+ * @type {String}
1645
+ */
1646
+ get url() {
1647
+ return this._url;
1648
+ }
1649
+ /**
1650
+ * Set up the socket and the internal resources.
1651
+ *
1652
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
1653
+ * server and client
1654
+ * @param {Buffer} head The first packet of the upgraded stream
1655
+ * @param {Object} options Options object
1656
+ * @param {Function} [options.generateMask] The function used to generate the
1657
+ * masking key
1658
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
1659
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
1660
+ * not to skip UTF-8 validation for text and close messages
1661
+ * @private
1662
+ */
1663
+ setSocket(e, t, r) {
1664
+ const i = new hs({
1665
+ binaryType: this.binaryType,
1666
+ extensions: this._extensions,
1667
+ isServer: this._isServer,
1668
+ maxPayload: r.maxPayload,
1669
+ skipUTF8Validation: r.skipUTF8Validation
1670
+ });
1671
+ this._sender = new cs(e, this._extensions, r.generateMask), this._receiver = i, this._socket = e, i[y] = this, e[y] = this, i.on("conclude", ks), i.on("drain", ws), i.on("error", Os), i.on("message", Cs), i.on("ping", Ts), i.on("pong", Ls), e.setTimeout(0), e.setNoDelay(), t.length > 0 && e.unshift(t), e.on("close", ut), e.on("data", fe), e.on("end", dt), e.on("error", _t), this._readyState = d.OPEN, this.emit("open");
1672
+ }
1673
+ /**
1674
+ * Emit the `'close'` event.
1675
+ *
1676
+ * @private
1677
+ */
1678
+ emitClose() {
1679
+ if (!this._socket) {
1680
+ this._readyState = d.CLOSED, this.emit("close", this._closeCode, this._closeMessage);
1681
+ return;
1682
+ }
1683
+ this._extensions[T.extensionName] && this._extensions[T.extensionName].cleanup(), this._receiver.removeAllListeners(), this._readyState = d.CLOSED, this.emit("close", this._closeCode, this._closeMessage);
1684
+ }
1685
+ /**
1686
+ * Start a closing handshake.
1687
+ *
1688
+ * +----------+ +-----------+ +----------+
1689
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
1690
+ * | +----------+ +-----------+ +----------+ |
1691
+ * +----------+ +-----------+ |
1692
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
1693
+ * +----------+ +-----------+ |
1694
+ * | | | +---+ |
1695
+ * +------------------------+-->|fin| - - - -
1696
+ * | +---+ | +---+
1697
+ * - - - - -|fin|<---------------------+
1698
+ * +---+
1699
+ *
1700
+ * @param {Number} [code] Status code explaining why the connection is closing
1701
+ * @param {(String|Buffer)} [data] The reason why the connection is
1702
+ * closing
1703
+ * @public
1704
+ */
1705
+ close(e, t) {
1706
+ if (this.readyState !== d.CLOSED) {
1707
+ if (this.readyState === d.CONNECTING) {
1708
+ const r = "WebSocket was closed before the connection was established";
1709
+ b(this, this._req, r);
1710
+ return;
1711
+ }
1712
+ if (this.readyState === d.CLOSING) {
1713
+ this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) && this._socket.end();
1714
+ return;
1715
+ }
1716
+ this._readyState = d.CLOSING, this._sender.close(e, t, !this._isServer, (r) => {
1717
+ r || (this._closeFrameSent = !0, (this._closeFrameReceived || this._receiver._writableState.errorEmitted) && this._socket.end());
1718
+ }), this._closeTimer = setTimeout(
1719
+ this._socket.destroy.bind(this._socket),
1720
+ Ss
1721
+ );
1722
+ }
1723
+ }
1724
+ /**
1725
+ * Pause the socket.
1726
+ *
1727
+ * @public
1728
+ */
1729
+ pause() {
1730
+ this.readyState === d.CONNECTING || this.readyState === d.CLOSED || (this._paused = !0, this._socket.pause());
1731
+ }
1732
+ /**
1733
+ * Send a ping.
1734
+ *
1735
+ * @param {*} [data] The data to send
1736
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
1737
+ * @param {Function} [cb] Callback which is executed when the ping is sent
1738
+ * @public
1739
+ */
1740
+ ping(e, t, r) {
1741
+ if (this.readyState === d.CONNECTING)
1742
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1743
+ if (typeof e == "function" ? (r = e, e = t = void 0) : typeof t == "function" && (r = t, t = void 0), typeof e == "number" && (e = e.toString()), this.readyState !== d.OPEN) {
1744
+ ve(this, e, r);
1745
+ return;
1746
+ }
1747
+ t === void 0 && (t = !this._isServer), this._sender.ping(e || Q, t, r);
1748
+ }
1749
+ /**
1750
+ * Send a pong.
1751
+ *
1752
+ * @param {*} [data] The data to send
1753
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
1754
+ * @param {Function} [cb] Callback which is executed when the pong is sent
1755
+ * @public
1756
+ */
1757
+ pong(e, t, r) {
1758
+ if (this.readyState === d.CONNECTING)
1759
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1760
+ if (typeof e == "function" ? (r = e, e = t = void 0) : typeof t == "function" && (r = t, t = void 0), typeof e == "number" && (e = e.toString()), this.readyState !== d.OPEN) {
1761
+ ve(this, e, r);
1762
+ return;
1763
+ }
1764
+ t === void 0 && (t = !this._isServer), this._sender.pong(e || Q, t, r);
1765
+ }
1766
+ /**
1767
+ * Resume the socket.
1768
+ *
1769
+ * @public
1770
+ */
1771
+ resume() {
1772
+ this.readyState === d.CONNECTING || this.readyState === d.CLOSED || (this._paused = !1, this._receiver._writableState.needDrain || this._socket.resume());
1773
+ }
1774
+ /**
1775
+ * Send a data message.
1776
+ *
1777
+ * @param {*} data The message to send
1778
+ * @param {Object} [options] Options object
1779
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
1780
+ * text
1781
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
1782
+ * `data`
1783
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
1784
+ * last one
1785
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
1786
+ * @param {Function} [cb] Callback which is executed when data is written out
1787
+ * @public
1788
+ */
1789
+ send(e, t, r) {
1790
+ if (this.readyState === d.CONNECTING)
1791
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1792
+ if (typeof t == "function" && (r = t, t = {}), typeof e == "number" && (e = e.toString()), this.readyState !== d.OPEN) {
1793
+ ve(this, e, r);
1794
+ return;
1795
+ }
1796
+ const i = {
1797
+ binary: typeof e != "string",
1798
+ mask: !this._isServer,
1799
+ compress: !0,
1800
+ fin: !0,
1801
+ ...t
1802
+ };
1803
+ this._extensions[T.extensionName] || (i.compress = !1), this._sender.send(e || Q, i, r);
1804
+ }
1805
+ /**
1806
+ * Forcibly close the connection.
1807
+ *
1808
+ * @public
1809
+ */
1810
+ terminate() {
1811
+ if (this.readyState !== d.CLOSED) {
1812
+ if (this.readyState === d.CONNECTING) {
1813
+ const e = "WebSocket was closed before the connection was established";
1814
+ b(this, this._req, e);
1815
+ return;
1816
+ }
1817
+ this._socket && (this._readyState = d.CLOSING, this._socket.destroy());
1818
+ }
1819
+ }
1820
+ };
1821
+ Object.defineProperty(m, "CONNECTING", {
1822
+ enumerable: !0,
1823
+ value: O.indexOf("CONNECTING")
1824
+ });
1825
+ Object.defineProperty(m.prototype, "CONNECTING", {
1826
+ enumerable: !0,
1827
+ value: O.indexOf("CONNECTING")
1828
+ });
1829
+ Object.defineProperty(m, "OPEN", {
1830
+ enumerable: !0,
1831
+ value: O.indexOf("OPEN")
1832
+ });
1833
+ Object.defineProperty(m.prototype, "OPEN", {
1834
+ enumerable: !0,
1835
+ value: O.indexOf("OPEN")
1836
+ });
1837
+ Object.defineProperty(m, "CLOSING", {
1838
+ enumerable: !0,
1839
+ value: O.indexOf("CLOSING")
1840
+ });
1841
+ Object.defineProperty(m.prototype, "CLOSING", {
1842
+ enumerable: !0,
1843
+ value: O.indexOf("CLOSING")
1844
+ });
1845
+ Object.defineProperty(m, "CLOSED", {
1846
+ enumerable: !0,
1847
+ value: O.indexOf("CLOSED")
1848
+ });
1849
+ Object.defineProperty(m.prototype, "CLOSED", {
1850
+ enumerable: !0,
1851
+ value: O.indexOf("CLOSED")
1852
+ });
1853
+ [
1854
+ "binaryType",
1855
+ "bufferedAmount",
1856
+ "extensions",
1857
+ "isPaused",
1858
+ "protocol",
1859
+ "readyState",
1860
+ "url"
1861
+ ].forEach((s) => {
1862
+ Object.defineProperty(m.prototype, s, { enumerable: !0 });
1863
+ });
1864
+ ["open", "error", "close", "message"].forEach((s) => {
1865
+ Object.defineProperty(m.prototype, `on${s}`, {
1866
+ enumerable: !0,
1867
+ get() {
1868
+ for (const e of this.listeners(s))
1869
+ if (e[ge])
1870
+ return e[ds];
1871
+ return null;
1872
+ },
1873
+ set(e) {
1874
+ for (const t of this.listeners(s))
1875
+ if (t[ge]) {
1876
+ this.removeListener(s, t);
1877
+ break;
1878
+ }
1879
+ typeof e == "function" && this.addEventListener(s, e, {
1880
+ [ge]: !0
1881
+ });
1882
+ }
1883
+ });
1884
+ });
1885
+ m.prototype.addEventListener = ps;
1886
+ m.prototype.removeEventListener = ms;
1887
+ var ft = m;
1888
+ function ht(s, e, t, r) {
1889
+ const i = {
1890
+ protocolVersion: ye[1],
1891
+ maxPayload: 104857600,
1892
+ skipUTF8Validation: !1,
1893
+ perMessageDeflate: !0,
1894
+ followRedirects: !1,
1895
+ maxRedirects: 10,
1896
+ ...r,
1897
+ createConnection: void 0,
1898
+ socketPath: void 0,
1899
+ hostname: void 0,
1900
+ protocol: void 0,
1901
+ timeout: void 0,
1902
+ method: "GET",
1903
+ host: void 0,
1904
+ path: void 0,
1905
+ port: void 0
1906
+ };
1907
+ if (!ye.includes(i.protocolVersion))
1908
+ throw new RangeError(
1909
+ `Unsupported protocol version: ${i.protocolVersion} (supported versions: ${ye.join(", ")})`
1910
+ );
1911
+ let n;
1912
+ if (e instanceof me)
1913
+ n = e, s._url = e.href;
1914
+ else {
1915
+ try {
1916
+ n = new me(e);
1917
+ } catch {
1918
+ throw new SyntaxError(`Invalid URL: ${e}`);
1919
+ }
1920
+ s._url = e;
1921
+ }
1922
+ const o = n.protocol === "wss:", l = n.protocol === "ws+unix:";
1923
+ let f;
1924
+ if (n.protocol !== "ws:" && !o && !l ? f = `The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"` : l && !n.pathname ? f = "The URL's pathname is empty" : n.hash && (f = "The URL contains a fragment identifier"), f) {
1925
+ const u = new SyntaxError(f);
1926
+ if (s._redirects === 0)
1927
+ throw u;
1928
+ ee(s, u);
1929
+ return;
1930
+ }
1931
+ const a = o ? 443 : 80, c = ls(16).toString("base64"), h = o ? ns.request : os.request, p = /* @__PURE__ */ new Set();
1932
+ let v;
1933
+ if (i.createConnection = o ? xs : bs, i.defaultPort = i.defaultPort || a, i.port = n.port || a, i.host = n.hostname.startsWith("[") ? n.hostname.slice(1, -1) : n.hostname, i.headers = {
1934
+ ...i.headers,
1935
+ "Sec-WebSocket-Version": i.protocolVersion,
1936
+ "Sec-WebSocket-Key": c,
1937
+ Connection: "Upgrade",
1938
+ Upgrade: "websocket"
1939
+ }, i.path = n.pathname + n.search, i.timeout = i.handshakeTimeout, i.perMessageDeflate && (v = new T(
1940
+ i.perMessageDeflate !== !0 ? i.perMessageDeflate : {},
1941
+ !1,
1942
+ i.maxPayload
1943
+ ), i.headers["Sec-WebSocket-Extensions"] = gs({
1944
+ [T.extensionName]: v.offer()
1945
+ })), t.length) {
1946
+ for (const u of t) {
1947
+ if (typeof u != "string" || !Es.test(u) || p.has(u))
1948
+ throw new SyntaxError(
1949
+ "An invalid or duplicated subprotocol was specified"
1950
+ );
1951
+ p.add(u);
1952
+ }
1953
+ i.headers["Sec-WebSocket-Protocol"] = t.join(",");
1954
+ }
1955
+ if (i.origin && (i.protocolVersion < 13 ? i.headers["Sec-WebSocket-Origin"] = i.origin : i.headers.Origin = i.origin), (n.username || n.password) && (i.auth = `${n.username}:${n.password}`), l) {
1956
+ const u = i.path.split(":");
1957
+ i.socketPath = u[0], i.path = u[1];
1958
+ }
1959
+ let _;
1960
+ if (i.followRedirects) {
1961
+ if (s._redirects === 0) {
1962
+ s._originalIpc = l, s._originalSecure = o, s._originalHostOrSocketPath = l ? i.socketPath : n.host;
1963
+ const u = r && r.headers;
1964
+ if (r = { ...r, headers: {} }, u)
1965
+ for (const [E, $] of Object.entries(u))
1966
+ r.headers[E.toLowerCase()] = $;
1967
+ } else if (s.listenerCount("redirect") === 0) {
1968
+ const u = l ? s._originalIpc ? i.socketPath === s._originalHostOrSocketPath : !1 : s._originalIpc ? !1 : n.host === s._originalHostOrSocketPath;
1969
+ (!u || s._originalSecure && !o) && (delete i.headers.authorization, delete i.headers.cookie, u || delete i.headers.host, i.auth = void 0);
1970
+ }
1971
+ i.auth && !r.headers.authorization && (r.headers.authorization = "Basic " + Buffer.from(i.auth).toString("base64")), _ = s._req = h(i), s._redirects && s.emit("redirect", s.url, _);
1972
+ } else
1973
+ _ = s._req = h(i);
1974
+ i.timeout && _.on("timeout", () => {
1975
+ b(s, _, "Opening handshake has timed out");
1976
+ }), _.on("error", (u) => {
1977
+ _ === null || _[lt] || (_ = s._req = null, ee(s, u));
1978
+ }), _.on("response", (u) => {
1979
+ const E = u.headers.location, $ = u.statusCode;
1980
+ if (E && i.followRedirects && $ >= 300 && $ < 400) {
1981
+ if (++s._redirects > i.maxRedirects) {
1982
+ b(s, _, "Maximum redirects exceeded");
1983
+ return;
1984
+ }
1985
+ _.abort();
1986
+ let q;
1987
+ try {
1988
+ q = new me(E, e);
1989
+ } catch {
1990
+ const L = new SyntaxError(`Invalid URL: ${E}`);
1991
+ ee(s, L);
1992
+ return;
1993
+ }
1994
+ ht(s, q, t, r);
1995
+ } else
1996
+ s.emit("unexpected-response", _, u) || b(
1997
+ s,
1998
+ _,
1999
+ `Unexpected server response: ${u.statusCode}`
2000
+ );
2001
+ }), _.on("upgrade", (u, E, $) => {
2002
+ if (s.emit("upgrade", u), s.readyState !== m.CONNECTING)
2003
+ return;
2004
+ if (_ = s._req = null, u.headers.upgrade.toLowerCase() !== "websocket") {
2005
+ b(s, E, "Invalid Upgrade header");
2006
+ return;
2007
+ }
2008
+ const q = fs("sha1").update(c + us).digest("base64");
2009
+ if (u.headers["sec-websocket-accept"] !== q) {
2010
+ b(s, E, "Invalid Sec-WebSocket-Accept header");
2011
+ return;
2012
+ }
2013
+ const D = u.headers["sec-websocket-protocol"];
2014
+ let L;
2015
+ if (D !== void 0 ? p.size ? p.has(D) || (L = "Server sent an invalid subprotocol") : L = "Server sent a subprotocol but none was requested" : p.size && (L = "Server sent no subprotocol"), L) {
2016
+ b(s, E, L);
2017
+ return;
2018
+ }
2019
+ D && (s._protocol = D);
2020
+ const ke = u.headers["sec-websocket-extensions"];
2021
+ if (ke !== void 0) {
2022
+ if (!v) {
2023
+ b(s, E, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2024
+ return;
2025
+ }
2026
+ let he;
2027
+ try {
2028
+ he = ys(ke);
2029
+ } catch {
2030
+ b(s, E, "Invalid Sec-WebSocket-Extensions header");
2031
+ return;
2032
+ }
2033
+ const we = Object.keys(he);
2034
+ if (we.length !== 1 || we[0] !== T.extensionName) {
2035
+ b(s, E, "Server indicated an extension that was not requested");
2036
+ return;
2037
+ }
2038
+ try {
2039
+ v.accept(he[T.extensionName]);
2040
+ } catch {
2041
+ b(s, E, "Invalid Sec-WebSocket-Extensions header");
2042
+ return;
2043
+ }
2044
+ s._extensions[T.extensionName] = v;
2045
+ }
2046
+ s.setSocket(E, $, {
2047
+ generateMask: i.generateMask,
2048
+ maxPayload: i.maxPayload,
2049
+ skipUTF8Validation: i.skipUTF8Validation
2050
+ });
2051
+ }), i.finishRequest ? i.finishRequest(_, s) : _.end();
2052
+ }
2053
+ function ee(s, e) {
2054
+ s._readyState = m.CLOSING, s.emit("error", e), s.emitClose();
2055
+ }
2056
+ function bs(s) {
2057
+ return s.path = s.socketPath, ot.connect(s);
2058
+ }
2059
+ function xs(s) {
2060
+ return s.path = void 0, !s.servername && s.servername !== "" && (s.servername = ot.isIP(s.host) ? "" : s.host), as.connect(s);
2061
+ }
2062
+ function b(s, e, t) {
2063
+ s._readyState = m.CLOSING;
2064
+ const r = new Error(t);
2065
+ Error.captureStackTrace(r, b), e.setHeader ? (e[lt] = !0, e.abort(), e.socket && !e.socket.destroyed && e.socket.destroy(), process.nextTick(ee, s, r)) : (e.destroy(r), e.once("error", s.emit.bind(s, "error")), e.once("close", s.emitClose.bind(s)));
2066
+ }
2067
+ function ve(s, e, t) {
2068
+ if (e) {
2069
+ const r = vs(e).length;
2070
+ s._socket ? s._sender._bufferedBytes += r : s._bufferedAmount += r;
2071
+ }
2072
+ if (t) {
2073
+ const r = new Error(
2074
+ `WebSocket is not open: readyState ${s.readyState} (${O[s.readyState]})`
2075
+ );
2076
+ process.nextTick(t, r);
2077
+ }
2078
+ }
2079
+ function ks(s, e) {
2080
+ const t = this[y];
2081
+ t._closeFrameReceived = !0, t._closeMessage = e, t._closeCode = s, t._socket[y] !== void 0 && (t._socket.removeListener("data", fe), process.nextTick(ct, t._socket), s === 1005 ? t.close() : t.close(s, e));
2082
+ }
2083
+ function ws() {
2084
+ const s = this[y];
2085
+ s.isPaused || s._socket.resume();
2086
+ }
2087
+ function Os(s) {
2088
+ const e = this[y];
2089
+ e._socket[y] !== void 0 && (e._socket.removeListener("data", fe), process.nextTick(ct, e._socket), e.close(s[_s])), e.emit("error", s);
2090
+ }
2091
+ function Ye() {
2092
+ this[y].emitClose();
2093
+ }
2094
+ function Cs(s, e) {
2095
+ this[y].emit("message", s, e);
2096
+ }
2097
+ function Ts(s) {
2098
+ const e = this[y];
2099
+ e.pong(s, !e._isServer, at), e.emit("ping", s);
2100
+ }
2101
+ function Ls(s) {
2102
+ this[y].emit("pong", s);
2103
+ }
2104
+ function ct(s) {
2105
+ s.resume();
2106
+ }
2107
+ function ut() {
2108
+ const s = this[y];
2109
+ this.removeListener("close", ut), this.removeListener("data", fe), this.removeListener("end", dt), s._readyState = m.CLOSING;
2110
+ let e;
2111
+ !this._readableState.endEmitted && !s._closeFrameReceived && !s._receiver._writableState.errorEmitted && (e = s._socket.read()) !== null && s._receiver.write(e), s._receiver.end(), this[y] = void 0, clearTimeout(s._closeTimer), s._receiver._writableState.finished || s._receiver._writableState.errorEmitted ? s.emitClose() : (s._receiver.on("error", Ye), s._receiver.on("finish", Ye));
2112
+ }
2113
+ function fe(s) {
2114
+ this[y]._receiver.write(s) || this.pause();
2115
+ }
2116
+ function dt() {
2117
+ const s = this[y];
2118
+ s._readyState = m.CLOSING, s._receiver.end(), this.end();
2119
+ }
2120
+ function _t() {
2121
+ const s = this[y];
2122
+ this.removeListener("error", _t), this.on("error", at), s && (s._readyState = m.CLOSING, this.destroy());
2123
+ }
2124
+ const Xs = /* @__PURE__ */ z(ft), { tokenChars: Ns } = ae;
2125
+ function Ps(s) {
2126
+ const e = /* @__PURE__ */ new Set();
2127
+ let t = -1, r = -1, i = 0;
2128
+ for (i; i < s.length; i++) {
2129
+ const o = s.charCodeAt(i);
2130
+ if (r === -1 && Ns[o] === 1)
2131
+ t === -1 && (t = i);
2132
+ else if (i !== 0 && (o === 32 || o === 9))
2133
+ r === -1 && t !== -1 && (r = i);
2134
+ else if (o === 44) {
2135
+ if (t === -1)
2136
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2137
+ r === -1 && (r = i);
2138
+ const l = s.slice(t, r);
2139
+ if (e.has(l))
2140
+ throw new SyntaxError(`The "${l}" subprotocol is duplicated`);
2141
+ e.add(l), t = r = -1;
2142
+ } else
2143
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2144
+ }
2145
+ if (t === -1 || r !== -1)
2146
+ throw new SyntaxError("Unexpected end of input");
2147
+ const n = s.slice(t, i);
2148
+ if (e.has(n))
2149
+ throw new SyntaxError(`The "${n}" subprotocol is duplicated`);
2150
+ return e.add(n), e;
2151
+ }
2152
+ var Rs = { parse: Ps };
2153
+ const Us = S, ie = S, { createHash: Bs } = S, qe = nt, N = oe, $s = Rs, Ms = ft, { GUID: Is, kWebSocket: Ds } = U, Ws = /^[+/0-9A-Za-z]{22}==$/, Ke = 0, Xe = 1, pt = 2;
2154
+ class As extends Us {
2155
+ /**
2156
+ * Create a `WebSocketServer` instance.
2157
+ *
2158
+ * @param {Object} options Configuration options
2159
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
2160
+ * pending connections
2161
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
2162
+ * track clients
2163
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
2164
+ * @param {String} [options.host] The hostname where to bind the server
2165
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2166
+ * size
2167
+ * @param {Boolean} [options.noServer=false] Enable no server mode
2168
+ * @param {String} [options.path] Accept only connections matching this path
2169
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
2170
+ * permessage-deflate
2171
+ * @param {Number} [options.port] The port where to bind the server
2172
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
2173
+ * server to use
2174
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2175
+ * not to skip UTF-8 validation for text and close messages
2176
+ * @param {Function} [options.verifyClient] A hook to reject connections
2177
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
2178
+ * class to use. It must be the `WebSocket` class or class that extends it
2179
+ * @param {Function} [callback] A listener for the `listening` event
2180
+ */
2181
+ constructor(e, t) {
2182
+ if (super(), e = {
2183
+ maxPayload: 100 * 1024 * 1024,
2184
+ skipUTF8Validation: !1,
2185
+ perMessageDeflate: !1,
2186
+ handleProtocols: null,
2187
+ clientTracking: !0,
2188
+ verifyClient: null,
2189
+ noServer: !1,
2190
+ backlog: null,
2191
+ // use default (511 as implemented in net.js)
2192
+ server: null,
2193
+ host: null,
2194
+ path: null,
2195
+ port: null,
2196
+ WebSocket: Ms,
2197
+ ...e
2198
+ }, e.port == null && !e.server && !e.noServer || e.port != null && (e.server || e.noServer) || e.server && e.noServer)
2199
+ throw new TypeError(
2200
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
2201
+ );
2202
+ if (e.port != null ? (this._server = ie.createServer((r, i) => {
2203
+ const n = ie.STATUS_CODES[426];
2204
+ i.writeHead(426, {
2205
+ "Content-Length": n.length,
2206
+ "Content-Type": "text/plain"
2207
+ }), i.end(n);
2208
+ }), this._server.listen(
2209
+ e.port,
2210
+ e.host,
2211
+ e.backlog,
2212
+ t
2213
+ )) : e.server && (this._server = e.server), this._server) {
2214
+ const r = this.emit.bind(this, "connection");
2215
+ this._removeListeners = js(this._server, {
2216
+ listening: this.emit.bind(this, "listening"),
2217
+ error: this.emit.bind(this, "error"),
2218
+ upgrade: (i, n, o) => {
2219
+ this.handleUpgrade(i, n, o, r);
2220
+ }
2221
+ });
2222
+ }
2223
+ e.perMessageDeflate === !0 && (e.perMessageDeflate = {}), e.clientTracking && (this.clients = /* @__PURE__ */ new Set(), this._shouldEmitClose = !1), this.options = e, this._state = Ke;
2224
+ }
2225
+ /**
2226
+ * Returns the bound address, the address family name, and port of the server
2227
+ * as reported by the operating system if listening on an IP socket.
2228
+ * If the server is listening on a pipe or UNIX domain socket, the name is
2229
+ * returned as a string.
2230
+ *
2231
+ * @return {(Object|String|null)} The address of the server
2232
+ * @public
2233
+ */
2234
+ address() {
2235
+ if (this.options.noServer)
2236
+ throw new Error('The server is operating in "noServer" mode');
2237
+ return this._server ? this._server.address() : null;
2238
+ }
2239
+ /**
2240
+ * Stop the server from accepting new connections and emit the `'close'` event
2241
+ * when all existing connections are closed.
2242
+ *
2243
+ * @param {Function} [cb] A one-time listener for the `'close'` event
2244
+ * @public
2245
+ */
2246
+ close(e) {
2247
+ if (this._state === pt) {
2248
+ e && this.once("close", () => {
2249
+ e(new Error("The server is not running"));
2250
+ }), process.nextTick(G, this);
2251
+ return;
2252
+ }
2253
+ if (e && this.once("close", e), this._state !== Xe)
2254
+ if (this._state = Xe, this.options.noServer || this.options.server)
2255
+ this._server && (this._removeListeners(), this._removeListeners = this._server = null), this.clients ? this.clients.size ? this._shouldEmitClose = !0 : process.nextTick(G, this) : process.nextTick(G, this);
2256
+ else {
2257
+ const t = this._server;
2258
+ this._removeListeners(), this._removeListeners = this._server = null, t.close(() => {
2259
+ G(this);
2260
+ });
2261
+ }
2262
+ }
2263
+ /**
2264
+ * See if a given request should be handled by this server instance.
2265
+ *
2266
+ * @param {http.IncomingMessage} req Request object to inspect
2267
+ * @return {Boolean} `true` if the request is valid, else `false`
2268
+ * @public
2269
+ */
2270
+ shouldHandle(e) {
2271
+ if (this.options.path) {
2272
+ const t = e.url.indexOf("?");
2273
+ if ((t !== -1 ? e.url.slice(0, t) : e.url) !== this.options.path)
2274
+ return !1;
2275
+ }
2276
+ return !0;
2277
+ }
2278
+ /**
2279
+ * Handle a HTTP Upgrade request.
2280
+ *
2281
+ * @param {http.IncomingMessage} req The request object
2282
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
2283
+ * server and client
2284
+ * @param {Buffer} head The first packet of the upgraded stream
2285
+ * @param {Function} cb Callback
2286
+ * @public
2287
+ */
2288
+ handleUpgrade(e, t, r, i) {
2289
+ t.on("error", Ze);
2290
+ const n = e.headers["sec-websocket-key"], o = +e.headers["sec-websocket-version"];
2291
+ if (e.method !== "GET") {
2292
+ R(this, e, t, 405, "Invalid HTTP method");
2293
+ return;
2294
+ }
2295
+ if (e.headers.upgrade.toLowerCase() !== "websocket") {
2296
+ R(this, e, t, 400, "Invalid Upgrade header");
2297
+ return;
2298
+ }
2299
+ if (!n || !Ws.test(n)) {
2300
+ R(this, e, t, 400, "Missing or invalid Sec-WebSocket-Key header");
2301
+ return;
2302
+ }
2303
+ if (o !== 8 && o !== 13) {
2304
+ R(this, e, t, 400, "Missing or invalid Sec-WebSocket-Version header");
2305
+ return;
2306
+ }
2307
+ if (!this.shouldHandle(e)) {
2308
+ H(t, 400);
2309
+ return;
2310
+ }
2311
+ const l = e.headers["sec-websocket-protocol"];
2312
+ let f = /* @__PURE__ */ new Set();
2313
+ if (l !== void 0)
2314
+ try {
2315
+ f = $s.parse(l);
2316
+ } catch {
2317
+ R(this, e, t, 400, "Invalid Sec-WebSocket-Protocol header");
2318
+ return;
2319
+ }
2320
+ const a = e.headers["sec-websocket-extensions"], c = {};
2321
+ if (this.options.perMessageDeflate && a !== void 0) {
2322
+ const h = new N(
2323
+ this.options.perMessageDeflate,
2324
+ !0,
2325
+ this.options.maxPayload
2326
+ );
2327
+ try {
2328
+ const p = qe.parse(a);
2329
+ p[N.extensionName] && (h.accept(p[N.extensionName]), c[N.extensionName] = h);
2330
+ } catch {
2331
+ R(this, e, t, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
2332
+ return;
2333
+ }
2334
+ }
2335
+ if (this.options.verifyClient) {
2336
+ const h = {
2337
+ origin: e.headers[`${o === 8 ? "sec-websocket-origin" : "origin"}`],
2338
+ secure: !!(e.socket.authorized || e.socket.encrypted),
2339
+ req: e
2340
+ };
2341
+ if (this.options.verifyClient.length === 2) {
2342
+ this.options.verifyClient(h, (p, v, _, u) => {
2343
+ if (!p)
2344
+ return H(t, v || 401, _, u);
2345
+ this.completeUpgrade(
2346
+ c,
2347
+ n,
2348
+ f,
2349
+ e,
2350
+ t,
2351
+ r,
2352
+ i
2353
+ );
2354
+ });
2355
+ return;
2356
+ }
2357
+ if (!this.options.verifyClient(h))
2358
+ return H(t, 401);
2359
+ }
2360
+ this.completeUpgrade(c, n, f, e, t, r, i);
2361
+ }
2362
+ /**
2363
+ * Upgrade the connection to WebSocket.
2364
+ *
2365
+ * @param {Object} extensions The accepted extensions
2366
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
2367
+ * @param {Set} protocols The subprotocols
2368
+ * @param {http.IncomingMessage} req The request object
2369
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
2370
+ * server and client
2371
+ * @param {Buffer} head The first packet of the upgraded stream
2372
+ * @param {Function} cb Callback
2373
+ * @throws {Error} If called more than once with the same socket
2374
+ * @private
2375
+ */
2376
+ completeUpgrade(e, t, r, i, n, o, l) {
2377
+ if (!n.readable || !n.writable)
2378
+ return n.destroy();
2379
+ if (n[Ds])
2380
+ throw new Error(
2381
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
2382
+ );
2383
+ if (this._state > Ke)
2384
+ return H(n, 503);
2385
+ const a = [
2386
+ "HTTP/1.1 101 Switching Protocols",
2387
+ "Upgrade: websocket",
2388
+ "Connection: Upgrade",
2389
+ `Sec-WebSocket-Accept: ${Bs("sha1").update(t + Is).digest("base64")}`
2390
+ ], c = new this.options.WebSocket(null);
2391
+ if (r.size) {
2392
+ const h = this.options.handleProtocols ? this.options.handleProtocols(r, i) : r.values().next().value;
2393
+ h && (a.push(`Sec-WebSocket-Protocol: ${h}`), c._protocol = h);
2394
+ }
2395
+ if (e[N.extensionName]) {
2396
+ const h = e[N.extensionName].params, p = qe.format({
2397
+ [N.extensionName]: [h]
2398
+ });
2399
+ a.push(`Sec-WebSocket-Extensions: ${p}`), c._extensions = e;
2400
+ }
2401
+ this.emit("headers", a, i), n.write(a.concat(`\r
2402
+ `).join(`\r
2403
+ `)), n.removeListener("error", Ze), c.setSocket(n, o, {
2404
+ maxPayload: this.options.maxPayload,
2405
+ skipUTF8Validation: this.options.skipUTF8Validation
2406
+ }), this.clients && (this.clients.add(c), c.on("close", () => {
2407
+ this.clients.delete(c), this._shouldEmitClose && !this.clients.size && process.nextTick(G, this);
2408
+ })), l(c, i);
2409
+ }
2410
+ }
2411
+ var Fs = As;
2412
+ function js(s, e) {
2413
+ for (const t of Object.keys(e))
2414
+ s.on(t, e[t]);
2415
+ return function() {
2416
+ for (const r of Object.keys(e))
2417
+ s.removeListener(r, e[r]);
2418
+ };
2419
+ }
2420
+ function G(s) {
2421
+ s._state = pt, s.emit("close");
2422
+ }
2423
+ function Ze() {
2424
+ this.destroy();
2425
+ }
2426
+ function H(s, e, t, r) {
2427
+ t = t || ie.STATUS_CODES[e], r = {
2428
+ Connection: "close",
2429
+ "Content-Type": "text/html",
2430
+ "Content-Length": Buffer.byteLength(t),
2431
+ ...r
2432
+ }, s.once("finish", s.destroy), s.end(
2433
+ `HTTP/1.1 ${e} ${ie.STATUS_CODES[e]}\r
2434
+ ` + Object.keys(r).map((i) => `${i}: ${r[i]}`).join(`\r
2435
+ `) + `\r
2436
+ \r
2437
+ ` + t
2438
+ );
2439
+ }
2440
+ function R(s, e, t, r, i) {
2441
+ if (s.listenerCount("wsClientError")) {
2442
+ const n = new Error(i);
2443
+ Error.captureStackTrace(n, R), s.emit("wsClientError", n, t, e);
2444
+ } else
2445
+ H(t, r, i);
2446
+ }
2447
+ const Zs = /* @__PURE__ */ z(Fs);
2448
+ export {
2449
+ qs as Receiver,
2450
+ Ks as Sender,
2451
+ Xs as WebSocket,
2452
+ Zs as WebSocketServer,
2453
+ Vs as createWebSocketStream,
2454
+ Xs as default
2455
+ };
src/backend/gradio_coolimage/templates/example/index.js ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { setContext: ee, getContext: v } = window.__gradio__svelte__internal, y = "WORKER_PROXY_CONTEXT_KEY";
2
+ function k() {
3
+ return v(y);
4
+ }
5
+ async function f(s) {
6
+ if (s == null)
7
+ return s;
8
+ const e = new URL(s);
9
+ if (e.host !== window.location.host && e.host !== "localhost:7860" && e.host !== "127.0.0.1:7860" || e.protocol !== "http:" && e.protocol !== "https:")
10
+ return s;
11
+ const r = k();
12
+ if (r == null)
13
+ return s;
14
+ const n = e.pathname;
15
+ return r.httpRequest({
16
+ method: "GET",
17
+ path: n,
18
+ headers: {},
19
+ query_string: ""
20
+ }).then((t) => {
21
+ if (t.status !== 200)
22
+ throw new Error(`Failed to get file ${n} from the Wasm worker.`);
23
+ const l = new Blob([t.body], {
24
+ type: t.headers["Content-Type"]
25
+ });
26
+ return URL.createObjectURL(l);
27
+ });
28
+ }
29
+ const {
30
+ SvelteComponent: w,
31
+ append: C,
32
+ assign: i,
33
+ compute_rest_props: d,
34
+ detach: u,
35
+ element: b,
36
+ empty: E,
37
+ exclude_internal_props: R,
38
+ get_spread_update: q,
39
+ handle_promise: g,
40
+ init: O,
41
+ insert: m,
42
+ noop: c,
43
+ safe_not_equal: T,
44
+ set_attributes: h,
45
+ set_data: P,
46
+ set_style: U,
47
+ src_url_equal: W,
48
+ text: K,
49
+ toggle_class: p,
50
+ update_await_block_branch: X
51
+ } = window.__gradio__svelte__internal;
52
+ function Y(s) {
53
+ let e, r = (
54
+ /*error*/
55
+ s[3].message + ""
56
+ ), n;
57
+ return {
58
+ c() {
59
+ e = b("p"), n = K(r), U(e, "color", "red");
60
+ },
61
+ m(t, l) {
62
+ m(t, e, l), C(e, n);
63
+ },
64
+ p(t, l) {
65
+ l & /*src*/
66
+ 1 && r !== (r = /*error*/
67
+ t[3].message + "") && P(n, r);
68
+ },
69
+ d(t) {
70
+ t && u(e);
71
+ }
72
+ };
73
+ }
74
+ function L(s) {
75
+ let e, r, n = [
76
+ {
77
+ src: r = /*resolved_src*/
78
+ s[2]
79
+ },
80
+ /*$$restProps*/
81
+ s[1]
82
+ ], t = {};
83
+ for (let l = 0; l < n.length; l += 1)
84
+ t = i(t, n[l]);
85
+ return {
86
+ c() {
87
+ e = b("img"), h(e, t), p(e, "svelte-1k8xp4f", !0);
88
+ },
89
+ m(l, o) {
90
+ m(l, e, o);
91
+ },
92
+ p(l, o) {
93
+ h(e, t = q(n, [
94
+ o & /*src*/
95
+ 1 && !W(e.src, r = /*resolved_src*/
96
+ l[2]) && { src: r },
97
+ o & /*$$restProps*/
98
+ 2 && /*$$restProps*/
99
+ l[1]
100
+ ])), p(e, "svelte-1k8xp4f", !0);
101
+ },
102
+ d(l) {
103
+ l && u(e);
104
+ }
105
+ };
106
+ }
107
+ function N(s) {
108
+ return { c, m: c, p: c, d: c };
109
+ }
110
+ function S(s) {
111
+ let e, r, n = {
112
+ ctx: s,
113
+ current: null,
114
+ token: null,
115
+ hasCatch: !0,
116
+ pending: N,
117
+ then: L,
118
+ catch: Y,
119
+ value: 2,
120
+ error: 3
121
+ };
122
+ return g(r = f(
123
+ /*src*/
124
+ s[0]
125
+ ), n), {
126
+ c() {
127
+ e = E(), n.block.c();
128
+ },
129
+ m(t, l) {
130
+ m(t, e, l), n.block.m(t, n.anchor = l), n.mount = () => e.parentNode, n.anchor = e;
131
+ },
132
+ p(t, [l]) {
133
+ s = t, n.ctx = s, l & /*src*/
134
+ 1 && r !== (r = f(
135
+ /*src*/
136
+ s[0]
137
+ )) && g(r, n) || X(n, s, l);
138
+ },
139
+ i: c,
140
+ o: c,
141
+ d(t) {
142
+ t && u(e), n.block.d(t), n.token = null, n = null;
143
+ }
144
+ };
145
+ }
146
+ function j(s, e, r) {
147
+ const n = ["src"];
148
+ let t = d(e, n), { src: l = void 0 } = e;
149
+ return s.$$set = (o) => {
150
+ e = i(i({}, e), R(o)), r(1, t = d(e, n)), "src" in o && r(0, l = o.src);
151
+ }, [l, t];
152
+ }
153
+ class I extends w {
154
+ constructor(e) {
155
+ super(), O(this, e, j, S, T, { src: 0 });
156
+ }
157
+ }
158
+ const {
159
+ SvelteComponent: x,
160
+ attr: z,
161
+ create_component: B,
162
+ destroy_component: F,
163
+ detach: G,
164
+ element: A,
165
+ init: D,
166
+ insert: H,
167
+ mount_component: J,
168
+ safe_not_equal: M,
169
+ toggle_class: _,
170
+ transition_in: Q,
171
+ transition_out: V
172
+ } = window.__gradio__svelte__internal;
173
+ function Z(s) {
174
+ let e, r, n;
175
+ return r = new I({
176
+ props: {
177
+ src: (
178
+ /*samples_dir*/
179
+ s[1] + /*value*/
180
+ s[0]
181
+ ),
182
+ alt: ""
183
+ }
184
+ }), {
185
+ c() {
186
+ e = A("div"), B(r.$$.fragment), z(e, "class", "container svelte-1iqucjz"), _(
187
+ e,
188
+ "table",
189
+ /*type*/
190
+ s[2] === "table"
191
+ ), _(
192
+ e,
193
+ "gallery",
194
+ /*type*/
195
+ s[2] === "gallery"
196
+ ), _(
197
+ e,
198
+ "selected",
199
+ /*selected*/
200
+ s[3]
201
+ );
202
+ },
203
+ m(t, l) {
204
+ H(t, e, l), J(r, e, null), n = !0;
205
+ },
206
+ p(t, [l]) {
207
+ const o = {};
208
+ l & /*samples_dir, value*/
209
+ 3 && (o.src = /*samples_dir*/
210
+ t[1] + /*value*/
211
+ t[0]), r.$set(o), (!n || l & /*type*/
212
+ 4) && _(
213
+ e,
214
+ "table",
215
+ /*type*/
216
+ t[2] === "table"
217
+ ), (!n || l & /*type*/
218
+ 4) && _(
219
+ e,
220
+ "gallery",
221
+ /*type*/
222
+ t[2] === "gallery"
223
+ ), (!n || l & /*selected*/
224
+ 8) && _(
225
+ e,
226
+ "selected",
227
+ /*selected*/
228
+ t[3]
229
+ );
230
+ },
231
+ i(t) {
232
+ n || (Q(r.$$.fragment, t), n = !0);
233
+ },
234
+ o(t) {
235
+ V(r.$$.fragment, t), n = !1;
236
+ },
237
+ d(t) {
238
+ t && G(e), F(r);
239
+ }
240
+ };
241
+ }
242
+ function $(s, e, r) {
243
+ let { value: n } = e, { samples_dir: t } = e, { type: l } = e, { selected: o = !1 } = e;
244
+ return s.$$set = (a) => {
245
+ "value" in a && r(0, n = a.value), "samples_dir" in a && r(1, t = a.samples_dir), "type" in a && r(2, l = a.type), "selected" in a && r(3, o = a.selected);
246
+ }, [n, t, l, o];
247
+ }
248
+ class te extends x {
249
+ constructor(e) {
250
+ super(), D(this, e, $, Z, M, {
251
+ value: 0,
252
+ samples_dir: 1,
253
+ type: 2,
254
+ selected: 3
255
+ });
256
+ }
257
+ }
258
+ export {
259
+ te as default
260
+ };
src/backend/gradio_coolimage/templates/example/style.css ADDED
@@ -0,0 +1 @@
 
 
1
+ img.svelte-1k8xp4f{max-width:100%;max-height:100%;border-radius:var(--radius-lg);max-width:none}.container.selected.svelte-1iqucjz{border-color:var(--border-color-accent)}.container.table.svelte-1iqucjz{margin:0 auto;border:2px solid var(--border-color-primary);border-radius:var(--radius-lg);width:var(--size-20);height:var(--size-20);object-fit:cover}.container.gallery.svelte-1iqucjz{border:2px solid var(--border-color-primary);height:var(--size-20);max-height:var(--size-20);object-fit:cover}
src/demo/__init__.py ADDED
File without changes
src/demo/app.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from gradio_coolimage import CoolImage
4
+
5
+
6
+ example = CoolImage().example_inputs()
7
+
8
+ demo = gr.Interface(
9
+ lambda x:x,
10
+ CoolImage(), # interactive version of your component
11
+ CoolImage(), # static version of your component
12
+ # examples=[[example]], # uncomment this line to view the "example version" of your component
13
+ )
14
+
15
+
16
+ demo.launch()
src/frontend/Example.svelte ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import Image from "./shared/Image.svelte";
3
+
4
+ export let value: string;
5
+ export let samples_dir: string;
6
+ export let type: "gallery" | "table";
7
+ export let selected = false;
8
+ </script>
9
+
10
+ <div
11
+ class="container"
12
+ class:table={type === "table"}
13
+ class:gallery={type === "gallery"}
14
+ class:selected
15
+ >
16
+ <Image src={samples_dir + value} alt="" />
17
+ </div>
18
+
19
+ <style>
20
+ .container.selected {
21
+ border-color: var(--border-color-accent);
22
+ }
23
+
24
+ .container.table {
25
+ margin: 0 auto;
26
+ border: 2px solid var(--border-color-primary);
27
+ border-radius: var(--radius-lg);
28
+ width: var(--size-20);
29
+ height: var(--size-20);
30
+ object-fit: cover;
31
+ }
32
+
33
+ .container.gallery {
34
+ border: 2px solid var(--border-color-primary);
35
+ height: var(--size-20);
36
+ max-height: var(--size-20);
37
+ object-fit: cover;
38
+ }
39
+ </style>
src/frontend/Index.svelte ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <svelte:options accessors={true} />
2
+
3
+ <script context="module" lang="ts">
4
+ export { default as Webcam } from "./shared/Webcam.svelte";
5
+ </script>
6
+
7
+ <script lang="ts">
8
+ import type { Gradio, SelectData } from "@gradio/utils";
9
+ import StaticImage from "./shared/ImagePreview.svelte";
10
+ import Image from "./shared/ImageEditor.svelte";
11
+
12
+ import { Block, UploadText } from "@gradio/atoms";
13
+
14
+ import { StatusTracker } from "@gradio/statustracker";
15
+ import type { FileData } from "js/upload/src";
16
+ import type { LoadingStatus } from "@gradio/statustracker";
17
+
18
+ export let elem_id = "";
19
+ export let elem_classes: string[] = [];
20
+ export let visible = true;
21
+ export let value: null | FileData = null;
22
+ export let label: string;
23
+ export let show_label: boolean;
24
+ export let show_download_button: boolean;
25
+ export let root: string;
26
+
27
+ export let height: number | undefined;
28
+ export let width: number | undefined;
29
+
30
+ export let selectable = false;
31
+ export let container = true;
32
+ export let scale: number | null = null;
33
+ export let min_width: number | undefined = undefined;
34
+ export let loading_status: LoadingStatus;
35
+ export let show_share_button = false;
36
+
37
+ export let mode: "static" | "interactive";
38
+ export let source: "canvas" | "webcam" | "upload" = "upload";
39
+ export let tool: "editor" | "select" | "sketch" | "color-sketch" = "editor";
40
+ export let streaming: boolean;
41
+ export let pending: boolean;
42
+ export let mirror_webcam: boolean;
43
+ export let shape: [number, number];
44
+ export let brush_radius: number;
45
+ export let brush_color: string;
46
+ export let mask_opacity: number;
47
+
48
+ export let gradio: Gradio<{
49
+ change: never;
50
+ error: string;
51
+ edit: never;
52
+ stream: never;
53
+ drag: never;
54
+ upload: never;
55
+ clear: never;
56
+ select: SelectData;
57
+ share: ShareData;
58
+ }>;
59
+
60
+ $: value, gradio.dispatch("change");
61
+ let dragging: boolean;
62
+
63
+ $: value = !value ? null : value;
64
+
65
+ const FIXED_HEIGHT = 240;
66
+ </script>
67
+
68
+ {#if mode === "static"}
69
+ <Block
70
+ {visible}
71
+ variant={"solid"}
72
+ border_mode={dragging ? "focus" : "base"}
73
+ padding={false}
74
+ {elem_id}
75
+ {elem_classes}
76
+ height={height || undefined}
77
+ {width}
78
+ allow_overflow={false}
79
+ {container}
80
+ {scale}
81
+ {min_width}
82
+ >
83
+ <StatusTracker
84
+ autoscroll={gradio.autoscroll}
85
+ i18n={gradio.i18n}
86
+ {...loading_status}
87
+ />
88
+ <StaticImage
89
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
90
+ on:share={({ detail }) => gradio.dispatch("share", detail)}
91
+ on:error={({ detail }) => gradio.dispatch("error", detail)}
92
+ {root}
93
+ {value}
94
+ {label}
95
+ {show_label}
96
+ {show_download_button}
97
+ {selectable}
98
+ {show_share_button}
99
+ i18n={gradio.i18n}
100
+ />
101
+ </Block>
102
+ {:else}
103
+ <Block
104
+ {visible}
105
+ variant={value === null && source === "upload" ? "dashed" : "solid"}
106
+ border_mode={dragging ? "focus" : "base"}
107
+ padding={false}
108
+ {elem_id}
109
+ {elem_classes}
110
+ height={height || (source === "webcam" ? undefined : FIXED_HEIGHT)}
111
+ {width}
112
+ allow_overflow={false}
113
+ {container}
114
+ {scale}
115
+ {min_width}
116
+ >
117
+ <StatusTracker
118
+ autoscroll={gradio.autoscroll}
119
+ i18n={gradio.i18n}
120
+ {...loading_status}
121
+ />
122
+
123
+ <Image
124
+ {brush_radius}
125
+ {brush_color}
126
+ {shape}
127
+ bind:value
128
+ {source}
129
+ {tool}
130
+ {selectable}
131
+ {mask_opacity}
132
+ {root}
133
+ on:edit={() => gradio.dispatch("edit")}
134
+ on:clear={() => gradio.dispatch("clear")}
135
+ on:stream={() => gradio.dispatch("stream")}
136
+ on:drag={({ detail }) => (dragging = detail)}
137
+ on:upload={() => gradio.dispatch("upload")}
138
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
139
+ on:share={({ detail }) => gradio.dispatch("share", detail)}
140
+ on:error={({ detail }) => {
141
+ loading_status = loading_status || {};
142
+ loading_status.status = "error";
143
+ gradio.dispatch("error", detail);
144
+ }}
145
+ {label}
146
+ {show_label}
147
+ {pending}
148
+ {streaming}
149
+ {mirror_webcam}
150
+ i18n={gradio.i18n}
151
+ >
152
+ <UploadText i18n={gradio.i18n} type="image" />
153
+ </Image>
154
+ </Block>
155
+ {/if}
src/frontend/package-lock.json ADDED
@@ -0,0 +1,1032 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gradio_coolimage",
3
+ "version": "0.3.0-beta.7",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "gradio_coolimage",
9
+ "version": "0.3.0-beta.7",
10
+ "license": "ISC",
11
+ "dependencies": {
12
+ "@gradio/atoms": "0.2.0-beta.4",
13
+ "@gradio/icons": "0.2.0-beta.1",
14
+ "@gradio/statustracker": "0.3.0-beta.6",
15
+ "@gradio/upload": "0.3.0-beta.4",
16
+ "@gradio/utils": "0.2.0-beta.4",
17
+ "@gradio/wasm": "0.2.0-beta.1",
18
+ "cropperjs": "^1.5.12",
19
+ "lazy-brush": "^1.0.1",
20
+ "resize-observer-polyfill": "^1.5.1"
21
+ }
22
+ },
23
+ "node_modules/@ampproject/remapping": {
24
+ "version": "2.2.1",
25
+ "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz",
26
+ "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==",
27
+ "peer": true,
28
+ "dependencies": {
29
+ "@jridgewell/gen-mapping": "^0.3.0",
30
+ "@jridgewell/trace-mapping": "^0.3.9"
31
+ },
32
+ "engines": {
33
+ "node": ">=6.0.0"
34
+ }
35
+ },
36
+ "node_modules/@esbuild/android-arm": {
37
+ "version": "0.19.5",
38
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.5.tgz",
39
+ "integrity": "sha512-bhvbzWFF3CwMs5tbjf3ObfGqbl/17ict2/uwOSfr3wmxDE6VdS2GqY/FuzIPe0q0bdhj65zQsvqfArI9MY6+AA==",
40
+ "cpu": [
41
+ "arm"
42
+ ],
43
+ "optional": true,
44
+ "os": [
45
+ "android"
46
+ ],
47
+ "engines": {
48
+ "node": ">=12"
49
+ }
50
+ },
51
+ "node_modules/@esbuild/android-arm64": {
52
+ "version": "0.19.5",
53
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.5.tgz",
54
+ "integrity": "sha512-5d1OkoJxnYQfmC+Zd8NBFjkhyCNYwM4n9ODrycTFY6Jk1IGiZ+tjVJDDSwDt77nK+tfpGP4T50iMtVi4dEGzhQ==",
55
+ "cpu": [
56
+ "arm64"
57
+ ],
58
+ "optional": true,
59
+ "os": [
60
+ "android"
61
+ ],
62
+ "engines": {
63
+ "node": ">=12"
64
+ }
65
+ },
66
+ "node_modules/@esbuild/android-x64": {
67
+ "version": "0.19.5",
68
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.5.tgz",
69
+ "integrity": "sha512-9t+28jHGL7uBdkBjL90QFxe7DVA+KGqWlHCF8ChTKyaKO//VLuoBricQCgwhOjA1/qOczsw843Fy4cbs4H3DVA==",
70
+ "cpu": [
71
+ "x64"
72
+ ],
73
+ "optional": true,
74
+ "os": [
75
+ "android"
76
+ ],
77
+ "engines": {
78
+ "node": ">=12"
79
+ }
80
+ },
81
+ "node_modules/@esbuild/darwin-arm64": {
82
+ "version": "0.19.5",
83
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.5.tgz",
84
+ "integrity": "sha512-mvXGcKqqIqyKoxq26qEDPHJuBYUA5KizJncKOAf9eJQez+L9O+KfvNFu6nl7SCZ/gFb2QPaRqqmG0doSWlgkqw==",
85
+ "cpu": [
86
+ "arm64"
87
+ ],
88
+ "optional": true,
89
+ "os": [
90
+ "darwin"
91
+ ],
92
+ "engines": {
93
+ "node": ">=12"
94
+ }
95
+ },
96
+ "node_modules/@esbuild/darwin-x64": {
97
+ "version": "0.19.5",
98
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.5.tgz",
99
+ "integrity": "sha512-Ly8cn6fGLNet19s0X4unjcniX24I0RqjPv+kurpXabZYSXGM4Pwpmf85WHJN3lAgB8GSth7s5A0r856S+4DyiA==",
100
+ "cpu": [
101
+ "x64"
102
+ ],
103
+ "optional": true,
104
+ "os": [
105
+ "darwin"
106
+ ],
107
+ "engines": {
108
+ "node": ">=12"
109
+ }
110
+ },
111
+ "node_modules/@esbuild/freebsd-arm64": {
112
+ "version": "0.19.5",
113
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.5.tgz",
114
+ "integrity": "sha512-GGDNnPWTmWE+DMchq1W8Sd0mUkL+APvJg3b11klSGUDvRXh70JqLAO56tubmq1s2cgpVCSKYywEiKBfju8JztQ==",
115
+ "cpu": [
116
+ "arm64"
117
+ ],
118
+ "optional": true,
119
+ "os": [
120
+ "freebsd"
121
+ ],
122
+ "engines": {
123
+ "node": ">=12"
124
+ }
125
+ },
126
+ "node_modules/@esbuild/freebsd-x64": {
127
+ "version": "0.19.5",
128
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.5.tgz",
129
+ "integrity": "sha512-1CCwDHnSSoA0HNwdfoNY0jLfJpd7ygaLAp5EHFos3VWJCRX9DMwWODf96s9TSse39Br7oOTLryRVmBoFwXbuuQ==",
130
+ "cpu": [
131
+ "x64"
132
+ ],
133
+ "optional": true,
134
+ "os": [
135
+ "freebsd"
136
+ ],
137
+ "engines": {
138
+ "node": ">=12"
139
+ }
140
+ },
141
+ "node_modules/@esbuild/linux-arm": {
142
+ "version": "0.19.5",
143
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.5.tgz",
144
+ "integrity": "sha512-lrWXLY/vJBzCPC51QN0HM71uWgIEpGSjSZZADQhq7DKhPcI6NH1IdzjfHkDQws2oNpJKpR13kv7/pFHBbDQDwQ==",
145
+ "cpu": [
146
+ "arm"
147
+ ],
148
+ "optional": true,
149
+ "os": [
150
+ "linux"
151
+ ],
152
+ "engines": {
153
+ "node": ">=12"
154
+ }
155
+ },
156
+ "node_modules/@esbuild/linux-arm64": {
157
+ "version": "0.19.5",
158
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.5.tgz",
159
+ "integrity": "sha512-o3vYippBmSrjjQUCEEiTZ2l+4yC0pVJD/Dl57WfPwwlvFkrxoSO7rmBZFii6kQB3Wrn/6GwJUPLU5t52eq2meA==",
160
+ "cpu": [
161
+ "arm64"
162
+ ],
163
+ "optional": true,
164
+ "os": [
165
+ "linux"
166
+ ],
167
+ "engines": {
168
+ "node": ">=12"
169
+ }
170
+ },
171
+ "node_modules/@esbuild/linux-ia32": {
172
+ "version": "0.19.5",
173
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.5.tgz",
174
+ "integrity": "sha512-MkjHXS03AXAkNp1KKkhSKPOCYztRtK+KXDNkBa6P78F8Bw0ynknCSClO/ztGszILZtyO/lVKpa7MolbBZ6oJtQ==",
175
+ "cpu": [
176
+ "ia32"
177
+ ],
178
+ "optional": true,
179
+ "os": [
180
+ "linux"
181
+ ],
182
+ "engines": {
183
+ "node": ">=12"
184
+ }
185
+ },
186
+ "node_modules/@esbuild/linux-loong64": {
187
+ "version": "0.19.5",
188
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.5.tgz",
189
+ "integrity": "sha512-42GwZMm5oYOD/JHqHska3Jg0r+XFb/fdZRX+WjADm3nLWLcIsN27YKtqxzQmGNJgu0AyXg4HtcSK9HuOk3v1Dw==",
190
+ "cpu": [
191
+ "loong64"
192
+ ],
193
+ "optional": true,
194
+ "os": [
195
+ "linux"
196
+ ],
197
+ "engines": {
198
+ "node": ">=12"
199
+ }
200
+ },
201
+ "node_modules/@esbuild/linux-mips64el": {
202
+ "version": "0.19.5",
203
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.5.tgz",
204
+ "integrity": "sha512-kcjndCSMitUuPJobWCnwQ9lLjiLZUR3QLQmlgaBfMX23UEa7ZOrtufnRds+6WZtIS9HdTXqND4yH8NLoVVIkcg==",
205
+ "cpu": [
206
+ "mips64el"
207
+ ],
208
+ "optional": true,
209
+ "os": [
210
+ "linux"
211
+ ],
212
+ "engines": {
213
+ "node": ">=12"
214
+ }
215
+ },
216
+ "node_modules/@esbuild/linux-ppc64": {
217
+ "version": "0.19.5",
218
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.5.tgz",
219
+ "integrity": "sha512-yJAxJfHVm0ZbsiljbtFFP1BQKLc8kUF6+17tjQ78QjqjAQDnhULWiTA6u0FCDmYT1oOKS9PzZ2z0aBI+Mcyj7Q==",
220
+ "cpu": [
221
+ "ppc64"
222
+ ],
223
+ "optional": true,
224
+ "os": [
225
+ "linux"
226
+ ],
227
+ "engines": {
228
+ "node": ">=12"
229
+ }
230
+ },
231
+ "node_modules/@esbuild/linux-riscv64": {
232
+ "version": "0.19.5",
233
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.5.tgz",
234
+ "integrity": "sha512-5u8cIR/t3gaD6ad3wNt1MNRstAZO+aNyBxu2We8X31bA8XUNyamTVQwLDA1SLoPCUehNCymhBhK3Qim1433Zag==",
235
+ "cpu": [
236
+ "riscv64"
237
+ ],
238
+ "optional": true,
239
+ "os": [
240
+ "linux"
241
+ ],
242
+ "engines": {
243
+ "node": ">=12"
244
+ }
245
+ },
246
+ "node_modules/@esbuild/linux-s390x": {
247
+ "version": "0.19.5",
248
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.5.tgz",
249
+ "integrity": "sha512-Z6JrMyEw/EmZBD/OFEFpb+gao9xJ59ATsoTNlj39jVBbXqoZm4Xntu6wVmGPB/OATi1uk/DB+yeDPv2E8PqZGw==",
250
+ "cpu": [
251
+ "s390x"
252
+ ],
253
+ "optional": true,
254
+ "os": [
255
+ "linux"
256
+ ],
257
+ "engines": {
258
+ "node": ">=12"
259
+ }
260
+ },
261
+ "node_modules/@esbuild/linux-x64": {
262
+ "version": "0.19.5",
263
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.5.tgz",
264
+ "integrity": "sha512-psagl+2RlK1z8zWZOmVdImisMtrUxvwereIdyJTmtmHahJTKb64pAcqoPlx6CewPdvGvUKe2Jw+0Z/0qhSbG1A==",
265
+ "cpu": [
266
+ "x64"
267
+ ],
268
+ "optional": true,
269
+ "os": [
270
+ "linux"
271
+ ],
272
+ "engines": {
273
+ "node": ">=12"
274
+ }
275
+ },
276
+ "node_modules/@esbuild/netbsd-x64": {
277
+ "version": "0.19.5",
278
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.5.tgz",
279
+ "integrity": "sha512-kL2l+xScnAy/E/3119OggX8SrWyBEcqAh8aOY1gr4gPvw76la2GlD4Ymf832UCVbmuWeTf2adkZDK+h0Z/fB4g==",
280
+ "cpu": [
281
+ "x64"
282
+ ],
283
+ "optional": true,
284
+ "os": [
285
+ "netbsd"
286
+ ],
287
+ "engines": {
288
+ "node": ">=12"
289
+ }
290
+ },
291
+ "node_modules/@esbuild/openbsd-x64": {
292
+ "version": "0.19.5",
293
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.5.tgz",
294
+ "integrity": "sha512-sPOfhtzFufQfTBgRnE1DIJjzsXukKSvZxloZbkJDG383q0awVAq600pc1nfqBcl0ice/WN9p4qLc39WhBShRTA==",
295
+ "cpu": [
296
+ "x64"
297
+ ],
298
+ "optional": true,
299
+ "os": [
300
+ "openbsd"
301
+ ],
302
+ "engines": {
303
+ "node": ">=12"
304
+ }
305
+ },
306
+ "node_modules/@esbuild/sunos-x64": {
307
+ "version": "0.19.5",
308
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.5.tgz",
309
+ "integrity": "sha512-dGZkBXaafuKLpDSjKcB0ax0FL36YXCvJNnztjKV+6CO82tTYVDSH2lifitJ29jxRMoUhgkg9a+VA/B03WK5lcg==",
310
+ "cpu": [
311
+ "x64"
312
+ ],
313
+ "optional": true,
314
+ "os": [
315
+ "sunos"
316
+ ],
317
+ "engines": {
318
+ "node": ">=12"
319
+ }
320
+ },
321
+ "node_modules/@esbuild/win32-arm64": {
322
+ "version": "0.19.5",
323
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.5.tgz",
324
+ "integrity": "sha512-dWVjD9y03ilhdRQ6Xig1NWNgfLtf2o/STKTS+eZuF90fI2BhbwD6WlaiCGKptlqXlURVB5AUOxUj09LuwKGDTg==",
325
+ "cpu": [
326
+ "arm64"
327
+ ],
328
+ "optional": true,
329
+ "os": [
330
+ "win32"
331
+ ],
332
+ "engines": {
333
+ "node": ">=12"
334
+ }
335
+ },
336
+ "node_modules/@esbuild/win32-ia32": {
337
+ "version": "0.19.5",
338
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.5.tgz",
339
+ "integrity": "sha512-4liggWIA4oDgUxqpZwrDhmEfAH4d0iljanDOK7AnVU89T6CzHon/ony8C5LeOdfgx60x5cnQJFZwEydVlYx4iw==",
340
+ "cpu": [
341
+ "ia32"
342
+ ],
343
+ "optional": true,
344
+ "os": [
345
+ "win32"
346
+ ],
347
+ "engines": {
348
+ "node": ">=12"
349
+ }
350
+ },
351
+ "node_modules/@esbuild/win32-x64": {
352
+ "version": "0.19.5",
353
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.5.tgz",
354
+ "integrity": "sha512-czTrygUsB/jlM8qEW5MD8bgYU2Xg14lo6kBDXW6HdxKjh8M5PzETGiSHaz9MtbXBYDloHNUAUW2tMiKW4KM9Mw==",
355
+ "cpu": [
356
+ "x64"
357
+ ],
358
+ "optional": true,
359
+ "os": [
360
+ "win32"
361
+ ],
362
+ "engines": {
363
+ "node": ">=12"
364
+ }
365
+ },
366
+ "node_modules/@formatjs/ecma402-abstract": {
367
+ "version": "1.11.4",
368
+ "resolved": "https://registry.npmjs.org/@formatjs/ecma402-abstract/-/ecma402-abstract-1.11.4.tgz",
369
+ "integrity": "sha512-EBikYFp2JCdIfGEb5G9dyCkTGDmC57KSHhRQOC3aYxoPWVZvfWCDjZwkGYHN7Lis/fmuWl906bnNTJifDQ3sXw==",
370
+ "dependencies": {
371
+ "@formatjs/intl-localematcher": "0.2.25",
372
+ "tslib": "^2.1.0"
373
+ }
374
+ },
375
+ "node_modules/@formatjs/fast-memoize": {
376
+ "version": "1.2.1",
377
+ "resolved": "https://registry.npmjs.org/@formatjs/fast-memoize/-/fast-memoize-1.2.1.tgz",
378
+ "integrity": "sha512-Rg0e76nomkz3vF9IPlKeV+Qynok0r7YZjL6syLz4/urSg0IbjPZCB/iYUMNsYA643gh4mgrX3T7KEIFIxJBQeg==",
379
+ "dependencies": {
380
+ "tslib": "^2.1.0"
381
+ }
382
+ },
383
+ "node_modules/@formatjs/icu-messageformat-parser": {
384
+ "version": "2.1.0",
385
+ "resolved": "https://registry.npmjs.org/@formatjs/icu-messageformat-parser/-/icu-messageformat-parser-2.1.0.tgz",
386
+ "integrity": "sha512-Qxv/lmCN6hKpBSss2uQ8IROVnta2r9jd3ymUEIjm2UyIkUCHVcbUVRGL/KS/wv7876edvsPe+hjHVJ4z8YuVaw==",
387
+ "dependencies": {
388
+ "@formatjs/ecma402-abstract": "1.11.4",
389
+ "@formatjs/icu-skeleton-parser": "1.3.6",
390
+ "tslib": "^2.1.0"
391
+ }
392
+ },
393
+ "node_modules/@formatjs/icu-skeleton-parser": {
394
+ "version": "1.3.6",
395
+ "resolved": "https://registry.npmjs.org/@formatjs/icu-skeleton-parser/-/icu-skeleton-parser-1.3.6.tgz",
396
+ "integrity": "sha512-I96mOxvml/YLrwU2Txnd4klA7V8fRhb6JG/4hm3VMNmeJo1F03IpV2L3wWt7EweqNLES59SZ4d6hVOPCSf80Bg==",
397
+ "dependencies": {
398
+ "@formatjs/ecma402-abstract": "1.11.4",
399
+ "tslib": "^2.1.0"
400
+ }
401
+ },
402
+ "node_modules/@formatjs/intl-localematcher": {
403
+ "version": "0.2.25",
404
+ "resolved": "https://registry.npmjs.org/@formatjs/intl-localematcher/-/intl-localematcher-0.2.25.tgz",
405
+ "integrity": "sha512-YmLcX70BxoSopLFdLr1Ds99NdlTI2oWoLbaUW2M406lxOIPzE1KQhRz2fPUkq34xVZQaihCoU29h0KK7An3bhA==",
406
+ "dependencies": {
407
+ "tslib": "^2.1.0"
408
+ }
409
+ },
410
+ "node_modules/@gradio/atoms": {
411
+ "version": "0.2.0-beta.4",
412
+ "resolved": "https://registry.npmjs.org/@gradio/atoms/-/atoms-0.2.0-beta.4.tgz",
413
+ "integrity": "sha512-xZfP9oPmb7iiuGl7KB4vVELSVk9f3w5Y9KRIxkAaMb+oeRpmb5uDtKQPAxntpm0W9rKAZmYG+DIWhInlu1eeKA==",
414
+ "dependencies": {
415
+ "@gradio/icons": "^0.2.0-beta.1",
416
+ "@gradio/utils": "^0.2.0-beta.4"
417
+ }
418
+ },
419
+ "node_modules/@gradio/client": {
420
+ "version": "0.5.2",
421
+ "resolved": "https://registry.npmjs.org/@gradio/client/-/client-0.5.2.tgz",
422
+ "integrity": "sha512-aQk3FEJt3R/7d7Xul0KqSUDqh0rwgQQwTXBuLS5qHuf861ym7bJcm/kDqqBgyu3/9pxAsybSdgA/G0QyZSBKgA==",
423
+ "dependencies": {
424
+ "bufferutil": "^4.0.7",
425
+ "semiver": "^1.1.0",
426
+ "ws": "^8.13.0"
427
+ },
428
+ "engines": {
429
+ "node": ">=18.0.0"
430
+ }
431
+ },
432
+ "node_modules/@gradio/column": {
433
+ "version": "0.1.0-beta.2",
434
+ "resolved": "https://registry.npmjs.org/@gradio/column/-/column-0.1.0-beta.2.tgz",
435
+ "integrity": "sha512-vL0GECdNL4wAaO/o0JcF3fm2xyMrx5DJWXUiPq/sUwqZwwB95srPGKBVTmVja3HproVXCBEnTzPQmRlrwWK67w=="
436
+ },
437
+ "node_modules/@gradio/icons": {
438
+ "version": "0.2.0-beta.1",
439
+ "resolved": "https://registry.npmjs.org/@gradio/icons/-/icons-0.2.0-beta.1.tgz",
440
+ "integrity": "sha512-6nwP1NIi0u4YQoSoaqC/rY0wuCvJHsnK+8aHDOE37070JpzBGuxB/VUlEgO7trNz5zI/EJy2htIRYsqz1vKmXA=="
441
+ },
442
+ "node_modules/@gradio/statustracker": {
443
+ "version": "0.3.0-beta.6",
444
+ "resolved": "https://registry.npmjs.org/@gradio/statustracker/-/statustracker-0.3.0-beta.6.tgz",
445
+ "integrity": "sha512-AIhaMCnr2uibHdqRrs4K8ZUvZK0q5e430TcvoduLOkaoOrkfnqetrHaHdOLNBz+H4kJlXJRsmt7ZZYV4wwMXRQ==",
446
+ "dependencies": {
447
+ "@gradio/atoms": "^0.2.0-beta.4",
448
+ "@gradio/column": "^0.1.0-beta.2",
449
+ "@gradio/icons": "^0.2.0-beta.1",
450
+ "@gradio/utils": "^0.2.0-beta.4"
451
+ }
452
+ },
453
+ "node_modules/@gradio/theme": {
454
+ "version": "0.2.0-beta.2",
455
+ "resolved": "https://registry.npmjs.org/@gradio/theme/-/theme-0.2.0-beta.2.tgz",
456
+ "integrity": "sha512-yKrA8eE02URtXUC9w98lBW8tqZk5oGumbBH7bFKOAhsrv1sbVZKir18P4a2/EL4XJ6Um36MwhPB3D5ipMniV5g=="
457
+ },
458
+ "node_modules/@gradio/upload": {
459
+ "version": "0.3.0-beta.4",
460
+ "resolved": "https://registry.npmjs.org/@gradio/upload/-/upload-0.3.0-beta.4.tgz",
461
+ "integrity": "sha512-JFajJHKJCAjZjtXDRZvLifGOs/b38fAuzAMshkDUQaJloRYk4KKpjnyj8d68wkQFzq3SK8ChKwfYoeMX8zp3yA==",
462
+ "dependencies": {
463
+ "@gradio/atoms": "^0.2.0-beta.4",
464
+ "@gradio/client": "^0.5.2",
465
+ "@gradio/icons": "^0.2.0-beta.1",
466
+ "@gradio/upload": "^0.3.0-beta.4",
467
+ "@gradio/utils": "^0.2.0-beta.4"
468
+ }
469
+ },
470
+ "node_modules/@gradio/utils": {
471
+ "version": "0.2.0-beta.4",
472
+ "resolved": "https://registry.npmjs.org/@gradio/utils/-/utils-0.2.0-beta.4.tgz",
473
+ "integrity": "sha512-jaOY3IQs1MnWRagXBICHXl5ZDKFqgF4XMfgsZNjTQxTG6THFOCsrUc14X1BNmXWkh9zVXJJTZcXifekj8O6LZQ==",
474
+ "dependencies": {
475
+ "@gradio/theme": "^0.2.0-beta.2",
476
+ "svelte-i18n": "^3.6.0"
477
+ }
478
+ },
479
+ "node_modules/@gradio/wasm": {
480
+ "version": "0.2.0-beta.1",
481
+ "resolved": "https://registry.npmjs.org/@gradio/wasm/-/wasm-0.2.0-beta.1.tgz",
482
+ "integrity": "sha512-BrEml+laheF0k7T90nR/QMkoQRhGSOIa2b8DOFLcjVhfr1LdNoGS7YCTB7XSd4qq1FlWmhNAWq63avcLFECnkg==",
483
+ "dependencies": {
484
+ "@types/path-browserify": "^1.0.0",
485
+ "path-browserify": "^1.0.1"
486
+ }
487
+ },
488
+ "node_modules/@jridgewell/gen-mapping": {
489
+ "version": "0.3.3",
490
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz",
491
+ "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==",
492
+ "peer": true,
493
+ "dependencies": {
494
+ "@jridgewell/set-array": "^1.0.1",
495
+ "@jridgewell/sourcemap-codec": "^1.4.10",
496
+ "@jridgewell/trace-mapping": "^0.3.9"
497
+ },
498
+ "engines": {
499
+ "node": ">=6.0.0"
500
+ }
501
+ },
502
+ "node_modules/@jridgewell/resolve-uri": {
503
+ "version": "3.1.1",
504
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz",
505
+ "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==",
506
+ "peer": true,
507
+ "engines": {
508
+ "node": ">=6.0.0"
509
+ }
510
+ },
511
+ "node_modules/@jridgewell/set-array": {
512
+ "version": "1.1.2",
513
+ "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz",
514
+ "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==",
515
+ "peer": true,
516
+ "engines": {
517
+ "node": ">=6.0.0"
518
+ }
519
+ },
520
+ "node_modules/@jridgewell/sourcemap-codec": {
521
+ "version": "1.4.15",
522
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
523
+ "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
524
+ "peer": true
525
+ },
526
+ "node_modules/@jridgewell/trace-mapping": {
527
+ "version": "0.3.20",
528
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz",
529
+ "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==",
530
+ "peer": true,
531
+ "dependencies": {
532
+ "@jridgewell/resolve-uri": "^3.1.0",
533
+ "@jridgewell/sourcemap-codec": "^1.4.14"
534
+ }
535
+ },
536
+ "node_modules/@types/estree": {
537
+ "version": "1.0.3",
538
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.3.tgz",
539
+ "integrity": "sha512-CS2rOaoQ/eAgAfcTfq6amKG7bsN+EMcgGY4FAFQdvSj2y1ixvOZTUA9mOtCai7E1SYu283XNw7urKK30nP3wkQ==",
540
+ "peer": true
541
+ },
542
+ "node_modules/@types/path-browserify": {
543
+ "version": "1.0.1",
544
+ "resolved": "https://registry.npmjs.org/@types/path-browserify/-/path-browserify-1.0.1.tgz",
545
+ "integrity": "sha512-rUSqIy7fAfK6sRasdFCukWO4S77pXcTxViURlLdo1VKuekTDS8ASMdX1LA0TFlbzT3fZgFlgQTCrqmJBuTHpxA=="
546
+ },
547
+ "node_modules/acorn": {
548
+ "version": "8.11.1",
549
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.1.tgz",
550
+ "integrity": "sha512-IJTNCJMRHfRfb8un89z1QtS0x890C2QUrUxFMK8zy+RizcId6mfnqOf68Bu9YkDgpLYuvCm6aYbwDatXVZPjMQ==",
551
+ "peer": true,
552
+ "bin": {
553
+ "acorn": "bin/acorn"
554
+ },
555
+ "engines": {
556
+ "node": ">=0.4.0"
557
+ }
558
+ },
559
+ "node_modules/aria-query": {
560
+ "version": "5.3.0",
561
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",
562
+ "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
563
+ "peer": true,
564
+ "dependencies": {
565
+ "dequal": "^2.0.3"
566
+ }
567
+ },
568
+ "node_modules/axobject-query": {
569
+ "version": "3.2.1",
570
+ "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.2.1.tgz",
571
+ "integrity": "sha512-jsyHu61e6N4Vbz/v18DHwWYKK0bSWLqn47eeDSKPB7m8tqMHF9YJ+mhIk2lVteyZrY8tnSj/jHOv4YiTCuCJgg==",
572
+ "peer": true,
573
+ "dependencies": {
574
+ "dequal": "^2.0.3"
575
+ }
576
+ },
577
+ "node_modules/bufferutil": {
578
+ "version": "4.0.8",
579
+ "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz",
580
+ "integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==",
581
+ "hasInstallScript": true,
582
+ "dependencies": {
583
+ "node-gyp-build": "^4.3.0"
584
+ },
585
+ "engines": {
586
+ "node": ">=6.14.2"
587
+ }
588
+ },
589
+ "node_modules/cli-color": {
590
+ "version": "2.0.3",
591
+ "resolved": "https://registry.npmjs.org/cli-color/-/cli-color-2.0.3.tgz",
592
+ "integrity": "sha512-OkoZnxyC4ERN3zLzZaY9Emb7f/MhBOIpePv0Ycok0fJYT+Ouo00UBEIwsVsr0yoow++n5YWlSUgST9GKhNHiRQ==",
593
+ "dependencies": {
594
+ "d": "^1.0.1",
595
+ "es5-ext": "^0.10.61",
596
+ "es6-iterator": "^2.0.3",
597
+ "memoizee": "^0.4.15",
598
+ "timers-ext": "^0.1.7"
599
+ },
600
+ "engines": {
601
+ "node": ">=0.10"
602
+ }
603
+ },
604
+ "node_modules/code-red": {
605
+ "version": "1.0.4",
606
+ "resolved": "https://registry.npmjs.org/code-red/-/code-red-1.0.4.tgz",
607
+ "integrity": "sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==",
608
+ "peer": true,
609
+ "dependencies": {
610
+ "@jridgewell/sourcemap-codec": "^1.4.15",
611
+ "@types/estree": "^1.0.1",
612
+ "acorn": "^8.10.0",
613
+ "estree-walker": "^3.0.3",
614
+ "periscopic": "^3.1.0"
615
+ }
616
+ },
617
+ "node_modules/cropperjs": {
618
+ "version": "1.6.1",
619
+ "resolved": "https://registry.npmjs.org/cropperjs/-/cropperjs-1.6.1.tgz",
620
+ "integrity": "sha512-F4wsi+XkDHCOMrHMYjrTEE4QBOrsHHN5/2VsVAaRq8P7E5z7xQpT75S+f/9WikmBEailas3+yo+6zPIomW+NOA=="
621
+ },
622
+ "node_modules/css-tree": {
623
+ "version": "2.3.1",
624
+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.3.1.tgz",
625
+ "integrity": "sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==",
626
+ "peer": true,
627
+ "dependencies": {
628
+ "mdn-data": "2.0.30",
629
+ "source-map-js": "^1.0.1"
630
+ },
631
+ "engines": {
632
+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
633
+ }
634
+ },
635
+ "node_modules/d": {
636
+ "version": "1.0.1",
637
+ "resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz",
638
+ "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==",
639
+ "dependencies": {
640
+ "es5-ext": "^0.10.50",
641
+ "type": "^1.0.1"
642
+ }
643
+ },
644
+ "node_modules/deepmerge": {
645
+ "version": "4.3.1",
646
+ "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
647
+ "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
648
+ "engines": {
649
+ "node": ">=0.10.0"
650
+ }
651
+ },
652
+ "node_modules/dequal": {
653
+ "version": "2.0.3",
654
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
655
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
656
+ "peer": true,
657
+ "engines": {
658
+ "node": ">=6"
659
+ }
660
+ },
661
+ "node_modules/es5-ext": {
662
+ "version": "0.10.62",
663
+ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.62.tgz",
664
+ "integrity": "sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA==",
665
+ "hasInstallScript": true,
666
+ "dependencies": {
667
+ "es6-iterator": "^2.0.3",
668
+ "es6-symbol": "^3.1.3",
669
+ "next-tick": "^1.1.0"
670
+ },
671
+ "engines": {
672
+ "node": ">=0.10"
673
+ }
674
+ },
675
+ "node_modules/es6-iterator": {
676
+ "version": "2.0.3",
677
+ "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",
678
+ "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==",
679
+ "dependencies": {
680
+ "d": "1",
681
+ "es5-ext": "^0.10.35",
682
+ "es6-symbol": "^3.1.1"
683
+ }
684
+ },
685
+ "node_modules/es6-symbol": {
686
+ "version": "3.1.3",
687
+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz",
688
+ "integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==",
689
+ "dependencies": {
690
+ "d": "^1.0.1",
691
+ "ext": "^1.1.2"
692
+ }
693
+ },
694
+ "node_modules/es6-weak-map": {
695
+ "version": "2.0.3",
696
+ "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.3.tgz",
697
+ "integrity": "sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==",
698
+ "dependencies": {
699
+ "d": "1",
700
+ "es5-ext": "^0.10.46",
701
+ "es6-iterator": "^2.0.3",
702
+ "es6-symbol": "^3.1.1"
703
+ }
704
+ },
705
+ "node_modules/esbuild": {
706
+ "version": "0.19.5",
707
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.5.tgz",
708
+ "integrity": "sha512-bUxalY7b1g8vNhQKdB24QDmHeY4V4tw/s6Ak5z+jJX9laP5MoQseTOMemAr0gxssjNcH0MCViG8ONI2kksvfFQ==",
709
+ "hasInstallScript": true,
710
+ "bin": {
711
+ "esbuild": "bin/esbuild"
712
+ },
713
+ "engines": {
714
+ "node": ">=12"
715
+ },
716
+ "optionalDependencies": {
717
+ "@esbuild/android-arm": "0.19.5",
718
+ "@esbuild/android-arm64": "0.19.5",
719
+ "@esbuild/android-x64": "0.19.5",
720
+ "@esbuild/darwin-arm64": "0.19.5",
721
+ "@esbuild/darwin-x64": "0.19.5",
722
+ "@esbuild/freebsd-arm64": "0.19.5",
723
+ "@esbuild/freebsd-x64": "0.19.5",
724
+ "@esbuild/linux-arm": "0.19.5",
725
+ "@esbuild/linux-arm64": "0.19.5",
726
+ "@esbuild/linux-ia32": "0.19.5",
727
+ "@esbuild/linux-loong64": "0.19.5",
728
+ "@esbuild/linux-mips64el": "0.19.5",
729
+ "@esbuild/linux-ppc64": "0.19.5",
730
+ "@esbuild/linux-riscv64": "0.19.5",
731
+ "@esbuild/linux-s390x": "0.19.5",
732
+ "@esbuild/linux-x64": "0.19.5",
733
+ "@esbuild/netbsd-x64": "0.19.5",
734
+ "@esbuild/openbsd-x64": "0.19.5",
735
+ "@esbuild/sunos-x64": "0.19.5",
736
+ "@esbuild/win32-arm64": "0.19.5",
737
+ "@esbuild/win32-ia32": "0.19.5",
738
+ "@esbuild/win32-x64": "0.19.5"
739
+ }
740
+ },
741
+ "node_modules/estree-walker": {
742
+ "version": "3.0.3",
743
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
744
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
745
+ "peer": true,
746
+ "dependencies": {
747
+ "@types/estree": "^1.0.0"
748
+ }
749
+ },
750
+ "node_modules/event-emitter": {
751
+ "version": "0.3.5",
752
+ "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz",
753
+ "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==",
754
+ "dependencies": {
755
+ "d": "1",
756
+ "es5-ext": "~0.10.14"
757
+ }
758
+ },
759
+ "node_modules/ext": {
760
+ "version": "1.7.0",
761
+ "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz",
762
+ "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==",
763
+ "dependencies": {
764
+ "type": "^2.7.2"
765
+ }
766
+ },
767
+ "node_modules/ext/node_modules/type": {
768
+ "version": "2.7.2",
769
+ "resolved": "https://registry.npmjs.org/type/-/type-2.7.2.tgz",
770
+ "integrity": "sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw=="
771
+ },
772
+ "node_modules/globalyzer": {
773
+ "version": "0.1.0",
774
+ "resolved": "https://registry.npmjs.org/globalyzer/-/globalyzer-0.1.0.tgz",
775
+ "integrity": "sha512-40oNTM9UfG6aBmuKxk/giHn5nQ8RVz/SS4Ir6zgzOv9/qC3kKZ9v4etGTcJbEl/NyVQH7FGU7d+X1egr57Md2Q=="
776
+ },
777
+ "node_modules/globrex": {
778
+ "version": "0.1.2",
779
+ "resolved": "https://registry.npmjs.org/globrex/-/globrex-0.1.2.tgz",
780
+ "integrity": "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg=="
781
+ },
782
+ "node_modules/intl-messageformat": {
783
+ "version": "9.13.0",
784
+ "resolved": "https://registry.npmjs.org/intl-messageformat/-/intl-messageformat-9.13.0.tgz",
785
+ "integrity": "sha512-7sGC7QnSQGa5LZP7bXLDhVDtQOeKGeBFGHF2Y8LVBwYZoQZCgWeKoPGTa5GMG8g/TzDgeXuYJQis7Ggiw2xTOw==",
786
+ "dependencies": {
787
+ "@formatjs/ecma402-abstract": "1.11.4",
788
+ "@formatjs/fast-memoize": "1.2.1",
789
+ "@formatjs/icu-messageformat-parser": "2.1.0",
790
+ "tslib": "^2.1.0"
791
+ }
792
+ },
793
+ "node_modules/is-promise": {
794
+ "version": "2.2.2",
795
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz",
796
+ "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ=="
797
+ },
798
+ "node_modules/is-reference": {
799
+ "version": "3.0.2",
800
+ "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.2.tgz",
801
+ "integrity": "sha512-v3rht/LgVcsdZa3O2Nqs+NMowLOxeOm7Ay9+/ARQ2F+qEoANRcqrjAZKGN0v8ymUetZGgkp26LTnGT7H0Qo9Pg==",
802
+ "peer": true,
803
+ "dependencies": {
804
+ "@types/estree": "*"
805
+ }
806
+ },
807
+ "node_modules/lazy-brush": {
808
+ "version": "1.0.1",
809
+ "resolved": "https://registry.npmjs.org/lazy-brush/-/lazy-brush-1.0.1.tgz",
810
+ "integrity": "sha512-xT/iSClTVi7vLoF8dCWTBhCuOWqsLXCMPa6ucVmVAk6hyNCM5JeS1NLhXqIrJktUg+caEYKlqSOUU4u3cpXzKg=="
811
+ },
812
+ "node_modules/locate-character": {
813
+ "version": "3.0.0",
814
+ "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
815
+ "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
816
+ "peer": true
817
+ },
818
+ "node_modules/lru-queue": {
819
+ "version": "0.1.0",
820
+ "resolved": "https://registry.npmjs.org/lru-queue/-/lru-queue-0.1.0.tgz",
821
+ "integrity": "sha512-BpdYkt9EvGl8OfWHDQPISVpcl5xZthb+XPsbELj5AQXxIC8IriDZIQYjBJPEm5rS420sjZ0TLEzRcq5KdBhYrQ==",
822
+ "dependencies": {
823
+ "es5-ext": "~0.10.2"
824
+ }
825
+ },
826
+ "node_modules/magic-string": {
827
+ "version": "0.30.5",
828
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz",
829
+ "integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==",
830
+ "peer": true,
831
+ "dependencies": {
832
+ "@jridgewell/sourcemap-codec": "^1.4.15"
833
+ },
834
+ "engines": {
835
+ "node": ">=12"
836
+ }
837
+ },
838
+ "node_modules/mdn-data": {
839
+ "version": "2.0.30",
840
+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.30.tgz",
841
+ "integrity": "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==",
842
+ "peer": true
843
+ },
844
+ "node_modules/memoizee": {
845
+ "version": "0.4.15",
846
+ "resolved": "https://registry.npmjs.org/memoizee/-/memoizee-0.4.15.tgz",
847
+ "integrity": "sha512-UBWmJpLZd5STPm7PMUlOw/TSy972M+z8gcyQ5veOnSDRREz/0bmpyTfKt3/51DhEBqCZQn1udM/5flcSPYhkdQ==",
848
+ "dependencies": {
849
+ "d": "^1.0.1",
850
+ "es5-ext": "^0.10.53",
851
+ "es6-weak-map": "^2.0.3",
852
+ "event-emitter": "^0.3.5",
853
+ "is-promise": "^2.2.2",
854
+ "lru-queue": "^0.1.0",
855
+ "next-tick": "^1.1.0",
856
+ "timers-ext": "^0.1.7"
857
+ }
858
+ },
859
+ "node_modules/mri": {
860
+ "version": "1.2.0",
861
+ "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
862
+ "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
863
+ "engines": {
864
+ "node": ">=4"
865
+ }
866
+ },
867
+ "node_modules/next-tick": {
868
+ "version": "1.1.0",
869
+ "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz",
870
+ "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ=="
871
+ },
872
+ "node_modules/node-gyp-build": {
873
+ "version": "4.6.1",
874
+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.6.1.tgz",
875
+ "integrity": "sha512-24vnklJmyRS8ViBNI8KbtK/r/DmXQMRiOMXTNz2nrTnAYUwjmEEbnnpB/+kt+yWRv73bPsSPRFddrcIbAxSiMQ==",
876
+ "bin": {
877
+ "node-gyp-build": "bin.js",
878
+ "node-gyp-build-optional": "optional.js",
879
+ "node-gyp-build-test": "build-test.js"
880
+ }
881
+ },
882
+ "node_modules/path-browserify": {
883
+ "version": "1.0.1",
884
+ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
885
+ "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="
886
+ },
887
+ "node_modules/periscopic": {
888
+ "version": "3.1.0",
889
+ "resolved": "https://registry.npmjs.org/periscopic/-/periscopic-3.1.0.tgz",
890
+ "integrity": "sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==",
891
+ "peer": true,
892
+ "dependencies": {
893
+ "@types/estree": "^1.0.0",
894
+ "estree-walker": "^3.0.0",
895
+ "is-reference": "^3.0.0"
896
+ }
897
+ },
898
+ "node_modules/resize-observer-polyfill": {
899
+ "version": "1.5.1",
900
+ "resolved": "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz",
901
+ "integrity": "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg=="
902
+ },
903
+ "node_modules/sade": {
904
+ "version": "1.8.1",
905
+ "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz",
906
+ "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==",
907
+ "dependencies": {
908
+ "mri": "^1.1.0"
909
+ },
910
+ "engines": {
911
+ "node": ">=6"
912
+ }
913
+ },
914
+ "node_modules/semiver": {
915
+ "version": "1.1.0",
916
+ "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz",
917
+ "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==",
918
+ "engines": {
919
+ "node": ">=6"
920
+ }
921
+ },
922
+ "node_modules/source-map-js": {
923
+ "version": "1.0.2",
924
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz",
925
+ "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
926
+ "peer": true,
927
+ "engines": {
928
+ "node": ">=0.10.0"
929
+ }
930
+ },
931
+ "node_modules/svelte": {
932
+ "version": "4.2.2",
933
+ "resolved": "https://registry.npmjs.org/svelte/-/svelte-4.2.2.tgz",
934
+ "integrity": "sha512-My2tytF2e2NnHSpn2M7/3VdXT4JdTglYVUuSuK/mXL2XtulPYbeBfl8Dm1QiaKRn0zoULRnL+EtfZHHP0k4H3A==",
935
+ "peer": true,
936
+ "dependencies": {
937
+ "@ampproject/remapping": "^2.2.1",
938
+ "@jridgewell/sourcemap-codec": "^1.4.15",
939
+ "@jridgewell/trace-mapping": "^0.3.18",
940
+ "acorn": "^8.9.0",
941
+ "aria-query": "^5.3.0",
942
+ "axobject-query": "^3.2.1",
943
+ "code-red": "^1.0.3",
944
+ "css-tree": "^2.3.1",
945
+ "estree-walker": "^3.0.3",
946
+ "is-reference": "^3.0.1",
947
+ "locate-character": "^3.0.0",
948
+ "magic-string": "^0.30.4",
949
+ "periscopic": "^3.1.0"
950
+ },
951
+ "engines": {
952
+ "node": ">=16"
953
+ }
954
+ },
955
+ "node_modules/svelte-i18n": {
956
+ "version": "3.7.4",
957
+ "resolved": "https://registry.npmjs.org/svelte-i18n/-/svelte-i18n-3.7.4.tgz",
958
+ "integrity": "sha512-yGRCNo+eBT4cPuU7IVsYTYjxB7I2V8qgUZPlHnNctJj5IgbJgV78flsRzpjZ/8iUYZrS49oCt7uxlU3AZv/N5Q==",
959
+ "dependencies": {
960
+ "cli-color": "^2.0.3",
961
+ "deepmerge": "^4.2.2",
962
+ "esbuild": "^0.19.2",
963
+ "estree-walker": "^2",
964
+ "intl-messageformat": "^9.13.0",
965
+ "sade": "^1.8.1",
966
+ "tiny-glob": "^0.2.9"
967
+ },
968
+ "bin": {
969
+ "svelte-i18n": "dist/cli.js"
970
+ },
971
+ "engines": {
972
+ "node": ">= 16"
973
+ },
974
+ "peerDependencies": {
975
+ "svelte": "^3 || ^4"
976
+ }
977
+ },
978
+ "node_modules/svelte-i18n/node_modules/estree-walker": {
979
+ "version": "2.0.2",
980
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
981
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="
982
+ },
983
+ "node_modules/timers-ext": {
984
+ "version": "0.1.7",
985
+ "resolved": "https://registry.npmjs.org/timers-ext/-/timers-ext-0.1.7.tgz",
986
+ "integrity": "sha512-b85NUNzTSdodShTIbky6ZF02e8STtVVfD+fu4aXXShEELpozH+bCpJLYMPZbsABN2wDH7fJpqIoXxJpzbf0NqQ==",
987
+ "dependencies": {
988
+ "es5-ext": "~0.10.46",
989
+ "next-tick": "1"
990
+ }
991
+ },
992
+ "node_modules/tiny-glob": {
993
+ "version": "0.2.9",
994
+ "resolved": "https://registry.npmjs.org/tiny-glob/-/tiny-glob-0.2.9.tgz",
995
+ "integrity": "sha512-g/55ssRPUjShh+xkfx9UPDXqhckHEsHr4Vd9zX55oSdGZc/MD0m3sferOkwWtp98bv+kcVfEHtRJgBVJzelrzg==",
996
+ "dependencies": {
997
+ "globalyzer": "0.1.0",
998
+ "globrex": "^0.1.2"
999
+ }
1000
+ },
1001
+ "node_modules/tslib": {
1002
+ "version": "2.6.2",
1003
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz",
1004
+ "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="
1005
+ },
1006
+ "node_modules/type": {
1007
+ "version": "1.2.0",
1008
+ "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz",
1009
+ "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg=="
1010
+ },
1011
+ "node_modules/ws": {
1012
+ "version": "8.14.2",
1013
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz",
1014
+ "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==",
1015
+ "engines": {
1016
+ "node": ">=10.0.0"
1017
+ },
1018
+ "peerDependencies": {
1019
+ "bufferutil": "^4.0.1",
1020
+ "utf-8-validate": ">=5.0.2"
1021
+ },
1022
+ "peerDependenciesMeta": {
1023
+ "bufferutil": {
1024
+ "optional": true
1025
+ },
1026
+ "utf-8-validate": {
1027
+ "optional": true
1028
+ }
1029
+ }
1030
+ }
1031
+ }
1032
+ }
src/frontend/package.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gradio_coolimage",
3
+ "version": "0.3.0-beta.7",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@gradio/atoms": "0.2.0-beta.4",
11
+ "@gradio/icons": "0.2.0-beta.1",
12
+ "@gradio/statustracker": "0.3.0-beta.6",
13
+ "@gradio/upload": "0.3.0-beta.4",
14
+ "@gradio/utils": "0.2.0-beta.4",
15
+ "@gradio/wasm": "0.2.0-beta.1",
16
+ "cropperjs": "^1.5.12",
17
+ "lazy-brush": "^1.0.1",
18
+ "resize-observer-polyfill": "^1.5.1"
19
+ },
20
+ "main_changeset": true,
21
+ "main": "./Index.svelte",
22
+ "exports": {
23
+ ".": "./Index.svelte",
24
+ "./example": "./Example.svelte",
25
+ "./package.json": "./package.json"
26
+ }
27
+ }
src/frontend/shared/Cropper.svelte ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <svelte:options accessors={true} />
2
+
3
+ <script lang="ts">
4
+ import Cropper from "cropperjs";
5
+ import { onMount, createEventDispatcher } from "svelte";
6
+
7
+ export let image: string;
8
+ let el: HTMLImageElement;
9
+
10
+ const dispatch = createEventDispatcher();
11
+ let cropper: Cropper;
12
+
13
+ export function destroy(): void {
14
+ cropper.destroy();
15
+ }
16
+
17
+ export function create(): void {
18
+ if (cropper) {
19
+ destroy();
20
+ }
21
+ cropper = new Cropper(el, {
22
+ autoCropArea: 1,
23
+ cropend(): void {
24
+ const image_data = cropper.getCroppedCanvas().toDataURL();
25
+ dispatch("crop", image_data);
26
+ }
27
+ });
28
+
29
+ dispatch("crop", image);
30
+ }
31
+ </script>
32
+
33
+ <img src={image} bind:this={el} alt="" />
src/frontend/shared/Image.svelte ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { HTMLImgAttributes } from "svelte/elements";
3
+ type $$Props = HTMLImgAttributes;
4
+
5
+ import { resolve_wasm_src } from "@gradio/wasm/svelte";
6
+
7
+ export let src: HTMLImgAttributes["src"] = undefined;
8
+ </script>
9
+
10
+ {#await resolve_wasm_src(src) then resolved_src}
11
+ <!-- svelte-ignore a11y-missing-attribute -->
12
+ <img src={resolved_src} {...$$restProps} />
13
+ {:catch error}
14
+ <p style="color: red;">{error.message}</p>
15
+ {/await}
16
+
17
+ <style>
18
+ img {
19
+ max-width: 100%;
20
+ max-height: 100%;
21
+ border-radius: var(--radius-lg);
22
+ max-width: none;
23
+ }
24
+ </style>
src/frontend/shared/ImageEditor.svelte ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ // @ts-nocheck
3
+ import { createEventDispatcher, tick, onMount } from "svelte";
4
+ import { BlockLabel } from "@gradio/atoms";
5
+ import { Image, Sketch as SketchIcon } from "@gradio/icons";
6
+ import type { SelectData, I18nFormatter } from "@gradio/utils";
7
+ import { get_coordinates_of_clicked_image } from "./utils";
8
+
9
+ import Cropper from "./Cropper.svelte";
10
+ import Sketch from "./Sketch.svelte";
11
+ import Webcam from "./Webcam.svelte";
12
+ import ModifySketch from "./ModifySketch.svelte";
13
+ import SketchSettings from "./SketchSettings.svelte";
14
+ import {
15
+ Upload,
16
+ ModifyUpload,
17
+ type FileData,
18
+ normalise_file
19
+ } from "@gradio/upload";
20
+
21
+ export let value:
22
+ | null
23
+ | { image: string | null; mask: string | null }
24
+ | FileData;
25
+ export let label: string | undefined = undefined;
26
+ export let show_label: boolean;
27
+
28
+ export let source: "canvas" | "webcam" | "upload" = "upload";
29
+ export let tool: "editor" | "select" | "sketch" | "color-sketch" = "editor";
30
+ export let shape: [number, number];
31
+ export let streaming = false;
32
+ export let pending = false;
33
+ export let mirror_webcam: boolean;
34
+ export let brush_radius: number;
35
+ export let brush_color = "#000000";
36
+ export let mask_opacity;
37
+ export let selectable = false;
38
+ export let root: string;
39
+ export let i18n: I18nFormatter;
40
+
41
+ let sketch: Sketch;
42
+ let cropper: Cropper;
43
+
44
+ if (
45
+ value &&
46
+ (source === "upload" || source === "webcam") &&
47
+ tool === "sketch"
48
+ ) {
49
+ value = { image: value as string, mask: null };
50
+ }
51
+
52
+ function handle_upload({ detail }: CustomEvent<string>): void {
53
+ if (tool === "color-sketch") {
54
+ static_image = normalise_file(detail, root, null)?.data;
55
+ } else {
56
+ value =
57
+ (source === "upload" || source === "webcam") && tool === "sketch"
58
+ ? { image: normalise_file(detail, root, null), mask: null }
59
+ : normalise_file(detail, root, null);
60
+ }
61
+
62
+ dispatch("upload", normalise_file(detail, root, null));
63
+ }
64
+
65
+ function handle_clear({ detail }: CustomEvent<null>): void {
66
+ value = null;
67
+ static_image = undefined;
68
+ dispatch("clear");
69
+ }
70
+
71
+ async function handle_save(
72
+ { detail }: { detail: string },
73
+ initial
74
+ ): Promise<void> {
75
+ if (mode === "mask") {
76
+ if (source === "webcam" && initial) {
77
+ value = {
78
+ image: detail,
79
+ mask: null
80
+ };
81
+ } else {
82
+ value = {
83
+ image: typeof value === "string" ? value : value?.image || null,
84
+ mask: detail
85
+ };
86
+ }
87
+ } else if (
88
+ (source === "upload" || source === "webcam") &&
89
+ tool === "sketch"
90
+ ) {
91
+ value = { image: detail, mask: null };
92
+ } else {
93
+ value = detail;
94
+ }
95
+
96
+ await tick();
97
+
98
+ dispatch(streaming ? "stream" : "edit");
99
+ }
100
+
101
+ const dispatch = createEventDispatcher<{
102
+ change: string | null;
103
+ stream: string | null;
104
+ edit: undefined;
105
+ clear: undefined;
106
+ drag: boolean;
107
+ upload: FileData;
108
+ select: SelectData;
109
+ }>();
110
+
111
+ let dragging = false;
112
+
113
+ $: dispatch("drag", dragging);
114
+
115
+ let value_: null | FileData = null;
116
+
117
+ $: if (value !== value_) {
118
+ value_ = value;
119
+ normalise_file(value_, root, null);
120
+ }
121
+
122
+ function handle_image_load(event: Event): void {
123
+ const element = event.currentTarget as HTMLImageElement;
124
+ img_width = element.naturalWidth;
125
+ img_height = element.naturalHeight;
126
+ container_height = element.getBoundingClientRect().height;
127
+ }
128
+
129
+ async function handle_sketch_clear(): Promise<void> {
130
+ dispatch("clear");
131
+ sketch.clear();
132
+ await tick();
133
+ value = null;
134
+ static_image = undefined;
135
+ }
136
+
137
+ async function handle_mask_clear(): Promise<void> {
138
+ sketch.clear_mask();
139
+ await tick();
140
+ }
141
+
142
+ let img_height = 0;
143
+ let img_width = 0;
144
+ let container_height = 0;
145
+
146
+ let mode;
147
+
148
+ $: {
149
+ if (source === "canvas" && tool === "sketch") {
150
+ mode = "bw-sketch";
151
+ } else if (tool === "color-sketch") {
152
+ mode = "color-sketch";
153
+ } else if (
154
+ (source === "upload" || source === "webcam") &&
155
+ tool === "sketch"
156
+ ) {
157
+ mode = "mask";
158
+ } else {
159
+ mode = "editor";
160
+ }
161
+ }
162
+ let value_img;
163
+ let max_height;
164
+ let max_width;
165
+
166
+ let static_image = undefined;
167
+
168
+ $: {
169
+ if (value === null || (value.image === null && value.mask === null)) {
170
+ static_image = undefined;
171
+ }
172
+ }
173
+
174
+ $: {
175
+ if (cropper) {
176
+ if (value) {
177
+ cropper.image = value;
178
+ cropper.create();
179
+ } else {
180
+ cropper.destroy();
181
+ }
182
+ }
183
+ }
184
+
185
+ onMount(async () => {
186
+ if (tool === "color-sketch" && value && typeof value === "string") {
187
+ static_image = value;
188
+ await tick();
189
+ handle_image_load({ currentTarget: value_img });
190
+ }
191
+ });
192
+
193
+ function handle_click(evt: MouseEvent): void {
194
+ let coordinates = get_coordinates_of_clicked_image(evt);
195
+ if (coordinates) {
196
+ dispatch("select", { index: coordinates, value: null });
197
+ }
198
+ }
199
+ </script>
200
+
201
+ <BlockLabel
202
+ {show_label}
203
+ Icon={source === "canvas" ? SketchIcon : Image}
204
+ label={label || (source === "canvas" ? "Sketch" : "Image")}
205
+ />
206
+
207
+ <div
208
+ data-testid="image"
209
+ class="image-container"
210
+ bind:offsetHeight={max_height}
211
+ bind:offsetWidth={max_width}
212
+ >
213
+ {#if source === "upload"}
214
+ <Upload
215
+ bind:dragging
216
+ filetype="image/*"
217
+ on:load={handle_upload}
218
+ include_file_metadata={false}
219
+ disable_click={!!value}
220
+ {root}
221
+ >
222
+ {#if (value === null && !static_image) || streaming}
223
+ <slot />
224
+ {:else if tool === "select"}
225
+ <Cropper
226
+ bind:this={cropper}
227
+ image={value_.data}
228
+ on:crop={handle_save}
229
+ />
230
+ <ModifyUpload
231
+ {i18n}
232
+ on:clear={(e) => (handle_clear(e), (tool = "editor"))}
233
+ />
234
+ {:else if tool === "editor"}
235
+ <ModifyUpload
236
+ {i18n}
237
+ on:edit={() => (tool = "select")}
238
+ on:clear={handle_clear}
239
+ editable
240
+ />
241
+
242
+ <!-- TODO: fix-->
243
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
244
+ <!-- svelte-ignore a11y-no-noninteractive-element-interactions-->
245
+ <img
246
+ src={value_.data}
247
+ alt=""
248
+ class:scale-x-[-1]={source === "webcam" && mirror_webcam}
249
+ class:selectable
250
+ on:click={handle_click}
251
+ loading="lazy"
252
+ />
253
+ {:else if (tool === "sketch" || tool === "color-sketch") && (value !== null || static_image)}
254
+ {#key static_image}
255
+ <img
256
+ bind:this={value_img}
257
+ class="absolute-img"
258
+ src={static_image || value?.image?.data || value?.data}
259
+ alt=""
260
+ on:load={handle_image_load}
261
+ class:webcam={source === "webcam" && mirror_webcam}
262
+ loading="lazy"
263
+ crossorigin="anonymous"
264
+ />
265
+ {/key}
266
+ {#if img_width > 0}
267
+ <Sketch
268
+ {value}
269
+ bind:this={sketch}
270
+ bind:brush_radius
271
+ bind:brush_color
272
+ {mask_opacity}
273
+ on:change={handle_save}
274
+ {mode}
275
+ width={img_width || max_width}
276
+ height={img_height || max_height}
277
+ container_height={container_height || max_height}
278
+ {value_img}
279
+ {source}
280
+ {shape}
281
+ />
282
+ <ModifySketch
283
+ show_eraser={value_img}
284
+ on:undo={() => sketch.undo()}
285
+ on:clear_mask={handle_mask_clear}
286
+ on:remove_image={handle_sketch_clear}
287
+ />
288
+ {#if tool === "color-sketch" || tool === "sketch"}
289
+ <SketchSettings
290
+ bind:brush_radius
291
+ bind:brush_color
292
+ container_height={container_height || max_height}
293
+ img_width={img_width || max_width}
294
+ img_height={img_height || max_height}
295
+ {mode}
296
+ />
297
+ {/if}
298
+ {/if}
299
+ {:else}
300
+ <!-- TODO: fix-->
301
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
302
+ <!-- svelte-ignore a11y-no-noninteractive-element-interactions-->
303
+ <img
304
+ src={value.image || value}
305
+ alt=""
306
+ class:webcam={source === "webcam" && mirror_webcam}
307
+ class:selectable
308
+ on:click={handle_click}
309
+ loading="lazy"
310
+ />
311
+ {/if}
312
+ </Upload>
313
+ {:else if source === "canvas"}
314
+ <ModifySketch
315
+ on:undo={() => sketch.undo()}
316
+ on:remove_image={handle_sketch_clear}
317
+ />
318
+ {#if tool === "color-sketch"}
319
+ <SketchSettings
320
+ bind:brush_radius
321
+ bind:brush_color
322
+ container_height={container_height || max_height}
323
+ img_width={img_width || max_width}
324
+ img_height={img_height || max_height}
325
+ />
326
+ {/if}
327
+ <Sketch
328
+ {value}
329
+ bind:brush_radius
330
+ bind:brush_color
331
+ bind:this={sketch}
332
+ on:change={handle_save}
333
+ on:clear={handle_sketch_clear}
334
+ {mode}
335
+ width={img_width || max_width}
336
+ height={img_height || max_height}
337
+ container_height={container_height || max_height}
338
+ {shape}
339
+ />
340
+ {:else if (value === null && !static_image) || streaming}
341
+ {#if source === "webcam" && !static_image}
342
+ <Webcam
343
+ on:capture={(e) =>
344
+ tool === "color-sketch" ? handle_upload(e) : handle_save(e, true)}
345
+ on:stream={handle_save}
346
+ on:error
347
+ {streaming}
348
+ {pending}
349
+ {mirror_webcam}
350
+ />
351
+ {/if}
352
+ {:else if tool === "select"}
353
+ <Cropper bind:this={cropper} image={value.data} on:crop={handle_save} />
354
+ <ModifyUpload
355
+ {i18n}
356
+ on:clear={(e) => (handle_clear(e), (tool = "editor"))}
357
+ />
358
+ {:else if tool === "editor"}
359
+ <ModifyUpload
360
+ {i18n}
361
+ on:edit={() => (tool = "select")}
362
+ on:clear={handle_clear}
363
+ editable
364
+ />
365
+
366
+ <!-- TODO: fix -->
367
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
368
+ <!-- svelte-ignore a11y-no-noninteractive-element-interactions-->
369
+ <img
370
+ src={value_}
371
+ alt=""
372
+ class:selectable
373
+ class:webcam={source === "webcam" && mirror_webcam}
374
+ on:click={handle_click}
375
+ loading="lazy"
376
+ />
377
+ {:else if (tool === "sketch" || tool === "color-sketch") && (value !== null || static_image)}
378
+ {#key static_image}
379
+ <img
380
+ bind:this={value_img}
381
+ class="absolute-img"
382
+ src={static_image || value_}
383
+ alt=""
384
+ on:load={handle_image_load}
385
+ class:webcam={source === "webcam" && mirror_webcam}
386
+ loading="lazy"
387
+ />
388
+ {/key}
389
+ {#if img_width > 0}
390
+ <Sketch
391
+ {value}
392
+ bind:this={sketch}
393
+ bind:brush_radius
394
+ bind:brush_color
395
+ on:change={handle_save}
396
+ {mode}
397
+ width={img_width || max_width}
398
+ height={img_height || max_height}
399
+ container_height={container_height || max_height}
400
+ {value_img}
401
+ {source}
402
+ />
403
+ <ModifySketch
404
+ on:undo={() => sketch.undo()}
405
+ on:remove_image={handle_sketch_clear}
406
+ />
407
+ {#if tool === "color-sketch" || tool === "sketch"}
408
+ <SketchSettings
409
+ bind:brush_radius
410
+ bind:brush_color
411
+ container_height={container_height || max_height}
412
+ img_width={img_width || max_width}
413
+ img_height={img_height || max_height}
414
+ {mode}
415
+ />
416
+ {/if}
417
+ {/if}
418
+ {:else}
419
+ <!-- TODO: fix -->
420
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
421
+ <!-- svelte-ignore a11y-no-noninteractive-element-interactions-->
422
+
423
+ <img
424
+ src={value_.image || value_.data}
425
+ alt=""
426
+ class:webcam={source === "webcam" && mirror_webcam}
427
+ class:selectable
428
+ on:click={handle_click}
429
+ loading="lazy"
430
+ />
431
+ {/if}
432
+ </div>
433
+
434
+ <style>
435
+ .image-container,
436
+ img {
437
+ width: var(--size-full);
438
+ height: var(--size-full);
439
+ }
440
+ img {
441
+ object-fit: contain;
442
+ }
443
+
444
+ .selectable {
445
+ cursor: crosshair;
446
+ }
447
+
448
+ .absolute-img {
449
+ position: absolute;
450
+ opacity: 0;
451
+ }
452
+
453
+ .webcam {
454
+ transform: scaleX(-1);
455
+ }
456
+ </style>
src/frontend/shared/ImagePreview.svelte ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher } from "svelte";
3
+ import type { SelectData } from "@gradio/utils";
4
+ import { uploadToHuggingFace } from "@gradio/utils";
5
+ import { BlockLabel, Empty, IconButton, ShareButton } from "@gradio/atoms";
6
+ import { Download } from "@gradio/icons";
7
+ import { get_coordinates_of_clicked_image } from "./utils";
8
+
9
+ import { Image } from "@gradio/icons";
10
+ import { type FileData, normalise_file } from "@gradio/upload";
11
+ import type { I18nFormatter } from "@gradio/utils";
12
+
13
+ export let value: null | FileData;
14
+ let value_: null | FileData;
15
+ export let label: string | undefined = undefined;
16
+ export let show_label: boolean;
17
+ export let show_download_button = true;
18
+ export let selectable = false;
19
+ export let show_share_button = false;
20
+ export let root: string;
21
+ export let i18n: I18nFormatter;
22
+
23
+ const dispatch = createEventDispatcher<{
24
+ change: string;
25
+ select: SelectData;
26
+ }>();
27
+
28
+ $: value && dispatch("change", value.data);
29
+
30
+ $: if (value !== value_) {
31
+ value_ = value;
32
+ normalise_file(value_, root, null);
33
+ }
34
+
35
+ const handle_click = (evt: MouseEvent): void => {
36
+ let coordinates = get_coordinates_of_clicked_image(evt);
37
+ if (coordinates) {
38
+ dispatch("select", { index: coordinates, value: null });
39
+ }
40
+ };
41
+ </script>
42
+
43
+ <BlockLabel {show_label} Icon={Image} label={label || i18n("image.image")} />
44
+ {#if value_ === null}
45
+ <Empty unpadded_box={true} size="large"><Image /></Empty>
46
+ {:else}
47
+ <div class="icon-buttons">
48
+ {#if show_download_button}
49
+ <a
50
+ href={value_.data}
51
+ target={window.__is_colab__ ? "_blank" : null}
52
+ download={"image"}
53
+ >
54
+ <IconButton Icon={Download} label={i18n("common.download")} />
55
+ </a>
56
+ {/if}
57
+ {#if show_share_button}
58
+ <ShareButton
59
+ {i18n}
60
+ on:share
61
+ on:error
62
+ formatter={async (value) => {
63
+ if (!value) return "";
64
+ let url = await uploadToHuggingFace(value, "base64");
65
+ return `<img src="${url}" />`;
66
+ }}
67
+ {value}
68
+ />
69
+ {/if}
70
+ </div>
71
+ <button on:click={handle_click}>
72
+ <img src={value_.data} alt="" class:selectable loading="lazy" />
73
+ </button>
74
+ {/if}
75
+
76
+ <style>
77
+ img {
78
+ width: var(--size-full);
79
+ height: var(--size-full);
80
+ object-fit: contain;
81
+ }
82
+
83
+ .selectable {
84
+ cursor: crosshair;
85
+ }
86
+
87
+ .icon-buttons {
88
+ display: flex;
89
+ position: absolute;
90
+ top: 6px;
91
+ right: 6px;
92
+ gap: var(--size-1);
93
+ }
94
+ </style>
src/frontend/shared/ModifySketch.svelte ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher } from "svelte";
3
+ import { IconButton } from "@gradio/atoms";
4
+ import { Undo, Clear, Erase } from "@gradio/icons";
5
+
6
+ const dispatch = createEventDispatcher();
7
+
8
+ export let show_eraser = false;
9
+ </script>
10
+
11
+ <div>
12
+ <IconButton Icon={Undo} label="Undo" on:click={() => dispatch("undo")} />
13
+
14
+ {#if show_eraser}
15
+ <IconButton
16
+ Icon={Erase}
17
+ label="Clear"
18
+ on:click={(event) => {
19
+ dispatch("clear_mask");
20
+ event.stopPropagation();
21
+ }}
22
+ />
23
+ {/if}
24
+
25
+ <IconButton
26
+ Icon={Clear}
27
+ label="Remove Image"
28
+ on:click={(event) => {
29
+ dispatch("remove_image");
30
+ event.stopPropagation();
31
+ }}
32
+ />
33
+ </div>
34
+
35
+ <style>
36
+ div {
37
+ display: flex;
38
+ position: absolute;
39
+ top: var(--size-2);
40
+ right: var(--size-2);
41
+ justify-content: flex-end;
42
+ gap: var(--spacing-sm);
43
+ z-index: var(--layer-5);
44
+ }
45
+ </style>
src/frontend/shared/Sketch.svelte ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script>
2
+ // @ts-nocheck
3
+ /* eslint-disable */
4
+
5
+ import { onMount, onDestroy, createEventDispatcher, tick } from "svelte";
6
+ import { fade } from "svelte/transition";
7
+ import { LazyBrush } from "lazy-brush/src";
8
+ import ResizeObserver from "resize-observer-polyfill";
9
+
10
+ const dispatch = createEventDispatcher();
11
+
12
+ export let value;
13
+ export let value_img;
14
+ export let mode = "sketch";
15
+ export let brush_color = "#0b0f19";
16
+ export let brush_radius;
17
+ export let mask_opacity = 0.7;
18
+ export let source;
19
+
20
+ export let width = 400;
21
+ export let height = 200;
22
+ export let container_height = 200;
23
+ export let shape;
24
+
25
+ $: {
26
+ if (shape && (width || height)) {
27
+ width = shape[0];
28
+ height = shape[1];
29
+ }
30
+ }
31
+
32
+ let mounted;
33
+
34
+ let catenary_color = "#aaa";
35
+
36
+ let canvas_width = width;
37
+ let canvas_height = height;
38
+
39
+ $: mounted && !value && clear();
40
+
41
+ let last_value_img;
42
+
43
+ $: {
44
+ if (mounted && value_img !== last_value_img) {
45
+ last_value_img = value_img;
46
+
47
+ clear();
48
+
49
+ setTimeout(() => {
50
+ if (source === "webcam") {
51
+ ctx.temp.save();
52
+ ctx.temp.translate(width, 0);
53
+ ctx.temp.scale(-1, 1);
54
+ ctx.temp.drawImage(value_img, 0, 0);
55
+ ctx.temp.restore();
56
+ } else {
57
+ draw_cropped_image();
58
+ }
59
+
60
+ ctx.drawing.drawImage(canvas.temp, 0, 0, width, height);
61
+
62
+ draw_lines({ lines: lines.slice() });
63
+ trigger_on_change();
64
+ }, 50);
65
+ }
66
+ }
67
+
68
+ function mid_point(p1, p2) {
69
+ return {
70
+ x: p1.x + (p2.x - p1.x) / 2,
71
+ y: p1.y + (p2.y - p1.y) / 2
72
+ };
73
+ }
74
+
75
+ const canvas_types = [
76
+ {
77
+ name: "interface",
78
+ zIndex: 15
79
+ },
80
+ {
81
+ name: "mask",
82
+ zIndex: 13,
83
+ opacity: mask_opacity
84
+ },
85
+ {
86
+ name: "drawing",
87
+ zIndex: 11
88
+ },
89
+ {
90
+ name: "temp",
91
+ zIndex: 12
92
+ }
93
+ ];
94
+
95
+ let canvas = {};
96
+ let ctx = {};
97
+ let points = [];
98
+ let lines = [];
99
+ let mouse_has_moved = true;
100
+ let values_changed = true;
101
+ let is_drawing = false;
102
+ let is_pressing = false;
103
+ let lazy = null;
104
+ let canvas_container = null;
105
+ let canvas_observer = null;
106
+ let line_count = 0;
107
+
108
+ function draw_cropped_image() {
109
+ if (!shape) {
110
+ ctx.temp.drawImage(value_img, 0, 0, width, height);
111
+ return;
112
+ }
113
+
114
+ let _width = value_img.naturalWidth;
115
+ let _height = value_img.naturalHeight;
116
+
117
+ const shape_ratio = shape[0] / shape[1];
118
+ const image_ratio = _width / _height;
119
+
120
+ let x = 0;
121
+ let y = 0;
122
+
123
+ if (shape_ratio < image_ratio) {
124
+ _width = shape[1] * image_ratio;
125
+ _height = shape[1];
126
+ x = (shape[0] - _width) / 2;
127
+ } else if (shape_ratio > image_ratio) {
128
+ _width = shape[0];
129
+ _height = shape[0] / image_ratio;
130
+ y = (shape[1] - _height) / 2;
131
+ } else {
132
+ x = 0;
133
+ y = 0;
134
+ _width = shape[0];
135
+ _height = shape[1];
136
+ }
137
+
138
+ ctx.temp.drawImage(value_img, x, y, _width, _height);
139
+ }
140
+
141
+ onMount(async () => {
142
+ Object.keys(canvas).forEach((key) => {
143
+ ctx[key] = canvas[key].getContext("2d");
144
+ });
145
+
146
+ await tick();
147
+
148
+ if (value_img) {
149
+ value_img.addEventListener("load", (_) => {
150
+ if (source === "webcam") {
151
+ ctx.temp.save();
152
+ ctx.temp.translate(width, 0);
153
+ ctx.temp.scale(-1, 1);
154
+ ctx.temp.drawImage(value_img, 0, 0);
155
+ ctx.temp.restore();
156
+ } else {
157
+ draw_cropped_image();
158
+ }
159
+ ctx.drawing.drawImage(canvas.temp, 0, 0, width, height);
160
+
161
+ trigger_on_change();
162
+ });
163
+
164
+ setTimeout(() => {
165
+ if (source === "webcam") {
166
+ ctx.temp.save();
167
+ ctx.temp.translate(width, 0);
168
+ ctx.temp.scale(-1, 1);
169
+ ctx.temp.drawImage(value_img, 0, 0);
170
+ ctx.temp.restore();
171
+ } else {
172
+ draw_cropped_image();
173
+ }
174
+
175
+ ctx.drawing.drawImage(canvas.temp, 0, 0, width, height);
176
+
177
+ draw_lines({ lines: lines.slice() });
178
+ trigger_on_change();
179
+ }, 100);
180
+ }
181
+
182
+ lazy = new LazyBrush({
183
+ radius: brush_radius * 0.05,
184
+ enabled: true,
185
+ initialPoint: {
186
+ x: width / 2,
187
+ y: height / 2
188
+ }
189
+ });
190
+
191
+ canvas_observer = new ResizeObserver((entries, observer, ...rest) => {
192
+ handle_canvas_resize(entries, observer);
193
+ });
194
+ canvas_observer.observe(canvas_container);
195
+
196
+ loop();
197
+ mounted = true;
198
+
199
+ requestAnimationFrame(() => {
200
+ init();
201
+ requestAnimationFrame(() => {
202
+ clear();
203
+ });
204
+ });
205
+ });
206
+
207
+ function init() {
208
+ const initX = width / 2;
209
+ const initY = height / 2;
210
+ lazy.update({ x: initX, y: initY }, { both: true });
211
+ lazy.update({ x: initX, y: initY }, { both: false });
212
+ mouse_has_moved = true;
213
+ values_changed = true;
214
+ }
215
+
216
+ onDestroy(() => {
217
+ mounted = false;
218
+ canvas_observer.unobserve(canvas_container);
219
+ });
220
+
221
+ function redraw_image(_lines) {
222
+ clear_canvas();
223
+
224
+ if (value_img) {
225
+ if (source === "webcam") {
226
+ ctx.temp.save();
227
+ ctx.temp.translate(width, 0);
228
+ ctx.temp.scale(-1, 1);
229
+ ctx.temp.drawImage(value_img, 0, 0);
230
+ ctx.temp.restore();
231
+ } else {
232
+ draw_cropped_image();
233
+ }
234
+
235
+ if (!lines || !lines.length) {
236
+ ctx.drawing.drawImage(canvas.temp, 0, 0, width, height);
237
+ }
238
+ }
239
+
240
+ draw_lines({ lines: _lines });
241
+ line_count = _lines.length;
242
+
243
+ lines = _lines;
244
+ ctx.drawing.drawImage(canvas.temp, 0, 0, width, height);
245
+
246
+ if (lines.length == 0) {
247
+ dispatch("clear");
248
+ }
249
+ }
250
+
251
+ export function clear_mask() {
252
+ const _lines = [];
253
+
254
+ redraw_image(_lines);
255
+ trigger_on_change();
256
+ }
257
+
258
+ export function undo() {
259
+ const _lines = lines.slice(0, -1);
260
+
261
+ redraw_image(_lines);
262
+ trigger_on_change();
263
+ }
264
+
265
+ let get_save_data = () => {
266
+ return JSON.stringify({
267
+ lines: lines,
268
+ width: canvas_width,
269
+ height: canvas_height
270
+ });
271
+ };
272
+
273
+ let draw_lines = ({ lines }) => {
274
+ lines.forEach((line) => {
275
+ const { points: _points, brush_color, brush_radius } = line;
276
+ draw_points({
277
+ points: _points,
278
+ brush_color,
279
+ brush_radius,
280
+ mask: mode === "mask"
281
+ });
282
+ });
283
+
284
+ saveLine({ brush_color, brush_radius });
285
+ if (mode === "mask") {
286
+ save_mask_line();
287
+ }
288
+ };
289
+
290
+ let handle_draw_start = (e) => {
291
+ e.preventDefault();
292
+ is_pressing = true;
293
+ const { x, y } = get_pointer_pos(e);
294
+ if (e.touches && e.touches.length > 0) {
295
+ lazy.update({ x, y }, { both: true });
296
+ }
297
+ handle_pointer_move(x, y);
298
+ line_count += 1;
299
+ };
300
+
301
+ let handle_draw_move = (e) => {
302
+ e.preventDefault();
303
+ const { x, y } = get_pointer_pos(e);
304
+ handle_pointer_move(x, y);
305
+ };
306
+
307
+ let handle_draw_end = (e) => {
308
+ e.preventDefault();
309
+ handle_draw_move(e);
310
+ is_drawing = false;
311
+ is_pressing = false;
312
+ saveLine();
313
+
314
+ if (mode === "mask") {
315
+ save_mask_line();
316
+ }
317
+ };
318
+
319
+ let old_width = 0;
320
+ let old_height = 0;
321
+ let old_container_height = 0;
322
+ let add_lr_border = false;
323
+
324
+ let handle_canvas_resize = async () => {
325
+ if (shape && canvas_container) {
326
+ const x = canvas_container?.getBoundingClientRect();
327
+ const shape_ratio = shape[0] / shape[1];
328
+ const container_ratio = x.width / x.height;
329
+ add_lr_border = shape_ratio < container_ratio;
330
+ }
331
+
332
+ if (
333
+ width === old_width &&
334
+ height === old_height &&
335
+ old_container_height === container_height
336
+ ) {
337
+ return;
338
+ }
339
+ const dimensions = { width: width, height: height };
340
+
341
+ const container_dimensions = {
342
+ height: container_height,
343
+ width: container_height * (dimensions.width / dimensions.height)
344
+ };
345
+
346
+ await Promise.all([
347
+ set_canvas_size(canvas.interface, dimensions, container_dimensions),
348
+ set_canvas_size(canvas.drawing, dimensions, container_dimensions),
349
+ set_canvas_size(canvas.temp, dimensions, container_dimensions),
350
+ set_canvas_size(canvas.mask, dimensions, container_dimensions, false)
351
+ ]);
352
+
353
+ if (!brush_radius) {
354
+ brush_radius = 20 * (dimensions.width / container_dimensions.width);
355
+ }
356
+
357
+ loop({ once: true });
358
+
359
+ setTimeout(() => {
360
+ old_height = height;
361
+ old_width = width;
362
+ old_container_height = container_height;
363
+ }, 10);
364
+ await tick();
365
+
366
+ clear();
367
+ };
368
+
369
+ $: {
370
+ if (lazy) {
371
+ init();
372
+ lazy.setRadius(brush_radius * 0.05);
373
+ }
374
+ }
375
+
376
+ $: {
377
+ if (width || height) {
378
+ handle_canvas_resize();
379
+ }
380
+ }
381
+
382
+ let set_canvas_size = async (canvas, dimensions, container, scale = true) => {
383
+ if (!mounted) return;
384
+ await tick();
385
+
386
+ const dpr = window.devicePixelRatio || 1;
387
+ canvas.width = dimensions.width * (scale ? dpr : 1);
388
+ canvas.height = dimensions.height * (scale ? dpr : 1);
389
+
390
+ const ctx = canvas.getContext("2d");
391
+ scale && ctx.scale(dpr, dpr);
392
+
393
+ canvas.style.width = `${container.width}px`;
394
+ canvas.style.height = `${container.height}px`;
395
+ };
396
+
397
+ let get_pointer_pos = (e) => {
398
+ const rect = canvas.interface.getBoundingClientRect();
399
+
400
+ let clientX = e.clientX;
401
+ let clientY = e.clientY;
402
+ if (e.changedTouches && e.changedTouches.length > 0) {
403
+ clientX = e.changedTouches[0].clientX;
404
+ clientY = e.changedTouches[0].clientY;
405
+ }
406
+
407
+ return {
408
+ x: ((clientX - rect.left) / rect.width) * width,
409
+ y: ((clientY - rect.top) / rect.height) * height
410
+ };
411
+ };
412
+
413
+ let handle_pointer_move = (x, y) => {
414
+ lazy.update({ x: x, y: y });
415
+ const is_disabled = !lazy.isEnabled();
416
+ if ((is_pressing && !is_drawing) || (is_disabled && is_pressing)) {
417
+ is_drawing = true;
418
+ points.push(lazy.brush.toObject());
419
+ }
420
+ if (is_drawing) {
421
+ points.push(lazy.brush.toObject());
422
+ draw_points({
423
+ points: points,
424
+ brush_color,
425
+ brush_radius,
426
+ mask: mode === "mask"
427
+ });
428
+ }
429
+ mouse_has_moved = true;
430
+ };
431
+
432
+ let draw_points = ({ points, brush_color, brush_radius, mask }) => {
433
+ if (!points || points.length < 2) return;
434
+ let target_ctx = mask ? ctx.mask : ctx.temp;
435
+ target_ctx.lineJoin = "round";
436
+ target_ctx.lineCap = "round";
437
+
438
+ target_ctx.strokeStyle = brush_color;
439
+ target_ctx.lineWidth = brush_radius;
440
+ let p1 = points[0];
441
+ let p2 = points[1];
442
+ target_ctx.moveTo(p2.x, p2.y);
443
+ target_ctx.beginPath();
444
+ for (var i = 1, len = points.length; i < len; i++) {
445
+ var midPoint = mid_point(p1, p2);
446
+ target_ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
447
+ p1 = points[i];
448
+ p2 = points[i + 1];
449
+ }
450
+
451
+ target_ctx.lineTo(p1.x, p1.y);
452
+ target_ctx.stroke();
453
+ };
454
+
455
+ let save_mask_line = () => {
456
+ if (points.length < 1) return;
457
+ points.length = 0;
458
+
459
+ trigger_on_change();
460
+ };
461
+
462
+ let saveLine = () => {
463
+ if (points.length < 1) return;
464
+
465
+ lines.push({
466
+ points: points.slice(),
467
+ brush_color: brush_color,
468
+ brush_radius
469
+ });
470
+
471
+ if (mode !== "mask") {
472
+ points.length = 0;
473
+ }
474
+
475
+ ctx.drawing.drawImage(canvas.temp, 0, 0, width, height);
476
+
477
+ trigger_on_change();
478
+ };
479
+
480
+ let trigger_on_change = () => {
481
+ const x = get_image_data();
482
+ dispatch("change", x);
483
+ };
484
+
485
+ export function clear() {
486
+ lines = [];
487
+ clear_canvas();
488
+ line_count = 0;
489
+
490
+ return true;
491
+ }
492
+
493
+ function clear_canvas() {
494
+ values_changed = true;
495
+ ctx.temp.clearRect(0, 0, width, height);
496
+
497
+ ctx.temp.fillStyle = mode === "mask" ? "transparent" : "#FFFFFF";
498
+ ctx.temp.fillRect(0, 0, width, height);
499
+
500
+ if (mode === "mask") {
501
+ ctx.mask.clearRect(0, 0, canvas.mask.width, canvas.mask.height);
502
+ }
503
+ }
504
+
505
+ let loop = ({ once = false } = {}) => {
506
+ if (mouse_has_moved || values_changed) {
507
+ const pointer = lazy.getPointerCoordinates();
508
+ const brush = lazy.getBrushCoordinates();
509
+ draw_interface(ctx.interface, pointer, brush);
510
+ mouse_has_moved = false;
511
+ values_changed = false;
512
+ }
513
+ if (!once) {
514
+ window.requestAnimationFrame(() => {
515
+ loop();
516
+ });
517
+ }
518
+ };
519
+
520
+ $: brush_dot = brush_radius * 0.075;
521
+
522
+ let draw_interface = (ctx, pointer, brush) => {
523
+ ctx.clearRect(0, 0, width, height);
524
+
525
+ // brush preview
526
+ ctx.beginPath();
527
+ ctx.fillStyle = brush_color;
528
+ ctx.arc(brush.x, brush.y, brush_radius / 2, 0, Math.PI * 2, true);
529
+ ctx.fill();
530
+
531
+ // tiny brush point dot
532
+ ctx.beginPath();
533
+ ctx.fillStyle = catenary_color;
534
+ ctx.arc(brush.x, brush.y, brush_dot, 0, Math.PI * 2, true);
535
+ ctx.fill();
536
+ };
537
+
538
+ export function get_image_data() {
539
+ return mode === "mask"
540
+ ? canvas.mask.toDataURL("image/png")
541
+ : canvas.drawing.toDataURL("image/jpg");
542
+ }
543
+ </script>
544
+
545
+ <div
546
+ class="wrap"
547
+ bind:this={canvas_container}
548
+ bind:offsetWidth={canvas_width}
549
+ bind:offsetHeight={canvas_height}
550
+ >
551
+ {#if line_count === 0}
552
+ <div transition:fade={{ duration: 50 }} class="start-prompt">
553
+ Start drawing
554
+ </div>
555
+ {/if}
556
+ {#each canvas_types as { name, zIndex, opacity }}
557
+ <canvas
558
+ key={name}
559
+ style=" z-index:{zIndex};"
560
+ style:opacity
561
+ class:lr={add_lr_border}
562
+ class:tb={!add_lr_border}
563
+ bind:this={canvas[name]}
564
+ on:mousedown={name === "interface" ? handle_draw_start : undefined}
565
+ on:mousemove={name === "interface" ? handle_draw_move : undefined}
566
+ on:mouseup={name === "interface" ? handle_draw_end : undefined}
567
+ on:mouseout={name === "interface" ? handle_draw_end : undefined}
568
+ on:blur={name === "interface" ? handle_draw_end : undefined}
569
+ on:touchstart={name === "interface" ? handle_draw_start : undefined}
570
+ on:touchmove={name === "interface" ? handle_draw_move : undefined}
571
+ on:touchend={name === "interface" ? handle_draw_end : undefined}
572
+ on:touchcancel={name === "interface" ? handle_draw_end : undefined}
573
+ on:click|stopPropagation
574
+ />
575
+ {/each}
576
+ </div>
577
+
578
+ <style>
579
+ canvas {
580
+ display: block;
581
+ position: absolute;
582
+ top: 0px;
583
+ right: 0px;
584
+ bottom: 0px;
585
+ left: 0px;
586
+ margin: auto;
587
+ }
588
+
589
+ .lr {
590
+ border-right: 1px solid var(--border-color-primary);
591
+ border-left: 1px solid var(--border-color-primary);
592
+ }
593
+
594
+ .tb {
595
+ border-top: 1px solid var(--border-color-primary);
596
+ border-bottom: 1px solid var(--border-color-primary);
597
+ }
598
+
599
+ canvas:hover {
600
+ cursor: none;
601
+ }
602
+
603
+ .wrap {
604
+ position: relative;
605
+ width: var(--size-full);
606
+ height: var(--size-full);
607
+ touch-action: none;
608
+ }
609
+
610
+ .start-prompt {
611
+ display: flex;
612
+ position: absolute;
613
+ top: 0px;
614
+ right: 0px;
615
+ bottom: 0px;
616
+ left: 0px;
617
+ justify-content: center;
618
+ align-items: center;
619
+ z-index: var(--layer-4);
620
+ touch-action: none;
621
+ pointer-events: none;
622
+ color: var(--body-text-color-subdued);
623
+ }
624
+ </style>
src/frontend/shared/SketchSettings.svelte ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { IconButton } from "@gradio/atoms";
3
+ import { Brush, Color } from "@gradio/icons";
4
+
5
+ let show_size = false;
6
+ let show_col = false;
7
+
8
+ export let brush_radius = 20;
9
+ export let brush_color = "#000";
10
+ export let container_height: number;
11
+ export let img_width: number;
12
+ export let img_height: number;
13
+ export let mode: "mask" | "other" = "other";
14
+
15
+ $: width = container_height * (img_width / img_height);
16
+ </script>
17
+
18
+ <div class="wrap">
19
+ <span class="brush">
20
+ <IconButton
21
+ Icon={Brush}
22
+ label="Use brush"
23
+ on:click={() => (show_size = !show_size)}
24
+ />
25
+ {#if show_size}
26
+ <input
27
+ aria-label="Brush radius"
28
+ bind:value={brush_radius}
29
+ type="range"
30
+ min={0.5 * (img_width / width)}
31
+ max={75 * (img_width / width)}
32
+ />
33
+ {/if}
34
+ </span>
35
+
36
+ {#if mode !== "mask"}
37
+ <span class="col">
38
+ <IconButton
39
+ Icon={Color}
40
+ label="Select brush color"
41
+ on:click={() => (show_col = !show_col)}
42
+ />
43
+ {#if show_col}
44
+ <input aria-label="Brush color" bind:value={brush_color} type="color" />
45
+ {/if}
46
+ </span>
47
+ {/if}
48
+ </div>
49
+
50
+ <style>
51
+ .wrap {
52
+ display: flex;
53
+ position: absolute;
54
+ top: var(--size-10);
55
+ right: var(--size-2);
56
+ flex-direction: column;
57
+ justify-content: flex-end;
58
+ gap: var(--spacing-sm);
59
+ z-index: var(--layer-5);
60
+ }
61
+ .brush {
62
+ top: 0;
63
+ right: 0;
64
+ }
65
+
66
+ .brush input {
67
+ position: absolute;
68
+ top: 3px;
69
+ right: calc(100% + 5px);
70
+ }
71
+
72
+ .col input {
73
+ position: absolute;
74
+ right: calc(100% + 5px);
75
+ bottom: -4px;
76
+ }
77
+ </style>
src/frontend/shared/Webcam.svelte ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher, onMount } from "svelte";
3
+ import { Camera, Circle, Square } from "@gradio/icons";
4
+ import type { I18nFormatter } from "js/utils/src";
5
+
6
+ let video_source: HTMLVideoElement;
7
+ let canvas: HTMLCanvasElement;
8
+ export let streaming = false;
9
+ export let pending = false;
10
+
11
+ export let mode: "image" | "video" = "image";
12
+ export let mirror_webcam: boolean;
13
+ export let include_audio: boolean;
14
+ export let i18n: I18nFormatter;
15
+
16
+ const dispatch = createEventDispatcher<{
17
+ stream: undefined;
18
+ capture:
19
+ | {
20
+ data: FileReader["result"];
21
+ name: string;
22
+ is_example?: boolean;
23
+ is_file: boolean;
24
+ }
25
+ | string;
26
+ error: string;
27
+ start_recording: undefined;
28
+ stop_recording: undefined;
29
+ }>();
30
+
31
+ onMount(() => (canvas = document.createElement("canvas")));
32
+
33
+ async function access_webcam(): Promise<void> {
34
+ try {
35
+ stream = await navigator.mediaDevices.getUserMedia({
36
+ video: true,
37
+ audio: include_audio
38
+ });
39
+ video_source.srcObject = stream;
40
+ video_source.muted = true;
41
+ video_source.play();
42
+ } catch (err) {
43
+ if (err instanceof DOMException && err.name == "NotAllowedError") {
44
+ dispatch("error", i18n("image.allow_webcam_access"));
45
+ } else {
46
+ throw err;
47
+ }
48
+ }
49
+ }
50
+
51
+ function take_picture(): void {
52
+ var context = canvas.getContext("2d")!;
53
+
54
+ if (video_source.videoWidth && video_source.videoHeight) {
55
+ canvas.width = video_source.videoWidth;
56
+ canvas.height = video_source.videoHeight;
57
+ context.drawImage(
58
+ video_source,
59
+ 0,
60
+ 0,
61
+ video_source.videoWidth,
62
+ video_source.videoHeight
63
+ );
64
+
65
+ var data = canvas.toDataURL("image/png");
66
+ dispatch(streaming ? "stream" : "capture", data);
67
+ }
68
+ }
69
+
70
+ let recording = false;
71
+ let recorded_blobs: BlobPart[] = [];
72
+ let stream: MediaStream;
73
+ let mimeType: string;
74
+ let media_recorder: MediaRecorder;
75
+
76
+ function take_recording(): void {
77
+ if (recording) {
78
+ media_recorder.stop();
79
+ let video_blob = new Blob(recorded_blobs, { type: mimeType });
80
+ let ReaderObj = new FileReader();
81
+ ReaderObj.onload = function (e): void {
82
+ if (e.target) {
83
+ dispatch("capture", {
84
+ data: e.target.result,
85
+ name: "sample." + mimeType.substring(6),
86
+ is_example: false,
87
+ is_file: false
88
+ });
89
+ dispatch("stop_recording");
90
+ }
91
+ };
92
+ ReaderObj.readAsDataURL(video_blob);
93
+ } else {
94
+ dispatch("start_recording");
95
+ recorded_blobs = [];
96
+ let validMimeTypes = ["video/webm", "video/mp4"];
97
+ for (let validMimeType of validMimeTypes) {
98
+ if (MediaRecorder.isTypeSupported(validMimeType)) {
99
+ mimeType = validMimeType;
100
+ break;
101
+ }
102
+ }
103
+ if (mimeType === null) {
104
+ console.error("No supported MediaRecorder mimeType");
105
+ return;
106
+ }
107
+ media_recorder = new MediaRecorder(stream, {
108
+ mimeType: mimeType
109
+ });
110
+ media_recorder.addEventListener("dataavailable", function (e) {
111
+ recorded_blobs.push(e.data);
112
+ });
113
+ media_recorder.start(200);
114
+ }
115
+ recording = !recording;
116
+ }
117
+
118
+ access_webcam();
119
+
120
+ if (streaming && mode === "image") {
121
+ window.setInterval(() => {
122
+ if (video_source && !pending) {
123
+ take_picture();
124
+ }
125
+ }, 500);
126
+ }
127
+ </script>
128
+
129
+ <div class="wrap">
130
+ <!-- svelte-ignore a11y-media-has-caption -->
131
+ <!-- need to suppress for video streaming https://github.com/sveltejs/svelte/issues/5967 -->
132
+ <video bind:this={video_source} class:flip={mirror_webcam} />
133
+ {#if !streaming}
134
+ <button
135
+ on:click={mode === "image" ? take_picture : take_recording}
136
+ aria-label={mode === "image" ? "capture photo" : "start recording"}
137
+ >
138
+ {#if mode === "video"}
139
+ {#if recording}
140
+ <div class="icon" title="stop recording">
141
+ <Square />
142
+ </div>
143
+ {:else}
144
+ <div class="icon" title="start recording">
145
+ <Circle />
146
+ </div>
147
+ {/if}
148
+ {:else}
149
+ <div class="icon" title="capture photo">
150
+ <Camera />
151
+ </div>
152
+ {/if}
153
+ </button>
154
+ {/if}
155
+ </div>
156
+
157
+ <style>
158
+ .wrap {
159
+ position: relative;
160
+ width: var(--size-full);
161
+ height: var(--size-full);
162
+ min-height: var(--size-60);
163
+ }
164
+
165
+ video {
166
+ width: var(--size-full);
167
+ height: var(--size-full);
168
+ }
169
+
170
+ button {
171
+ display: flex;
172
+ position: absolute;
173
+ right: 0px;
174
+ bottom: var(--size-2);
175
+ left: 0px;
176
+ justify-content: center;
177
+ align-items: center;
178
+ margin: auto;
179
+ box-shadow: var(--shadow-drop-lg);
180
+ border-radius: var(--radius-xl);
181
+ background-color: rgba(0, 0, 0, 0.9);
182
+ width: var(--size-10);
183
+ height: var(--size-10);
184
+ }
185
+
186
+ @media (--screen-md) {
187
+ button {
188
+ bottom: var(--size-4);
189
+ }
190
+ }
191
+
192
+ @media (--screen-xl) {
193
+ button {
194
+ bottom: var(--size-8);
195
+ }
196
+ }
197
+
198
+ .icon {
199
+ opacity: 0.8;
200
+ width: 50%;
201
+ height: 50%;
202
+ color: white;
203
+ }
204
+
205
+ .flip {
206
+ transform: scaleX(-1);
207
+ }
208
+ </style>
src/frontend/shared/utils.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const get_coordinates_of_clicked_image = (
2
+ evt: MouseEvent
3
+ ): [number, number] | null => {
4
+ let image = evt.currentTarget as HTMLImageElement;
5
+
6
+ const imageRect = image.getBoundingClientRect();
7
+ const xScale = image.naturalWidth / imageRect.width;
8
+ const yScale = image.naturalHeight / imageRect.height;
9
+ if (xScale > yScale) {
10
+ const displayed_height = image.naturalHeight / xScale;
11
+ const y_offset = (imageRect.height - displayed_height) / 2;
12
+ var x = Math.round((evt.clientX - imageRect.left) * xScale);
13
+ var y = Math.round((evt.clientY - imageRect.top - y_offset) * xScale);
14
+ } else {
15
+ const displayed_width = image.naturalWidth / yScale;
16
+ const x_offset = (imageRect.width - displayed_width) / 2;
17
+ var x = Math.round((evt.clientX - imageRect.left - x_offset) * yScale);
18
+ var y = Math.round((evt.clientY - imageRect.top) * yScale);
19
+ }
20
+ if (x < 0 || x >= image.naturalWidth || y < 0 || y >= image.naturalHeight) {
21
+ return null;
22
+ }
23
+ return [x, y];
24
+ };
src/pyproject.toml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = [
3
+ "hatchling",
4
+ "hatch-requirements-txt",
5
+ "hatch-fancy-pypi-readme>=22.5.0",
6
+ ]
7
+ build-backend = "hatchling.build"
8
+
9
+ [project]
10
+ name = "gradio_coolimage"
11
+ version = "0.0.1"
12
+ description = "Python library for easily interacting with trained machine learning models"
13
+ readme = "README.md"
14
+ license = "Apache-2.0"
15
+ requires-python = ">=3.8"
16
+ authors = [{ name = "YOUR NAME", email = "YOUREMAIL@domain.com" }]
17
+ keywords = [
18
+ "machine learning",
19
+ "reproducibility",
20
+ "visualization",
21
+ "gradio",
22
+ "gradio custom component",
23
+ "gradio-template-Image"
24
+ ]
25
+ # Add dependencies here
26
+ dependencies = ["gradio"]
27
+ classifiers = [
28
+ 'Development Status :: 3 - Alpha',
29
+ 'License :: OSI Approved :: Apache Software License',
30
+ 'Operating System :: OS Independent',
31
+ 'Programming Language :: Python :: 3',
32
+ 'Programming Language :: Python :: 3 :: Only',
33
+ 'Programming Language :: Python :: 3.8',
34
+ 'Programming Language :: Python :: 3.9',
35
+ 'Programming Language :: Python :: 3.10',
36
+ 'Programming Language :: Python :: 3.11',
37
+ 'Topic :: Scientific/Engineering',
38
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
39
+ 'Topic :: Scientific/Engineering :: Visualization',
40
+ ]
41
+
42
+ [project.optional-dependencies]
43
+ dev = ["build", "twine"]
44
+
45
+ [tool.hatch.build]
46
+ artifacts = ["/backend/gradio_coolimage/templates", "*.pyi", "backend/gradio_coolimage/templates"]
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["/backend/gradio_coolimage"]