edgargg commited on
Commit
458a49d
·
verified ·
1 Parent(s): 9a8b071

Upload folder using huggingface_hub

Browse files
Files changed (44) hide show
  1. README.md +14 -30
  2. app.py +109 -109
  3. space.py +2 -2
  4. src/.github/workflows/python-publish.yml +39 -39
  5. src/LICENSE +21 -21
  6. src/README.md +14 -14
  7. src/backend/gradio_image_annotation/image_annotator.py +358 -358
  8. src/backend/gradio_image_annotation/templates/component/index.js +0 -0
  9. src/demo/app.py +109 -109
  10. src/demo/space.py +2 -2
  11. src/frontend/Example.svelte +48 -48
  12. src/frontend/Index.svelte +143 -143
  13. src/frontend/package-lock.json +0 -0
  14. src/frontend/package.json +35 -35
  15. src/frontend/shared/AnnotatedImageData.ts +8 -8
  16. src/frontend/shared/Box.ts +567 -567
  17. src/frontend/shared/Canvas.svelte +869 -872
  18. src/frontend/shared/ClearImage.svelte +30 -30
  19. src/frontend/shared/Colors.js +15 -15
  20. src/frontend/shared/ImageAnnotator.svelte +248 -248
  21. src/frontend/shared/ImageCanvas.svelte +80 -80
  22. src/frontend/shared/ModalBox.svelte +189 -189
  23. src/frontend/shared/WindowViewer.ts +115 -115
  24. src/frontend/shared/icons/Label.svelte +15 -15
  25. src/frontend/shared/icons/Lock.svelte +14 -14
  26. src/frontend/shared/icons/Unlock.svelte +14 -14
  27. src/frontend/shared/icons/index.ts +6 -6
  28. src/frontend/shared/index.ts +1 -1
  29. src/frontend/shared/patched_dropdown/CHANGELOG.md +245 -245
  30. src/frontend/shared/patched_dropdown/Dropdown.stories.svelte +60 -60
  31. src/frontend/shared/patched_dropdown/Example.svelte +33 -33
  32. src/frontend/shared/patched_dropdown/Index.svelte +99 -99
  33. src/frontend/shared/patched_dropdown/LICENSE +201 -201
  34. src/frontend/shared/patched_dropdown/Multiselect.stories.svelte +48 -48
  35. src/frontend/shared/patched_dropdown/README.md +43 -43
  36. src/frontend/shared/patched_dropdown/dropdown.test.ts +515 -515
  37. src/frontend/shared/patched_dropdown/package.json +20 -20
  38. src/frontend/shared/patched_dropdown/shared/Dropdown.svelte +326 -326
  39. src/frontend/shared/patched_dropdown/shared/DropdownOptions.svelte +144 -144
  40. src/frontend/shared/patched_dropdown/shared/Multiselect.svelte +416 -416
  41. src/frontend/shared/patched_dropdown/shared/utils.ts +56 -56
  42. src/frontend/shared/utils.ts +29 -29
  43. src/package.json +5 -5
  44. src/pyproject.toml +2 -2
README.md CHANGED
@@ -1,19 +1,3 @@
1
- ---
2
- tags:
3
- - gradio-custom-component
4
- - gradio-template-Image
5
- - bounding box
6
- - annotator
7
- - annotate
8
- - boxes
9
- title: gradio_image_annotation V0.4.0
10
- colorFrom: yellow
11
- colorTo: green
12
- sdk: docker
13
- pinned: false
14
- license: apache-2.0
15
- short_description: A Gradio component for image annotation
16
- ---
17
 
18
  # `gradio_image_annotation`
19
  <a href="https://pypi.org/project/gradio_image_annotation/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/gradio_image_annotation"></a>
@@ -184,11 +168,11 @@ dict | None
184
  <td align="left" style="width: 25%;">
185
 
186
  ```python
187
- float | None
188
  ```
189
 
190
  </td>
191
- <td align="left"><code>None</code></td>
192
  <td align="left">Opacity of the bounding boxes 0 and 1.</td>
193
  </tr>
194
 
@@ -197,11 +181,11 @@ float | None
197
  <td align="left" style="width: 25%;">
198
 
199
  ```python
200
- list[str] | None
201
  ```
202
 
203
  </td>
204
- <td align="left"><code>None</code></td>
205
  <td align="left">List of valid labels.</td>
206
  </tr>
207
 
@@ -210,11 +194,11 @@ list[str] | None
210
  <td align="left" style="width: 25%;">
211
 
212
  ```python
213
- list[str] | None
214
  ```
215
 
216
  </td>
217
- <td align="left"><code>None</code></td>
218
  <td align="left">Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).</td>
219
  </tr>
220
 
@@ -223,11 +207,11 @@ list[str] | None
223
  <td align="left" style="width: 25%;">
224
 
225
  ```python
226
- int | None
227
  ```
228
 
229
  </td>
230
- <td align="left"><code>None</code></td>
231
  <td align="left">Minimum valid bounding box size.</td>
232
  </tr>
233
 
@@ -236,11 +220,11 @@ int | None
236
  <td align="left" style="width: 25%;">
237
 
238
  ```python
239
- int | None
240
  ```
241
 
242
  </td>
243
- <td align="left"><code>None</code></td>
244
  <td align="left">Size of the bounding box resize handles.</td>
245
  </tr>
246
 
@@ -249,11 +233,11 @@ int | None
249
  <td align="left" style="width: 25%;">
250
 
251
  ```python
252
- int | None
253
  ```
254
 
255
  </td>
256
- <td align="left"><code>None</code></td>
257
  <td align="left">Thickness of the bounding box outline.</td>
258
  </tr>
259
 
@@ -262,11 +246,11 @@ int | None
262
  <td align="left" style="width: 25%;">
263
 
264
  ```python
265
- int | None
266
  ```
267
 
268
  </td>
269
- <td align="left"><code>None</code></td>
270
  <td align="left">Thickness of the bounding box outline when it is selected.</td>
271
  </tr>
272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
  # `gradio_image_annotation`
3
  <a href="https://pypi.org/project/gradio_image_annotation/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/gradio_image_annotation"></a>
 
168
  <td align="left" style="width: 25%;">
169
 
170
  ```python
171
+ float
172
  ```
173
 
174
  </td>
175
+ <td align="left"><code>0.5</code></td>
176
  <td align="left">Opacity of the bounding boxes 0 and 1.</td>
177
  </tr>
178
 
 
181
  <td align="left" style="width: 25%;">
182
 
183
  ```python
184
+ list[str]
185
  ```
186
 
187
  </td>
188
+ <td align="left"><code>[]</code></td>
189
  <td align="left">List of valid labels.</td>
190
  </tr>
191
 
 
194
  <td align="left" style="width: 25%;">
195
 
196
  ```python
197
+ list[str]
198
  ```
199
 
200
  </td>
201
+ <td align="left"><code>[]</code></td>
202
  <td align="left">Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).</td>
203
  </tr>
204
 
 
207
  <td align="left" style="width: 25%;">
208
 
209
  ```python
210
+ int
211
  ```
212
 
213
  </td>
214
+ <td align="left"><code>10</code></td>
215
  <td align="left">Minimum valid bounding box size.</td>
216
  </tr>
217
 
 
220
  <td align="left" style="width: 25%;">
221
 
222
  ```python
223
+ int
224
  ```
225
 
226
  </td>
227
+ <td align="left"><code>8</code></td>
228
  <td align="left">Size of the bounding box resize handles.</td>
229
  </tr>
230
 
 
233
  <td align="left" style="width: 25%;">
234
 
235
  ```python
236
+ int
237
  ```
238
 
239
  </td>
240
+ <td align="left"><code>2</code></td>
241
  <td align="left">Thickness of the bounding box outline.</td>
242
  </tr>
243
 
 
246
  <td align="left" style="width: 25%;">
247
 
248
  ```python
249
+ int
250
  ```
251
 
252
  </td>
253
+ <td align="left"><code>4</code></td>
254
  <td align="left">Thickness of the bounding box outline when it is selected.</td>
255
  </tr>
256
 
app.py CHANGED
@@ -1,109 +1,109 @@
1
- import gradio as gr
2
- from gradio_image_annotation import image_annotator
3
- import numpy as np
4
-
5
-
6
- example_annotation = {
7
- "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
8
- "boxes": [
9
- {
10
- "xmin": 636,
11
- "ymin": 575,
12
- "xmax": 801,
13
- "ymax": 697,
14
- "label": "Vehicle",
15
- "color": (255, 0, 0)
16
- },
17
- {
18
- "xmin": 360,
19
- "ymin": 615,
20
- "xmax": 386,
21
- "ymax": 702,
22
- "label": "Person",
23
- "color": (0, 255, 0)
24
- }
25
- ]
26
- }
27
-
28
- examples_crop = [
29
- {
30
- "image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
31
- "boxes": [
32
- {
33
- "xmin": 30,
34
- "ymin": 70,
35
- "xmax": 530,
36
- "ymax": 500,
37
- "color": (100, 200, 255),
38
- }
39
- ],
40
- },
41
- {
42
- "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
43
- "boxes": [
44
- {
45
- "xmin": 636,
46
- "ymin": 575,
47
- "xmax": 801,
48
- "ymax": 697,
49
- "color": (255, 0, 0),
50
- },
51
- ],
52
- },
53
- ]
54
-
55
-
56
- def crop(annotations):
57
- if angle := annotations.get("orientation", None):
58
- annotations["image"] = np.rot90(annotations["image"], k=-angle)
59
- if annotations["boxes"]:
60
- box = annotations["boxes"][0]
61
- return annotations["image"][
62
- box["ymin"]:box["ymax"],
63
- box["xmin"]:box["xmax"]
64
- ]
65
- return None
66
-
67
-
68
- def get_boxes_json(annotations):
69
- return annotations["boxes"]
70
-
71
-
72
- with gr.Blocks() as demo:
73
- with gr.Tab("Object annotation", id="tab_object_annotation"):
74
- annotator = image_annotator(
75
- example_annotation,
76
- label_list=["Person", "Vehicle"],
77
- label_colors=[(0, 255, 0), (255, 0, 0)],
78
- )
79
- button_get = gr.Button("Get bounding boxes")
80
- json_boxes = gr.JSON()
81
- button_get.click(get_boxes_json, annotator, json_boxes)
82
-
83
- with gr.Tab("Crop", id="tab_crop"):
84
- with gr.Row():
85
- annotator_crop = image_annotator(
86
- examples_crop[0],
87
- image_type="numpy",
88
- disable_edit_boxes=True,
89
- single_box=True,
90
- )
91
- image_crop = gr.Image()
92
- button_crop = gr.Button("Crop")
93
- button_crop.click(crop, annotator_crop, image_crop)
94
-
95
- gr.Examples(examples_crop, annotator_crop)
96
-
97
- with gr.Accordion("Keyboard Shortcuts"):
98
- gr.Markdown("""
99
- - ``C``: Create mode
100
- - ``D``: Drag mode
101
- - ``E``: Edit selected box (same as double-click a box)
102
- - ``Delete``: Remove selected box
103
- - ``Space``: Reset view (zoom/pan)
104
- - ``Enter``: Confirm modal dialog
105
- - ``Escape``: Cancel/close modal dialog
106
- """)
107
-
108
- if __name__ == "__main__":
109
- demo.launch()
 
1
+ import gradio as gr
2
+ from gradio_image_annotation import image_annotator
3
+ import numpy as np
4
+
5
+
6
+ example_annotation = {
7
+ "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
8
+ "boxes": [
9
+ {
10
+ "xmin": 636,
11
+ "ymin": 575,
12
+ "xmax": 801,
13
+ "ymax": 697,
14
+ "label": "Vehicle",
15
+ "color": (255, 0, 0)
16
+ },
17
+ {
18
+ "xmin": 360,
19
+ "ymin": 615,
20
+ "xmax": 386,
21
+ "ymax": 702,
22
+ "label": "Person",
23
+ "color": (0, 255, 0)
24
+ }
25
+ ]
26
+ }
27
+
28
+ examples_crop = [
29
+ {
30
+ "image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
31
+ "boxes": [
32
+ {
33
+ "xmin": 30,
34
+ "ymin": 70,
35
+ "xmax": 530,
36
+ "ymax": 500,
37
+ "color": (100, 200, 255),
38
+ }
39
+ ],
40
+ },
41
+ {
42
+ "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
43
+ "boxes": [
44
+ {
45
+ "xmin": 636,
46
+ "ymin": 575,
47
+ "xmax": 801,
48
+ "ymax": 697,
49
+ "color": (255, 0, 0),
50
+ },
51
+ ],
52
+ },
53
+ ]
54
+
55
+
56
+ def crop(annotations):
57
+ if angle := annotations.get("orientation", None):
58
+ annotations["image"] = np.rot90(annotations["image"], k=-angle)
59
+ if annotations["boxes"]:
60
+ box = annotations["boxes"][0]
61
+ return annotations["image"][
62
+ box["ymin"]:box["ymax"],
63
+ box["xmin"]:box["xmax"]
64
+ ]
65
+ return None
66
+
67
+
68
+ def get_boxes_json(annotations):
69
+ return annotations["boxes"]
70
+
71
+
72
+ with gr.Blocks() as demo:
73
+ with gr.Tab("Object annotation", id="tab_object_annotation"):
74
+ annotator = image_annotator(
75
+ example_annotation,
76
+ label_list=["Person", "Vehicle"],
77
+ label_colors=[(0, 255, 0), (255, 0, 0)],
78
+ )
79
+ button_get = gr.Button("Get bounding boxes")
80
+ json_boxes = gr.JSON()
81
+ button_get.click(get_boxes_json, annotator, json_boxes)
82
+
83
+ with gr.Tab("Crop", id="tab_crop"):
84
+ with gr.Row():
85
+ annotator_crop = image_annotator(
86
+ examples_crop[0],
87
+ image_type="numpy",
88
+ disable_edit_boxes=True,
89
+ single_box=True,
90
+ )
91
+ image_crop = gr.Image()
92
+ button_crop = gr.Button("Crop")
93
+ button_crop.click(crop, annotator_crop, image_crop)
94
+
95
+ gr.Examples(examples_crop, annotator_crop)
96
+
97
+ with gr.Accordion("Keyboard Shortcuts"):
98
+ gr.Markdown("""
99
+ - ``C``: Create mode
100
+ - ``D``: Drag mode
101
+ - ``E``: Edit selected box (same as double-click a box)
102
+ - ``Delete``: Remove selected box
103
+ - ``Space``: Reset view (zoom/pan)
104
+ - ``Enter``: Confirm modal dialog
105
+ - ``Escape``: Cancel/close modal dialog
106
+ """)
107
+
108
+ if __name__ == "__main__":
109
+ demo.launch()
space.py CHANGED
@@ -3,7 +3,7 @@ import gradio as gr
3
  from app import demo as app
4
  import os
5
 
6
- _docs = {'image_annotator': {'description': 'Creates a component to annotate images with bounding boxes. The bounding boxes can be created and edited by the user or be passed by code.\nIt is also possible to predefine a set of valid classes and colors.', 'members': {'__init__': {'value': {'type': 'dict | None', 'default': 'None', 'description': "A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. Optionally it may contain a key 'boxes' with a list of boxes. Each box must be a dict wit the keys: 'xmin', 'ymin', 'xmax' and 'ymax' with the absolute image coordinates of the box. Optionally can also include the keys 'label' and 'color' describing the label and color of the box. Color must be a tuple of RGB values (e.g. `(255,255,255)`). Optionally can also include the keys 'orientation' with a integer between 0 and 3, describing the number of times the image is rotated by 90 degrees in frontend, the rotation is clockwise."}, 'boxes_alpha': {'type': 'float | None', 'default': 'None', 'description': 'Opacity of the bounding boxes 0 and 1.'}, 'label_list': {'type': 'list[str] | None', 'default': 'None', 'description': 'List of valid labels.'}, 'label_colors': {'type': 'list[str] | None', 'default': 'None', 'description': 'Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).'}, 'box_min_size': {'type': 'int | None', 'default': 'None', 'description': 'Minimum valid bounding box size.'}, 'handle_size': {'type': 'int | None', 'default': 'None', 'description': 'Size of the bounding box resize handles.'}, 'box_thickness': {'type': 'int | None', 'default': 'None', 'description': 'Thickness of the bounding box outline.'}, 'box_selected_thickness': {'type': 'int | None', 'default': 'None', 'description': 'Thickness of the bounding box outline when it is selected.'}, 'disable_edit_boxes': {'type': 'bool | None', 'default': 'None', 'description': 'Disables the ability to set and edit the label and color of the boxes.'}, 'single_box': {'type': 'bool', 'default': 'False', 'description': 'If True, at most one box can be drawn.'}, 'height': {'type': 'int | str | None', 'default': 'None', 'description': 'The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'width': {'type': 'int | str | None', 'default': 'None', 'description': 'The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'image_mode': {'type': '"1"\n | "L"\n | "P"\n | "RGB"\n | "RGBA"\n | "CMYK"\n | "YCbCr"\n | "LAB"\n | "HSV"\n | "I"\n | "F"', 'default': '"RGB"', 'description': '"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.'}, 'sources': {'type': 'list["upload" | "webcam" | "clipboard"] | None', 'default': '["upload", "webcam", "clipboard"]', 'description': 'List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].'}, 'image_type': {'type': '"numpy" | "pil" | "filepath"', 'default': '"numpy"', 'description': 'The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': '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.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': '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.'}, 'interactive': {'type': 'bool | None', 'default': 'True', 'description': 'if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': '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.'}, 'render': {'type': 'bool', 'default': 'True', 'description': '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.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'show_download_button': {'type': 'bool', 'default': 'True', 'description': 'If True, will show a button to download the image.'}, 'show_share_button': {'type': 'bool | None', 'default': 'None', 'description': '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.'}, 'show_clear_button': {'type': 'bool | None', 'default': 'True', 'description': 'If True, will show a button to clear the current image.'}, 'show_remove_button': {'type': 'bool | None', 'default': 'None', 'description': 'If True, will show a button to remove the selected bounding box.'}, 'handles_cursor': {'type': 'bool | None', 'default': 'True', 'description': 'If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.'}, 'use_default_label': {'type': 'bool | None', 'default': 'False', 'description': 'If True, the first item in label_list will be used as the default label when creating boxes.'}, 'enable_keyboard_shortcuts': {'type': 'bool', 'default': 'True', 'description': 'If True, the component will respond to keyboard events.'}}, 'postprocess': {'value': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with an image and an optional list of boxes or None.'}}, 'preprocess': {'return': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with the image and boxes or None.'}, 'value': None}}, 'events': {'clear': {'type': None, 'default': None, 'description': 'This listener is triggered when the user clears the image_annotator using the clear button for the component.'}, 'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the image_annotator changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.'}, 'upload': {'type': None, 'default': None, 'description': 'This listener is triggered when the user uploads a file into the image_annotator.'}}}, '__meta__': {'additional_interfaces': {'AnnotatedImageValue': {'source': 'class AnnotatedImageValue(TypedDict):\n image: Optional[np.ndarray | PIL.Image.Image | str]\n boxes: Optional[List[dict]]\n orientation: Optional[int]'}}, 'user_fn_refs': {'image_annotator': ['AnnotatedImageValue']}}}
7
 
8
  abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
 
@@ -133,7 +133,7 @@ with gr.Blocks() as demo:
133
  button_crop.click(crop, annotator_crop, image_crop)
134
 
135
  gr.Examples(examples_crop, annotator_crop)
136
-
137
  with gr.Accordion("Keyboard Shortcuts"):
138
  gr.Markdown(\"\"\"
139
  - ``C``: Create mode
 
3
  from app import demo as app
4
  import os
5
 
6
+ _docs = {'image_annotator': {'description': 'Creates a component to annotate images with bounding boxes. The bounding boxes can be created and edited by the user or be passed by code.\nIt is also possible to predefine a set of valid classes and colors.', 'members': {'__init__': {'value': {'type': 'dict | None', 'default': 'None', 'description': "A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. Optionally it may contain a key 'boxes' with a list of boxes. Each box must be a dict wit the keys: 'xmin', 'ymin', 'xmax' and 'ymax' with the absolute image coordinates of the box. Optionally can also include the keys 'label' and 'color' describing the label and color of the box. Color must be a tuple of RGB values (e.g. `(255,255,255)`). Optionally can also include the keys 'orientation' with a integer between 0 and 3, describing the number of times the image is rotated by 90 degrees in frontend, the rotation is clockwise."}, 'boxes_alpha': {'type': 'float', 'default': '0.5', 'description': 'Opacity of the bounding boxes 0 and 1.'}, 'label_list': {'type': 'list[str]', 'default': '[]', 'description': 'List of valid labels.'}, 'label_colors': {'type': 'list[str]', 'default': '[]', 'description': 'Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).'}, 'box_min_size': {'type': 'int', 'default': '10', 'description': 'Minimum valid bounding box size.'}, 'handle_size': {'type': 'int', 'default': '8', 'description': 'Size of the bounding box resize handles.'}, 'box_thickness': {'type': 'int', 'default': '2', 'description': 'Thickness of the bounding box outline.'}, 'box_selected_thickness': {'type': 'int', 'default': '4', 'description': 'Thickness of the bounding box outline when it is selected.'}, 'disable_edit_boxes': {'type': 'bool | None', 'default': 'None', 'description': 'Disables the ability to set and edit the label and color of the boxes.'}, 'single_box': {'type': 'bool', 'default': 'False', 'description': 'If True, at most one box can be drawn.'}, 'height': {'type': 'int | str | None', 'default': 'None', 'description': 'The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'width': {'type': 'int | str | None', 'default': 'None', 'description': 'The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'image_mode': {'type': '"1"\n | "L"\n | "P"\n | "RGB"\n | "RGBA"\n | "CMYK"\n | "YCbCr"\n | "LAB"\n | "HSV"\n | "I"\n | "F"', 'default': '"RGB"', 'description': '"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.'}, 'sources': {'type': 'list["upload" | "webcam" | "clipboard"] | None', 'default': '["upload", "webcam", "clipboard"]', 'description': 'List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].'}, 'image_type': {'type': '"numpy" | "pil" | "filepath"', 'default': '"numpy"', 'description': 'The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': '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.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': '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.'}, 'interactive': {'type': 'bool | None', 'default': 'True', 'description': 'if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': '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.'}, 'render': {'type': 'bool', 'default': 'True', 'description': '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.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'show_download_button': {'type': 'bool', 'default': 'True', 'description': 'If True, will show a button to download the image.'}, 'show_share_button': {'type': 'bool | None', 'default': 'None', 'description': '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.'}, 'show_clear_button': {'type': 'bool | None', 'default': 'True', 'description': 'If True, will show a button to clear the current image.'}, 'show_remove_button': {'type': 'bool | None', 'default': 'None', 'description': 'If True, will show a button to remove the selected bounding box.'}, 'handles_cursor': {'type': 'bool | None', 'default': 'True', 'description': 'If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.'}, 'use_default_label': {'type': 'bool | None', 'default': 'False', 'description': 'If True, the first item in label_list will be used as the default label when creating boxes.'}, 'enable_keyboard_shortcuts': {'type': 'bool', 'default': 'True', 'description': 'If True, the component will respond to keyboard events.'}}, 'postprocess': {'value': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with an image and an optional list of boxes or None.'}}, 'preprocess': {'return': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with the image and boxes or None.'}, 'value': None}}, 'events': {'clear': {'type': None, 'default': None, 'description': 'This listener is triggered when the user clears the image_annotator using the clear button for the component.'}, 'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the image_annotator changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.'}, 'upload': {'type': None, 'default': None, 'description': 'This listener is triggered when the user uploads a file into the image_annotator.'}}}, '__meta__': {'additional_interfaces': {'AnnotatedImageValue': {'source': 'class AnnotatedImageValue(TypedDict):\n image: Optional[np.ndarray | PIL.Image.Image | str]\n boxes: Optional[List[dict]]\n orientation: Optional[int]'}}, 'user_fn_refs': {'image_annotator': ['AnnotatedImageValue']}}}
7
 
8
  abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
 
 
133
  button_crop.click(crop, annotator_crop, image_crop)
134
 
135
  gr.Examples(examples_crop, annotator_crop)
136
+
137
  with gr.Accordion("Keyboard Shortcuts"):
138
  gr.Markdown(\"\"\"
139
  - ``C``: Create mode
src/.github/workflows/python-publish.yml CHANGED
@@ -1,39 +1,39 @@
1
- # This workflow will upload a Python Package using Twine when a release is created
2
- # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
3
-
4
- # This workflow uses actions that are not certified by GitHub.
5
- # They are provided by a third-party and are governed by
6
- # separate terms of service, privacy policy, and support
7
- # documentation.
8
-
9
- name: Upload Python Package
10
-
11
- on:
12
- release:
13
- types: [published]
14
-
15
- permissions:
16
- contents: read
17
-
18
- jobs:
19
- deploy:
20
-
21
- runs-on: ubuntu-latest
22
-
23
- steps:
24
- - uses: actions/checkout@v3
25
- - name: Set up Python
26
- uses: actions/setup-python@v3
27
- with:
28
- python-version: '3.x'
29
- - name: Install dependencies
30
- run: |
31
- python -m pip install --upgrade pip
32
- pip install build
33
- - name: Build package
34
- run: python -m build
35
- - name: Publish package
36
- uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
37
- with:
38
- user: __token__
39
- password: ${{ secrets.PYPI_API_TOKEN }}
 
1
+ # This workflow will upload a Python Package using Twine when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
3
+
4
+ # This workflow uses actions that are not certified by GitHub.
5
+ # They are provided by a third-party and are governed by
6
+ # separate terms of service, privacy policy, and support
7
+ # documentation.
8
+
9
+ name: Upload Python Package
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ deploy:
20
+
21
+ runs-on: ubuntu-latest
22
+
23
+ steps:
24
+ - uses: actions/checkout@v3
25
+ - name: Set up Python
26
+ uses: actions/setup-python@v3
27
+ with:
28
+ python-version: '3.x'
29
+ - name: Install dependencies
30
+ run: |
31
+ python -m pip install --upgrade pip
32
+ pip install build
33
+ - name: Build package
34
+ run: python -m build
35
+ - name: Publish package
36
+ uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
37
+ with:
38
+ user: __token__
39
+ password: ${{ secrets.PYPI_API_TOKEN }}
src/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Edgar Gracia
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Edgar Gracia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
src/README.md CHANGED
@@ -168,11 +168,11 @@ dict | None
168
  <td align="left" style="width: 25%;">
169
 
170
  ```python
171
- float | None
172
  ```
173
 
174
  </td>
175
- <td align="left"><code>None</code></td>
176
  <td align="left">Opacity of the bounding boxes 0 and 1.</td>
177
  </tr>
178
 
@@ -181,11 +181,11 @@ float | None
181
  <td align="left" style="width: 25%;">
182
 
183
  ```python
184
- list[str] | None
185
  ```
186
 
187
  </td>
188
- <td align="left"><code>None</code></td>
189
  <td align="left">List of valid labels.</td>
190
  </tr>
191
 
@@ -194,11 +194,11 @@ list[str] | None
194
  <td align="left" style="width: 25%;">
195
 
196
  ```python
197
- list[str] | None
198
  ```
199
 
200
  </td>
201
- <td align="left"><code>None</code></td>
202
  <td align="left">Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).</td>
203
  </tr>
204
 
@@ -207,11 +207,11 @@ list[str] | None
207
  <td align="left" style="width: 25%;">
208
 
209
  ```python
210
- int | None
211
  ```
212
 
213
  </td>
214
- <td align="left"><code>None</code></td>
215
  <td align="left">Minimum valid bounding box size.</td>
216
  </tr>
217
 
@@ -220,11 +220,11 @@ int | None
220
  <td align="left" style="width: 25%;">
221
 
222
  ```python
223
- int | None
224
  ```
225
 
226
  </td>
227
- <td align="left"><code>None</code></td>
228
  <td align="left">Size of the bounding box resize handles.</td>
229
  </tr>
230
 
@@ -233,11 +233,11 @@ int | None
233
  <td align="left" style="width: 25%;">
234
 
235
  ```python
236
- int | None
237
  ```
238
 
239
  </td>
240
- <td align="left"><code>None</code></td>
241
  <td align="left">Thickness of the bounding box outline.</td>
242
  </tr>
243
 
@@ -246,11 +246,11 @@ int | None
246
  <td align="left" style="width: 25%;">
247
 
248
  ```python
249
- int | None
250
  ```
251
 
252
  </td>
253
- <td align="left"><code>None</code></td>
254
  <td align="left">Thickness of the bounding box outline when it is selected.</td>
255
  </tr>
256
 
 
168
  <td align="left" style="width: 25%;">
169
 
170
  ```python
171
+ float
172
  ```
173
 
174
  </td>
175
+ <td align="left"><code>0.5</code></td>
176
  <td align="left">Opacity of the bounding boxes 0 and 1.</td>
177
  </tr>
178
 
 
181
  <td align="left" style="width: 25%;">
182
 
183
  ```python
184
+ list[str]
185
  ```
186
 
187
  </td>
188
+ <td align="left"><code>[]</code></td>
189
  <td align="left">List of valid labels.</td>
190
  </tr>
191
 
 
194
  <td align="left" style="width: 25%;">
195
 
196
  ```python
197
+ list[str]
198
  ```
199
 
200
  </td>
201
+ <td align="left"><code>[]</code></td>
202
  <td align="left">Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).</td>
203
  </tr>
204
 
 
207
  <td align="left" style="width: 25%;">
208
 
209
  ```python
210
+ int
211
  ```
212
 
213
  </td>
214
+ <td align="left"><code>10</code></td>
215
  <td align="left">Minimum valid bounding box size.</td>
216
  </tr>
217
 
 
220
  <td align="left" style="width: 25%;">
221
 
222
  ```python
223
+ int
224
  ```
225
 
226
  </td>
227
+ <td align="left"><code>8</code></td>
228
  <td align="left">Size of the bounding box resize handles.</td>
229
  </tr>
230
 
 
233
  <td align="left" style="width: 25%;">
234
 
235
  ```python
236
+ int
237
  ```
238
 
239
  </td>
240
+ <td align="left"><code>2</code></td>
241
  <td align="left">Thickness of the bounding box outline.</td>
242
  </tr>
243
 
 
246
  <td align="left" style="width: 25%;">
247
 
248
  ```python
249
+ int
250
  ```
251
 
252
  </td>
253
+ <td align="left"><code>4</code></td>
254
  <td align="left">Thickness of the bounding box outline when it is selected.</td>
255
  </tr>
256
 
src/backend/gradio_image_annotation/image_annotator.py CHANGED
@@ -1,358 +1,358 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- import warnings
5
- from pathlib import Path
6
- from typing import Any, List, Optional, Literal, TypedDict, cast
7
-
8
- import numpy as np
9
- import PIL.Image
10
- from PIL import ImageOps
11
-
12
- from gradio import image_utils, utils
13
- from gradio.components.base import Component
14
- from gradio.data_classes import FileData, GradioModel
15
- from gradio.events import Events
16
-
17
- PIL.Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
18
-
19
-
20
- class AnnotatedImageData(GradioModel):
21
- image: FileData
22
- boxes: List[dict] = []
23
- orientation: int = 0
24
-
25
-
26
- class AnnotatedImageValue(TypedDict):
27
- image: Optional[np.ndarray | PIL.Image.Image | str]
28
- boxes: Optional[List[dict]]
29
- orientation: Optional[int]
30
-
31
-
32
- def rgb2hex(r,g,b):
33
- def clip(x):
34
- return max(min(x, 255), 0)
35
- return "#{:02x}{:02x}{:02x}".format(clip(r),clip(g),clip(b))
36
-
37
-
38
- class image_annotator(Component):
39
- """
40
- Creates a component to annotate images with bounding boxes. The bounding boxes can be created and edited by the user or be passed by code.
41
- It is also possible to predefine a set of valid classes and colors.
42
- """
43
-
44
- EVENTS = [
45
- Events.clear,
46
- Events.change,
47
- Events.upload,
48
- ]
49
-
50
- data_model = AnnotatedImageData
51
-
52
- def __init__(
53
- self,
54
- value: dict | None = None,
55
- *,
56
- boxes_alpha: float | None = None,
57
- label_list: list[str] | None = None,
58
- label_colors: list[str] | None = None,
59
- box_min_size: int | None = None,
60
- handle_size: int | None = None,
61
- box_thickness: int | None = None,
62
- box_selected_thickness: int | None = None,
63
- disable_edit_boxes: bool | None = None,
64
- single_box: bool = False,
65
- height: int | str | None = None,
66
- width: int | str | None = None,
67
- image_mode: Literal[
68
- "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F"
69
- ] = "RGB",
70
- sources: list[Literal["upload", "webcam", "clipboard"]] | None = [
71
- "upload",
72
- "webcam",
73
- "clipboard",
74
- ],
75
- image_type: Literal["numpy", "pil", "filepath"] = "numpy",
76
- label: str | None = None,
77
- container: bool = True,
78
- scale: int | None = None,
79
- min_width: int = 160,
80
- interactive: bool | None = True,
81
- visible: bool = True,
82
- elem_id: str | None = None,
83
- elem_classes: list[str] | str | None = None,
84
- render: bool = True,
85
- show_label: bool | None = None,
86
- show_download_button: bool = True,
87
- show_share_button: bool | None = None,
88
- show_clear_button: bool | None = True,
89
- show_remove_button: bool | None = None,
90
- handles_cursor: bool | None = True,
91
- use_default_label: bool | None = False,
92
- enable_keyboard_shortcuts: bool = True,
93
- ):
94
- """
95
- Parameters:
96
- value: A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. Optionally it may contain a key 'boxes' with a list of boxes. Each box must be a dict wit the keys: 'xmin', 'ymin', 'xmax' and 'ymax' with the absolute image coordinates of the box. Optionally can also include the keys 'label' and 'color' describing the label and color of the box. Color must be a tuple of RGB values (e.g. `(255,255,255)`). Optionally can also include the keys 'orientation' with a integer between 0 and 3, describing the number of times the image is rotated by 90 degrees in frontend, the rotation is clockwise.
97
- boxes_alpha: Opacity of the bounding boxes 0 and 1.
98
- label_list: List of valid labels.
99
- label_colors: Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).
100
- box_min_size: Minimum valid bounding box size.
101
- handle_size: Size of the bounding box resize handles.
102
- box_thickness: Thickness of the bounding box outline.
103
- box_selected_thickness: Thickness of the bounding box outline when it is selected.
104
- disable_edit_boxes: Disables the ability to set and edit the label and color of the boxes.
105
- single_box: If True, at most one box can be drawn.
106
- height: The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.
107
- width: The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.
108
- 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.
109
- sources: List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].
110
- image_type: The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.
111
- 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.
112
- container: If True, will place the component in a container - providing some extra padding around the border.
113
- scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
114
- 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.
115
- interactive: if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.
116
- visible: If False, component will be hidden.
117
- 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.
118
- 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.
119
- 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.
120
- show_label: if True, will display label.
121
- show_download_button: If True, will show a button to download the image.
122
- 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.
123
- show_clear_button: If True, will show a button to clear the current image.
124
- show_remove_button: If True, will show a button to remove the selected bounding box.
125
- handles_cursor: If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.
126
- use_default_label: If True, the first item in label_list will be used as the default label when creating boxes.
127
- enable_keyboard_shortcuts: If True, the component will respond to keyboard events.
128
- """
129
-
130
- valid_types = ["numpy", "pil", "filepath"]
131
- if image_type not in valid_types:
132
- raise ValueError(
133
- f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
134
- )
135
- self.image_type = image_type
136
- self.height = height
137
- self.width = width
138
- self.image_mode = image_mode
139
-
140
- self.sources = sources
141
- valid_sources = ["upload", "clipboard", "webcam", None]
142
- if isinstance(sources, str):
143
- self.sources = [sources]
144
- if self.sources is None:
145
- self.sources = []
146
- if self.sources is not None:
147
- for source in self.sources:
148
- if source not in valid_sources:
149
- raise ValueError(
150
- f"`sources` must a list consisting of elements in {valid_sources}"
151
- )
152
-
153
- self.show_download_button = show_download_button
154
- self.show_share_button = (
155
- (utils.get_space() is not None)
156
- if show_share_button is None
157
- else show_share_button
158
- )
159
- self.show_clear_button = show_clear_button
160
- self.show_remove_button = show_remove_button
161
- self.handles_cursor = handles_cursor
162
- self.use_default_label = use_default_label
163
- self.enable_keyboard_shortcuts = enable_keyboard_shortcuts
164
-
165
- self.boxes_alpha = boxes_alpha
166
- self.box_min_size = box_min_size
167
- self.handle_size = handle_size
168
- self.box_thickness = box_thickness
169
- self.box_selected_thickness = box_selected_thickness
170
- self.disable_edit_boxes = disable_edit_boxes
171
- self.single_box = single_box
172
- if label_list:
173
- self.label_list = [(l, i) for i, l in enumerate(label_list)]
174
- else:
175
- self.label_list = None
176
-
177
- # Parse colors
178
- self.label_colors = label_colors
179
- if self.label_colors:
180
- if (not isinstance(self.label_colors, list)
181
- or self.label_list is None
182
- or len(self.label_colors) != len(self.label_list)):
183
- raise ValueError("``label_colors`` must be a list with the "
184
- "same length as ``label_list``")
185
- for i, color in enumerate(self.label_colors):
186
- if isinstance(color, str):
187
- if len(color) != 7 or color[0] != "#":
188
- raise ValueError(f"Invalid color value {color}")
189
- elif isinstance(color, (list, tuple)):
190
- self.label_colors[i] = rgb2hex(*color)
191
-
192
- super().__init__(
193
- label=label,
194
- every=None,
195
- show_label=show_label,
196
- container=container,
197
- scale=scale,
198
- min_width=min_width,
199
- interactive=interactive,
200
- visible=visible,
201
- elem_id=elem_id,
202
- elem_classes=elem_classes,
203
- render=render,
204
- value=value,
205
- )
206
-
207
- def preprocess_image(self, image: FileData | None) -> str | None:
208
- if image is None:
209
- return None
210
- file_path = Path(image.path)
211
- if image.orig_name:
212
- p = Path(image.orig_name)
213
- name = p.stem
214
- suffix = p.suffix.replace(".", "")
215
- if suffix in ["jpg", "jpeg"]:
216
- suffix = "jpeg"
217
- else:
218
- name = "image"
219
- suffix = "png"
220
-
221
- if suffix.lower() == "svg":
222
- return str(file_path)
223
-
224
- im = PIL.Image.open(file_path)
225
- exif = im.getexif()
226
- # 274 is the code for image rotation and 1 means "correct orientation"
227
- if exif.get(274, 1) != 1 and hasattr(ImageOps, "exif_transpose"):
228
- try:
229
- im = ImageOps.exif_transpose(im)
230
- except Exception:
231
- warnings.warn(
232
- f"Failed to transpose image {file_path} based on EXIF data."
233
- )
234
- with warnings.catch_warnings():
235
- warnings.simplefilter("ignore")
236
- im = im.convert(self.image_mode)
237
- return image_utils.format_image(
238
- im,
239
- cast(Literal["numpy", "pil", "filepath"], self.image_type),
240
- self.GRADIO_CACHE,
241
- name=name,
242
- format=suffix,
243
- )
244
-
245
- def preprocess_boxes(self, boxes: List[dict] | None) -> list:
246
- parsed_boxes = []
247
- for box in boxes:
248
- new_box = {}
249
- new_box["label"] = box.get("label", "")
250
- new_box["color"] = (0,0,0)
251
- if "color" in box:
252
- match = re.match(r'rgb\((\d+), (\d+), (\d+)\)', box["color"])
253
- if match:
254
- new_box["color"] = tuple(int(match.group(i)) for i in range(1, 4))
255
- scale_factor = box.get("scaleFactor", 1)
256
- new_box["xmin"] = round(box["xmin"] / scale_factor)
257
- new_box["ymin"] = round(box["ymin"] / scale_factor)
258
- new_box["xmax"] = round(box["xmax"] / scale_factor)
259
- new_box["ymax"] = round(box["ymax"] / scale_factor)
260
- parsed_boxes.append(new_box)
261
- return parsed_boxes
262
-
263
- def preprocess(self, payload: AnnotatedImageData | None) -> AnnotatedImageValue | None:
264
- """
265
- Parameters:
266
- payload: an AnnotatedImageData object.
267
- Returns:
268
- A dict with the image and boxes or None.
269
- """
270
- if payload is None:
271
- return None
272
-
273
- ret_value = {
274
- "image": self.preprocess_image(payload.image),
275
- "boxes": self.preprocess_boxes(payload.boxes),
276
- "orientation": payload.orientation,
277
- }
278
- return ret_value
279
-
280
- def postprocess(self, value: AnnotatedImageValue | None) -> AnnotatedImageData | None:
281
- """
282
- Parameters:
283
- value: A dict with an image and an optional list of boxes or None.
284
- Returns:
285
- Returns an AnnotatedImageData object.
286
- """
287
- # Check value
288
- if value is None:
289
- return None
290
- if not isinstance(value, dict):
291
- raise ValueError(f"``value`` must be a dict. Got {type(value)}")
292
-
293
- # Check and get boxes
294
- boxes = value.setdefault("boxes", [])
295
- if boxes:
296
- if not isinstance(value["boxes"], (list, tuple)):
297
- raise ValueError(f"'boxes' must be a list of dicts. Got "
298
- f"{type(value['boxes'])}")
299
- for box in value["boxes"]:
300
- if (not isinstance(box, dict)
301
- or not set(box.keys()).issubset({"label", "xmin", "ymin", "xmax", "ymax", "color"})
302
- or not set(box.keys()).issuperset({"xmin", "ymin", "xmax", "ymax"})
303
- ):
304
- raise ValueError("Box must be a dict with the following "
305
- "keys: 'xmin', 'ymin', 'xmax', 'ymax', "
306
- f"['label', 'color']'. Got {box}")
307
-
308
- # Check and parse image
309
- image = value.setdefault("image", None)
310
- if image is not None:
311
- if isinstance(image, str) and image.lower().endswith(".svg"):
312
- image = FileData(path=image, orig_name=Path(image).name)
313
- else:
314
- saved = image_utils.save_image(image, self.GRADIO_CACHE)
315
- orig_name = Path(saved).name if Path(saved).exists() else None
316
- image = FileData(path=saved, orig_name=orig_name)
317
- else:
318
- raise ValueError(f"An image must be provided. Got {value}")
319
-
320
- orientation = value.setdefault("orientation", 0)
321
- if orientation is None:
322
- orientation = 0
323
-
324
- return AnnotatedImageData(image=image, boxes=boxes, orientation=orientation)
325
-
326
- def process_example(self, value: dict | None) -> FileData | None:
327
- if value is None:
328
- return None
329
- if not isinstance(value, dict):
330
- raise ValueError(f"``value`` must be a dict. Got {type(value)}")
331
-
332
- image = value.setdefault("image", None)
333
- if image is not None:
334
- if isinstance(image, str) and image.lower().endswith(".svg"):
335
- image = FileData(path=image, orig_name=Path(image).name)
336
- else:
337
- saved = image_utils.save_image(image, self.GRADIO_CACHE)
338
- orig_name = Path(saved).name if Path(saved).exists() else None
339
- image = FileData(path=saved, orig_name=orig_name)
340
- else:
341
- raise ValueError(f"An image must be provided. Got {value}")
342
-
343
- return image
344
-
345
- def example_inputs(self) -> Any:
346
- return {
347
- "image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
348
- "boxes": [
349
- {
350
- "xmin": 30,
351
- "ymin": 70,
352
- "xmax": 530,
353
- "ymax": 500,
354
- "label": "Gradio",
355
- "color": (250,185,0),
356
- }
357
- ]
358
- }
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import warnings
5
+ from pathlib import Path
6
+ from typing import Any, List, Optional, Literal, TypedDict, cast
7
+
8
+ import numpy as np
9
+ import PIL.Image
10
+ from PIL import ImageOps
11
+
12
+ from gradio import image_utils, utils
13
+ from gradio.components.base import Component
14
+ from gradio.data_classes import FileData, GradioModel
15
+ from gradio.events import Events
16
+
17
+ PIL.Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
18
+
19
+
20
+ class AnnotatedImageData(GradioModel):
21
+ image: FileData
22
+ boxes: List[dict] = []
23
+ orientation: int = 0
24
+
25
+
26
+ class AnnotatedImageValue(TypedDict):
27
+ image: Optional[np.ndarray | PIL.Image.Image | str]
28
+ boxes: Optional[List[dict]]
29
+ orientation: Optional[int]
30
+
31
+
32
+ def rgb2hex(r,g,b):
33
+ def clip(x):
34
+ return max(min(x, 255), 0)
35
+ return "#{:02x}{:02x}{:02x}".format(clip(r),clip(g),clip(b))
36
+
37
+
38
+ class image_annotator(Component):
39
+ """
40
+ Creates a component to annotate images with bounding boxes. The bounding boxes can be created and edited by the user or be passed by code.
41
+ It is also possible to predefine a set of valid classes and colors.
42
+ """
43
+
44
+ EVENTS = [
45
+ Events.clear,
46
+ Events.change,
47
+ Events.upload,
48
+ ]
49
+
50
+ data_model = AnnotatedImageData
51
+
52
+ def __init__(
53
+ self,
54
+ value: dict | None = None,
55
+ *,
56
+ boxes_alpha: float = 0.5,
57
+ label_list: list[str] = [],
58
+ label_colors: list[str] = [],
59
+ box_min_size: int = 10,
60
+ handle_size: int = 8,
61
+ box_thickness: int = 2,
62
+ box_selected_thickness: int = 4,
63
+ disable_edit_boxes: bool | None = None,
64
+ single_box: bool = False,
65
+ height: int | str | None = None,
66
+ width: int | str | None = None,
67
+ image_mode: Literal[
68
+ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F"
69
+ ] = "RGB",
70
+ sources: list[Literal["upload", "webcam", "clipboard"]] | None = [
71
+ "upload",
72
+ "webcam",
73
+ "clipboard",
74
+ ],
75
+ image_type: Literal["numpy", "pil", "filepath"] = "numpy",
76
+ label: str | None = None,
77
+ container: bool = True,
78
+ scale: int | None = None,
79
+ min_width: int = 160,
80
+ interactive: bool | None = True,
81
+ visible: bool = True,
82
+ elem_id: str | None = None,
83
+ elem_classes: list[str] | str | None = None,
84
+ render: bool = True,
85
+ show_label: bool | None = None,
86
+ show_download_button: bool = True,
87
+ show_share_button: bool | None = None,
88
+ show_clear_button: bool | None = True,
89
+ show_remove_button: bool | None = None,
90
+ handles_cursor: bool | None = True,
91
+ use_default_label: bool | None = False,
92
+ enable_keyboard_shortcuts: bool = True,
93
+ ):
94
+ """
95
+ Parameters:
96
+ value: A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. Optionally it may contain a key 'boxes' with a list of boxes. Each box must be a dict wit the keys: 'xmin', 'ymin', 'xmax' and 'ymax' with the absolute image coordinates of the box. Optionally can also include the keys 'label' and 'color' describing the label and color of the box. Color must be a tuple of RGB values (e.g. `(255,255,255)`). Optionally can also include the keys 'orientation' with a integer between 0 and 3, describing the number of times the image is rotated by 90 degrees in frontend, the rotation is clockwise.
97
+ boxes_alpha: Opacity of the bounding boxes 0 and 1.
98
+ label_list: List of valid labels.
99
+ label_colors: Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).
100
+ box_min_size: Minimum valid bounding box size.
101
+ handle_size: Size of the bounding box resize handles.
102
+ box_thickness: Thickness of the bounding box outline.
103
+ box_selected_thickness: Thickness of the bounding box outline when it is selected.
104
+ disable_edit_boxes: Disables the ability to set and edit the label and color of the boxes.
105
+ single_box: If True, at most one box can be drawn.
106
+ height: The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.
107
+ width: The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.
108
+ 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.
109
+ sources: List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].
110
+ image_type: The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.
111
+ 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.
112
+ container: If True, will place the component in a container - providing some extra padding around the border.
113
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
114
+ 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.
115
+ interactive: if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.
116
+ visible: If False, component will be hidden.
117
+ 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.
118
+ 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.
119
+ 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.
120
+ show_label: if True, will display label.
121
+ show_download_button: If True, will show a button to download the image.
122
+ 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.
123
+ show_clear_button: If True, will show a button to clear the current image.
124
+ show_remove_button: If True, will show a button to remove the selected bounding box.
125
+ handles_cursor: If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.
126
+ use_default_label: If True, the first item in label_list will be used as the default label when creating boxes.
127
+ enable_keyboard_shortcuts: If True, the component will respond to keyboard events.
128
+ """
129
+
130
+ valid_types = ["numpy", "pil", "filepath"]
131
+ if image_type not in valid_types:
132
+ raise ValueError(
133
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
134
+ )
135
+ self.image_type = image_type
136
+ self.height = height
137
+ self.width = width
138
+ self.image_mode = image_mode
139
+
140
+ self.sources = sources
141
+ valid_sources = ["upload", "clipboard", "webcam", None]
142
+ if isinstance(sources, str):
143
+ self.sources = [sources]
144
+ if self.sources is None:
145
+ self.sources = []
146
+ if self.sources is not None:
147
+ for source in self.sources:
148
+ if source not in valid_sources:
149
+ raise ValueError(
150
+ f"`sources` must a list consisting of elements in {valid_sources}"
151
+ )
152
+
153
+ self.show_download_button = show_download_button
154
+ self.show_share_button = (
155
+ (utils.get_space() is not None)
156
+ if show_share_button is None
157
+ else show_share_button
158
+ )
159
+ self.show_clear_button = show_clear_button
160
+ self.show_remove_button = show_remove_button
161
+ self.handles_cursor = handles_cursor
162
+ self.use_default_label = use_default_label
163
+ self.enable_keyboard_shortcuts = enable_keyboard_shortcuts
164
+
165
+ self.boxes_alpha = boxes_alpha
166
+ self.box_min_size = box_min_size
167
+ self.handle_size = handle_size
168
+ self.box_thickness = box_thickness
169
+ self.box_selected_thickness = box_selected_thickness
170
+ self.disable_edit_boxes = disable_edit_boxes
171
+ self.single_box = single_box
172
+ if label_list:
173
+ self.label_list = [(l, i) for i, l in enumerate(label_list)]
174
+ else:
175
+ self.label_list = None
176
+
177
+ # Parse colors
178
+ self.label_colors = label_colors
179
+ if self.label_colors:
180
+ if (not isinstance(self.label_colors, list)
181
+ or self.label_list is None
182
+ or len(self.label_colors) != len(self.label_list)):
183
+ raise ValueError("``label_colors`` must be a list with the "
184
+ "same length as ``label_list``")
185
+ for i, color in enumerate(self.label_colors):
186
+ if isinstance(color, str):
187
+ if len(color) != 7 or color[0] != "#":
188
+ raise ValueError(f"Invalid color value {color}")
189
+ elif isinstance(color, (list, tuple)):
190
+ self.label_colors[i] = rgb2hex(*color)
191
+
192
+ super().__init__(
193
+ label=label,
194
+ every=None,
195
+ show_label=show_label,
196
+ container=container,
197
+ scale=scale,
198
+ min_width=min_width,
199
+ interactive=interactive,
200
+ visible=visible,
201
+ elem_id=elem_id,
202
+ elem_classes=elem_classes,
203
+ render=render,
204
+ value=value,
205
+ )
206
+
207
+ def preprocess_image(self, image: FileData | None) -> str | None:
208
+ if image is None:
209
+ return None
210
+ file_path = Path(image.path)
211
+ if image.orig_name:
212
+ p = Path(image.orig_name)
213
+ name = p.stem
214
+ suffix = p.suffix.replace(".", "")
215
+ if suffix in ["jpg", "jpeg"]:
216
+ suffix = "jpeg"
217
+ else:
218
+ name = "image"
219
+ suffix = "png"
220
+
221
+ if suffix.lower() == "svg":
222
+ return str(file_path)
223
+
224
+ im = PIL.Image.open(file_path)
225
+ exif = im.getexif()
226
+ # 274 is the code for image rotation and 1 means "correct orientation"
227
+ if exif.get(274, 1) != 1 and hasattr(ImageOps, "exif_transpose"):
228
+ try:
229
+ im = ImageOps.exif_transpose(im)
230
+ except Exception:
231
+ warnings.warn(
232
+ f"Failed to transpose image {file_path} based on EXIF data."
233
+ )
234
+ with warnings.catch_warnings():
235
+ warnings.simplefilter("ignore")
236
+ im = im.convert(self.image_mode)
237
+ return image_utils.format_image(
238
+ im,
239
+ cast(Literal["numpy", "pil", "filepath"], self.image_type),
240
+ self.GRADIO_CACHE,
241
+ name=name,
242
+ format=suffix,
243
+ )
244
+
245
+ def preprocess_boxes(self, boxes: List[dict] | None) -> list:
246
+ parsed_boxes = []
247
+ for box in boxes:
248
+ new_box = {}
249
+ new_box["label"] = box.get("label", "")
250
+ new_box["color"] = (0,0,0)
251
+ if "color" in box:
252
+ match = re.match(r'rgb\((\d+), (\d+), (\d+)\)', box["color"])
253
+ if match:
254
+ new_box["color"] = tuple(int(match.group(i)) for i in range(1, 4))
255
+ scale_factor = box.get("scaleFactor", 1)
256
+ new_box["xmin"] = round(box["xmin"] / scale_factor)
257
+ new_box["ymin"] = round(box["ymin"] / scale_factor)
258
+ new_box["xmax"] = round(box["xmax"] / scale_factor)
259
+ new_box["ymax"] = round(box["ymax"] / scale_factor)
260
+ parsed_boxes.append(new_box)
261
+ return parsed_boxes
262
+
263
+ def preprocess(self, payload: AnnotatedImageData | None) -> AnnotatedImageValue | None:
264
+ """
265
+ Parameters:
266
+ payload: an AnnotatedImageData object.
267
+ Returns:
268
+ A dict with the image and boxes or None.
269
+ """
270
+ if payload is None:
271
+ return None
272
+
273
+ ret_value = {
274
+ "image": self.preprocess_image(payload.image),
275
+ "boxes": self.preprocess_boxes(payload.boxes),
276
+ "orientation": payload.orientation,
277
+ }
278
+ return ret_value
279
+
280
+ def postprocess(self, value: AnnotatedImageValue | None) -> AnnotatedImageData | None:
281
+ """
282
+ Parameters:
283
+ value: A dict with an image and an optional list of boxes or None.
284
+ Returns:
285
+ Returns an AnnotatedImageData object.
286
+ """
287
+ # Check value
288
+ if value is None:
289
+ return None
290
+ if not isinstance(value, dict):
291
+ raise ValueError(f"``value`` must be a dict. Got {type(value)}")
292
+
293
+ # Check and get boxes
294
+ boxes = value.setdefault("boxes", [])
295
+ if boxes:
296
+ if not isinstance(value["boxes"], (list, tuple)):
297
+ raise ValueError(f"'boxes' must be a list of dicts. Got "
298
+ f"{type(value['boxes'])}")
299
+ for box in value["boxes"]:
300
+ if (not isinstance(box, dict)
301
+ or not set(box.keys()).issubset({"label", "xmin", "ymin", "xmax", "ymax", "color"})
302
+ or not set(box.keys()).issuperset({"xmin", "ymin", "xmax", "ymax"})
303
+ ):
304
+ raise ValueError("Box must be a dict with the following "
305
+ "keys: 'xmin', 'ymin', 'xmax', 'ymax', "
306
+ f"['label', 'color']'. Got {box}")
307
+
308
+ # Check and parse image
309
+ image = value.setdefault("image", None)
310
+ if image is not None:
311
+ if isinstance(image, str) and image.lower().endswith(".svg"):
312
+ image = FileData(path=image, orig_name=Path(image).name)
313
+ else:
314
+ saved = image_utils.save_image(image, self.GRADIO_CACHE)
315
+ orig_name = Path(saved).name if Path(saved).exists() else None
316
+ image = FileData(path=saved, orig_name=orig_name)
317
+ else:
318
+ raise ValueError(f"An image must be provided. Got {value}")
319
+
320
+ orientation = value.setdefault("orientation", 0)
321
+ if orientation is None:
322
+ orientation = 0
323
+
324
+ return AnnotatedImageData(image=image, boxes=boxes, orientation=orientation)
325
+
326
+ def process_example(self, value: dict | None) -> FileData | None:
327
+ if value is None:
328
+ return None
329
+ if not isinstance(value, dict):
330
+ raise ValueError(f"``value`` must be a dict. Got {type(value)}")
331
+
332
+ image = value.setdefault("image", None)
333
+ if image is not None:
334
+ if isinstance(image, str) and image.lower().endswith(".svg"):
335
+ image = FileData(path=image, orig_name=Path(image).name)
336
+ else:
337
+ saved = image_utils.save_image(image, self.GRADIO_CACHE)
338
+ orig_name = Path(saved).name if Path(saved).exists() else None
339
+ image = FileData(path=saved, orig_name=orig_name)
340
+ else:
341
+ raise ValueError(f"An image must be provided. Got {value}")
342
+
343
+ return image
344
+
345
+ def example_inputs(self) -> Any:
346
+ return {
347
+ "image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
348
+ "boxes": [
349
+ {
350
+ "xmin": 30,
351
+ "ymin": 70,
352
+ "xmax": 530,
353
+ "ymax": 500,
354
+ "label": "Gradio",
355
+ "color": (250,185,0),
356
+ }
357
+ ]
358
+ }
src/backend/gradio_image_annotation/templates/component/index.js CHANGED
The diff for this file is too large to render. See raw diff
 
src/demo/app.py CHANGED
@@ -1,109 +1,109 @@
1
- import gradio as gr
2
- from gradio_image_annotation import image_annotator
3
- import numpy as np
4
-
5
-
6
- example_annotation = {
7
- "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
8
- "boxes": [
9
- {
10
- "xmin": 636,
11
- "ymin": 575,
12
- "xmax": 801,
13
- "ymax": 697,
14
- "label": "Vehicle",
15
- "color": (255, 0, 0)
16
- },
17
- {
18
- "xmin": 360,
19
- "ymin": 615,
20
- "xmax": 386,
21
- "ymax": 702,
22
- "label": "Person",
23
- "color": (0, 255, 0)
24
- }
25
- ]
26
- }
27
-
28
- examples_crop = [
29
- {
30
- "image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
31
- "boxes": [
32
- {
33
- "xmin": 30,
34
- "ymin": 70,
35
- "xmax": 530,
36
- "ymax": 500,
37
- "color": (100, 200, 255),
38
- }
39
- ],
40
- },
41
- {
42
- "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
43
- "boxes": [
44
- {
45
- "xmin": 636,
46
- "ymin": 575,
47
- "xmax": 801,
48
- "ymax": 697,
49
- "color": (255, 0, 0),
50
- },
51
- ],
52
- },
53
- ]
54
-
55
-
56
- def crop(annotations):
57
- if angle := annotations.get("orientation", None):
58
- annotations["image"] = np.rot90(annotations["image"], k=-angle)
59
- if annotations["boxes"]:
60
- box = annotations["boxes"][0]
61
- return annotations["image"][
62
- box["ymin"]:box["ymax"],
63
- box["xmin"]:box["xmax"]
64
- ]
65
- return None
66
-
67
-
68
- def get_boxes_json(annotations):
69
- return annotations["boxes"]
70
-
71
-
72
- with gr.Blocks() as demo:
73
- with gr.Tab("Object annotation", id="tab_object_annotation"):
74
- annotator = image_annotator(
75
- example_annotation,
76
- label_list=["Person", "Vehicle"],
77
- label_colors=[(0, 255, 0), (255, 0, 0)],
78
- )
79
- button_get = gr.Button("Get bounding boxes")
80
- json_boxes = gr.JSON()
81
- button_get.click(get_boxes_json, annotator, json_boxes)
82
-
83
- with gr.Tab("Crop", id="tab_crop"):
84
- with gr.Row():
85
- annotator_crop = image_annotator(
86
- examples_crop[0],
87
- image_type="numpy",
88
- disable_edit_boxes=True,
89
- single_box=True,
90
- )
91
- image_crop = gr.Image()
92
- button_crop = gr.Button("Crop")
93
- button_crop.click(crop, annotator_crop, image_crop)
94
-
95
- gr.Examples(examples_crop, annotator_crop)
96
-
97
- with gr.Accordion("Keyboard Shortcuts"):
98
- gr.Markdown("""
99
- - ``C``: Create mode
100
- - ``D``: Drag mode
101
- - ``E``: Edit selected box (same as double-click a box)
102
- - ``Delete``: Remove selected box
103
- - ``Space``: Reset view (zoom/pan)
104
- - ``Enter``: Confirm modal dialog
105
- - ``Escape``: Cancel/close modal dialog
106
- """)
107
-
108
- if __name__ == "__main__":
109
- demo.launch()
 
1
+ import gradio as gr
2
+ from gradio_image_annotation import image_annotator
3
+ import numpy as np
4
+
5
+
6
+ example_annotation = {
7
+ "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
8
+ "boxes": [
9
+ {
10
+ "xmin": 636,
11
+ "ymin": 575,
12
+ "xmax": 801,
13
+ "ymax": 697,
14
+ "label": "Vehicle",
15
+ "color": (255, 0, 0)
16
+ },
17
+ {
18
+ "xmin": 360,
19
+ "ymin": 615,
20
+ "xmax": 386,
21
+ "ymax": 702,
22
+ "label": "Person",
23
+ "color": (0, 255, 0)
24
+ }
25
+ ]
26
+ }
27
+
28
+ examples_crop = [
29
+ {
30
+ "image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
31
+ "boxes": [
32
+ {
33
+ "xmin": 30,
34
+ "ymin": 70,
35
+ "xmax": 530,
36
+ "ymax": 500,
37
+ "color": (100, 200, 255),
38
+ }
39
+ ],
40
+ },
41
+ {
42
+ "image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
43
+ "boxes": [
44
+ {
45
+ "xmin": 636,
46
+ "ymin": 575,
47
+ "xmax": 801,
48
+ "ymax": 697,
49
+ "color": (255, 0, 0),
50
+ },
51
+ ],
52
+ },
53
+ ]
54
+
55
+
56
+ def crop(annotations):
57
+ if angle := annotations.get("orientation", None):
58
+ annotations["image"] = np.rot90(annotations["image"], k=-angle)
59
+ if annotations["boxes"]:
60
+ box = annotations["boxes"][0]
61
+ return annotations["image"][
62
+ box["ymin"]:box["ymax"],
63
+ box["xmin"]:box["xmax"]
64
+ ]
65
+ return None
66
+
67
+
68
+ def get_boxes_json(annotations):
69
+ return annotations["boxes"]
70
+
71
+
72
+ with gr.Blocks() as demo:
73
+ with gr.Tab("Object annotation", id="tab_object_annotation"):
74
+ annotator = image_annotator(
75
+ example_annotation,
76
+ label_list=["Person", "Vehicle"],
77
+ label_colors=[(0, 255, 0), (255, 0, 0)],
78
+ )
79
+ button_get = gr.Button("Get bounding boxes")
80
+ json_boxes = gr.JSON()
81
+ button_get.click(get_boxes_json, annotator, json_boxes)
82
+
83
+ with gr.Tab("Crop", id="tab_crop"):
84
+ with gr.Row():
85
+ annotator_crop = image_annotator(
86
+ examples_crop[0],
87
+ image_type="numpy",
88
+ disable_edit_boxes=True,
89
+ single_box=True,
90
+ )
91
+ image_crop = gr.Image()
92
+ button_crop = gr.Button("Crop")
93
+ button_crop.click(crop, annotator_crop, image_crop)
94
+
95
+ gr.Examples(examples_crop, annotator_crop)
96
+
97
+ with gr.Accordion("Keyboard Shortcuts"):
98
+ gr.Markdown("""
99
+ - ``C``: Create mode
100
+ - ``D``: Drag mode
101
+ - ``E``: Edit selected box (same as double-click a box)
102
+ - ``Delete``: Remove selected box
103
+ - ``Space``: Reset view (zoom/pan)
104
+ - ``Enter``: Confirm modal dialog
105
+ - ``Escape``: Cancel/close modal dialog
106
+ """)
107
+
108
+ if __name__ == "__main__":
109
+ demo.launch()
src/demo/space.py CHANGED
@@ -3,7 +3,7 @@ import gradio as gr
3
  from app import demo as app
4
  import os
5
 
6
- _docs = {'image_annotator': {'description': 'Creates a component to annotate images with bounding boxes. The bounding boxes can be created and edited by the user or be passed by code.\nIt is also possible to predefine a set of valid classes and colors.', 'members': {'__init__': {'value': {'type': 'dict | None', 'default': 'None', 'description': "A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. Optionally it may contain a key 'boxes' with a list of boxes. Each box must be a dict wit the keys: 'xmin', 'ymin', 'xmax' and 'ymax' with the absolute image coordinates of the box. Optionally can also include the keys 'label' and 'color' describing the label and color of the box. Color must be a tuple of RGB values (e.g. `(255,255,255)`). Optionally can also include the keys 'orientation' with a integer between 0 and 3, describing the number of times the image is rotated by 90 degrees in frontend, the rotation is clockwise."}, 'boxes_alpha': {'type': 'float | None', 'default': 'None', 'description': 'Opacity of the bounding boxes 0 and 1.'}, 'label_list': {'type': 'list[str] | None', 'default': 'None', 'description': 'List of valid labels.'}, 'label_colors': {'type': 'list[str] | None', 'default': 'None', 'description': 'Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).'}, 'box_min_size': {'type': 'int | None', 'default': 'None', 'description': 'Minimum valid bounding box size.'}, 'handle_size': {'type': 'int | None', 'default': 'None', 'description': 'Size of the bounding box resize handles.'}, 'box_thickness': {'type': 'int | None', 'default': 'None', 'description': 'Thickness of the bounding box outline.'}, 'box_selected_thickness': {'type': 'int | None', 'default': 'None', 'description': 'Thickness of the bounding box outline when it is selected.'}, 'disable_edit_boxes': {'type': 'bool | None', 'default': 'None', 'description': 'Disables the ability to set and edit the label and color of the boxes.'}, 'single_box': {'type': 'bool', 'default': 'False', 'description': 'If True, at most one box can be drawn.'}, 'height': {'type': 'int | str | None', 'default': 'None', 'description': 'The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'width': {'type': 'int | str | None', 'default': 'None', 'description': 'The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'image_mode': {'type': '"1"\n | "L"\n | "P"\n | "RGB"\n | "RGBA"\n | "CMYK"\n | "YCbCr"\n | "LAB"\n | "HSV"\n | "I"\n | "F"', 'default': '"RGB"', 'description': '"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.'}, 'sources': {'type': 'list["upload" | "webcam" | "clipboard"] | None', 'default': '["upload", "webcam", "clipboard"]', 'description': 'List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].'}, 'image_type': {'type': '"numpy" | "pil" | "filepath"', 'default': '"numpy"', 'description': 'The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': '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.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': '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.'}, 'interactive': {'type': 'bool | None', 'default': 'True', 'description': 'if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': '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.'}, 'render': {'type': 'bool', 'default': 'True', 'description': '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.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'show_download_button': {'type': 'bool', 'default': 'True', 'description': 'If True, will show a button to download the image.'}, 'show_share_button': {'type': 'bool | None', 'default': 'None', 'description': '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.'}, 'show_clear_button': {'type': 'bool | None', 'default': 'True', 'description': 'If True, will show a button to clear the current image.'}, 'show_remove_button': {'type': 'bool | None', 'default': 'None', 'description': 'If True, will show a button to remove the selected bounding box.'}, 'handles_cursor': {'type': 'bool | None', 'default': 'True', 'description': 'If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.'}, 'use_default_label': {'type': 'bool | None', 'default': 'False', 'description': 'If True, the first item in label_list will be used as the default label when creating boxes.'}, 'enable_keyboard_shortcuts': {'type': 'bool', 'default': 'True', 'description': 'If True, the component will respond to keyboard events.'}}, 'postprocess': {'value': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with an image and an optional list of boxes or None.'}}, 'preprocess': {'return': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with the image and boxes or None.'}, 'value': None}}, 'events': {'clear': {'type': None, 'default': None, 'description': 'This listener is triggered when the user clears the image_annotator using the clear button for the component.'}, 'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the image_annotator changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.'}, 'upload': {'type': None, 'default': None, 'description': 'This listener is triggered when the user uploads a file into the image_annotator.'}}}, '__meta__': {'additional_interfaces': {'AnnotatedImageValue': {'source': 'class AnnotatedImageValue(TypedDict):\n image: Optional[np.ndarray | PIL.Image.Image | str]\n boxes: Optional[List[dict]]\n orientation: Optional[int]'}}, 'user_fn_refs': {'image_annotator': ['AnnotatedImageValue']}}}
7
 
8
  abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
 
@@ -133,7 +133,7 @@ with gr.Blocks() as demo:
133
  button_crop.click(crop, annotator_crop, image_crop)
134
 
135
  gr.Examples(examples_crop, annotator_crop)
136
-
137
  with gr.Accordion("Keyboard Shortcuts"):
138
  gr.Markdown(\"\"\"
139
  - ``C``: Create mode
 
3
  from app import demo as app
4
  import os
5
 
6
+ _docs = {'image_annotator': {'description': 'Creates a component to annotate images with bounding boxes. The bounding boxes can be created and edited by the user or be passed by code.\nIt is also possible to predefine a set of valid classes and colors.', 'members': {'__init__': {'value': {'type': 'dict | None', 'default': 'None', 'description': "A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. Optionally it may contain a key 'boxes' with a list of boxes. Each box must be a dict wit the keys: 'xmin', 'ymin', 'xmax' and 'ymax' with the absolute image coordinates of the box. Optionally can also include the keys 'label' and 'color' describing the label and color of the box. Color must be a tuple of RGB values (e.g. `(255,255,255)`). Optionally can also include the keys 'orientation' with a integer between 0 and 3, describing the number of times the image is rotated by 90 degrees in frontend, the rotation is clockwise."}, 'boxes_alpha': {'type': 'float', 'default': '0.5', 'description': 'Opacity of the bounding boxes 0 and 1.'}, 'label_list': {'type': 'list[str]', 'default': '[]', 'description': 'List of valid labels.'}, 'label_colors': {'type': 'list[str]', 'default': '[]', 'description': 'Optional list of colors for each label when `label_list` is used. Colors must be a tuple of RGB values (e.g. `(255,255,255)`).'}, 'box_min_size': {'type': 'int', 'default': '10', 'description': 'Minimum valid bounding box size.'}, 'handle_size': {'type': 'int', 'default': '8', 'description': 'Size of the bounding box resize handles.'}, 'box_thickness': {'type': 'int', 'default': '2', 'description': 'Thickness of the bounding box outline.'}, 'box_selected_thickness': {'type': 'int', 'default': '4', 'description': 'Thickness of the bounding box outline when it is selected.'}, 'disable_edit_boxes': {'type': 'bool | None', 'default': 'None', 'description': 'Disables the ability to set and edit the label and color of the boxes.'}, 'single_box': {'type': 'bool', 'default': 'False', 'description': 'If True, at most one box can be drawn.'}, 'height': {'type': 'int | str | None', 'default': 'None', 'description': 'The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'width': {'type': 'int | str | None', 'default': 'None', 'description': 'The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.'}, 'image_mode': {'type': '"1"\n | "L"\n | "P"\n | "RGB"\n | "RGBA"\n | "CMYK"\n | "YCbCr"\n | "LAB"\n | "HSV"\n | "I"\n | "F"', 'default': '"RGB"', 'description': '"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.'}, 'sources': {'type': 'list["upload" | "webcam" | "clipboard"] | None', 'default': '["upload", "webcam", "clipboard"]', 'description': 'List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].'}, 'image_type': {'type': '"numpy" | "pil" | "filepath"', 'default': '"numpy"', 'description': 'The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': '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.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': '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.'}, 'interactive': {'type': 'bool | None', 'default': 'True', 'description': 'if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': '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.'}, 'render': {'type': 'bool', 'default': 'True', 'description': '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.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'show_download_button': {'type': 'bool', 'default': 'True', 'description': 'If True, will show a button to download the image.'}, 'show_share_button': {'type': 'bool | None', 'default': 'None', 'description': '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.'}, 'show_clear_button': {'type': 'bool | None', 'default': 'True', 'description': 'If True, will show a button to clear the current image.'}, 'show_remove_button': {'type': 'bool | None', 'default': 'None', 'description': 'If True, will show a button to remove the selected bounding box.'}, 'handles_cursor': {'type': 'bool | None', 'default': 'True', 'description': 'If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.'}, 'use_default_label': {'type': 'bool | None', 'default': 'False', 'description': 'If True, the first item in label_list will be used as the default label when creating boxes.'}, 'enable_keyboard_shortcuts': {'type': 'bool', 'default': 'True', 'description': 'If True, the component will respond to keyboard events.'}}, 'postprocess': {'value': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with an image and an optional list of boxes or None.'}}, 'preprocess': {'return': {'type': 'AnnotatedImageValue | None', 'description': 'A dict with the image and boxes or None.'}, 'value': None}}, 'events': {'clear': {'type': None, 'default': None, 'description': 'This listener is triggered when the user clears the image_annotator using the clear button for the component.'}, 'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the image_annotator changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.'}, 'upload': {'type': None, 'default': None, 'description': 'This listener is triggered when the user uploads a file into the image_annotator.'}}}, '__meta__': {'additional_interfaces': {'AnnotatedImageValue': {'source': 'class AnnotatedImageValue(TypedDict):\n image: Optional[np.ndarray | PIL.Image.Image | str]\n boxes: Optional[List[dict]]\n orientation: Optional[int]'}}, 'user_fn_refs': {'image_annotator': ['AnnotatedImageValue']}}}
7
 
8
  abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
 
 
133
  button_crop.click(crop, annotator_crop, image_crop)
134
 
135
  gr.Examples(examples_crop, annotator_crop)
136
+
137
  with gr.Accordion("Keyboard Shortcuts"):
138
  gr.Markdown(\"\"\"
139
  - ``C``: Create mode
src/frontend/Example.svelte CHANGED
@@ -1,48 +1,48 @@
1
- <script lang="ts">
2
- import type { FileData } from "@gradio/client";
3
-
4
- export let value: null | FileData;
5
- export let type: "gallery" | "table";
6
- export let selected = false;
7
- </script>
8
-
9
- <div
10
- class="container"
11
- class:table={type === "table"}
12
- class:gallery={type === "gallery"}
13
- class:selected
14
- class:border={value}
15
- >
16
- {#if value}
17
- <img src={value.url} alt="" />
18
- {/if}
19
- </div>
20
-
21
- <style>
22
- .container :global(img) {
23
- width: 100%;
24
- height: 100%;
25
- }
26
-
27
- .container.selected {
28
- border-color: var(--border-color-accent);
29
- }
30
- .border.table {
31
- border: 2px solid var(--border-color-primary);
32
- }
33
-
34
- .container.table {
35
- margin: 0 auto;
36
- border-radius: var(--radius-lg);
37
- overflow: hidden;
38
- width: var(--size-20);
39
- height: var(--size-20);
40
- object-fit: cover;
41
- }
42
-
43
- .container.gallery {
44
- width: var(--size-20);
45
- max-width: var(--size-20);
46
- object-fit: cover;
47
- }
48
- </style>
 
1
+ <script lang="ts">
2
+ import type { FileData } from "@gradio/client";
3
+
4
+ export let value: null | FileData;
5
+ export let type: "gallery" | "table";
6
+ export let selected = false;
7
+ </script>
8
+
9
+ <div
10
+ class="container"
11
+ class:table={type === "table"}
12
+ class:gallery={type === "gallery"}
13
+ class:selected
14
+ class:border={value}
15
+ >
16
+ {#if value}
17
+ <img src={value.url} alt="" />
18
+ {/if}
19
+ </div>
20
+
21
+ <style>
22
+ .container :global(img) {
23
+ width: 100%;
24
+ height: 100%;
25
+ }
26
+
27
+ .container.selected {
28
+ border-color: var(--border-color-accent);
29
+ }
30
+ .border.table {
31
+ border: 2px solid var(--border-color-primary);
32
+ }
33
+
34
+ .container.table {
35
+ margin: 0 auto;
36
+ border-radius: var(--radius-lg);
37
+ overflow: hidden;
38
+ width: var(--size-20);
39
+ height: var(--size-20);
40
+ object-fit: cover;
41
+ }
42
+
43
+ .container.gallery {
44
+ width: var(--size-20);
45
+ max-width: var(--size-20);
46
+ object-fit: cover;
47
+ }
48
+ </style>
src/frontend/Index.svelte CHANGED
@@ -1,143 +1,143 @@
1
- <svelte:options accessors={true} />
2
-
3
- <script context="module" lang="ts">
4
- export { default as BaseExample } from "./Example.svelte";
5
- </script>
6
-
7
- <script lang="ts">
8
- import type { Gradio, SelectData } from "@gradio/utils";
9
- import { Block, Empty, UploadText } from "@gradio/atoms";
10
- import { Image } from "@gradio/icons";
11
- import { StatusTracker } from "@gradio/statustracker";
12
- import type { LoadingStatus } from "@gradio/statustracker";
13
- import AnnotatedImageData from "./shared/AnnotatedImageData";
14
- import ImageAnnotator from "./shared/ImageAnnotator.svelte";
15
-
16
- type sources = "upload" | "webcam" | "clipboard" | null;
17
-
18
- export let elem_id = "";
19
- export let elem_classes: string[] = [];
20
- export let visible = true;
21
- export let value: null | AnnotatedImageData = null;
22
- export let label: string;
23
- export let show_label: boolean;
24
- export let root: string;
25
- export let height: number | string | undefined;
26
- export let width: number | string | undefined;
27
- export let _selectable = false;
28
- export let container = true;
29
- export let scale: number | null = null;
30
- export let min_width: number | undefined = undefined;
31
- export let loading_status: LoadingStatus;
32
- export let sources: ("upload" | "webcam" | "clipboard")[] = [
33
- "upload",
34
- "webcam",
35
- "clipboard",
36
- ];
37
- export let show_download_button: boolean;
38
- export let show_share_button: boolean;
39
- export let show_clear_button: boolean;
40
- export let interactive: boolean;
41
- export let boxes_alpha: number;
42
- export let label_list: string[];
43
- export let label_colors: string[];
44
- export let box_min_size: number;
45
- export let handle_size: number;
46
- export let box_thickness: number;
47
- export let box_selected_thickness: number;
48
- export let disable_edit_boxes: boolean;
49
- export let single_box: boolean;
50
- export let show_remove_button: boolean;
51
- export let handles_cursor: boolean;
52
- export let use_default_label: boolean;
53
- export let enable_keyboard_shortcuts: boolean;
54
-
55
- export let gradio: Gradio<{
56
- change: never;
57
- error: string;
58
- edit: never;
59
- drag: never;
60
- upload: never;
61
- clear: never;
62
- select: SelectData;
63
- share: ShareData;
64
- }>;
65
-
66
- let dragging: boolean;
67
- let active_source: sources = null;
68
- </script>
69
-
70
- <Block
71
- {visible}
72
- variant={"solid"}
73
- border_mode={dragging ? "focus" : "base"}
74
- padding={false}
75
- {elem_id}
76
- {elem_classes}
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
-
89
- <ImageAnnotator
90
- bind:active_source
91
- bind:value
92
- on:change={() => gradio.dispatch("change")}
93
- selectable={_selectable}
94
- {root}
95
- {sources}
96
- {interactive}
97
- showDownloadButton={show_download_button}
98
- showShareButton={show_share_button}
99
- showClearButton={show_clear_button}
100
- i18n={gradio.i18n}
101
- boxesAlpha={boxes_alpha}
102
- height={height}
103
- width={width}
104
- labelList={label_list}
105
- labelColors={label_colors}
106
- boxMinSize={box_min_size}
107
- on:edit={() => gradio.dispatch("edit")}
108
- on:clear={() => {
109
- gradio.dispatch("clear");
110
- }}
111
- on:drag={({ detail }) => (dragging = detail)}
112
- on:upload={() => gradio.dispatch("upload")}
113
- on:select={({ detail }) => gradio.dispatch("select", detail)}
114
- on:share={({ detail }) => gradio.dispatch("share", detail)}
115
- on:error={({ detail }) => {
116
- loading_status = loading_status || {};
117
- loading_status.status = "error";
118
- gradio.dispatch("error", detail);
119
- }}
120
- {label}
121
- {show_label}
122
- max_file_size={gradio.max_file_size}
123
- cli_upload={gradio.client.upload}
124
- stream_handler={gradio.client.stream}
125
- handleSize={handle_size}
126
- boxThickness={box_thickness}
127
- boxSelectedThickness={box_selected_thickness}
128
- disableEditBoxes={disable_edit_boxes}
129
- singleBox={single_box}
130
- showRemoveButton={show_remove_button}
131
- handlesCursor={handles_cursor}
132
- useDefaultLabel={use_default_label}
133
- enableKeyboardShortcuts={enable_keyboard_shortcuts}
134
- >
135
- {#if active_source === "upload"}
136
- <UploadText i18n={gradio.i18n} type="image" />
137
- {:else if active_source === "clipboard"}
138
- <UploadText i18n={gradio.i18n} type="clipboard" mode="short" />
139
- {:else}
140
- <Empty unpadded_box={true} size="large"><Image /></Empty>
141
- {/if}
142
- </ImageAnnotator>
143
- </Block>
 
1
+ <svelte:options accessors={true} />
2
+
3
+ <script context="module" lang="ts">
4
+ export { default as BaseExample } from "./Example.svelte";
5
+ </script>
6
+
7
+ <script lang="ts">
8
+ import type { Gradio, SelectData } from "@gradio/utils";
9
+ import { Block, Empty, UploadText } from "@gradio/atoms";
10
+ import { Image } from "@gradio/icons";
11
+ import { StatusTracker } from "@gradio/statustracker";
12
+ import type { LoadingStatus } from "@gradio/statustracker";
13
+ import AnnotatedImageData from "./shared/AnnotatedImageData";
14
+ import ImageAnnotator from "./shared/ImageAnnotator.svelte";
15
+
16
+ type sources = "upload" | "webcam" | "clipboard" | null;
17
+
18
+ export let elem_id = "";
19
+ export let elem_classes: string[] = [];
20
+ export let visible = true;
21
+ export let value: null | AnnotatedImageData = null;
22
+ export let label: string;
23
+ export let show_label: boolean;
24
+ export let root: string;
25
+ export let height: number | string | undefined;
26
+ export let width: number | string | undefined;
27
+ export let _selectable = false;
28
+ export let container = true;
29
+ export let scale: number | null = null;
30
+ export let min_width: number | undefined = undefined;
31
+ export let loading_status: LoadingStatus;
32
+ export let sources: ("upload" | "webcam" | "clipboard")[] = [
33
+ "upload",
34
+ "webcam",
35
+ "clipboard",
36
+ ];
37
+ export let show_download_button: boolean;
38
+ export let show_share_button: boolean;
39
+ export let show_clear_button: boolean;
40
+ export let interactive: boolean;
41
+ export let boxes_alpha: number;
42
+ export let label_list: string[];
43
+ export let label_colors: string[];
44
+ export let box_min_size: number;
45
+ export let handle_size: number;
46
+ export let box_thickness: number;
47
+ export let box_selected_thickness: number;
48
+ export let disable_edit_boxes: boolean;
49
+ export let single_box: boolean;
50
+ export let show_remove_button: boolean;
51
+ export let handles_cursor: boolean;
52
+ export let use_default_label: boolean;
53
+ export let enable_keyboard_shortcuts: boolean;
54
+
55
+ export let gradio: Gradio<{
56
+ change: never;
57
+ error: string;
58
+ edit: never;
59
+ drag: never;
60
+ upload: never;
61
+ clear: never;
62
+ select: SelectData;
63
+ share: ShareData;
64
+ }>;
65
+
66
+ let dragging: boolean;
67
+ let active_source: sources = null;
68
+ </script>
69
+
70
+ <Block
71
+ {visible}
72
+ variant={"solid"}
73
+ border_mode={dragging ? "focus" : "base"}
74
+ padding={false}
75
+ {elem_id}
76
+ {elem_classes}
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
+
89
+ <ImageAnnotator
90
+ bind:active_source
91
+ bind:value
92
+ on:change={() => gradio.dispatch("change")}
93
+ selectable={_selectable}
94
+ {root}
95
+ {sources}
96
+ {interactive}
97
+ showDownloadButton={show_download_button}
98
+ showShareButton={show_share_button}
99
+ showClearButton={show_clear_button}
100
+ i18n={gradio.i18n}
101
+ boxesAlpha={boxes_alpha}
102
+ height={height}
103
+ width={width}
104
+ labelList={label_list}
105
+ labelColors={label_colors}
106
+ boxMinSize={box_min_size}
107
+ on:edit={() => gradio.dispatch("edit")}
108
+ on:clear={() => {
109
+ gradio.dispatch("clear");
110
+ }}
111
+ on:drag={({ detail }) => (dragging = detail)}
112
+ on:upload={() => gradio.dispatch("upload")}
113
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
114
+ on:share={({ detail }) => gradio.dispatch("share", detail)}
115
+ on:error={({ detail }) => {
116
+ loading_status = loading_status || {};
117
+ loading_status.status = "error";
118
+ gradio.dispatch("error", detail);
119
+ }}
120
+ {label}
121
+ {show_label}
122
+ max_file_size={gradio.max_file_size}
123
+ cli_upload={gradio.client.upload}
124
+ stream_handler={gradio.client.stream}
125
+ handleSize={handle_size}
126
+ boxThickness={box_thickness}
127
+ boxSelectedThickness={box_selected_thickness}
128
+ disableEditBoxes={disable_edit_boxes}
129
+ singleBox={single_box}
130
+ showRemoveButton={show_remove_button}
131
+ handlesCursor={handles_cursor}
132
+ useDefaultLabel={use_default_label}
133
+ enableKeyboardShortcuts={enable_keyboard_shortcuts}
134
+ >
135
+ {#if active_source === "upload"}
136
+ <UploadText i18n={gradio.i18n} type="image" />
137
+ {:else if active_source === "clipboard"}
138
+ <UploadText i18n={gradio.i18n} type="clipboard" mode="short" />
139
+ {:else}
140
+ <Empty unpadded_box={true} size="large"><Image /></Empty>
141
+ {/if}
142
+ </ImageAnnotator>
143
+ </Block>
src/frontend/package-lock.json CHANGED
The diff for this file is too large to render. See raw diff
 
src/frontend/package.json CHANGED
@@ -1,35 +1,35 @@
1
- {
2
- "name": "gradio_image_annotator",
3
- "version": "0.11.9",
4
- "description": "Gradio UI packages",
5
- "type": "module",
6
- "author": "",
7
- "license": "ISC",
8
- "private": false,
9
- "dependencies": {
10
- "@gradio/atoms": "0.7.4",
11
- "@gradio/client": "1.1.0",
12
- "@gradio/icons": "0.4.1",
13
- "@gradio/statustracker": "0.6.0",
14
- "@gradio/upload": "0.11.1",
15
- "@gradio/image": "0.11.9",
16
- "@gradio/utils": "0.4.2",
17
- "@gradio/wasm": "0.10.1",
18
- "cropperjs": "^1.5.12",
19
- "lazy-brush": "^1.0.1",
20
- "resize-observer-polyfill": "^1.5.1",
21
- "@gradio/colorpicker": "^0.2.11",
22
- "@gradio/button": "^0.2.24"
23
- },
24
- "devDependencies": {
25
- "@gradio/preview": "0.9.1"
26
- },
27
- "main_changeset": true,
28
- "main": "./Index.svelte",
29
- "exports": {
30
- ".": "./Index.svelte",
31
- "./shared": "./shared/index.ts",
32
- "./example": "./Example.svelte",
33
- "./package.json": "./package.json"
34
- }
35
- }
 
1
+ {
2
+ "name": "gradio_image_annotator",
3
+ "version": "0.11.9",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@gradio/atoms": "0.7.4",
11
+ "@gradio/client": "1.1.0",
12
+ "@gradio/icons": "0.4.1",
13
+ "@gradio/statustracker": "0.6.0",
14
+ "@gradio/upload": "0.11.1",
15
+ "@gradio/image": "0.11.9",
16
+ "@gradio/utils": "0.4.2",
17
+ "@gradio/wasm": "0.10.1",
18
+ "cropperjs": "^1.5.12",
19
+ "lazy-brush": "^1.0.1",
20
+ "resize-observer-polyfill": "^1.5.1",
21
+ "@gradio/colorpicker": "^0.2.11",
22
+ "@gradio/button": "^0.2.24"
23
+ },
24
+ "devDependencies": {
25
+ "@gradio/preview": "0.9.1"
26
+ },
27
+ "main_changeset": true,
28
+ "main": "./Index.svelte",
29
+ "exports": {
30
+ ".": "./Index.svelte",
31
+ "./shared": "./shared/index.ts",
32
+ "./example": "./Example.svelte",
33
+ "./package.json": "./package.json"
34
+ }
35
+ }
src/frontend/shared/AnnotatedImageData.ts CHANGED
@@ -1,8 +1,8 @@
1
- import type { FileData } from "@gradio/client";
2
- import Box from "./Box";
3
-
4
- export default class AnnotatedImageData {
5
- image: FileData;
6
- boxes: Box[] = [];
7
- orientation: number = 0;
8
- }
 
1
+ import type { FileData } from "@gradio/client";
2
+ import Box from "./Box";
3
+
4
+ export default class AnnotatedImageData {
5
+ image: FileData;
6
+ boxes: Box[] = [];
7
+ orientation: number = 0;
8
+ }
src/frontend/shared/Box.ts CHANGED
@@ -1,567 +1,567 @@
1
- import WindowViewer from "./WindowViewer";
2
- const clamp = (num: number, min: number, max: number) => Math.min(Math.max(num, min), max)
3
-
4
-
5
- function setAlpha(rgbColor: string, alpha: number) {
6
- if (rgbColor.startsWith('rgba')) {
7
- return rgbColor.replace(/[\d.]+$/, alpha.toString());
8
- }
9
- const matches = rgbColor.match(/\d+/g);
10
- if (!matches || matches.length !== 3) {
11
- return `rgba(50, 50, 50, ${alpha})`;
12
- }
13
- const [r, g, b] = matches;
14
- return `rgba(${r}, ${g}, ${b}, ${alpha})`;
15
- }
16
-
17
-
18
- export default class Box {
19
- label: string;
20
- xmin: number;
21
- ymin: number;
22
- xmax: number;
23
- ymax: number;
24
- _xmin: number;
25
- _ymin: number;
26
- _xmax: number;
27
- _ymax: number;
28
- color: string;
29
- alpha: number;
30
- isDragging: boolean;
31
- isResizing: boolean;
32
- isSelected: boolean;
33
- isCreating: boolean;
34
- offsetMouseX: number;
35
- offsetMouseY: number;
36
- resizeHandleSize: number;
37
- resizingHandleIndex: number;
38
- minSize: number;
39
- renderCallBack: () => void;
40
- onFinishCreation: () => void;
41
- canvasXmin: number;
42
- canvasYmin: number;
43
- canvasXmax: number;
44
- canvasYmax: number;
45
- scaleFactor: number;
46
- thickness: number;
47
- selectedThickness: number;
48
- creatingAnchorX: string;
49
- creatingAnchorY: string;
50
- resizeHandles: {
51
- xmin: number;
52
- ymin: number;
53
- xmax: number;
54
- ymax: number;
55
- cursor: string;
56
- }[];
57
- canvasWindow: WindowViewer;
58
- pointersCache: Map<number, PointerEvent>;
59
-
60
- constructor(
61
- renderCallBack: () => void,
62
- onFinishCreation: () => void,
63
- canvasWindow: WindowViewer,
64
- pointersCache: Map<number, PointerEvent>,
65
- canvasXmin: number,
66
- canvasYmin: number,
67
- canvasXmax: number,
68
- canvasYmax: number,
69
- label: string,
70
- xmin: number,
71
- ymin: number,
72
- xmax: number,
73
- ymax: number,
74
- color: string = "rgb(255, 255, 255)",
75
- alpha: number = 0.5,
76
- minSize: number = 25,
77
- handleSize: number = 8,
78
- thickness: number = 2,
79
- selectedThickness: number = 4,
80
- scaleFactor: number = 1,
81
- ) {
82
- this.renderCallBack = renderCallBack;
83
- this.onFinishCreation = onFinishCreation;
84
- this.canvasWindow = canvasWindow;
85
- this.pointersCache = pointersCache;
86
- this.canvasXmin = canvasXmin;
87
- this.canvasYmin = canvasYmin;
88
- this.canvasXmax = canvasXmax;
89
- this.canvasYmax = canvasYmax;
90
- this.scaleFactor = scaleFactor;
91
- this.label = label;
92
- this.isDragging = false;
93
- this.isCreating = false;
94
- this._xmin = xmin;
95
- this._ymin = ymin;
96
- this._xmax = xmax;
97
- this._ymax = ymax;
98
- this.xmin = this._xmin * this.canvasWindow.scale;
99
- this.ymin = this._ymin * this.canvasWindow.scale;
100
- this.xmax = this._xmax * this.canvasWindow.scale;
101
- this.ymax = this._ymax * this.canvasWindow.scale;
102
- this.isResizing = false;
103
- this.isSelected = false;
104
- this.offsetMouseX = 0;
105
- this.offsetMouseY = 0;
106
- this.resizeHandleSize = handleSize;
107
- this.thickness = thickness;
108
- this.selectedThickness = selectedThickness;
109
- this.updateHandles();
110
- this.resizingHandleIndex = -1;
111
- this.minSize = minSize;
112
- this.color = color;
113
- this.alpha = alpha;
114
- this.creatingAnchorX = "xmin";
115
- this.creatingAnchorY = "ymin";
116
- }
117
-
118
- toJSON() {
119
- return {
120
- label: this.label,
121
- xmin: this._xmin,
122
- ymin: this._ymin,
123
- xmax: this._xmax,
124
- ymax: this._ymax,
125
- color: this.color,
126
- scaleFactor: this.scaleFactor,
127
- };
128
- }
129
-
130
- setSelected(selected: boolean): void{
131
- this.isSelected = selected;
132
- }
133
-
134
- setScaleFactor(scaleFactor: number) {
135
- let scale = scaleFactor / this.scaleFactor;
136
- this._xmin = Math.round(this._xmin * scale);
137
- this._ymin = Math.round(this._ymin * scale);
138
- this._xmax = Math.round(this._xmax * scale);
139
- this._ymax = Math.round(this._ymax * scale);
140
- this.applyUserScale();
141
- // this.updateHandles();
142
- this.scaleFactor = scaleFactor;
143
- }
144
-
145
- updateHandles(): void {
146
- const halfSize = this.resizeHandleSize / 2;
147
- const width = this.getWidth();
148
- const height = this.getHeight();
149
- this.resizeHandles = [
150
- {
151
- // Top left
152
- xmin: this.xmin - halfSize,
153
- ymin: this.ymin - halfSize,
154
- xmax: this.xmin + halfSize,
155
- ymax: this.ymin + halfSize,
156
- cursor: "nwse-resize",
157
- },
158
- {
159
- // Top right
160
- xmin: this.xmax - halfSize,
161
- ymin: this.ymin - halfSize,
162
- xmax: this.xmax + halfSize,
163
- ymax: this.ymin + halfSize,
164
- cursor: "nesw-resize",
165
- },
166
- {
167
- // Bottom right
168
- xmin: this.xmax - halfSize,
169
- ymin: this.ymax - halfSize,
170
- xmax: this.xmax + halfSize,
171
- ymax: this.ymax + halfSize,
172
- cursor: "nwse-resize",
173
- },
174
- {
175
- // Bottom left
176
- xmin: this.xmin - halfSize,
177
- ymin: this.ymax - halfSize,
178
- xmax: this.xmin + halfSize,
179
- ymax: this.ymax + halfSize,
180
- cursor: "nesw-resize",
181
- },
182
- {
183
- // Top center
184
- xmin: this.xmin + (width / 2) - halfSize,
185
- ymin: this.ymin - halfSize,
186
- xmax: this.xmin + (width / 2) + halfSize,
187
- ymax: this.ymin + halfSize,
188
- cursor: "ns-resize",
189
- },
190
- {
191
- // Right center
192
- xmin: this.xmax - halfSize,
193
- ymin: this.ymin + (height / 2) - halfSize,
194
- xmax: this.xmax + halfSize,
195
- ymax: this.ymin + (height / 2) + halfSize,
196
- cursor: "ew-resize",
197
- },
198
- {
199
- // Bottom center
200
- xmin: this.xmin + (width / 2) - halfSize,
201
- ymin: this.ymax - halfSize,
202
- xmax: this.xmin + (width / 2) + halfSize,
203
- ymax: this.ymax + halfSize,
204
- cursor: "ns-resize",
205
- },
206
- {
207
- // Left center
208
- xmin: this.xmin - halfSize,
209
- ymin: this.ymin + (height / 2) - halfSize,
210
- xmax: this.xmin + halfSize,
211
- ymax: this.ymin + (height / 2) + halfSize,
212
- cursor: "ew-resize",
213
- },
214
- ];
215
- }
216
-
217
- getWidth(): number {
218
- return this.xmax - this.xmin;
219
- }
220
-
221
- getHeight(): number {
222
- return this.ymax - this.ymin;
223
- }
224
-
225
- getArea(): number {
226
- return this.getWidth() * this.getHeight();
227
- }
228
-
229
- toCanvasCoordinates(x: number, y: number): [number, number] {
230
- x = x + this.canvasXmin;
231
- y = y + this.canvasYmin;
232
- return [x, y];
233
- }
234
-
235
- toBoxCoordinates(x: number, y: number): [number, number] {
236
- x = x - this.canvasXmin;
237
- y = y - this.canvasYmin;
238
- return [x, y];
239
- }
240
-
241
- applyUserScale(): void {
242
- this.xmin = this._xmin * this.canvasWindow.scale;
243
- this.ymin = this._ymin * this.canvasWindow.scale;
244
- this.xmax = this._xmax * this.canvasWindow.scale;
245
- this.ymax = this._ymax * this.canvasWindow.scale;
246
- this.updateHandles();
247
- }
248
-
249
- updateOffset(): void {
250
- this.canvasXmin = this.canvasWindow.offsetX;
251
- this.canvasYmin = this.canvasWindow.offsetY;
252
- this.canvasXmax = this.canvasWindow.offsetX + this.canvasWindow.imageWidth * this.canvasWindow.scale;
253
- this.canvasYmax = this.canvasWindow.offsetY + this.canvasWindow.imageHeight * this.canvasWindow.scale;
254
- this.applyUserScale();
255
- }
256
- render(ctx: CanvasRenderingContext2D): void {
257
- let xmin: number, ymin: number;
258
-
259
- this.updateOffset()
260
- // Render the box and border
261
- ctx.beginPath();
262
- [xmin, ymin] = this.toCanvasCoordinates(this.xmin, this.ymin);
263
- ctx.rect(xmin, ymin, this.getWidth(), this.getHeight());
264
- ctx.fillStyle = setAlpha(this.color, this.alpha);
265
- ctx.fill();
266
- if (this.isSelected) {
267
- ctx.lineWidth = this.selectedThickness;
268
- } else {
269
- ctx.lineWidth = this.thickness;
270
- }
271
- ctx.strokeStyle = setAlpha(this.color, 1);
272
-
273
- ctx.stroke();
274
- ctx.closePath();
275
-
276
- // Render the label and background
277
- if (this.label !== null && this.label.trim() !== ""){
278
- if (this.isSelected) {
279
- ctx.font = "bold 14px Arial";
280
- } else {
281
- ctx.font = "12px Arial";
282
- }
283
- const labelWidth = ctx.measureText(this.label).width + 10;
284
- const labelHeight = 20;
285
- let labelX = this.xmin;
286
- let labelY = this.ymin - labelHeight;
287
- ctx.fillStyle = "white";
288
- [labelX, labelY] = this.toCanvasCoordinates(labelX, labelY);
289
- ctx.fillRect(labelX, labelY, labelWidth, labelHeight);
290
- ctx.lineWidth = 1;
291
- ctx.strokeStyle = "black";
292
- ctx.strokeRect(labelX, labelY, labelWidth, labelHeight);
293
- ctx.fillStyle = "black";
294
- ctx.fillText(this.label, labelX + 5, labelY + 15);
295
- }
296
-
297
- // Render the handles
298
- ctx.fillStyle = setAlpha(this.color, 1);
299
- for (const handle of this.resizeHandles) {
300
- [xmin, ymin] = this.toCanvasCoordinates(handle.xmin, handle.ymin);
301
- ctx.fillRect(
302
- xmin,
303
- ymin,
304
- handle.xmax - handle.xmin,
305
- handle.ymax - handle.ymin,
306
- );
307
- }
308
- }
309
-
310
- startDrag(event: MouseEvent): void {
311
- this.isDragging = true;
312
- this.offsetMouseX = event.clientX - this._xmin * this.canvasWindow.scale;
313
- this.offsetMouseY = event.clientY - this._ymin * this.canvasWindow.scale;
314
- document.addEventListener("pointermove", this.handleDrag);
315
- document.addEventListener("pointerup", this.stopDrag);
316
- }
317
-
318
- stopDrag = (): void => {
319
- this.isDragging = false;
320
- document.removeEventListener("pointermove", this.handleDrag);
321
- document.removeEventListener("pointerup", this.stopDrag);
322
- };
323
-
324
- handleDrag = (event: MouseEvent): void => {
325
- if (this.isDragging && this.pointersCache.size === 1) {
326
- let deltaX = (event.clientX - this.offsetMouseX) / this.canvasWindow.scale - this._xmin;
327
- let deltaY = (event.clientY - this.offsetMouseY) / this.canvasWindow.scale - this._ymin;
328
-
329
- const canvasW = (this.canvasXmax - this.canvasXmin) / this.canvasWindow.scale;
330
- const canvasH = (this.canvasYmax - this.canvasYmin) / this.canvasWindow.scale;
331
- deltaX = clamp(deltaX, -this._xmin, canvasW-this._xmax);
332
- deltaY = clamp(deltaY, -this._ymin, canvasH-this._ymax);
333
- this._xmin += deltaX;
334
- this._ymin += deltaY;
335
- this._xmax += deltaX;
336
- this._ymax += deltaY;
337
-
338
- this.applyUserScale();
339
- // this.updateHandles();
340
- this.renderCallBack();
341
- }
342
- };
343
-
344
- isPointInsideBox(x: number, y: number): boolean {
345
- [x, y] = this.toBoxCoordinates(x, y);
346
- return (
347
- x >= this.xmin &&
348
- x <= this.xmax &&
349
- y >= this.ymin &&
350
- y <= this.ymax
351
- );
352
- }
353
-
354
- indexOfPointInsideHandle(x: number, y: number): number {
355
- [x, y] = this.toBoxCoordinates(x, y);
356
- for (let i = 0; i < this.resizeHandles.length; i++) {
357
- const handle = this.resizeHandles[i];
358
- if (
359
- x >= handle.xmin &&
360
- x <= handle.xmax &&
361
- y >= handle.ymin &&
362
- y <= handle.ymax
363
- ) {
364
- this.resizingHandleIndex = i;
365
- return i;
366
- }
367
- }
368
- return -1;
369
- }
370
-
371
- startCreating(event: MouseEvent, canvasX: number, canvasY: number): void {
372
- this.isCreating = true;
373
- this.offsetMouseX = canvasX;
374
- this.offsetMouseY = canvasY;
375
- document.addEventListener("pointermove", this.handleCreating);
376
- document.addEventListener("pointerup", this.stopCreating);
377
- }
378
-
379
- handleCreating = (event: MouseEvent): void => {
380
- if (this.isCreating && this.pointersCache.size === 1) {
381
- let [x, y] = this.toBoxCoordinates(event.clientX, event.clientY);
382
- x = (x - this.offsetMouseX) / this.canvasWindow.scale;
383
- y = (y - this.offsetMouseY) / this.canvasWindow.scale;
384
-
385
- if (x > this._xmax) {
386
- if (this.creatingAnchorX == "xmax") {
387
- this._xmin = this._xmax;
388
- }
389
- this._xmax = x;
390
- this.creatingAnchorX = "xmin";
391
- } else if (x > this._xmin && x < this._xmax && this.creatingAnchorX == "xmin") {
392
- this._xmax = x;
393
- } else if (x > this._xmin && x < this._xmax && this.creatingAnchorX == "xmax") {
394
- this._xmin = x;
395
- } else if (x < this._xmin) {
396
- if (this.creatingAnchorX == "xmin") {
397
- this._xmax = this._xmin;
398
- }
399
- this._xmin = x;
400
- this.creatingAnchorX = "xmax";
401
- }
402
-
403
- if (y > this._ymax) {
404
- if (this.creatingAnchorY == "ymax") {
405
- this._ymin = this._ymax;
406
- }
407
- this._ymax = y;
408
- this.creatingAnchorY = "ymin";
409
- } else if (y > this._ymin && y < this._ymax && this.creatingAnchorY == "ymin") {
410
- this._ymax = y;
411
- } else if (y > this._ymin && y < this._ymax && this.creatingAnchorY == "ymax") {
412
- this._ymin = y;
413
- } else if (y < this._ymin) {
414
- if (this.creatingAnchorY == "ymin") {
415
- this._ymax = this._ymin;
416
- }
417
- this._ymin = y;
418
- this.creatingAnchorY = "ymax";
419
- }
420
- this.applyUserScale();
421
- // this.updateHandles();
422
- this.renderCallBack();
423
- }
424
- }
425
-
426
- stopCreating = (event: MouseEvent): void => {
427
- this.isCreating = false;
428
- document.removeEventListener("pointermove", this.handleCreating);
429
- document.removeEventListener("pointerup", this.stopCreating);
430
-
431
- if (this.getArea() > 0) {
432
- const canvasW = (this.canvasXmax - this.canvasXmin) / this.canvasWindow.scale;
433
- const canvasH = (this.canvasYmax - this.canvasYmin) / this.canvasWindow.scale;
434
- this._xmin = clamp(this._xmin, 0, canvasW - this.minSize);
435
- this._ymin = clamp(this._ymin, 0, canvasH - this.minSize);
436
- this._xmax = clamp(this._xmax, this.minSize, canvasW);
437
- this._ymax = clamp(this._ymax, this.minSize, canvasH);
438
-
439
- if (this.minSize > 0) {
440
- if (this.getWidth() / this.canvasWindow.scale < this.minSize) {
441
- if (this.creatingAnchorX == "xmin") {
442
- this._xmax = this._xmin + this.minSize;
443
- } else {
444
- this._xmin = this._xmax - this.minSize;
445
- }
446
- }
447
- if (this.getHeight() / this.canvasWindow.scale < this.minSize) {
448
- if (this.creatingAnchorY == "ymin") {
449
- this._ymax = this._ymin + this.minSize;
450
- } else {
451
- this._ymin = this._ymax - this.minSize;
452
- }
453
- }
454
- if (this._xmax > canvasW) {
455
- this._xmin -= this._xmax - canvasW;
456
- this._xmax = canvasW;
457
- } else if (this._xmin < 0) {
458
- this._xmax -= this._xmin;
459
- this._xmin = 0;
460
- }
461
- if (this._ymax > canvasH) {
462
- this._ymin -= this._ymax - canvasH;
463
- this._ymax = canvasH;
464
- } else if (this._ymin < 0) {
465
- this._ymax -= this._ymin;
466
- this._ymin = 0;
467
- }
468
- }
469
- this.applyUserScale();
470
- // this.updateHandles();
471
- this.renderCallBack();
472
- }
473
- this.onFinishCreation();
474
- }
475
-
476
- startResize(handleIndex: number, event: MouseEvent): void {
477
- this.resizingHandleIndex = handleIndex;
478
- this.isResizing = true;
479
- this.offsetMouseX = event.clientX - this.resizeHandles[handleIndex].xmin;
480
- this.offsetMouseY = event.clientY - this.resizeHandles[handleIndex].ymin;
481
- document.addEventListener("pointermove", this.handleResize);
482
- document.addEventListener("pointerup", this.stopResize);
483
- }
484
-
485
- handleResize = (event: MouseEvent): void => {
486
- if (this.isResizing && this.pointersCache.size === 1) {
487
- const mouseX = event.clientX;
488
- const mouseY = event.clientY;
489
- const deltaX = (mouseX - this.offsetMouseX - this.resizeHandles[this.resizingHandleIndex].xmin) / this.canvasWindow.scale;
490
- const deltaY = (mouseY - this.offsetMouseY - this.resizeHandles[this.resizingHandleIndex].ymin) / this.canvasWindow.scale;
491
- const canvasW = (this.canvasXmax - this.canvasXmin) / this.canvasWindow.scale;
492
- const canvasH = (this.canvasYmax - this.canvasYmin) / this.canvasWindow.scale;
493
- switch (this.resizingHandleIndex) {
494
- case 0: // Top-left handle
495
- this._xmin += deltaX;
496
- this._ymin += deltaY;
497
- this._xmin = clamp(this._xmin, 0, this._xmax - this.minSize);
498
- this._ymin = clamp(this._ymin, 0, this._ymax - this.minSize);
499
- break;
500
- case 1: // Top-right handle
501
- this._xmax += deltaX;
502
- this._ymin += deltaY;
503
- this._xmax = clamp(this._xmax, this._xmin + this.minSize, canvasW);
504
- this._ymin = clamp(this._ymin, 0, this._ymax - this.minSize);
505
- break;
506
- case 2: // Bottom-right handle
507
- this._xmax += deltaX;
508
- this._ymax += deltaY;
509
- this._xmax = clamp(this._xmax, this._xmin + this.minSize, canvasW);
510
- this._ymax = clamp(this._ymax, this._ymin + this.minSize, canvasH);
511
- break;
512
- case 3: // Bottom-left handle
513
- this._xmin += deltaX;
514
- this._ymax += deltaY;
515
- this._xmin = clamp(this._xmin, 0, this._xmax - this.minSize);
516
- this._ymax = clamp(this._ymax, this._ymin + this.minSize, canvasH);
517
- break;
518
- case 4: // Top center handle
519
- this._ymin += deltaY;
520
- this._ymin = clamp(this._ymin, 0, this._ymax - this.minSize);
521
- break;
522
- case 5: // Right center handle
523
- this._xmax += deltaX;
524
- this._xmax = clamp(this._xmax, this._xmin + this.minSize, canvasW);
525
- break;
526
- case 6: // Bottom center handle
527
- this._ymax += deltaY;
528
- this._ymax = clamp(this._ymax, this._ymin + this.minSize, canvasH);
529
- break;
530
- case 7: // Left center handle
531
- this._xmin += deltaX;
532
- this._xmin = clamp(this._xmin, 0, this._xmax - this.minSize);
533
- break;
534
- }
535
-
536
- // Update the resize handles
537
- this.applyUserScale();
538
- // this.updateHandles();
539
- this.renderCallBack();
540
- }
541
- };
542
-
543
- stopResize = (): void => {
544
- this.isResizing = false;
545
- document.removeEventListener("pointermove", this.handleResize);
546
- document.removeEventListener("pointerup", this.stopResize);
547
- };
548
-
549
- onRotate(op: number): void {
550
- const [_xmin, _xmax, _ymin, _ymax] = [this._xmin, this._xmax, this._ymin, this._ymax];
551
- switch (op) {
552
- case 1:
553
- this._xmin = this.canvasWindow.imageWidth - _ymax;
554
- this._xmax = this.canvasWindow.imageWidth - _ymin;
555
- this._ymin = _xmin;
556
- this._ymax = _xmax;
557
- break;
558
- case -1:
559
- this._xmin = _ymin;
560
- this._xmax = _ymax;
561
- this._ymin = this.canvasWindow.imageHeight - _xmax;
562
- this._ymax = this.canvasWindow.imageHeight - _xmin;
563
- break;
564
- }
565
- this.applyUserScale();
566
- }
567
- }
 
1
+ import WindowViewer from "./WindowViewer";
2
+ const clamp = (num: number, min: number, max: number) => Math.min(Math.max(num, min), max)
3
+
4
+
5
+ function setAlpha(rgbColor: string, alpha: number) {
6
+ if (rgbColor.startsWith('rgba')) {
7
+ return rgbColor.replace(/[\d.]+$/, alpha.toString());
8
+ }
9
+ const matches = rgbColor.match(/\d+/g);
10
+ if (!matches || matches.length !== 3) {
11
+ return `rgba(50, 50, 50, ${alpha})`;
12
+ }
13
+ const [r, g, b] = matches;
14
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
15
+ }
16
+
17
+
18
+ export default class Box {
19
+ label: string;
20
+ xmin: number;
21
+ ymin: number;
22
+ xmax: number;
23
+ ymax: number;
24
+ _xmin: number;
25
+ _ymin: number;
26
+ _xmax: number;
27
+ _ymax: number;
28
+ color: string;
29
+ alpha: number;
30
+ isDragging: boolean;
31
+ isResizing: boolean;
32
+ isSelected: boolean;
33
+ isCreating: boolean;
34
+ offsetMouseX: number;
35
+ offsetMouseY: number;
36
+ resizeHandleSize: number;
37
+ resizingHandleIndex: number;
38
+ minSize: number;
39
+ renderCallBack: () => void;
40
+ onFinishCreation: () => void;
41
+ canvasXmin: number;
42
+ canvasYmin: number;
43
+ canvasXmax: number;
44
+ canvasYmax: number;
45
+ scaleFactor: number;
46
+ thickness: number;
47
+ selectedThickness: number;
48
+ creatingAnchorX: string;
49
+ creatingAnchorY: string;
50
+ resizeHandles: {
51
+ xmin: number;
52
+ ymin: number;
53
+ xmax: number;
54
+ ymax: number;
55
+ cursor: string;
56
+ }[];
57
+ canvasWindow: WindowViewer;
58
+ pointersCache: Map<number, PointerEvent>;
59
+
60
+ constructor(
61
+ renderCallBack: () => void,
62
+ onFinishCreation: () => void,
63
+ canvasWindow: WindowViewer,
64
+ pointersCache: Map<number, PointerEvent>,
65
+ canvasXmin: number,
66
+ canvasYmin: number,
67
+ canvasXmax: number,
68
+ canvasYmax: number,
69
+ label: string,
70
+ xmin: number,
71
+ ymin: number,
72
+ xmax: number,
73
+ ymax: number,
74
+ color: string = "rgb(255, 255, 255)",
75
+ alpha: number = 0.5,
76
+ minSize: number = 25,
77
+ handleSize: number = 8,
78
+ thickness: number = 2,
79
+ selectedThickness: number = 4,
80
+ scaleFactor: number = 1,
81
+ ) {
82
+ this.renderCallBack = renderCallBack;
83
+ this.onFinishCreation = onFinishCreation;
84
+ this.canvasWindow = canvasWindow;
85
+ this.pointersCache = pointersCache;
86
+ this.canvasXmin = canvasXmin;
87
+ this.canvasYmin = canvasYmin;
88
+ this.canvasXmax = canvasXmax;
89
+ this.canvasYmax = canvasYmax;
90
+ this.scaleFactor = scaleFactor;
91
+ this.label = label;
92
+ this.isDragging = false;
93
+ this.isCreating = false;
94
+ this._xmin = xmin;
95
+ this._ymin = ymin;
96
+ this._xmax = xmax;
97
+ this._ymax = ymax;
98
+ this.xmin = this._xmin * this.canvasWindow.scale;
99
+ this.ymin = this._ymin * this.canvasWindow.scale;
100
+ this.xmax = this._xmax * this.canvasWindow.scale;
101
+ this.ymax = this._ymax * this.canvasWindow.scale;
102
+ this.isResizing = false;
103
+ this.isSelected = false;
104
+ this.offsetMouseX = 0;
105
+ this.offsetMouseY = 0;
106
+ this.resizeHandleSize = handleSize;
107
+ this.thickness = thickness;
108
+ this.selectedThickness = selectedThickness;
109
+ this.updateHandles();
110
+ this.resizingHandleIndex = -1;
111
+ this.minSize = minSize;
112
+ this.color = color;
113
+ this.alpha = alpha;
114
+ this.creatingAnchorX = "xmin";
115
+ this.creatingAnchorY = "ymin";
116
+ }
117
+
118
+ toJSON() {
119
+ return {
120
+ label: this.label,
121
+ xmin: this._xmin,
122
+ ymin: this._ymin,
123
+ xmax: this._xmax,
124
+ ymax: this._ymax,
125
+ color: this.color,
126
+ scaleFactor: this.scaleFactor,
127
+ };
128
+ }
129
+
130
+ setSelected(selected: boolean): void{
131
+ this.isSelected = selected;
132
+ }
133
+
134
+ setScaleFactor(scaleFactor: number) {
135
+ let scale = scaleFactor / this.scaleFactor;
136
+ this._xmin = Math.round(this._xmin * scale);
137
+ this._ymin = Math.round(this._ymin * scale);
138
+ this._xmax = Math.round(this._xmax * scale);
139
+ this._ymax = Math.round(this._ymax * scale);
140
+ this.applyUserScale();
141
+ // this.updateHandles();
142
+ this.scaleFactor = scaleFactor;
143
+ }
144
+
145
+ updateHandles(): void {
146
+ const halfSize = this.resizeHandleSize / 2;
147
+ const width = this.getWidth();
148
+ const height = this.getHeight();
149
+ this.resizeHandles = [
150
+ {
151
+ // Top left
152
+ xmin: this.xmin - halfSize,
153
+ ymin: this.ymin - halfSize,
154
+ xmax: this.xmin + halfSize,
155
+ ymax: this.ymin + halfSize,
156
+ cursor: "nwse-resize",
157
+ },
158
+ {
159
+ // Top right
160
+ xmin: this.xmax - halfSize,
161
+ ymin: this.ymin - halfSize,
162
+ xmax: this.xmax + halfSize,
163
+ ymax: this.ymin + halfSize,
164
+ cursor: "nesw-resize",
165
+ },
166
+ {
167
+ // Bottom right
168
+ xmin: this.xmax - halfSize,
169
+ ymin: this.ymax - halfSize,
170
+ xmax: this.xmax + halfSize,
171
+ ymax: this.ymax + halfSize,
172
+ cursor: "nwse-resize",
173
+ },
174
+ {
175
+ // Bottom left
176
+ xmin: this.xmin - halfSize,
177
+ ymin: this.ymax - halfSize,
178
+ xmax: this.xmin + halfSize,
179
+ ymax: this.ymax + halfSize,
180
+ cursor: "nesw-resize",
181
+ },
182
+ {
183
+ // Top center
184
+ xmin: this.xmin + (width / 2) - halfSize,
185
+ ymin: this.ymin - halfSize,
186
+ xmax: this.xmin + (width / 2) + halfSize,
187
+ ymax: this.ymin + halfSize,
188
+ cursor: "ns-resize",
189
+ },
190
+ {
191
+ // Right center
192
+ xmin: this.xmax - halfSize,
193
+ ymin: this.ymin + (height / 2) - halfSize,
194
+ xmax: this.xmax + halfSize,
195
+ ymax: this.ymin + (height / 2) + halfSize,
196
+ cursor: "ew-resize",
197
+ },
198
+ {
199
+ // Bottom center
200
+ xmin: this.xmin + (width / 2) - halfSize,
201
+ ymin: this.ymax - halfSize,
202
+ xmax: this.xmin + (width / 2) + halfSize,
203
+ ymax: this.ymax + halfSize,
204
+ cursor: "ns-resize",
205
+ },
206
+ {
207
+ // Left center
208
+ xmin: this.xmin - halfSize,
209
+ ymin: this.ymin + (height / 2) - halfSize,
210
+ xmax: this.xmin + halfSize,
211
+ ymax: this.ymin + (height / 2) + halfSize,
212
+ cursor: "ew-resize",
213
+ },
214
+ ];
215
+ }
216
+
217
+ getWidth(): number {
218
+ return this.xmax - this.xmin;
219
+ }
220
+
221
+ getHeight(): number {
222
+ return this.ymax - this.ymin;
223
+ }
224
+
225
+ getArea(): number {
226
+ return this.getWidth() * this.getHeight();
227
+ }
228
+
229
+ toCanvasCoordinates(x: number, y: number): [number, number] {
230
+ x = x + this.canvasXmin;
231
+ y = y + this.canvasYmin;
232
+ return [x, y];
233
+ }
234
+
235
+ toBoxCoordinates(x: number, y: number): [number, number] {
236
+ x = x - this.canvasXmin;
237
+ y = y - this.canvasYmin;
238
+ return [x, y];
239
+ }
240
+
241
+ applyUserScale(): void {
242
+ this.xmin = this._xmin * this.canvasWindow.scale;
243
+ this.ymin = this._ymin * this.canvasWindow.scale;
244
+ this.xmax = this._xmax * this.canvasWindow.scale;
245
+ this.ymax = this._ymax * this.canvasWindow.scale;
246
+ this.updateHandles();
247
+ }
248
+
249
+ updateOffset(): void {
250
+ this.canvasXmin = this.canvasWindow.offsetX;
251
+ this.canvasYmin = this.canvasWindow.offsetY;
252
+ this.canvasXmax = this.canvasWindow.offsetX + this.canvasWindow.imageWidth * this.canvasWindow.scale;
253
+ this.canvasYmax = this.canvasWindow.offsetY + this.canvasWindow.imageHeight * this.canvasWindow.scale;
254
+ this.applyUserScale();
255
+ }
256
+ render(ctx: CanvasRenderingContext2D): void {
257
+ let xmin: number, ymin: number;
258
+
259
+ this.updateOffset()
260
+ // Render the box and border
261
+ ctx.beginPath();
262
+ [xmin, ymin] = this.toCanvasCoordinates(this.xmin, this.ymin);
263
+ ctx.rect(xmin, ymin, this.getWidth(), this.getHeight());
264
+ ctx.fillStyle = setAlpha(this.color, this.alpha);
265
+ ctx.fill();
266
+ if (this.isSelected) {
267
+ ctx.lineWidth = this.selectedThickness;
268
+ } else {
269
+ ctx.lineWidth = this.thickness;
270
+ }
271
+ ctx.strokeStyle = setAlpha(this.color, 1);
272
+
273
+ ctx.stroke();
274
+ ctx.closePath();
275
+
276
+ // Render the label and background
277
+ if (this.label !== null && this.label.trim() !== ""){
278
+ if (this.isSelected) {
279
+ ctx.font = "bold 14px Arial";
280
+ } else {
281
+ ctx.font = "12px Arial";
282
+ }
283
+ const labelWidth = ctx.measureText(this.label).width + 10;
284
+ const labelHeight = 20;
285
+ let labelX = this.xmin;
286
+ let labelY = this.ymin - labelHeight;
287
+ ctx.fillStyle = "white";
288
+ [labelX, labelY] = this.toCanvasCoordinates(labelX, labelY);
289
+ ctx.fillRect(labelX, labelY, labelWidth, labelHeight);
290
+ ctx.lineWidth = 1;
291
+ ctx.strokeStyle = "black";
292
+ ctx.strokeRect(labelX, labelY, labelWidth, labelHeight);
293
+ ctx.fillStyle = "black";
294
+ ctx.fillText(this.label, labelX + 5, labelY + 15);
295
+ }
296
+
297
+ // Render the handles
298
+ ctx.fillStyle = setAlpha(this.color, 1);
299
+ for (const handle of this.resizeHandles) {
300
+ [xmin, ymin] = this.toCanvasCoordinates(handle.xmin, handle.ymin);
301
+ ctx.fillRect(
302
+ xmin,
303
+ ymin,
304
+ handle.xmax - handle.xmin,
305
+ handle.ymax - handle.ymin,
306
+ );
307
+ }
308
+ }
309
+
310
+ startDrag(event: MouseEvent): void {
311
+ this.isDragging = true;
312
+ this.offsetMouseX = event.clientX - this._xmin * this.canvasWindow.scale;
313
+ this.offsetMouseY = event.clientY - this._ymin * this.canvasWindow.scale;
314
+ document.addEventListener("pointermove", this.handleDrag);
315
+ document.addEventListener("pointerup", this.stopDrag);
316
+ }
317
+
318
+ stopDrag = (): void => {
319
+ this.isDragging = false;
320
+ document.removeEventListener("pointermove", this.handleDrag);
321
+ document.removeEventListener("pointerup", this.stopDrag);
322
+ };
323
+
324
+ handleDrag = (event: MouseEvent): void => {
325
+ if (this.isDragging && this.pointersCache.size === 1) {
326
+ let deltaX = (event.clientX - this.offsetMouseX) / this.canvasWindow.scale - this._xmin;
327
+ let deltaY = (event.clientY - this.offsetMouseY) / this.canvasWindow.scale - this._ymin;
328
+
329
+ const canvasW = (this.canvasXmax - this.canvasXmin) / this.canvasWindow.scale;
330
+ const canvasH = (this.canvasYmax - this.canvasYmin) / this.canvasWindow.scale;
331
+ deltaX = clamp(deltaX, -this._xmin, canvasW-this._xmax);
332
+ deltaY = clamp(deltaY, -this._ymin, canvasH-this._ymax);
333
+ this._xmin += deltaX;
334
+ this._ymin += deltaY;
335
+ this._xmax += deltaX;
336
+ this._ymax += deltaY;
337
+
338
+ this.applyUserScale();
339
+ // this.updateHandles();
340
+ this.renderCallBack();
341
+ }
342
+ };
343
+
344
+ isPointInsideBox(x: number, y: number): boolean {
345
+ [x, y] = this.toBoxCoordinates(x, y);
346
+ return (
347
+ x >= this.xmin &&
348
+ x <= this.xmax &&
349
+ y >= this.ymin &&
350
+ y <= this.ymax
351
+ );
352
+ }
353
+
354
+ indexOfPointInsideHandle(x: number, y: number): number {
355
+ [x, y] = this.toBoxCoordinates(x, y);
356
+ for (let i = 0; i < this.resizeHandles.length; i++) {
357
+ const handle = this.resizeHandles[i];
358
+ if (
359
+ x >= handle.xmin &&
360
+ x <= handle.xmax &&
361
+ y >= handle.ymin &&
362
+ y <= handle.ymax
363
+ ) {
364
+ this.resizingHandleIndex = i;
365
+ return i;
366
+ }
367
+ }
368
+ return -1;
369
+ }
370
+
371
+ startCreating(event: MouseEvent, canvasX: number, canvasY: number): void {
372
+ this.isCreating = true;
373
+ this.offsetMouseX = canvasX;
374
+ this.offsetMouseY = canvasY;
375
+ document.addEventListener("pointermove", this.handleCreating);
376
+ document.addEventListener("pointerup", this.stopCreating);
377
+ }
378
+
379
+ handleCreating = (event: MouseEvent): void => {
380
+ if (this.isCreating && this.pointersCache.size === 1) {
381
+ let [x, y] = this.toBoxCoordinates(event.clientX, event.clientY);
382
+ x = (x - this.offsetMouseX) / this.canvasWindow.scale;
383
+ y = (y - this.offsetMouseY) / this.canvasWindow.scale;
384
+
385
+ if (x > this._xmax) {
386
+ if (this.creatingAnchorX == "xmax") {
387
+ this._xmin = this._xmax;
388
+ }
389
+ this._xmax = x;
390
+ this.creatingAnchorX = "xmin";
391
+ } else if (x > this._xmin && x < this._xmax && this.creatingAnchorX == "xmin") {
392
+ this._xmax = x;
393
+ } else if (x > this._xmin && x < this._xmax && this.creatingAnchorX == "xmax") {
394
+ this._xmin = x;
395
+ } else if (x < this._xmin) {
396
+ if (this.creatingAnchorX == "xmin") {
397
+ this._xmax = this._xmin;
398
+ }
399
+ this._xmin = x;
400
+ this.creatingAnchorX = "xmax";
401
+ }
402
+
403
+ if (y > this._ymax) {
404
+ if (this.creatingAnchorY == "ymax") {
405
+ this._ymin = this._ymax;
406
+ }
407
+ this._ymax = y;
408
+ this.creatingAnchorY = "ymin";
409
+ } else if (y > this._ymin && y < this._ymax && this.creatingAnchorY == "ymin") {
410
+ this._ymax = y;
411
+ } else if (y > this._ymin && y < this._ymax && this.creatingAnchorY == "ymax") {
412
+ this._ymin = y;
413
+ } else if (y < this._ymin) {
414
+ if (this.creatingAnchorY == "ymin") {
415
+ this._ymax = this._ymin;
416
+ }
417
+ this._ymin = y;
418
+ this.creatingAnchorY = "ymax";
419
+ }
420
+ this.applyUserScale();
421
+ // this.updateHandles();
422
+ this.renderCallBack();
423
+ }
424
+ }
425
+
426
+ stopCreating = (event: MouseEvent): void => {
427
+ this.isCreating = false;
428
+ document.removeEventListener("pointermove", this.handleCreating);
429
+ document.removeEventListener("pointerup", this.stopCreating);
430
+
431
+ if (this.getArea() > 0) {
432
+ const canvasW = (this.canvasXmax - this.canvasXmin) / this.canvasWindow.scale;
433
+ const canvasH = (this.canvasYmax - this.canvasYmin) / this.canvasWindow.scale;
434
+ this._xmin = clamp(this._xmin, 0, canvasW - this.minSize);
435
+ this._ymin = clamp(this._ymin, 0, canvasH - this.minSize);
436
+ this._xmax = clamp(this._xmax, this.minSize, canvasW);
437
+ this._ymax = clamp(this._ymax, this.minSize, canvasH);
438
+
439
+ if (this.minSize > 0) {
440
+ if (this.getWidth() / this.canvasWindow.scale < this.minSize) {
441
+ if (this.creatingAnchorX == "xmin") {
442
+ this._xmax = this._xmin + this.minSize;
443
+ } else {
444
+ this._xmin = this._xmax - this.minSize;
445
+ }
446
+ }
447
+ if (this.getHeight() / this.canvasWindow.scale < this.minSize) {
448
+ if (this.creatingAnchorY == "ymin") {
449
+ this._ymax = this._ymin + this.minSize;
450
+ } else {
451
+ this._ymin = this._ymax - this.minSize;
452
+ }
453
+ }
454
+ if (this._xmax > canvasW) {
455
+ this._xmin -= this._xmax - canvasW;
456
+ this._xmax = canvasW;
457
+ } else if (this._xmin < 0) {
458
+ this._xmax -= this._xmin;
459
+ this._xmin = 0;
460
+ }
461
+ if (this._ymax > canvasH) {
462
+ this._ymin -= this._ymax - canvasH;
463
+ this._ymax = canvasH;
464
+ } else if (this._ymin < 0) {
465
+ this._ymax -= this._ymin;
466
+ this._ymin = 0;
467
+ }
468
+ }
469
+ this.applyUserScale();
470
+ // this.updateHandles();
471
+ this.renderCallBack();
472
+ }
473
+ this.onFinishCreation();
474
+ }
475
+
476
+ startResize(handleIndex: number, event: MouseEvent): void {
477
+ this.resizingHandleIndex = handleIndex;
478
+ this.isResizing = true;
479
+ this.offsetMouseX = event.clientX - this.resizeHandles[handleIndex].xmin;
480
+ this.offsetMouseY = event.clientY - this.resizeHandles[handleIndex].ymin;
481
+ document.addEventListener("pointermove", this.handleResize);
482
+ document.addEventListener("pointerup", this.stopResize);
483
+ }
484
+
485
+ handleResize = (event: MouseEvent): void => {
486
+ if (this.isResizing && this.pointersCache.size === 1) {
487
+ const mouseX = event.clientX;
488
+ const mouseY = event.clientY;
489
+ const deltaX = (mouseX - this.offsetMouseX - this.resizeHandles[this.resizingHandleIndex].xmin) / this.canvasWindow.scale;
490
+ const deltaY = (mouseY - this.offsetMouseY - this.resizeHandles[this.resizingHandleIndex].ymin) / this.canvasWindow.scale;
491
+ const canvasW = (this.canvasXmax - this.canvasXmin) / this.canvasWindow.scale;
492
+ const canvasH = (this.canvasYmax - this.canvasYmin) / this.canvasWindow.scale;
493
+ switch (this.resizingHandleIndex) {
494
+ case 0: // Top-left handle
495
+ this._xmin += deltaX;
496
+ this._ymin += deltaY;
497
+ this._xmin = clamp(this._xmin, 0, this._xmax - this.minSize);
498
+ this._ymin = clamp(this._ymin, 0, this._ymax - this.minSize);
499
+ break;
500
+ case 1: // Top-right handle
501
+ this._xmax += deltaX;
502
+ this._ymin += deltaY;
503
+ this._xmax = clamp(this._xmax, this._xmin + this.minSize, canvasW);
504
+ this._ymin = clamp(this._ymin, 0, this._ymax - this.minSize);
505
+ break;
506
+ case 2: // Bottom-right handle
507
+ this._xmax += deltaX;
508
+ this._ymax += deltaY;
509
+ this._xmax = clamp(this._xmax, this._xmin + this.minSize, canvasW);
510
+ this._ymax = clamp(this._ymax, this._ymin + this.minSize, canvasH);
511
+ break;
512
+ case 3: // Bottom-left handle
513
+ this._xmin += deltaX;
514
+ this._ymax += deltaY;
515
+ this._xmin = clamp(this._xmin, 0, this._xmax - this.minSize);
516
+ this._ymax = clamp(this._ymax, this._ymin + this.minSize, canvasH);
517
+ break;
518
+ case 4: // Top center handle
519
+ this._ymin += deltaY;
520
+ this._ymin = clamp(this._ymin, 0, this._ymax - this.minSize);
521
+ break;
522
+ case 5: // Right center handle
523
+ this._xmax += deltaX;
524
+ this._xmax = clamp(this._xmax, this._xmin + this.minSize, canvasW);
525
+ break;
526
+ case 6: // Bottom center handle
527
+ this._ymax += deltaY;
528
+ this._ymax = clamp(this._ymax, this._ymin + this.minSize, canvasH);
529
+ break;
530
+ case 7: // Left center handle
531
+ this._xmin += deltaX;
532
+ this._xmin = clamp(this._xmin, 0, this._xmax - this.minSize);
533
+ break;
534
+ }
535
+
536
+ // Update the resize handles
537
+ this.applyUserScale();
538
+ // this.updateHandles();
539
+ this.renderCallBack();
540
+ }
541
+ };
542
+
543
+ stopResize = (): void => {
544
+ this.isResizing = false;
545
+ document.removeEventListener("pointermove", this.handleResize);
546
+ document.removeEventListener("pointerup", this.stopResize);
547
+ };
548
+
549
+ onRotate(op: number): void {
550
+ const [_xmin, _xmax, _ymin, _ymax] = [this._xmin, this._xmax, this._ymin, this._ymax];
551
+ switch (op) {
552
+ case 1:
553
+ this._xmin = this.canvasWindow.imageWidth - _ymax;
554
+ this._xmax = this.canvasWindow.imageWidth - _ymin;
555
+ this._ymin = _xmin;
556
+ this._ymax = _xmax;
557
+ break;
558
+ case -1:
559
+ this._xmin = _ymin;
560
+ this._xmax = _ymax;
561
+ this._ymin = this.canvasWindow.imageHeight - _xmax;
562
+ this._ymax = this.canvasWindow.imageHeight - _xmin;
563
+ break;
564
+ }
565
+ this.applyUserScale();
566
+ }
567
+ }
src/frontend/shared/Canvas.svelte CHANGED
@@ -1,872 +1,869 @@
1
- <script lang="ts">
2
- import { onMount, createEventDispatcher } from "svelte";
3
- import { BoundingBox, Hand, Trash, Label } from "./icons/index";
4
- import ModalBox from "./ModalBox.svelte";
5
- import Box from "./Box";
6
- import { Colors } from './Colors.js';
7
- import AnnotatedImageData from "./AnnotatedImageData";
8
- import { Undo, Redo } from "@gradio/icons";
9
- import WindowViewer from "./WindowViewer";
10
-
11
- enum Mode {creation, drag}
12
-
13
- export let imageUrl: string | null = null;
14
- export let interactive: boolean;
15
- export let boxAlpha = 0.5;
16
- export let boxMinSize = 10;
17
- export let handleSize: number;
18
- export let boxThickness: number;
19
- export let boxSelectedThickness: number;
20
- export let value: null | AnnotatedImageData;
21
- export let choices = [];
22
- export let choicesColors = [];
23
- export let disableEditBoxes: boolean = false;
24
- export let height: number | string = "100%";
25
- export let width: number | string = "100%";
26
- export let singleBox: boolean = false;
27
- export let showRemoveButton: boolean = null;
28
- export let handlesCursor: boolean = true;
29
- export let useDefaultLabel: boolean = false;
30
- export let enableKeyboardShortcuts: boolean = true;
31
-
32
- if (showRemoveButton === null) {
33
- showRemoveButton = (disableEditBoxes);
34
- }
35
-
36
- let canvas: HTMLCanvasElement;
37
- let annotatorContainerDiv: HTMLDivElement;
38
- let ctx: CanvasRenderingContext2D;
39
- let image = null;
40
- let selectedBox = -1;
41
- let mode: Mode = Mode.drag;
42
- let pointersCache: Map<number, PointerEvent> = new Map();
43
- let canvasWindow: WindowViewer = new WindowViewer(draw, pointersCache);
44
-
45
- if (value !== null && value.boxes.length == 0) {
46
- mode = Mode.creation;
47
- }
48
-
49
- let canvasXmin = 0;
50
- let canvasYmin = 0;
51
- let canvasXmax = 0;
52
- let canvasYmax = 0;
53
- let scaleFactor = 1.0;
54
-
55
- let imageWidth = 0;
56
- let imageHeight = 0;
57
-
58
- let editModalVisible = false;
59
- let newModalVisible = false;
60
- let editDefaultLabelVisible = false;
61
-
62
- let labelDetailLock = useDefaultLabel;
63
- let defaultLabelCache = {
64
- label: "",
65
- color: ""
66
- };
67
-
68
- let touchScaleValues = {
69
- x: 0,
70
- y: 0,
71
- distance: 0,
72
- }
73
- const touchScaleDeadzone = 100;
74
-
75
- const dispatch = createEventDispatcher<{
76
- change: undefined;
77
- }>();
78
-
79
- function colorHexToRGB(hex: string) {
80
- var r = parseInt(hex.slice(1, 3), 16),
81
- g = parseInt(hex.slice(3, 5), 16),
82
- b = parseInt(hex.slice(5, 7), 16);
83
- return "rgb(" + r + ", " + g + ", " + b + ")";
84
- }
85
-
86
- function colorRGBAToHex(rgba: string) {
87
- const rgbaValues = rgba.match(/(\d+(\.\d+)?)/g);
88
- const r = parseInt(rgbaValues[0]);
89
- const g = parseInt(rgbaValues[1]);
90
- const b = parseInt(rgbaValues[2]);
91
- const hex = "#" + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);
92
- return hex;
93
- }
94
-
95
- function draw() {
96
- if (ctx) {
97
- ctx.clearRect(0, 0, canvas.width, canvas.height);
98
- ctx.save();
99
- ctx.translate(canvasWindow.offsetX, canvasWindow.offsetY);
100
- ctx.scale(canvasWindow.scale, canvasWindow.scale);
101
- if (image !== null){
102
- switch (value.orientation) {
103
- case 0:
104
- ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
105
- break;
106
- case 1:
107
- ctx.translate(imageWidth, 0);
108
- ctx.rotate(Math.PI / 2);
109
- ctx.drawImage(image, 0, 0, imageHeight, imageWidth);
110
- break;
111
- case 2:
112
- ctx.translate(imageWidth, imageHeight);
113
- ctx.rotate(Math.PI);
114
- ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
115
- break;
116
- case 3:
117
- ctx.translate(0, imageHeight);
118
- ctx.rotate(-Math.PI / 2);
119
- ctx.drawImage(image, 0, 0, imageHeight, imageWidth);
120
- break;
121
- }
122
-
123
-
124
- ctx.restore();
125
- // ctx.resetTransform();
126
- }
127
-
128
- for (const box of value.boxes.slice().reverse()) {
129
- box.render(ctx);
130
- }
131
- }
132
- }
133
-
134
- function selectBox(index: number) {
135
- selectedBox = index;
136
- value.boxes.forEach(box => {box.setSelected(false);});
137
- if (index >= 0 && index < value.boxes.length){
138
- value.boxes[index].setSelected(true);
139
- }
140
- draw();
141
- }
142
-
143
- const getDistance = (touch1: PointerEvent, touch2: PointerEvent) => {
144
- const distance = Math.sqrt(
145
- Math.pow(touch1.clientX - touch2.clientX, 2) +
146
- Math.pow(touch1.clientY - touch2.clientY, 2)
147
- );
148
- return distance < touchScaleDeadzone ? touchScaleDeadzone : distance;
149
- };
150
-
151
- function handlePointerDown(event: PointerEvent) {
152
- if (!interactive) {
153
- return;
154
- }
155
-
156
- event.preventDefault();
157
- canvas.setPointerCapture(event.pointerId);
158
- pointersCache.set(event.pointerId, event);
159
-
160
- if (pointersCache.size == 1) {
161
- if (mode === Mode.creation) {
162
- createBox(event);
163
- } else if (mode === Mode.drag) {
164
- clickBox(event);
165
- }
166
- } else if (pointersCache.size == 2) {
167
- canvasWindow.isDragging = false;
168
- value.boxes.forEach(box => {
169
- box.isCreating = false;
170
- box.isDragging = false;
171
- box.isResizing = false;
172
- });
173
- const pointerArray = Array.from(pointersCache.values());
174
- const touch1 = pointerArray[0];
175
- const touch2 = pointerArray[1];
176
- const distance = getDistance(touch1, touch2);
177
- const rect = canvas.getBoundingClientRect();
178
- const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
179
- const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
180
-
181
- touchScaleValues.distance = distance;
182
- touchScaleValues.x = centerX;
183
- touchScaleValues.y = centerY;
184
- }
185
-
186
- }
187
-
188
- function clickBox(event: PointerEvent) {
189
- const rect = canvas.getBoundingClientRect();
190
- const mouseX = event.clientX - rect.left;
191
- const mouseY = event.clientY - rect.top;
192
- let selectedBoxFlag = false;
193
-
194
- // Check if the mouse is over any of the resizing handles
195
- for (const [i, box] of value.boxes.entries()) {
196
- const handleIndex = box.indexOfPointInsideHandle(mouseX, mouseY);
197
- if (handleIndex >= 0) {
198
- selectedBoxFlag = true;
199
- selectBox(i);
200
- box.startResize(handleIndex, event);
201
- return;
202
- }
203
- }
204
-
205
- // Check if the mouse is inside a box
206
- for (const [i, box] of value.boxes.entries()) {
207
- if (box.isPointInsideBox(mouseX, mouseY)) {
208
- selectedBoxFlag = true;
209
- selectBox(i);
210
- box.startDrag(event);
211
- return;
212
- }
213
- }
214
-
215
- if (!singleBox) {
216
- selectBox(-1);
217
- }
218
-
219
- if (!selectedBoxFlag) {
220
- canvasWindow.startDrag(event);
221
- }
222
- }
223
-
224
- function handlePointerUp(event: PointerEvent) {
225
- if (!interactive) {
226
- return;
227
- }
228
- pointersCache.delete(event.pointerId);
229
- canvas.releasePointerCapture(event.pointerId);
230
- dispatch("change");
231
- }
232
-
233
- function handlePointerCancel(event: PointerEvent) {
234
- if (!interactive) {
235
- return;
236
- }
237
- pointersCache.delete(event.pointerId);
238
- canvas.releasePointerCapture(event.pointerId);
239
- dispatch("change");
240
- }
241
-
242
- function handlePointerMove(event: PointerEvent) {
243
- if (!interactive) {
244
- return;
245
- }
246
-
247
- event.preventDefault();
248
- if (event.pointerType === "mouse") {
249
- if (!handlesCursor) {
250
- return;
251
- }
252
-
253
- if (value === null) {
254
- return;
255
- }
256
-
257
- if (mode !== Mode.drag) {
258
- return;
259
- }
260
-
261
- const rect = canvas.getBoundingClientRect();
262
- const mouseX = event.clientX - rect.left;
263
- const mouseY = event.clientY - rect.top;
264
-
265
- for (const [_, box] of value.boxes.entries()) {
266
- const handleIndex = box.indexOfPointInsideHandle(mouseX, mouseY);
267
- if (handleIndex >= 0) {
268
- canvas.style.cursor = box.resizeHandles[handleIndex].cursor;
269
- return;
270
- }
271
- }
272
-
273
- canvas.style.cursor = "default";
274
-
275
- } else { // touch
276
- if (!pointersCache.has(event.pointerId)) {
277
- return;
278
- }
279
- pointersCache.set(event.pointerId, event);
280
-
281
- if (pointersCache.size === 2) {
282
- const pointerArray = Array.from(pointersCache.values());
283
- const touch1 = pointerArray[0];
284
- const touch2 = pointerArray[1];
285
- const distance = getDistance(touch1, touch2);
286
- const rect = canvas.getBoundingClientRect();
287
- const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
288
- const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
289
-
290
- const newScaleTmp = parseFloat(
291
- (canvasWindow.scale * (distance / touchScaleValues.distance)).toFixed(2)
292
- );
293
- const newScale = newScaleTmp < 1 ? 1 : newScaleTmp;
294
-
295
- const scaleDelta = newScale / canvasWindow.scale;
296
- canvasWindow.offsetX = touchScaleValues.x - (touchScaleValues.x - canvasWindow.offsetX) * scaleDelta;
297
- canvasWindow.offsetY = touchScaleValues.y - (touchScaleValues.y - canvasWindow.offsetY) * scaleDelta;
298
-
299
- const dx = centerX - touchScaleValues.x;
300
- const dy = centerY - touchScaleValues.y;
301
- canvasWindow.offsetX += dx;
302
- canvasWindow.offsetY += dy;
303
- canvasWindow.scale = newScale;
304
-
305
- touchScaleValues.x = centerX;
306
- touchScaleValues.y = centerY;
307
- touchScaleValues.distance = distance;
308
-
309
- draw();
310
- }
311
- }
312
- }
313
-
314
- function resetView() {
315
- // Calculate minimum scale to fit image
316
- const scaleX = canvas.width / imageWidth;
317
- const scaleY = canvas.height / imageHeight;
318
- const minScale = Math.min(scaleX, scaleY);
319
-
320
- // Set scale and center
321
- canvasWindow.scale = minScale;
322
- canvasWindow.offsetX = (canvas.width - imageWidth * minScale) / 2;
323
- canvasWindow.offsetY = (canvas.height - imageHeight * minScale) / 2;
324
-
325
- draw();
326
- }
327
-
328
- function handleKeyPress(event: KeyboardEvent) {
329
- if (!enableKeyboardShortcuts || event.target !== annotatorContainerDiv || !interactive) {
330
- return;
331
- }
332
-
333
- const key = event.key.toLowerCase();
334
- const blockedKeys = new Set(['delete', 'c', 'd', 'e', ' ']);
335
-
336
- if (blockedKeys.has(key)) {
337
- event.preventDefault();
338
- event.stopPropagation();
339
- }
340
-
341
- switch (key) {
342
- case 'delete': onDeleteBox(); break;
343
- case 'c': setCreateMode(); break;
344
- case 'd': setDragMode(); break;
345
- case 'e': onEditBox(); break;
346
- case ' ': resetView(); break;
347
- }
348
- }
349
-
350
- function focusAnnotator() {
351
- setTimeout(() => {annotatorContainerDiv?.focus();}, 0);
352
- }
353
-
354
- function handleMouseWheel(event: WheelEvent) {
355
- if (!interactive) {
356
- return;
357
- }
358
-
359
- event.preventDefault();
360
- const delta = 1 / (1 + (event.deltaY / 1000) * 0.5);
361
-
362
- const newScaleTmp = parseFloat((canvasWindow.scale * delta).toFixed(2));
363
- const newScale = newScaleTmp < 1 ? 1 : newScaleTmp;
364
- const rect = canvas.getBoundingClientRect();
365
- const mouseX = event.clientX - rect.left;
366
- const mouseY = event.clientY - rect.top;
367
-
368
- const worldX = (mouseX - canvasWindow.offsetX) / canvasWindow.scale;
369
- const worldY = (mouseY - canvasWindow.offsetY) / canvasWindow.scale;
370
-
371
- canvasWindow.offsetX = mouseX - worldX * newScale;
372
- canvasWindow.offsetY = mouseY - worldY * newScale;
373
-
374
- canvasWindow.scale = newScale;
375
- draw();
376
- }
377
-
378
- function createBox(event: PointerEvent) {
379
- const rect = canvas.getBoundingClientRect();
380
- const x = (event.clientX - rect.left - canvasWindow.offsetX) / scaleFactor / canvasWindow.scale;
381
- const y = (event.clientY - rect.top - canvasWindow.offsetY) / scaleFactor / canvasWindow.scale;
382
- let color;
383
- if (choicesColors.length > 0) {
384
- color = colorHexToRGB(choicesColors[0]);
385
- } else if (singleBox) {
386
- if (value.boxes.length > 0) {
387
- color = value.boxes[0].color;
388
- } else {
389
- color = Colors[0];
390
- }
391
- } else {
392
- color = Colors[value.boxes.length % Colors.length];
393
- }
394
-
395
- let box = new Box(
396
- draw,
397
- onBoxFinishCreation,
398
- canvasWindow,
399
- pointersCache,
400
- canvasXmin,
401
- canvasYmin,
402
- canvasXmax,
403
- canvasYmax,
404
- "",
405
- x,
406
- y,
407
- x,
408
- y,
409
- color,
410
- boxAlpha,
411
- boxMinSize,
412
- handleSize,
413
- boxThickness,
414
- boxSelectedThickness
415
- );
416
- box.startCreating(event, rect.left, rect.top);
417
- if (singleBox) {
418
- value.boxes = [box];
419
- } else {
420
- value.boxes = [box, ...value.boxes];
421
- }
422
- selectBox(0);
423
- draw();
424
- dispatch("change");
425
- }
426
-
427
- function setCreateMode() {
428
- mode = Mode.creation;
429
- canvas.style.cursor = "crosshair";
430
- }
431
-
432
- function setDragMode() {
433
- mode = Mode.drag;
434
- canvas.style.cursor = "default";
435
- }
436
-
437
- function onBoxFinishCreation() {
438
- if (selectedBox >= 0 && selectedBox < value.boxes.length) {
439
- if (value.boxes[selectedBox].getArea() < 1) {
440
- onDeleteBox();
441
- } else {
442
- if (!disableEditBoxes) {
443
- if (labelDetailLock) {
444
- onUseDefaultLabelModalNew();
445
- } else{
446
- newModalVisible = true;
447
- }
448
- }
449
- if (singleBox) {
450
- setDragMode();
451
- }
452
- }
453
- }
454
- }
455
-
456
- function onEditBox() {
457
- if (selectedBox >= 0 && selectedBox < value.boxes.length && !disableEditBoxes) {
458
- editModalVisible = true;
459
- }
460
- }
461
-
462
- function handleDoubleClick(event: MouseEvent){
463
- if (!interactive) {
464
- return;
465
- }
466
-
467
- onEditBox();
468
- }
469
-
470
- function onModalEditChange(event) {
471
- editModalVisible = false;
472
- focusAnnotator();
473
- const { detail } = event;
474
- let label = detail.label;
475
- let color = detail.color;
476
- let ret = detail.ret;
477
- if (selectedBox >= 0 && selectedBox < value.boxes.length) {
478
- let box = value.boxes[selectedBox];
479
- if (ret == 1) {
480
- box.label = label;
481
- box.color = colorHexToRGB(color);
482
- draw();
483
- dispatch("change");
484
- } else if (ret == -1) {
485
- onDeleteBox();
486
- }
487
- }
488
- }
489
-
490
- function onModalNewChange(event) {
491
- newModalVisible = false;
492
- focusAnnotator();
493
- const { detail } = event;
494
- let label = detail.label;
495
- let color = detail.color;
496
- let ret = detail.ret;
497
- let lock = detail.lock;
498
- if (selectedBox >= 0 && selectedBox < value.boxes.length) {
499
- let box = value.boxes[selectedBox];
500
- if (ret == 1) {
501
- labelDetailLock = lock;
502
- defaultLabelCache.label = label;
503
- defaultLabelCache.color = color;
504
- box.label = label;
505
- box.color = colorHexToRGB(color);
506
- draw();
507
- dispatch("change");
508
- } else {
509
- onDeleteBox();
510
- }
511
- }
512
- }
513
-
514
- function onDefaultLabelEditChange(event) {
515
- editDefaultLabelVisible = false;
516
- focusAnnotator();
517
- const { detail } = event;
518
- let label = detail.label;
519
- let color = detail.color;
520
- let ret = detail.ret;
521
- let lock = detail.lock;
522
- if (ret == 1) {
523
- labelDetailLock = lock;
524
- defaultLabelCache.label = label;
525
- defaultLabelCache.color = color;
526
- }
527
- }
528
-
529
- function onUseDefaultLabelModalNew(){
530
- if (selectedBox >= 0 && selectedBox < value.boxes.length) {
531
- let box = value.boxes[selectedBox];
532
- box.label = defaultLabelCache.label;
533
- if (defaultLabelCache.color !== "") {
534
- box.color = colorHexToRGB(defaultLabelCache.color);
535
- }
536
- draw();
537
- dispatch("change");
538
- }
539
- }
540
-
541
- function onDeleteBox() {
542
- if (selectedBox >= 0 && selectedBox < value.boxes.length) {
543
- value.boxes.splice(selectedBox, 1);
544
- selectBox(-1);
545
- if (singleBox) {
546
- setCreateMode();
547
- }
548
- dispatch("change");
549
- }
550
- }
551
-
552
- /**
553
- * Rotate the image and all the boxes
554
- * @param op 1: rotate clockwise, -1: rotate counterclockwise
555
- */
556
- function onRotateImage(op: number) {
557
- value.orientation = (((value.orientation + op) % 4) + 4 ) % 4;
558
- canvasWindow.orientation = value.orientation;
559
-
560
- resize();
561
- for (const box of value.boxes) {
562
- box.onRotate(op);
563
- }
564
- draw();
565
- }
566
-
567
- function resize() {
568
- if (canvas) {
569
- scaleFactor = 1;
570
- canvas.width = canvas.clientWidth;
571
-
572
- canvasWindow.setRotatedImage(image);
573
-
574
- if (image !== null) {
575
- if (canvasWindow.imageRotatedWidth > canvas.width) {
576
- scaleFactor = canvas.width / canvasWindow.imageRotatedWidth;
577
- imageWidth = Math.round(canvasWindow.imageRotatedWidth * scaleFactor);
578
- imageHeight = Math.round(canvasWindow.imageRotatedHeight * scaleFactor);
579
- canvasXmin = 0;
580
- canvasYmin = 0;
581
- canvasXmax = imageWidth;
582
- canvasYmax = imageHeight;
583
- canvas.height = imageHeight;
584
- } else {
585
- imageWidth = canvasWindow.imageRotatedWidth;
586
- imageHeight = canvasWindow.imageRotatedHeight;
587
- var x = (canvas.width - imageWidth) / 2;
588
- canvasXmin = x;
589
- canvasYmin = 0;
590
- canvasXmax = x + imageWidth;
591
- canvasYmax = imageHeight;
592
- canvas.height = imageHeight;
593
- }
594
-
595
- canvasWindow.imageWidth = imageWidth;
596
- canvasWindow.imageHeight = imageHeight;
597
-
598
- } else {
599
- canvasXmin = 0;
600
- canvasYmin = 0;
601
- canvasXmax = canvas.width;
602
- canvasYmax = canvas.height;
603
- canvas.height = canvas.clientHeight;
604
- }
605
-
606
- canvasWindow.resize(canvas.width, canvas.height, canvasXmin, canvasYmin);
607
-
608
- if (canvasXmax > 0 && canvasYmax > 0){
609
- for (const box of value.boxes) {
610
- box.canvasXmin = canvasXmin;
611
- box.canvasYmin = canvasYmin;
612
- box.canvasXmax = canvasXmax;
613
- box.canvasYmax = canvasYmax;
614
- box.setScaleFactor(scaleFactor);
615
- }
616
- }
617
- draw();
618
- dispatch("change");
619
- }
620
- }
621
- const observer = new ResizeObserver(resize);
622
-
623
- function parseInputBoxes() {
624
- for (let i = 0; i < value.boxes.length; i++) {
625
- let box = value.boxes[i];
626
- if (!(box instanceof Box)) {
627
- let color = "";
628
- let label = "";
629
- if (box.hasOwnProperty("color")) {
630
- color = box["color"];
631
- if (Array.isArray(color) && color.length === 3) {
632
- color = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
633
- }
634
- } else {
635
- color = Colors[i % Colors.length];
636
- }
637
- if (box.hasOwnProperty("label")) {
638
- label = box["label"];
639
- }
640
- box = new Box(
641
- draw,
642
- onBoxFinishCreation,
643
- canvasWindow,
644
- pointersCache,
645
- canvasXmin,
646
- canvasYmin,
647
- canvasXmax,
648
- canvasYmax,
649
- label,
650
- box["xmin"],
651
- box["ymin"],
652
- box["xmax"],
653
- box["ymax"],
654
- color,
655
- boxAlpha,
656
- boxMinSize,
657
- handleSize,
658
- boxThickness,
659
- boxSelectedThickness
660
- );
661
- value.boxes[i] = box;
662
- }
663
- }
664
- }
665
-
666
- $: {
667
- value;
668
- canvasWindow.orientation = value.orientation;
669
- setImage();
670
- parseInputBoxes();
671
- resize();
672
- draw();
673
- }
674
-
675
- function setImage(){
676
- if (imageUrl !== null) {
677
- if (image === null || image.src != imageUrl) {
678
- image = new Image();
679
- image.src = imageUrl;
680
- image.onload = function(){
681
- resize();
682
- draw();
683
- }
684
- }
685
- }
686
- }
687
-
688
- onMount(() => {
689
- if (Array.isArray(choices) && choices.length > 0) {
690
- if (!Array.isArray(choicesColors) || choicesColors.length == 0) {
691
- for (let i = 0; i < choices.length; i++) {
692
- let color = Colors[i % Colors.length];
693
- choicesColors.push(colorRGBAToHex(color));
694
- }
695
- }
696
- defaultLabelCache.label = choices[0][0];
697
- defaultLabelCache.color = choicesColors[0];
698
- }
699
-
700
- ctx = canvas.getContext("2d");
701
- observer.observe(canvas);
702
-
703
- if (selectedBox < 0 && value !== null && value.boxes.length > 0) {
704
- selectBox(0);
705
- }
706
-
707
- setImage();
708
- resize();
709
- draw();
710
- });
711
-
712
- </script>
713
-
714
- <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
715
- <!-- svelte-ignore a11y-no-static-element-interactions -->
716
- <div
717
- class="annotator-container"
718
- tabindex="0"
719
- bind:this={annotatorContainerDiv}
720
- on:keydown={handleKeyPress}
721
- on:click={() => annotatorContainerDiv.focus()}
722
- >
723
- <div class="canvas-container">
724
- <canvas
725
- bind:this={canvas}
726
- on:pointerdown={handlePointerDown}
727
- on:pointerup={handlePointerUp}
728
- on:pointermove={handlePointerMove}
729
- on:pointercancel={handlePointerCancel}
730
- on:dblclick={handleDoubleClick}
731
- on:wheel={handleMouseWheel}
732
- style="height: {height}; width: {width};"
733
- class="canvas-annotator"
734
- ></canvas>
735
- </div>
736
-
737
- {#if interactive}
738
- <span class="canvas-control">
739
- <button
740
- class="icon"
741
- class:selected={mode === Mode.creation}
742
- aria-label="Create box"
743
- title="Create box (C)"
744
- on:click={() => setCreateMode()}><BoundingBox/></button
745
- >
746
- <button
747
- class="icon"
748
- class:selected={mode === Mode.drag}
749
- aria-label="Drag boxes"
750
- title="Drag boxes (D)"
751
- on:click={() => setDragMode()}><Hand/></button
752
- >
753
- {#if showRemoveButton}
754
- <button
755
- class="icon"
756
- aria-label="Remove box"
757
- title="Remove box (Del)"
758
- on:click={() => onDeleteBox()}><Trash/></button
759
- >
760
- {/if}
761
- {#if !disableEditBoxes && labelDetailLock}
762
- <button
763
- class="icon"
764
- aria-label="Edit label"
765
- title="Edit label"
766
- on:click={() => editDefaultLabelVisible = true}><Label/></button
767
- >
768
- {/if}
769
- <button
770
- class="icon"
771
- aria-label="Rotate counterclockwise"
772
- title="Rotate counterclockwise"
773
- on:click={() => onRotateImage(-1)}><Undo/></button
774
- >
775
- <button
776
- class="icon"
777
- aria-label="Rotate clockwise"
778
- title="Rotate clockwise"
779
- on:click={() => onRotateImage(1)}><Redo/></button
780
- >
781
- </span>
782
- {/if}
783
- </div>
784
-
785
- {#if editModalVisible}
786
- <ModalBox
787
- on:change={onModalEditChange}
788
- on:enter{onModalEditChange}
789
- choices={choices}
790
- choicesColors={choicesColors}
791
- label={selectedBox >= 0 && selectedBox < value.boxes.length ? value.boxes[selectedBox].label : ""}
792
- color={selectedBox >= 0 && selectedBox < value.boxes.length ? colorRGBAToHex(value.boxes[selectedBox].color) : ""}
793
- />
794
- {/if}
795
-
796
- {#if newModalVisible}
797
- <ModalBox
798
- on:change={onModalNewChange}
799
- on:enter{onModalNewChange}
800
- choices={choices}
801
- showRemove={false}
802
- choicesColors={choicesColors}
803
- label={selectedBox >= 0 && selectedBox < value.boxes.length ? value.boxes[selectedBox].label : ""}
804
- color={selectedBox >= 0 && selectedBox < value.boxes.length ? colorRGBAToHex(value.boxes[selectedBox].color) : ""}
805
- labelDetailLock = {labelDetailLock}
806
- />
807
- {/if}
808
-
809
- {#if editDefaultLabelVisible}
810
- <ModalBox
811
- on:change={onDefaultLabelEditChange}
812
- on:enter{onDefaultLabelEditChange}
813
- choices={choices}
814
- showRemove={false}
815
- choicesColors={choicesColors}
816
- label={selectedBox >= 0 && selectedBox < value.boxes.length ? value.boxes[selectedBox].label : ""}
817
- color={selectedBox >= 0 && selectedBox < value.boxes.length ? colorRGBAToHex(value.boxes[selectedBox].color) : ""}
818
- labelDetailLock = {labelDetailLock}
819
- />
820
- {/if}
821
-
822
- <style>
823
- .canvas-annotator {
824
- border-color: var(--block-border-color);
825
- width: 100%;
826
- height: 100%;
827
- display: block;
828
- touch-action: none;
829
- }
830
-
831
- .canvas-control {
832
- display: flex;
833
- align-items: center;
834
- justify-content: center;
835
- border-top: 1px solid var(--border-color-primary);
836
- width: 95%;
837
- bottom: 0;
838
- left: 0;
839
- right: 0;
840
- margin-left: auto;
841
- margin-right: auto;
842
- margin-top: var(--size-2);
843
- }
844
-
845
- .icon {
846
- width: 22px;
847
- height: 22px;
848
- margin: var(--spacing-lg) var(--spacing-xs);
849
- padding: var(--spacing-xs);
850
- color: var(--neutral-400);
851
- border-radius: var(--radius-md);
852
- }
853
-
854
- .icon:hover,
855
- .icon:focus {
856
- color: var(--color-accent);
857
- }
858
-
859
- .selected {
860
- color: var(--color-accent);
861
- }
862
-
863
- .canvas-container {
864
- display: flex;
865
- justify-content: center;
866
- align-items: center;
867
- }
868
-
869
- .canvas-container:focus {
870
- outline: none;
871
- }
872
- </style>
 
1
+ <script lang="ts">
2
+ import { onMount, createEventDispatcher } from "svelte";
3
+ import { BoundingBox, Hand, Trash, Label } from "./icons/index";
4
+ import ModalBox from "./ModalBox.svelte";
5
+ import Box from "./Box";
6
+ import { Colors } from './Colors.js';
7
+ import AnnotatedImageData from "./AnnotatedImageData";
8
+ import { Undo, Redo } from "@gradio/icons";
9
+ import WindowViewer from "./WindowViewer";
10
+
11
+ enum Mode {creation, drag}
12
+
13
+ export let imageUrl: string | null = null;
14
+ export let interactive: boolean;
15
+ export let boxAlpha = 0.5;
16
+ export let boxMinSize = 10;
17
+ export let handleSize: number;
18
+ export let boxThickness: number;
19
+ export let boxSelectedThickness: number;
20
+ export let value: null | AnnotatedImageData;
21
+ export let choices = [];
22
+ export let choicesColors = [];
23
+ export let disableEditBoxes: boolean = false;
24
+ export let height: number | string = "100%";
25
+ export let width: number | string = "100%";
26
+ export let singleBox: boolean = false;
27
+ export let showRemoveButton: boolean = null;
28
+ export let handlesCursor: boolean = true;
29
+ export let useDefaultLabel: boolean = false;
30
+ export let enableKeyboardShortcuts: boolean = true;
31
+
32
+ if (showRemoveButton === null) {
33
+ showRemoveButton = (disableEditBoxes);
34
+ }
35
+
36
+ let canvas: HTMLCanvasElement;
37
+ let annotatorContainerDiv: HTMLDivElement;
38
+ let ctx: CanvasRenderingContext2D;
39
+ let image = null;
40
+ let selectedBox = -1;
41
+ let mode: Mode = Mode.drag;
42
+ let pointersCache: Map<number, PointerEvent> = new Map();
43
+ let canvasWindow: WindowViewer = new WindowViewer(draw, pointersCache);
44
+
45
+ if (value !== null && value.boxes.length == 0) {
46
+ mode = Mode.creation;
47
+ }
48
+
49
+ let canvasXmin = 0;
50
+ let canvasYmin = 0;
51
+ let canvasXmax = 0;
52
+ let canvasYmax = 0;
53
+ let scaleFactor = 1.0;
54
+
55
+ let imageWidth = 0;
56
+ let imageHeight = 0;
57
+
58
+ let editModalVisible = false;
59
+ let newModalVisible = false;
60
+ let editDefaultLabelVisible = false;
61
+
62
+ let labelDetailLock = useDefaultLabel;
63
+ let defaultLabelCache = {
64
+ label: "",
65
+ color: ""
66
+ };
67
+
68
+ let touchScaleValues = {
69
+ x: 0,
70
+ y: 0,
71
+ distance: 0,
72
+ }
73
+ const touchScaleDeadzone = 100;
74
+
75
+ const dispatch = createEventDispatcher<{
76
+ change: undefined;
77
+ }>();
78
+
79
+ function colorHexToRGB(hex: string) {
80
+ var r = parseInt(hex.slice(1, 3), 16),
81
+ g = parseInt(hex.slice(3, 5), 16),
82
+ b = parseInt(hex.slice(5, 7), 16);
83
+ return "rgb(" + r + ", " + g + ", " + b + ")";
84
+ }
85
+
86
+ function colorRGBAToHex(rgba: string) {
87
+ const rgbaValues = rgba.match(/(\d+(\.\d+)?)/g);
88
+ const r = parseInt(rgbaValues[0]);
89
+ const g = parseInt(rgbaValues[1]);
90
+ const b = parseInt(rgbaValues[2]);
91
+ const hex = "#" + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);
92
+ return hex;
93
+ }
94
+
95
+ function draw() {
96
+ if (ctx) {
97
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
98
+ ctx.save();
99
+ ctx.translate(canvasWindow.offsetX, canvasWindow.offsetY);
100
+ ctx.scale(canvasWindow.scale, canvasWindow.scale);
101
+ if (image !== null){
102
+ switch (value.orientation) {
103
+ case 0:
104
+ ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
105
+ break;
106
+ case 1:
107
+ ctx.translate(imageWidth, 0);
108
+ ctx.rotate(Math.PI / 2);
109
+ ctx.drawImage(image, 0, 0, imageHeight, imageWidth);
110
+ break;
111
+ case 2:
112
+ ctx.translate(imageWidth, imageHeight);
113
+ ctx.rotate(Math.PI);
114
+ ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
115
+ break;
116
+ case 3:
117
+ ctx.translate(0, imageHeight);
118
+ ctx.rotate(-Math.PI / 2);
119
+ ctx.drawImage(image, 0, 0, imageHeight, imageWidth);
120
+ break;
121
+ }
122
+
123
+ ctx.restore();
124
+ }
125
+
126
+ for (const box of value.boxes.slice().reverse()) {
127
+ box.render(ctx);
128
+ }
129
+ }
130
+ }
131
+
132
+ function selectBox(index: number) {
133
+ selectedBox = index;
134
+ value.boxes.forEach(box => {box.setSelected(false);});
135
+ if (index >= 0 && index < value.boxes.length){
136
+ value.boxes[index].setSelected(true);
137
+ }
138
+ draw();
139
+ }
140
+
141
+ const getDistance = (touch1: PointerEvent, touch2: PointerEvent) => {
142
+ const distance = Math.sqrt(
143
+ Math.pow(touch1.clientX - touch2.clientX, 2) +
144
+ Math.pow(touch1.clientY - touch2.clientY, 2)
145
+ );
146
+ return distance < touchScaleDeadzone ? touchScaleDeadzone : distance;
147
+ };
148
+
149
+ function handlePointerDown(event: PointerEvent) {
150
+ if (!interactive) {
151
+ return;
152
+ }
153
+
154
+ event.preventDefault();
155
+ canvas.setPointerCapture(event.pointerId);
156
+ pointersCache.set(event.pointerId, event);
157
+
158
+ if (pointersCache.size == 1) {
159
+ if (mode === Mode.creation) {
160
+ createBox(event);
161
+ } else if (mode === Mode.drag) {
162
+ clickBox(event);
163
+ }
164
+ } else if (pointersCache.size == 2) {
165
+ canvasWindow.isDragging = false;
166
+ value.boxes.forEach(box => {
167
+ box.isCreating = false;
168
+ box.isDragging = false;
169
+ box.isResizing = false;
170
+ });
171
+ const pointerArray = Array.from(pointersCache.values());
172
+ const touch1 = pointerArray[0];
173
+ const touch2 = pointerArray[1];
174
+ const distance = getDistance(touch1, touch2);
175
+ const rect = canvas.getBoundingClientRect();
176
+ const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
177
+ const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
178
+
179
+ touchScaleValues.distance = distance;
180
+ touchScaleValues.x = centerX;
181
+ touchScaleValues.y = centerY;
182
+ }
183
+ }
184
+
185
+ function clickBox(event: PointerEvent) {
186
+ const rect = canvas.getBoundingClientRect();
187
+ const mouseX = event.clientX - rect.left;
188
+ const mouseY = event.clientY - rect.top;
189
+ let selectedBoxFlag = false;
190
+
191
+ // Check if the mouse is over any of the resizing handles
192
+ for (const [i, box] of value.boxes.entries()) {
193
+ const handleIndex = box.indexOfPointInsideHandle(mouseX, mouseY);
194
+ if (handleIndex >= 0) {
195
+ selectedBoxFlag = true;
196
+ selectBox(i);
197
+ box.startResize(handleIndex, event);
198
+ return;
199
+ }
200
+ }
201
+
202
+ // Check if the mouse is inside a box
203
+ for (const [i, box] of value.boxes.entries()) {
204
+ if (box.isPointInsideBox(mouseX, mouseY)) {
205
+ selectedBoxFlag = true;
206
+ selectBox(i);
207
+ box.startDrag(event);
208
+ return;
209
+ }
210
+ }
211
+
212
+ if (!singleBox) {
213
+ selectBox(-1);
214
+ }
215
+
216
+ if (!selectedBoxFlag) {
217
+ canvasWindow.startDrag(event);
218
+ }
219
+ }
220
+
221
+ function handlePointerUp(event: PointerEvent) {
222
+ if (!interactive) {
223
+ return;
224
+ }
225
+ pointersCache.delete(event.pointerId);
226
+ canvas.releasePointerCapture(event.pointerId);
227
+ dispatch("change");
228
+ }
229
+
230
+ function handlePointerCancel(event: PointerEvent) {
231
+ if (!interactive) {
232
+ return;
233
+ }
234
+ pointersCache.delete(event.pointerId);
235
+ canvas.releasePointerCapture(event.pointerId);
236
+ dispatch("change");
237
+ }
238
+
239
+ function handlePointerMove(event: PointerEvent) {
240
+ if (!interactive) {
241
+ return;
242
+ }
243
+
244
+ event.preventDefault();
245
+ if (event.pointerType === "mouse") {
246
+ if (!handlesCursor) {
247
+ return;
248
+ }
249
+
250
+ if (value === null) {
251
+ return;
252
+ }
253
+
254
+ if (mode !== Mode.drag) {
255
+ return;
256
+ }
257
+
258
+ const rect = canvas.getBoundingClientRect();
259
+ const mouseX = event.clientX - rect.left;
260
+ const mouseY = event.clientY - rect.top;
261
+
262
+ for (const [_, box] of value.boxes.entries()) {
263
+ const handleIndex = box.indexOfPointInsideHandle(mouseX, mouseY);
264
+ if (handleIndex >= 0) {
265
+ canvas.style.cursor = box.resizeHandles[handleIndex].cursor;
266
+ return;
267
+ }
268
+ }
269
+
270
+ canvas.style.cursor = "default";
271
+
272
+ } else { // touch
273
+ if (!pointersCache.has(event.pointerId)) {
274
+ return;
275
+ }
276
+ pointersCache.set(event.pointerId, event);
277
+
278
+ if (pointersCache.size === 2) {
279
+ const pointerArray = Array.from(pointersCache.values());
280
+ const touch1 = pointerArray[0];
281
+ const touch2 = pointerArray[1];
282
+ const distance = getDistance(touch1, touch2);
283
+ const rect = canvas.getBoundingClientRect();
284
+ const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
285
+ const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
286
+
287
+ const newScaleTmp = parseFloat(
288
+ (canvasWindow.scale * (distance / touchScaleValues.distance)).toFixed(2)
289
+ );
290
+ const newScale = newScaleTmp < 1 ? 1 : newScaleTmp;
291
+
292
+ const scaleDelta = newScale / canvasWindow.scale;
293
+ canvasWindow.offsetX = touchScaleValues.x - (touchScaleValues.x - canvasWindow.offsetX) * scaleDelta;
294
+ canvasWindow.offsetY = touchScaleValues.y - (touchScaleValues.y - canvasWindow.offsetY) * scaleDelta;
295
+
296
+ const dx = centerX - touchScaleValues.x;
297
+ const dy = centerY - touchScaleValues.y;
298
+ canvasWindow.offsetX += dx;
299
+ canvasWindow.offsetY += dy;
300
+ canvasWindow.scale = newScale;
301
+
302
+ touchScaleValues.x = centerX;
303
+ touchScaleValues.y = centerY;
304
+ touchScaleValues.distance = distance;
305
+
306
+ draw();
307
+ }
308
+ }
309
+ }
310
+
311
+ function resetView() {
312
+ // Calculate minimum scale to fit image
313
+ const scaleX = canvas.width / imageWidth;
314
+ const scaleY = canvas.height / imageHeight;
315
+ const minScale = Math.min(scaleX, scaleY);
316
+
317
+ // Set scale and center
318
+ canvasWindow.scale = minScale;
319
+ canvasWindow.offsetX = (canvas.width - imageWidth * minScale) / 2;
320
+ canvasWindow.offsetY = (canvas.height - imageHeight * minScale) / 2;
321
+
322
+ draw();
323
+ }
324
+
325
+ function handleKeyPress(event: KeyboardEvent) {
326
+ if (!enableKeyboardShortcuts || event.target !== annotatorContainerDiv || !interactive) {
327
+ return;
328
+ }
329
+
330
+ const key = event.key.toLowerCase();
331
+ const blockedKeys = new Set(['delete', 'c', 'd', 'e', ' ']);
332
+
333
+ if (blockedKeys.has(key)) {
334
+ event.preventDefault();
335
+ event.stopPropagation();
336
+ }
337
+
338
+ switch (key) {
339
+ case 'delete': onDeleteBox(); break;
340
+ case 'c': setCreateMode(); break;
341
+ case 'd': setDragMode(); break;
342
+ case 'e': onEditBox(); break;
343
+ case ' ': resetView(); break;
344
+ }
345
+ }
346
+
347
+ function focusAnnotator() {
348
+ setTimeout(() => {annotatorContainerDiv?.focus();}, 0);
349
+ }
350
+
351
+ function handleMouseWheel(event: WheelEvent) {
352
+ if (!interactive) {
353
+ return;
354
+ }
355
+
356
+ event.preventDefault();
357
+ const delta = 1 / (1 + (event.deltaY / 1000) * 0.5);
358
+
359
+ const newScaleTmp = parseFloat((canvasWindow.scale * delta).toFixed(2));
360
+ const newScale = newScaleTmp < 1 ? 1 : newScaleTmp;
361
+ const rect = canvas.getBoundingClientRect();
362
+ const mouseX = event.clientX - rect.left;
363
+ const mouseY = event.clientY - rect.top;
364
+
365
+ const worldX = (mouseX - canvasWindow.offsetX) / canvasWindow.scale;
366
+ const worldY = (mouseY - canvasWindow.offsetY) / canvasWindow.scale;
367
+
368
+ canvasWindow.offsetX = mouseX - worldX * newScale;
369
+ canvasWindow.offsetY = mouseY - worldY * newScale;
370
+
371
+ canvasWindow.scale = newScale;
372
+ draw();
373
+ }
374
+
375
+ function createBox(event: PointerEvent) {
376
+ const rect = canvas.getBoundingClientRect();
377
+ const x = (event.clientX - rect.left - canvasWindow.offsetX) / scaleFactor / canvasWindow.scale;
378
+ const y = (event.clientY - rect.top - canvasWindow.offsetY) / scaleFactor / canvasWindow.scale;
379
+ let color;
380
+ if (choicesColors.length > 0) {
381
+ color = colorHexToRGB(choicesColors[0]);
382
+ } else if (singleBox) {
383
+ if (value.boxes.length > 0) {
384
+ color = value.boxes[0].color;
385
+ } else {
386
+ color = Colors[0];
387
+ }
388
+ } else {
389
+ color = Colors[value.boxes.length % Colors.length];
390
+ }
391
+
392
+ let box = new Box(
393
+ draw,
394
+ onBoxFinishCreation,
395
+ canvasWindow,
396
+ pointersCache,
397
+ canvasXmin,
398
+ canvasYmin,
399
+ canvasXmax,
400
+ canvasYmax,
401
+ "",
402
+ x,
403
+ y,
404
+ x,
405
+ y,
406
+ color,
407
+ boxAlpha,
408
+ boxMinSize,
409
+ handleSize,
410
+ boxThickness,
411
+ boxSelectedThickness
412
+ );
413
+ box.startCreating(event, rect.left, rect.top);
414
+ if (singleBox) {
415
+ value.boxes = [box];
416
+ } else {
417
+ value.boxes = [box, ...value.boxes];
418
+ }
419
+ selectBox(0);
420
+ draw();
421
+ dispatch("change");
422
+ }
423
+
424
+ function setCreateMode() {
425
+ mode = Mode.creation;
426
+ canvas.style.cursor = "crosshair";
427
+ }
428
+
429
+ function setDragMode() {
430
+ mode = Mode.drag;
431
+ canvas.style.cursor = "default";
432
+ }
433
+
434
+ function onBoxFinishCreation() {
435
+ if (selectedBox >= 0 && selectedBox < value.boxes.length) {
436
+ if (value.boxes[selectedBox].getArea() < 1) {
437
+ onDeleteBox();
438
+ } else {
439
+ if (!disableEditBoxes) {
440
+ if (labelDetailLock) {
441
+ onUseDefaultLabelModalNew();
442
+ } else{
443
+ newModalVisible = true;
444
+ }
445
+ }
446
+ if (singleBox) {
447
+ setDragMode();
448
+ }
449
+ }
450
+ }
451
+ }
452
+
453
+ function onEditBox() {
454
+ if (selectedBox >= 0 && selectedBox < value.boxes.length && !disableEditBoxes) {
455
+ editModalVisible = true;
456
+ }
457
+ }
458
+
459
+ function handleDoubleClick(event: MouseEvent){
460
+ if (!interactive) {
461
+ return;
462
+ }
463
+
464
+ onEditBox();
465
+ }
466
+
467
+ function onModalEditChange(event) {
468
+ editModalVisible = false;
469
+ focusAnnotator();
470
+ const { detail } = event;
471
+ let label = detail.label;
472
+ let color = detail.color;
473
+ let ret = detail.ret;
474
+ if (selectedBox >= 0 && selectedBox < value.boxes.length) {
475
+ let box = value.boxes[selectedBox];
476
+ if (ret == 1) {
477
+ box.label = label;
478
+ box.color = colorHexToRGB(color);
479
+ draw();
480
+ dispatch("change");
481
+ } else if (ret == -1) {
482
+ onDeleteBox();
483
+ }
484
+ }
485
+ }
486
+
487
+ function onModalNewChange(event) {
488
+ newModalVisible = false;
489
+ focusAnnotator();
490
+ const { detail } = event;
491
+ let label = detail.label;
492
+ let color = detail.color;
493
+ let ret = detail.ret;
494
+ let lock = detail.lock;
495
+ if (selectedBox >= 0 && selectedBox < value.boxes.length) {
496
+ let box = value.boxes[selectedBox];
497
+ if (ret == 1) {
498
+ labelDetailLock = lock;
499
+ defaultLabelCache.label = label;
500
+ defaultLabelCache.color = color;
501
+ box.label = label;
502
+ box.color = colorHexToRGB(color);
503
+ draw();
504
+ dispatch("change");
505
+ } else {
506
+ onDeleteBox();
507
+ }
508
+ }
509
+ }
510
+
511
+ function onDefaultLabelEditChange(event) {
512
+ editDefaultLabelVisible = false;
513
+ focusAnnotator();
514
+ const { detail } = event;
515
+ let label = detail.label;
516
+ let color = detail.color;
517
+ let ret = detail.ret;
518
+ let lock = detail.lock;
519
+ if (ret == 1) {
520
+ labelDetailLock = lock;
521
+ defaultLabelCache.label = label;
522
+ defaultLabelCache.color = color;
523
+ }
524
+ }
525
+
526
+ function onUseDefaultLabelModalNew(){
527
+ if (selectedBox >= 0 && selectedBox < value.boxes.length) {
528
+ let box = value.boxes[selectedBox];
529
+ box.label = defaultLabelCache.label;
530
+ if (defaultLabelCache.color !== "") {
531
+ box.color = colorHexToRGB(defaultLabelCache.color);
532
+ }
533
+ draw();
534
+ dispatch("change");
535
+ }
536
+ }
537
+
538
+ function onDeleteBox() {
539
+ if (selectedBox >= 0 && selectedBox < value.boxes.length) {
540
+ value.boxes.splice(selectedBox, 1);
541
+ selectBox(-1);
542
+ if (singleBox) {
543
+ setCreateMode();
544
+ }
545
+ dispatch("change");
546
+ }
547
+ }
548
+
549
+ /**
550
+ * Rotate the image and all the boxes
551
+ * @param op 1: rotate clockwise, -1: rotate counterclockwise
552
+ */
553
+ function onRotateImage(op: number) {
554
+ value.orientation = (((value.orientation + op) % 4) + 4 ) % 4;
555
+ canvasWindow.orientation = value.orientation;
556
+
557
+ resize();
558
+ for (const box of value.boxes) {
559
+ box.onRotate(op);
560
+ }
561
+ draw();
562
+ }
563
+
564
+ function resize() {
565
+ if (canvas) {
566
+ scaleFactor = 1;
567
+ canvas.width = canvas.clientWidth;
568
+
569
+ canvasWindow.setRotatedImage(image);
570
+
571
+ if (image !== null) {
572
+ if (canvasWindow.imageRotatedWidth > canvas.width) {
573
+ scaleFactor = canvas.width / canvasWindow.imageRotatedWidth;
574
+ imageWidth = Math.round(canvasWindow.imageRotatedWidth * scaleFactor);
575
+ imageHeight = Math.round(canvasWindow.imageRotatedHeight * scaleFactor);
576
+ canvasXmin = 0;
577
+ canvasYmin = 0;
578
+ canvasXmax = imageWidth;
579
+ canvasYmax = imageHeight;
580
+ canvas.height = imageHeight;
581
+ } else {
582
+ imageWidth = canvasWindow.imageRotatedWidth;
583
+ imageHeight = canvasWindow.imageRotatedHeight;
584
+ var x = (canvas.width - imageWidth) / 2;
585
+ canvasXmin = x;
586
+ canvasYmin = 0;
587
+ canvasXmax = x + imageWidth;
588
+ canvasYmax = imageHeight;
589
+ canvas.height = imageHeight;
590
+ }
591
+
592
+ canvasWindow.imageWidth = imageWidth;
593
+ canvasWindow.imageHeight = imageHeight;
594
+
595
+ } else {
596
+ canvasXmin = 0;
597
+ canvasYmin = 0;
598
+ canvasXmax = canvas.width;
599
+ canvasYmax = canvas.height;
600
+ canvas.height = canvas.clientHeight;
601
+ }
602
+
603
+ canvasWindow.resize(canvas.width, canvas.height, canvasXmin, canvasYmin);
604
+
605
+ if (canvasXmax > 0 && canvasYmax > 0){
606
+ for (const box of value.boxes) {
607
+ box.canvasXmin = canvasXmin;
608
+ box.canvasYmin = canvasYmin;
609
+ box.canvasXmax = canvasXmax;
610
+ box.canvasYmax = canvasYmax;
611
+ box.setScaleFactor(scaleFactor);
612
+ }
613
+ }
614
+ draw();
615
+ dispatch("change");
616
+ }
617
+ }
618
+ const observer = new ResizeObserver(resize);
619
+
620
+ function parseInputBoxes() {
621
+ for (let i = 0; i < value.boxes.length; i++) {
622
+ let box = value.boxes[i];
623
+ if (!(box instanceof Box)) {
624
+ let color = "";
625
+ let label = "";
626
+ if (box.hasOwnProperty("color")) {
627
+ color = box["color"];
628
+ if (Array.isArray(color) && color.length === 3) {
629
+ color = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
630
+ }
631
+ } else {
632
+ color = Colors[i % Colors.length];
633
+ }
634
+ if (box.hasOwnProperty("label")) {
635
+ label = box["label"];
636
+ }
637
+ box = new Box(
638
+ draw,
639
+ onBoxFinishCreation,
640
+ canvasWindow,
641
+ pointersCache,
642
+ canvasXmin,
643
+ canvasYmin,
644
+ canvasXmax,
645
+ canvasYmax,
646
+ label,
647
+ box["xmin"],
648
+ box["ymin"],
649
+ box["xmax"],
650
+ box["ymax"],
651
+ color,
652
+ boxAlpha,
653
+ boxMinSize,
654
+ handleSize,
655
+ boxThickness,
656
+ boxSelectedThickness
657
+ );
658
+ value.boxes[i] = box;
659
+ }
660
+ }
661
+ }
662
+
663
+ $: {
664
+ value;
665
+ canvasWindow.orientation = value.orientation;
666
+ setImage();
667
+ parseInputBoxes();
668
+ resize();
669
+ draw();
670
+ }
671
+
672
+ function setImage(){
673
+ if (imageUrl !== null) {
674
+ if (image === null || image.src != imageUrl) {
675
+ image = new Image();
676
+ image.src = imageUrl;
677
+ image.onload = function(){
678
+ resize();
679
+ draw();
680
+ }
681
+ }
682
+ }
683
+ }
684
+
685
+ onMount(() => {
686
+ if (Array.isArray(choices) && choices.length > 0) {
687
+ if (!Array.isArray(choicesColors) || choicesColors.length == 0) {
688
+ for (let i = 0; i < choices.length; i++) {
689
+ let color = Colors[i % Colors.length];
690
+ choicesColors.push(colorRGBAToHex(color));
691
+ }
692
+ }
693
+ defaultLabelCache.label = choices[0][0];
694
+ defaultLabelCache.color = choicesColors[0];
695
+ }
696
+
697
+ ctx = canvas.getContext("2d");
698
+ observer.observe(canvas);
699
+
700
+ if (selectedBox < 0 && value !== null && value.boxes.length > 0) {
701
+ selectBox(0);
702
+ }
703
+
704
+ setImage();
705
+ resize();
706
+ draw();
707
+ });
708
+
709
+ </script>
710
+
711
+ <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
712
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
713
+ <div
714
+ class="annotator-container"
715
+ tabindex="0"
716
+ bind:this={annotatorContainerDiv}
717
+ on:keydown={handleKeyPress}
718
+ on:click={() => annotatorContainerDiv.focus()}
719
+ >
720
+ <div class="canvas-container">
721
+ <canvas
722
+ bind:this={canvas}
723
+ on:pointerdown={handlePointerDown}
724
+ on:pointerup={handlePointerUp}
725
+ on:pointermove={handlePointerMove}
726
+ on:pointercancel={handlePointerCancel}
727
+ on:dblclick={handleDoubleClick}
728
+ on:wheel={handleMouseWheel}
729
+ style="height: {height}; width: {width};"
730
+ class="canvas-annotator"
731
+ ></canvas>
732
+ </div>
733
+
734
+ {#if interactive}
735
+ <span class="canvas-control">
736
+ <button
737
+ class="icon"
738
+ class:selected={mode === Mode.creation}
739
+ aria-label="Create box"
740
+ title="Create box (C)"
741
+ on:click={() => setCreateMode()}><BoundingBox/></button
742
+ >
743
+ <button
744
+ class="icon"
745
+ class:selected={mode === Mode.drag}
746
+ aria-label="Drag boxes"
747
+ title="Drag boxes (D)"
748
+ on:click={() => setDragMode()}><Hand/></button
749
+ >
750
+ {#if showRemoveButton}
751
+ <button
752
+ class="icon"
753
+ aria-label="Remove box"
754
+ title="Remove box (Del)"
755
+ on:click={() => onDeleteBox()}><Trash/></button
756
+ >
757
+ {/if}
758
+ {#if !disableEditBoxes && labelDetailLock}
759
+ <button
760
+ class="icon"
761
+ aria-label="Edit label"
762
+ title="Edit label"
763
+ on:click={() => editDefaultLabelVisible = true}><Label/></button
764
+ >
765
+ {/if}
766
+ <button
767
+ class="icon"
768
+ aria-label="Rotate counterclockwise"
769
+ title="Rotate counterclockwise"
770
+ on:click={() => onRotateImage(-1)}><Undo/></button
771
+ >
772
+ <button
773
+ class="icon"
774
+ aria-label="Rotate clockwise"
775
+ title="Rotate clockwise"
776
+ on:click={() => onRotateImage(1)}><Redo/></button
777
+ >
778
+ </span>
779
+ {/if}
780
+ </div>
781
+
782
+ {#if editModalVisible}
783
+ <ModalBox
784
+ on:change={onModalEditChange}
785
+ on:enter{onModalEditChange}
786
+ choices={choices}
787
+ choicesColors={choicesColors}
788
+ label={selectedBox >= 0 && selectedBox < value.boxes.length ? value.boxes[selectedBox].label : ""}
789
+ color={selectedBox >= 0 && selectedBox < value.boxes.length ? colorRGBAToHex(value.boxes[selectedBox].color) : ""}
790
+ />
791
+ {/if}
792
+
793
+ {#if newModalVisible}
794
+ <ModalBox
795
+ on:change={onModalNewChange}
796
+ on:enter{onModalNewChange}
797
+ choices={choices}
798
+ showRemove={false}
799
+ choicesColors={choicesColors}
800
+ label={selectedBox >= 0 && selectedBox < value.boxes.length ? value.boxes[selectedBox].label : ""}
801
+ color={selectedBox >= 0 && selectedBox < value.boxes.length ? colorRGBAToHex(value.boxes[selectedBox].color) : ""}
802
+ labelDetailLock = {labelDetailLock}
803
+ />
804
+ {/if}
805
+
806
+ {#if editDefaultLabelVisible}
807
+ <ModalBox
808
+ on:change={onDefaultLabelEditChange}
809
+ on:enter{onDefaultLabelEditChange}
810
+ choices={choices}
811
+ showRemove={false}
812
+ choicesColors={choicesColors}
813
+ label={selectedBox >= 0 && selectedBox < value.boxes.length ? value.boxes[selectedBox].label : ""}
814
+ color={selectedBox >= 0 && selectedBox < value.boxes.length ? colorRGBAToHex(value.boxes[selectedBox].color) : ""}
815
+ labelDetailLock = {labelDetailLock}
816
+ />
817
+ {/if}
818
+
819
+ <style>
820
+ .canvas-annotator {
821
+ border-color: var(--block-border-color);
822
+ width: 100%;
823
+ height: 100%;
824
+ display: block;
825
+ touch-action: none;
826
+ }
827
+
828
+ .canvas-control {
829
+ display: flex;
830
+ align-items: center;
831
+ justify-content: center;
832
+ border-top: 1px solid var(--border-color-primary);
833
+ width: 95%;
834
+ bottom: 0;
835
+ left: 0;
836
+ right: 0;
837
+ margin-left: auto;
838
+ margin-right: auto;
839
+ margin-top: var(--size-2);
840
+ }
841
+
842
+ .icon {
843
+ width: 22px;
844
+ height: 22px;
845
+ margin: var(--spacing-lg) var(--spacing-xs);
846
+ padding: var(--spacing-xs);
847
+ color: var(--neutral-400);
848
+ border-radius: var(--radius-md);
849
+ }
850
+
851
+ .icon:hover,
852
+ .icon:focus {
853
+ color: var(--color-accent);
854
+ }
855
+
856
+ .selected {
857
+ color: var(--color-accent);
858
+ }
859
+
860
+ .canvas-container {
861
+ display: flex;
862
+ justify-content: center;
863
+ align-items: center;
864
+ }
865
+
866
+ .canvas-container:focus {
867
+ outline: none;
868
+ }
869
+ </style>
 
 
 
src/frontend/shared/ClearImage.svelte CHANGED
@@ -1,30 +1,30 @@
1
- <script lang="ts">
2
- import { createEventDispatcher } from "svelte";
3
- import { IconButton } from "@gradio/atoms";
4
- import { Clear } from "@gradio/icons";
5
-
6
- const dispatch = createEventDispatcher();
7
- </script>
8
-
9
- <div>
10
- <IconButton
11
- Icon={Clear}
12
- label="Remove Image"
13
- on:click={(event) => {
14
- dispatch("remove_image");
15
- event.stopPropagation();
16
- }}
17
- />
18
- </div>
19
-
20
- <style>
21
- div {
22
- display: flex;
23
- position: absolute;
24
- top: var(--size-2);
25
- right: var(--size-2);
26
- justify-content: flex-end;
27
- gap: var(--spacing-sm);
28
- z-index: var(--layer-5);
29
- }
30
- </style>
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher } from "svelte";
3
+ import { IconButton } from "@gradio/atoms";
4
+ import { Clear } from "@gradio/icons";
5
+
6
+ const dispatch = createEventDispatcher();
7
+ </script>
8
+
9
+ <div>
10
+ <IconButton
11
+ Icon={Clear}
12
+ label="Remove Image"
13
+ on:click={(event) => {
14
+ dispatch("remove_image");
15
+ event.stopPropagation();
16
+ }}
17
+ />
18
+ </div>
19
+
20
+ <style>
21
+ div {
22
+ display: flex;
23
+ position: absolute;
24
+ top: var(--size-2);
25
+ right: var(--size-2);
26
+ justify-content: flex-end;
27
+ gap: var(--spacing-sm);
28
+ z-index: var(--layer-5);
29
+ }
30
+ </style>
src/frontend/shared/Colors.js CHANGED
@@ -1,15 +1,15 @@
1
- export const Colors = [
2
- "rgb(255, 168, 77)",
3
- "rgb(92, 172, 238)",
4
- "rgb(255, 99, 71)",
5
- "rgb(118, 238, 118)",
6
- "rgb(255, 145, 164)",
7
- "rgb(0, 191, 255)",
8
- "rgb(255, 218, 185)",
9
- "rgb(255, 69, 0)",
10
- "rgb(34, 139, 34)",
11
- "rgb(255, 240, 245)",
12
- "rgb(255, 193, 37)",
13
- "rgb(255, 193, 7)",
14
- "rgb(255, 250, 138)",
15
- ];
 
1
+ export const Colors = [
2
+ "rgb(255, 168, 77)",
3
+ "rgb(92, 172, 238)",
4
+ "rgb(255, 99, 71)",
5
+ "rgb(118, 238, 118)",
6
+ "rgb(255, 145, 164)",
7
+ "rgb(0, 191, 255)",
8
+ "rgb(255, 218, 185)",
9
+ "rgb(255, 69, 0)",
10
+ "rgb(34, 139, 34)",
11
+ "rgb(255, 240, 245)",
12
+ "rgb(255, 193, 37)",
13
+ "rgb(255, 193, 7)",
14
+ "rgb(255, 250, 138)",
15
+ ];
src/frontend/shared/ImageAnnotator.svelte CHANGED
@@ -1,248 +1,248 @@
1
- <script lang="ts">
2
- import { createEventDispatcher, tick } from "svelte";
3
- import { Download, Image as ImageIcon } from "@gradio/icons";
4
- import { DownloadLink } from "@gradio/wasm/svelte";
5
- import { uploadToHuggingFace } from "@gradio/utils";
6
- import { BlockLabel, IconButton, ShareButton, SelectSource} from "@gradio/atoms";
7
- import { Upload } from "@gradio/upload";
8
- import { Webcam } from "@gradio/image";
9
- import type { FileData, Client } from "@gradio/client";
10
- import type { I18nFormatter, SelectData } from "@gradio/utils";
11
- import { Clear } from "@gradio/icons";
12
- import ImageCanvas from "./ImageCanvas.svelte";
13
- import AnnotatedImageData from "./AnnotatedImageData";
14
-
15
- type source_type = "upload" | "webcam" | "clipboard" | null;
16
-
17
- export let value: null | AnnotatedImageData;
18
- export let label: string | undefined = undefined;
19
- export let show_label: boolean;
20
- export let sources: source_type[] = ["upload", "webcam", "clipboard"];
21
- export let selectable = false;
22
- export let root: string;
23
- export let interactive: boolean;
24
- export let i18n: I18nFormatter;
25
- export let showShareButton: boolean;
26
- export let showDownloadButton: boolean;
27
- export let showClearButton: boolean;
28
- export let boxesAlpha;
29
- export let labelList: string[];
30
- export let labelColors: string[];
31
- export let boxMinSize: number;
32
- export let handleSize: number;
33
- export let height: number | string;
34
- export let width: number | string;
35
- export let boxThickness: number;
36
- export let disableEditBoxes: boolean;
37
- export let singleBox: boolean;
38
- export let showRemoveButton: boolean;
39
- export let handlesCursor: boolean;
40
- export let boxSelectedThickness: number;
41
- export let max_file_size: number | null = null;
42
- export let cli_upload: Client["upload"];
43
- export let stream_handler: Client["stream_factory"];
44
- export let useDefaultLabel: boolean;
45
- export let enableKeyboardShortcuts: boolean;
46
-
47
- let upload: Upload;
48
- let uploading = false;
49
- export let active_source: source_type = null;
50
-
51
- function handle_upload({ detail }: CustomEvent<FileData>): void {
52
- value = new AnnotatedImageData();
53
- value.image = detail;
54
- dispatch("upload");
55
- }
56
-
57
- async function handle_save(img_blob: Blob | any): Promise<void> {
58
- const f = await upload.load_files([new File([img_blob], `webcam.png`)]);
59
- const image = f?.[0] || null;
60
- if (image) {
61
- value = new AnnotatedImageData();
62
- value.image = image;
63
- } else {
64
- value = null;
65
- }
66
- await tick();
67
- dispatch("change");
68
- }
69
-
70
- $: if (uploading) clear();
71
-
72
- const dispatch = createEventDispatcher<{
73
- change: undefined;
74
- clear: undefined;
75
- drag: boolean;
76
- upload?: never;
77
- select: SelectData;
78
- }>();
79
-
80
- let dragging = false;
81
-
82
- $: dispatch("drag", dragging);
83
-
84
- $: if (!active_source && sources) {
85
- active_source = sources[0];
86
- }
87
-
88
- async function handle_select_source(
89
- source: (typeof sources)[number]
90
- ): Promise<void> {
91
- switch (source) {
92
- case "clipboard":
93
- upload.paste_clipboard();
94
- break;
95
- default:
96
- break;
97
- }
98
- }
99
-
100
- function clear() {
101
- value = null;
102
- dispatch("clear");
103
- dispatch("change");
104
- }
105
- </script>
106
-
107
- <BlockLabel {show_label} Icon={ImageIcon} label={label || "Image Annotator"} />
108
-
109
- <div class="icon-buttons">
110
- {#if showDownloadButton && value !== null}
111
- <DownloadLink href={value.image.url} download={value.image.orig_name || "image"}>
112
- <IconButton Icon={Download} label={i18n("common.download")} />
113
- </DownloadLink>
114
- {/if}
115
- {#if showShareButton && value !== null}
116
- <ShareButton
117
- {i18n}
118
- on:share
119
- on:error
120
- formatter={async (value) => {
121
- if (value === null) return "";
122
- let url = await uploadToHuggingFace(value.image, "base64");
123
- return `<img src="${url}" />`;
124
- }}
125
- {value}
126
- />
127
- {/if}
128
- {#if showClearButton && value !== null && interactive}
129
- <div>
130
- <IconButton
131
- Icon={Clear}
132
- label="Remove Image"
133
- on:click={clear}
134
- />
135
- </div>
136
- {/if}
137
- </div>
138
-
139
- <div data-testid="image" class="image-container">
140
- <div class="upload-container">
141
- <Upload
142
- hidden={value !== null || active_source === "webcam"}
143
- bind:this={upload}
144
- bind:uploading
145
- bind:dragging
146
- filetype={active_source === "clipboard" ? "clipboard" : "image/*"}
147
- on:load={handle_upload}
148
- on:error
149
- {root}
150
- {max_file_size}
151
- disable_click={!sources.includes("upload")}
152
- upload={cli_upload}
153
- {stream_handler}
154
- >
155
- {#if value === null}
156
- <slot />
157
- {/if}
158
- </Upload>
159
- {#if value === null && active_source === "webcam"}
160
- <Webcam
161
- {root}
162
- on:capture={(e) => handle_save(e.detail)}
163
- on:stream={(e) => handle_save(e.detail)}
164
- on:error
165
- on:drag
166
- on:upload={(e) => handle_save(e.detail)}
167
- mode="image"
168
- include_audio={false}
169
- {i18n}
170
- {upload}
171
- />
172
- {/if}
173
- {#if value !== null}
174
- <div class:selectable class="image-frame">
175
- <ImageCanvas
176
- bind:value
177
- on:change={() => dispatch("change")}
178
- {height}
179
- {width}
180
- {boxesAlpha}
181
- {labelList}
182
- {labelColors}
183
- {boxMinSize}
184
- {interactive}
185
- {handleSize}
186
- {boxThickness}
187
- {singleBox}
188
- {disableEditBoxes}
189
- {showRemoveButton}
190
- {handlesCursor}
191
- {boxSelectedThickness}
192
- {useDefaultLabel}
193
- {enableKeyboardShortcuts}
194
- src={value.image.url}
195
- />
196
- </div>
197
- {/if}
198
- </div>
199
- {#if (sources.length > 1 || sources.includes("clipboard")) && value === null && interactive}
200
- <SelectSource
201
- {sources}
202
- bind:active_source
203
- handle_clear={clear}
204
- handle_select={handle_select_source}
205
- />
206
- {/if}
207
- </div>
208
-
209
- <style>
210
- .image-frame :global(img) {
211
- width: var(--size-full);
212
- height: var(--size-full);
213
- object-fit: cover;
214
- }
215
-
216
- .image-frame {
217
- object-fit: cover;
218
- width: 100%;
219
- }
220
-
221
- .upload-container {
222
- height: 100%;
223
- width: 100%;
224
- flex-shrink: 1;
225
- max-height: 100%;
226
- }
227
-
228
- .image-container {
229
- display: flex;
230
- height: 100%;
231
- flex-direction: column;
232
- justify-content: center;
233
- align-items: center;
234
- max-height: 100%;
235
- }
236
-
237
- .selectable {
238
- cursor: crosshair;
239
- }
240
-
241
- .icon-buttons {
242
- display: flex;
243
- position: absolute;
244
- top: 6px;
245
- right: 6px;
246
- gap: var(--size-1);
247
- }
248
- </style>
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher, tick } from "svelte";
3
+ import { Download, Image as ImageIcon } from "@gradio/icons";
4
+ import { DownloadLink } from "@gradio/wasm/svelte";
5
+ import { uploadToHuggingFace } from "@gradio/utils";
6
+ import { BlockLabel, IconButton, ShareButton, SelectSource} from "@gradio/atoms";
7
+ import { Upload } from "@gradio/upload";
8
+ import { Webcam } from "@gradio/image";
9
+ import type { FileData, Client } from "@gradio/client";
10
+ import type { I18nFormatter, SelectData } from "@gradio/utils";
11
+ import { Clear } from "@gradio/icons";
12
+ import ImageCanvas from "./ImageCanvas.svelte";
13
+ import AnnotatedImageData from "./AnnotatedImageData";
14
+
15
+ type source_type = "upload" | "webcam" | "clipboard" | null;
16
+
17
+ export let value: null | AnnotatedImageData;
18
+ export let label: string | undefined = undefined;
19
+ export let show_label: boolean;
20
+ export let sources: source_type[] = ["upload", "webcam", "clipboard"];
21
+ export let selectable = false;
22
+ export let root: string;
23
+ export let interactive: boolean;
24
+ export let i18n: I18nFormatter;
25
+ export let showShareButton: boolean;
26
+ export let showDownloadButton: boolean;
27
+ export let showClearButton: boolean;
28
+ export let boxesAlpha;
29
+ export let labelList: string[];
30
+ export let labelColors: string[];
31
+ export let boxMinSize: number;
32
+ export let handleSize: number;
33
+ export let height: number | string;
34
+ export let width: number | string;
35
+ export let boxThickness: number;
36
+ export let disableEditBoxes: boolean;
37
+ export let singleBox: boolean;
38
+ export let showRemoveButton: boolean;
39
+ export let handlesCursor: boolean;
40
+ export let boxSelectedThickness: number;
41
+ export let max_file_size: number | null = null;
42
+ export let cli_upload: Client["upload"];
43
+ export let stream_handler: Client["stream_factory"];
44
+ export let useDefaultLabel: boolean;
45
+ export let enableKeyboardShortcuts: boolean;
46
+
47
+ let upload: Upload;
48
+ let uploading = false;
49
+ export let active_source: source_type = null;
50
+
51
+ function handle_upload({ detail }: CustomEvent<FileData>): void {
52
+ value = new AnnotatedImageData();
53
+ value.image = detail;
54
+ dispatch("upload");
55
+ }
56
+
57
+ async function handle_save(img_blob: Blob | any): Promise<void> {
58
+ const f = await upload.load_files([new File([img_blob], `webcam.png`)]);
59
+ const image = f?.[0] || null;
60
+ if (image) {
61
+ value = new AnnotatedImageData();
62
+ value.image = image;
63
+ } else {
64
+ value = null;
65
+ }
66
+ await tick();
67
+ dispatch("change");
68
+ }
69
+
70
+ $: if (uploading) clear();
71
+
72
+ const dispatch = createEventDispatcher<{
73
+ change: undefined;
74
+ clear: undefined;
75
+ drag: boolean;
76
+ upload?: never;
77
+ select: SelectData;
78
+ }>();
79
+
80
+ let dragging = false;
81
+
82
+ $: dispatch("drag", dragging);
83
+
84
+ $: if (!active_source && sources) {
85
+ active_source = sources[0];
86
+ }
87
+
88
+ async function handle_select_source(
89
+ source: (typeof sources)[number]
90
+ ): Promise<void> {
91
+ switch (source) {
92
+ case "clipboard":
93
+ upload.paste_clipboard();
94
+ break;
95
+ default:
96
+ break;
97
+ }
98
+ }
99
+
100
+ function clear() {
101
+ value = null;
102
+ dispatch("clear");
103
+ dispatch("change");
104
+ }
105
+ </script>
106
+
107
+ <BlockLabel {show_label} Icon={ImageIcon} label={label || "Image Annotator"} />
108
+
109
+ <div class="icon-buttons">
110
+ {#if showDownloadButton && value !== null}
111
+ <DownloadLink href={value.image.url} download={value.image.orig_name || "image"}>
112
+ <IconButton Icon={Download} label={i18n("common.download")} />
113
+ </DownloadLink>
114
+ {/if}
115
+ {#if showShareButton && value !== null}
116
+ <ShareButton
117
+ {i18n}
118
+ on:share
119
+ on:error
120
+ formatter={async (value) => {
121
+ if (value === null) return "";
122
+ let url = await uploadToHuggingFace(value.image, "base64");
123
+ return `<img src="${url}" />`;
124
+ }}
125
+ {value}
126
+ />
127
+ {/if}
128
+ {#if showClearButton && value !== null && interactive}
129
+ <div>
130
+ <IconButton
131
+ Icon={Clear}
132
+ label="Remove Image"
133
+ on:click={clear}
134
+ />
135
+ </div>
136
+ {/if}
137
+ </div>
138
+
139
+ <div data-testid="image" class="image-container">
140
+ <div class="upload-container">
141
+ <Upload
142
+ hidden={value !== null || active_source === "webcam"}
143
+ bind:this={upload}
144
+ bind:uploading
145
+ bind:dragging
146
+ filetype={active_source === "clipboard" ? "clipboard" : "image/*"}
147
+ on:load={handle_upload}
148
+ on:error
149
+ {root}
150
+ {max_file_size}
151
+ disable_click={!sources.includes("upload")}
152
+ upload={cli_upload}
153
+ {stream_handler}
154
+ >
155
+ {#if value === null}
156
+ <slot />
157
+ {/if}
158
+ </Upload>
159
+ {#if value === null && active_source === "webcam"}
160
+ <Webcam
161
+ {root}
162
+ on:capture={(e) => handle_save(e.detail)}
163
+ on:stream={(e) => handle_save(e.detail)}
164
+ on:error
165
+ on:drag
166
+ on:upload={(e) => handle_save(e.detail)}
167
+ mode="image"
168
+ include_audio={false}
169
+ {i18n}
170
+ {upload}
171
+ />
172
+ {/if}
173
+ {#if value !== null}
174
+ <div class:selectable class="image-frame">
175
+ <ImageCanvas
176
+ bind:value
177
+ on:change={() => dispatch("change")}
178
+ {height}
179
+ {width}
180
+ {boxesAlpha}
181
+ {labelList}
182
+ {labelColors}
183
+ {boxMinSize}
184
+ {interactive}
185
+ {handleSize}
186
+ {boxThickness}
187
+ {singleBox}
188
+ {disableEditBoxes}
189
+ {showRemoveButton}
190
+ {handlesCursor}
191
+ {boxSelectedThickness}
192
+ {useDefaultLabel}
193
+ {enableKeyboardShortcuts}
194
+ src={value.image.url}
195
+ />
196
+ </div>
197
+ {/if}
198
+ </div>
199
+ {#if (sources.length > 1 || sources.includes("clipboard")) && value === null && interactive}
200
+ <SelectSource
201
+ {sources}
202
+ bind:active_source
203
+ handle_clear={clear}
204
+ handle_select={handle_select_source}
205
+ />
206
+ {/if}
207
+ </div>
208
+
209
+ <style>
210
+ .image-frame :global(img) {
211
+ width: var(--size-full);
212
+ height: var(--size-full);
213
+ object-fit: cover;
214
+ }
215
+
216
+ .image-frame {
217
+ object-fit: cover;
218
+ width: 100%;
219
+ }
220
+
221
+ .upload-container {
222
+ height: 100%;
223
+ width: 100%;
224
+ flex-shrink: 1;
225
+ max-height: 100%;
226
+ }
227
+
228
+ .image-container {
229
+ display: flex;
230
+ height: 100%;
231
+ flex-direction: column;
232
+ justify-content: center;
233
+ align-items: center;
234
+ max-height: 100%;
235
+ }
236
+
237
+ .selectable {
238
+ cursor: crosshair;
239
+ }
240
+
241
+ .icon-buttons {
242
+ display: flex;
243
+ position: absolute;
244
+ top: 6px;
245
+ right: 6px;
246
+ gap: var(--size-1);
247
+ }
248
+ </style>
src/frontend/shared/ImageCanvas.svelte CHANGED
@@ -1,80 +1,80 @@
1
- <script lang="ts">
2
- import { resolve_wasm_src } from "@gradio/wasm/svelte";
3
- import type { HTMLImgAttributes } from "svelte/elements";
4
- import { createEventDispatcher } from "svelte";
5
- import Canvas from "./Canvas.svelte"
6
- import AnnotatedImageData from "./AnnotatedImageData";
7
-
8
- interface Props extends HTMLImgAttributes {
9
- "data-testid"?: string;
10
- }
11
-
12
- export let src: HTMLImgAttributes["src"] = undefined;
13
- export let interactive: boolean;
14
- export let boxesAlpha: number;
15
- export let labelList: string[];
16
- export let labelColors: string[];
17
- export let boxMinSize: number;
18
- export let handleSize: number;
19
- export let boxThickness: number;
20
- export let height: number | string;
21
- export let width: number | string;
22
- export let boxSelectedThickness: number;
23
- export let value: null | AnnotatedImageData;
24
- export let disableEditBoxes: boolean;
25
- export let singleBox: boolean;
26
- export let showRemoveButton: boolean;
27
- export let handlesCursor: boolean;
28
- export let useDefaultLabel: boolean;
29
- export let enableKeyboardShortcuts: boolean;
30
-
31
- let resolved_src: typeof src;
32
-
33
- // The `src` prop can be updated before the Promise from `resolve_wasm_src` is resolved.
34
- // In such a case, the resolved value for the old `src` has to be discarded,
35
- // This variable `latest_src` is used to pick up only the value resolved for the latest `src` prop.
36
- let latest_src: typeof src;
37
- $: {
38
- // In normal (non-Wasm) Gradio, the `<img>` element should be rendered with the passed `src` props immediately
39
- // without waiting for `resolve_wasm_src()` to resolve.
40
- // If it waits, a blank image is displayed until the async task finishes
41
- // and it leads to undesirable flickering.
42
- // So set `src` to `resolved_src` here.
43
- resolved_src = src;
44
-
45
- latest_src = src;
46
- const resolving_src = src;
47
- resolve_wasm_src(resolving_src).then((s) => {
48
- if (latest_src === resolving_src) {
49
- resolved_src = s;
50
- }
51
- });
52
- }
53
-
54
- const dispatch = createEventDispatcher<{
55
- change: undefined;
56
- }>();
57
-
58
- </script>
59
-
60
- <Canvas
61
- bind:value
62
- on:change={() => dispatch("change")}
63
- {interactive}
64
- boxAlpha={boxesAlpha}
65
- choices={labelList}
66
- choicesColors={labelColors}
67
- {height}
68
- {width}
69
- {boxMinSize}
70
- {handleSize}
71
- {boxThickness}
72
- {boxSelectedThickness}
73
- {disableEditBoxes}
74
- {singleBox}
75
- {showRemoveButton}
76
- {handlesCursor}
77
- {useDefaultLabel}
78
- {enableKeyboardShortcuts}
79
- imageUrl={resolved_src}
80
- />
 
1
+ <script lang="ts">
2
+ import { resolve_wasm_src } from "@gradio/wasm/svelte";
3
+ import type { HTMLImgAttributes } from "svelte/elements";
4
+ import { createEventDispatcher } from "svelte";
5
+ import Canvas from "./Canvas.svelte"
6
+ import AnnotatedImageData from "./AnnotatedImageData";
7
+
8
+ interface Props extends HTMLImgAttributes {
9
+ "data-testid"?: string;
10
+ }
11
+
12
+ export let src: HTMLImgAttributes["src"] = undefined;
13
+ export let interactive: boolean;
14
+ export let boxesAlpha: number;
15
+ export let labelList: string[];
16
+ export let labelColors: string[];
17
+ export let boxMinSize: number;
18
+ export let handleSize: number;
19
+ export let boxThickness: number;
20
+ export let height: number | string;
21
+ export let width: number | string;
22
+ export let boxSelectedThickness: number;
23
+ export let value: null | AnnotatedImageData;
24
+ export let disableEditBoxes: boolean;
25
+ export let singleBox: boolean;
26
+ export let showRemoveButton: boolean;
27
+ export let handlesCursor: boolean;
28
+ export let useDefaultLabel: boolean;
29
+ export let enableKeyboardShortcuts: boolean;
30
+
31
+ let resolved_src: typeof src;
32
+
33
+ // The `src` prop can be updated before the Promise from `resolve_wasm_src` is resolved.
34
+ // In such a case, the resolved value for the old `src` has to be discarded,
35
+ // This variable `latest_src` is used to pick up only the value resolved for the latest `src` prop.
36
+ let latest_src: typeof src;
37
+ $: {
38
+ // In normal (non-Wasm) Gradio, the `<img>` element should be rendered with the passed `src` props immediately
39
+ // without waiting for `resolve_wasm_src()` to resolve.
40
+ // If it waits, a blank image is displayed until the async task finishes
41
+ // and it leads to undesirable flickering.
42
+ // So set `src` to `resolved_src` here.
43
+ resolved_src = src;
44
+
45
+ latest_src = src;
46
+ const resolving_src = src;
47
+ resolve_wasm_src(resolving_src).then((s) => {
48
+ if (latest_src === resolving_src) {
49
+ resolved_src = s;
50
+ }
51
+ });
52
+ }
53
+
54
+ const dispatch = createEventDispatcher<{
55
+ change: undefined;
56
+ }>();
57
+
58
+ </script>
59
+
60
+ <Canvas
61
+ bind:value
62
+ on:change={() => dispatch("change")}
63
+ {interactive}
64
+ boxAlpha={boxesAlpha}
65
+ choices={labelList}
66
+ choicesColors={labelColors}
67
+ {height}
68
+ {width}
69
+ {boxMinSize}
70
+ {handleSize}
71
+ {boxThickness}
72
+ {boxSelectedThickness}
73
+ {disableEditBoxes}
74
+ {singleBox}
75
+ {showRemoveButton}
76
+ {handlesCursor}
77
+ {useDefaultLabel}
78
+ {enableKeyboardShortcuts}
79
+ imageUrl={resolved_src}
80
+ />
src/frontend/shared/ModalBox.svelte CHANGED
@@ -1,189 +1,189 @@
1
- <script lang="ts">
2
- import { BaseColorPicker } from "@gradio/colorpicker";
3
- import { BaseButton } from "@gradio/button";
4
- import { BaseDropdown } from "./patched_dropdown/Index.svelte";
5
- import { createEventDispatcher } from "svelte";
6
- import { onMount } from "svelte";
7
- import { Lock, Unlock } from "./icons/index";
8
-
9
- export let label = "";
10
- export let currentLabel = "";
11
- export let choices = []; // [(label, i)]
12
- export let choicesColors = [];
13
- export let color = "";
14
- export let currentColor = "";
15
- export let showRemove = true;
16
- export let labelDetailLock = false;
17
-
18
- const dispatch = createEventDispatcher<{
19
- change: object;
20
- }>();
21
-
22
- function dispatchChange(ret: number) {
23
- dispatch("change", {
24
- label: currentLabel,
25
- color: currentColor,
26
- lock: labelDetailLock,
27
- ret: ret // -1: remove, 0: cancel, 1: change
28
- });
29
- }
30
-
31
- function onDropDownChange(event) {
32
- const { detail } = event;
33
- let choice = detail;
34
-
35
- if (Number.isInteger(choice)) {
36
- if (Array.isArray(choicesColors) && choice < choicesColors.length) {
37
- currentColor = choicesColors[choice];
38
- }
39
- if (Array.isArray(choices) && choice < choices.length) {
40
- currentLabel = choices[choice][0];
41
- }
42
- } else {
43
- currentLabel = choice;
44
- }
45
- }
46
-
47
- function onColorChange(event) {
48
- const { detail } = event;
49
- currentColor = detail;
50
- }
51
-
52
- function onDropDownEnter(event) {
53
- onDropDownChange(event);
54
- dispatchChange(1);
55
- }
56
-
57
- function onLockClick(event) {
58
- labelDetailLock = !labelDetailLock;
59
- }
60
-
61
- function handleKeyPress(event: KeyboardEvent) {
62
- switch (event.key.toLowerCase()) {
63
- case "enter":
64
- dispatchChange(1);
65
- break;
66
- case "escape":
67
- dispatchChange(0);
68
- break;
69
- }
70
- }
71
-
72
- onMount(() => {
73
- document.addEventListener("keydown", handleKeyPress);
74
- currentLabel = label;
75
- currentColor = color;
76
-
77
- return () => {
78
- document.removeEventListener("keydown", handleKeyPress);
79
- };
80
- });
81
-
82
- </script>
83
-
84
- <div class="modal" id="model-box-edit">
85
- <div class="modal-container">
86
- <span class="model-content">
87
- {#if !showRemove}
88
- <div style="margin-right: 8px;">
89
- <button
90
- class="icon"
91
- class:selected={labelDetailLock === true}
92
- aria-label="Lock label detail"
93
- on:click={onLockClick}>
94
- {#if labelDetailLock}<Lock/>{:else}<Unlock/>{/if}</button
95
- >
96
- </div>
97
- {/if}
98
- <div style="margin-right: 10px;">
99
- <BaseDropdown
100
- value={currentLabel}
101
- label="Label"
102
- {choices}
103
- show_label={false}
104
- allow_custom_value={true}
105
- on:change={onDropDownChange}
106
- on:enter={onDropDownEnter}
107
- />
108
- </div>
109
- <div style="margin-right: 40px; margin-bottom: 8px;">
110
- <BaseColorPicker
111
- value={currentColor}
112
- label="Color"
113
- show_label={false}
114
- on:change={onColorChange}
115
- />
116
- </div>
117
- <div style="margin-right: 8px;">
118
- <BaseButton
119
- on:click={() => dispatchChange(0)}
120
- >Cancel</BaseButton>
121
- </div>
122
- {#if showRemove}
123
- <div style="margin-right: 8px;">
124
- <BaseButton
125
- variant="stop"
126
- on:click={() => dispatchChange(-1)}
127
- >Remove</BaseButton>
128
- </div>
129
- {/if}
130
- <div>
131
- <BaseButton
132
- variant="primary"
133
- on:click={() => dispatchChange(1)}
134
- >OK</BaseButton>
135
- </div>
136
- </span>
137
- </div>
138
- </div>
139
-
140
- <style>
141
- .modal {
142
- position: fixed;
143
- left: 0;
144
- top: 0;
145
- width: 100%;
146
- height: 100%;
147
- z-index: var(--layer-top);
148
- -webkit-backdrop-filter: blur(4px);
149
- backdrop-filter: blur(4px);
150
- }
151
-
152
- .modal-container {
153
- border-style: solid;
154
- border-width: var(--block-border-width);
155
- border-color: var(--block-border-color);
156
- margin-top: 10%;
157
- padding: 20px;
158
- box-shadow: var(--block-shadow);
159
- border-color: var(--block-border-color);
160
- border-radius: var(--block-radius);
161
- background: var(--block-background-fill);
162
- position: fixed;
163
- left: 50%;
164
- transform: translateX(-50%);
165
- width: fit-content;
166
- }
167
-
168
- .model-content {
169
- display: flex;
170
- align-items: flex-end;
171
- }
172
-
173
- .icon {
174
- width: 22px;
175
- height: 22px;
176
- margin: var(--spacing-lg) var(--spacing-xs);
177
- padding: var(--spacing-xs);
178
- color: var(--neutral-400);
179
- border-radius: var(--radius-md);
180
- }
181
-
182
- .icon:hover{
183
- color: var(--color-accent);
184
- }
185
-
186
- .selected {
187
- color: var(--color-accent);
188
- }
189
- </style>
 
1
+ <script lang="ts">
2
+ import { BaseColorPicker } from "@gradio/colorpicker";
3
+ import { BaseButton } from "@gradio/button";
4
+ import { BaseDropdown } from "./patched_dropdown/Index.svelte";
5
+ import { createEventDispatcher } from "svelte";
6
+ import { onMount } from "svelte";
7
+ import { Lock, Unlock } from "./icons/index";
8
+
9
+ export let label = "";
10
+ export let currentLabel = "";
11
+ export let choices = []; // [(label, i)]
12
+ export let choicesColors = [];
13
+ export let color = "";
14
+ export let currentColor = "";
15
+ export let showRemove = true;
16
+ export let labelDetailLock = false;
17
+
18
+ const dispatch = createEventDispatcher<{
19
+ change: object;
20
+ }>();
21
+
22
+ function dispatchChange(ret: number) {
23
+ dispatch("change", {
24
+ label: currentLabel,
25
+ color: currentColor,
26
+ lock: labelDetailLock,
27
+ ret: ret // -1: remove, 0: cancel, 1: change
28
+ });
29
+ }
30
+
31
+ function onDropDownChange(event) {
32
+ const { detail } = event;
33
+ let choice = detail;
34
+
35
+ if (Number.isInteger(choice)) {
36
+ if (Array.isArray(choicesColors) && choice < choicesColors.length) {
37
+ currentColor = choicesColors[choice];
38
+ }
39
+ if (Array.isArray(choices) && choice < choices.length) {
40
+ currentLabel = choices[choice][0];
41
+ }
42
+ } else {
43
+ currentLabel = choice;
44
+ }
45
+ }
46
+
47
+ function onColorChange(event) {
48
+ const { detail } = event;
49
+ currentColor = detail;
50
+ }
51
+
52
+ function onDropDownEnter(event) {
53
+ onDropDownChange(event);
54
+ dispatchChange(1);
55
+ }
56
+
57
+ function onLockClick(event) {
58
+ labelDetailLock = !labelDetailLock;
59
+ }
60
+
61
+ function handleKeyPress(event: KeyboardEvent) {
62
+ switch (event.key.toLowerCase()) {
63
+ case "enter":
64
+ dispatchChange(1);
65
+ break;
66
+ case "escape":
67
+ dispatchChange(0);
68
+ break;
69
+ }
70
+ }
71
+
72
+ onMount(() => {
73
+ document.addEventListener("keydown", handleKeyPress);
74
+ currentLabel = label;
75
+ currentColor = color;
76
+
77
+ return () => {
78
+ document.removeEventListener("keydown", handleKeyPress);
79
+ };
80
+ });
81
+
82
+ </script>
83
+
84
+ <div class="modal" id="model-box-edit">
85
+ <div class="modal-container">
86
+ <span class="model-content">
87
+ {#if !showRemove}
88
+ <div style="margin-right: 8px;">
89
+ <button
90
+ class="icon"
91
+ class:selected={labelDetailLock === true}
92
+ aria-label="Lock label detail"
93
+ on:click={onLockClick}>
94
+ {#if labelDetailLock}<Lock/>{:else}<Unlock/>{/if}</button
95
+ >
96
+ </div>
97
+ {/if}
98
+ <div style="margin-right: 10px;">
99
+ <BaseDropdown
100
+ value={currentLabel}
101
+ label="Label"
102
+ {choices}
103
+ show_label={false}
104
+ allow_custom_value={true}
105
+ on:change={onDropDownChange}
106
+ on:enter={onDropDownEnter}
107
+ />
108
+ </div>
109
+ <div style="margin-right: 40px; margin-bottom: 8px;">
110
+ <BaseColorPicker
111
+ value={currentColor}
112
+ label="Color"
113
+ show_label={false}
114
+ on:change={onColorChange}
115
+ />
116
+ </div>
117
+ <div style="margin-right: 8px;">
118
+ <BaseButton
119
+ on:click={() => dispatchChange(0)}
120
+ >Cancel</BaseButton>
121
+ </div>
122
+ {#if showRemove}
123
+ <div style="margin-right: 8px;">
124
+ <BaseButton
125
+ variant="stop"
126
+ on:click={() => dispatchChange(-1)}
127
+ >Remove</BaseButton>
128
+ </div>
129
+ {/if}
130
+ <div>
131
+ <BaseButton
132
+ variant="primary"
133
+ on:click={() => dispatchChange(1)}
134
+ >OK</BaseButton>
135
+ </div>
136
+ </span>
137
+ </div>
138
+ </div>
139
+
140
+ <style>
141
+ .modal {
142
+ position: fixed;
143
+ left: 0;
144
+ top: 0;
145
+ width: 100%;
146
+ height: 100%;
147
+ z-index: var(--layer-top);
148
+ -webkit-backdrop-filter: blur(4px);
149
+ backdrop-filter: blur(4px);
150
+ }
151
+
152
+ .modal-container {
153
+ border-style: solid;
154
+ border-width: var(--block-border-width);
155
+ border-color: var(--block-border-color);
156
+ margin-top: 10%;
157
+ padding: 20px;
158
+ box-shadow: var(--block-shadow);
159
+ border-color: var(--block-border-color);
160
+ border-radius: var(--block-radius);
161
+ background: var(--block-background-fill);
162
+ position: fixed;
163
+ left: 50%;
164
+ transform: translateX(-50%);
165
+ width: fit-content;
166
+ }
167
+
168
+ .model-content {
169
+ display: flex;
170
+ align-items: flex-end;
171
+ }
172
+
173
+ .icon {
174
+ width: 22px;
175
+ height: 22px;
176
+ margin: var(--spacing-lg) var(--spacing-xs);
177
+ padding: var(--spacing-xs);
178
+ color: var(--neutral-400);
179
+ border-radius: var(--radius-md);
180
+ }
181
+
182
+ .icon:hover{
183
+ color: var(--color-accent);
184
+ }
185
+
186
+ .selected {
187
+ color: var(--color-accent);
188
+ }
189
+ </style>
src/frontend/shared/WindowViewer.ts CHANGED
@@ -1,115 +1,115 @@
1
- const clamp = (num: number, min: number, max: number) => Math.min(Math.max(num, min), max)
2
-
3
- export default class WindowViewer {
4
- scale: number;
5
- offsetX: number;
6
- offsetY: number;
7
- canvasWidth: number;
8
- canvasHeight: number;
9
- imageWidth: number;
10
- imageHeight: number;
11
- imageRotatedWidth: number;
12
- imageRotatedHeight: number;
13
- isDragging: boolean;
14
- startDragX: number;
15
- startDragY: number;
16
- orientation: number;
17
- renderCallBack: () => void;
18
- pointersCache: Map<number, PointerEvent>;
19
-
20
- constructor(
21
- renderCallBack: () => void,
22
- pointersCache: Map<number, PointerEvent>,
23
- ) {
24
- this.renderCallBack = renderCallBack;
25
- this.pointersCache = pointersCache;
26
- this.scale = 1.0;
27
- this.offsetX = 0;
28
- this.offsetY = 0;
29
- this.canvasWidth = 0;
30
- this.canvasHeight = 0;
31
- this.imageWidth = 0;
32
- this.imageHeight = 0;
33
- this.imageRotatedWidth = 0;
34
- this.imageRotatedHeight = 0;
35
- this.isDragging = false;
36
- this.startDragX = 0;
37
- this.startDragY = 0;
38
- this.orientation = 0;
39
- }
40
- startDrag(event: MouseEvent): void {
41
- this.isDragging = true;
42
- this.startDragX = event.clientX;
43
- this.startDragY = event.clientY;
44
-
45
- document.addEventListener("pointermove", this.handleDrag);
46
- document.addEventListener("pointerup", this.stopDrag);
47
- }
48
-
49
- stopDrag = (): void => {
50
- if (this.pointersCache.size === 0) {
51
- this.isDragging = false;
52
- document.removeEventListener("pointermove", this.handleDrag);
53
- document.removeEventListener("pointerup", this.stopDrag);
54
- } else if (this.pointersCache.size === 1) {
55
- this.isDragging = true;
56
- this.startDragX = this.pointersCache.values().next().value.clientX;
57
- this.startDragY = this.pointersCache.values().next().value.clientY;
58
- }
59
- };
60
-
61
- handleDrag = (event: MouseEvent): void => {
62
- if (this.isDragging && this.pointersCache.size === 1) {
63
-
64
- if (this.scale == 1.0){
65
- this.offsetX = (this.canvasWidth - this.imageWidth) / 2;
66
- this.offsetY = 0;
67
- this.renderCallBack();
68
- return;
69
- }
70
-
71
- let deltaX = event.clientX - this.startDragX;
72
- let deltaY = event.clientY - this.startDragY;
73
-
74
- if (this.imageWidth * this.scale > this.canvasWidth){
75
- deltaX = clamp(deltaX, this.canvasWidth-this.offsetX-(this.imageWidth*this.scale), -this.offsetX);
76
- } else {
77
- deltaX = clamp(deltaX, -this.offsetX, this.canvasWidth-this.offsetX-(this.imageWidth*this.scale));
78
- }
79
-
80
- if (this.imageHeight * this.scale > this.canvasHeight){
81
- deltaY = clamp(deltaY, this.canvasHeight-this.offsetY-(this.imageHeight*this.scale), -this.offsetY);
82
- } else {
83
- deltaY = clamp(deltaY, -this.offsetY, this.canvasHeight-this.offsetY-(this.imageHeight*this.scale));
84
- }
85
-
86
- this.offsetX += deltaX;
87
- this.offsetY += deltaY;
88
- this.startDragX = event.clientX;
89
- this.startDragY = event.clientY;
90
- this.renderCallBack();
91
- }
92
- };
93
-
94
- setRotatedImage(image: HTMLImageElement | null): void {
95
- if (image !== null) {
96
- if (this.orientation == 0 || this.orientation == 2) {
97
- this.imageRotatedWidth = image.width;
98
- this.imageRotatedHeight = image.height;
99
- } else { // (this.orientation == 1 || this.orientation == 3)
100
- this.imageRotatedWidth = image.height;
101
- this.imageRotatedHeight = image.width;
102
- }
103
- }
104
- }
105
-
106
- resize(width: number, height: number, offsetX: number=0, offsetY: number=0): void {
107
- if (this.canvasWidth == width && this.canvasHeight == height) return;
108
- this.canvasWidth = width;
109
- this.canvasHeight = height;
110
-
111
- this.scale = 1.0;
112
- this.offsetX = offsetX;
113
- this.offsetY = offsetY;
114
- }
115
- }
 
1
+ const clamp = (num: number, min: number, max: number) => Math.min(Math.max(num, min), max)
2
+
3
+ export default class WindowViewer {
4
+ scale: number;
5
+ offsetX: number;
6
+ offsetY: number;
7
+ canvasWidth: number;
8
+ canvasHeight: number;
9
+ imageWidth: number;
10
+ imageHeight: number;
11
+ imageRotatedWidth: number;
12
+ imageRotatedHeight: number;
13
+ isDragging: boolean;
14
+ startDragX: number;
15
+ startDragY: number;
16
+ orientation: number;
17
+ renderCallBack: () => void;
18
+ pointersCache: Map<number, PointerEvent>;
19
+
20
+ constructor(
21
+ renderCallBack: () => void,
22
+ pointersCache: Map<number, PointerEvent>,
23
+ ) {
24
+ this.renderCallBack = renderCallBack;
25
+ this.pointersCache = pointersCache;
26
+ this.scale = 1.0;
27
+ this.offsetX = 0;
28
+ this.offsetY = 0;
29
+ this.canvasWidth = 0;
30
+ this.canvasHeight = 0;
31
+ this.imageWidth = 0;
32
+ this.imageHeight = 0;
33
+ this.imageRotatedWidth = 0;
34
+ this.imageRotatedHeight = 0;
35
+ this.isDragging = false;
36
+ this.startDragX = 0;
37
+ this.startDragY = 0;
38
+ this.orientation = 0;
39
+ }
40
+ startDrag(event: MouseEvent): void {
41
+ this.isDragging = true;
42
+ this.startDragX = event.clientX;
43
+ this.startDragY = event.clientY;
44
+
45
+ document.addEventListener("pointermove", this.handleDrag);
46
+ document.addEventListener("pointerup", this.stopDrag);
47
+ }
48
+
49
+ stopDrag = (): void => {
50
+ if (this.pointersCache.size === 0) {
51
+ this.isDragging = false;
52
+ document.removeEventListener("pointermove", this.handleDrag);
53
+ document.removeEventListener("pointerup", this.stopDrag);
54
+ } else if (this.pointersCache.size === 1) {
55
+ this.isDragging = true;
56
+ this.startDragX = this.pointersCache.values().next().value.clientX;
57
+ this.startDragY = this.pointersCache.values().next().value.clientY;
58
+ }
59
+ };
60
+
61
+ handleDrag = (event: MouseEvent): void => {
62
+ if (this.isDragging && this.pointersCache.size === 1) {
63
+
64
+ if (this.scale == 1.0){
65
+ this.offsetX = (this.canvasWidth - this.imageWidth) / 2;
66
+ this.offsetY = 0;
67
+ this.renderCallBack();
68
+ return;
69
+ }
70
+
71
+ let deltaX = event.clientX - this.startDragX;
72
+ let deltaY = event.clientY - this.startDragY;
73
+
74
+ if (this.imageWidth * this.scale > this.canvasWidth){
75
+ deltaX = clamp(deltaX, this.canvasWidth-this.offsetX-(this.imageWidth*this.scale), -this.offsetX);
76
+ } else {
77
+ deltaX = clamp(deltaX, -this.offsetX, this.canvasWidth-this.offsetX-(this.imageWidth*this.scale));
78
+ }
79
+
80
+ if (this.imageHeight * this.scale > this.canvasHeight){
81
+ deltaY = clamp(deltaY, this.canvasHeight-this.offsetY-(this.imageHeight*this.scale), -this.offsetY);
82
+ } else {
83
+ deltaY = clamp(deltaY, -this.offsetY, this.canvasHeight-this.offsetY-(this.imageHeight*this.scale));
84
+ }
85
+
86
+ this.offsetX += deltaX;
87
+ this.offsetY += deltaY;
88
+ this.startDragX = event.clientX;
89
+ this.startDragY = event.clientY;
90
+ this.renderCallBack();
91
+ }
92
+ };
93
+
94
+ setRotatedImage(image: HTMLImageElement | null): void {
95
+ if (image !== null) {
96
+ if (this.orientation == 0 || this.orientation == 2) {
97
+ this.imageRotatedWidth = image.width;
98
+ this.imageRotatedHeight = image.height;
99
+ } else { // (this.orientation == 1 || this.orientation == 3)
100
+ this.imageRotatedWidth = image.height;
101
+ this.imageRotatedHeight = image.width;
102
+ }
103
+ }
104
+ }
105
+
106
+ resize(width: number, height: number, offsetX: number=0, offsetY: number=0): void {
107
+ if (this.canvasWidth == width && this.canvasHeight == height) return;
108
+ this.canvasWidth = width;
109
+ this.canvasHeight = height;
110
+
111
+ this.scale = 1.0;
112
+ this.offsetX = offsetX;
113
+ this.offsetY = offsetY;
114
+ }
115
+ }
src/frontend/shared/icons/Label.svelte CHANGED
@@ -1,15 +1,15 @@
1
- <svg
2
- width="100%"
3
- height="100%"
4
- viewBox="0 0 24 24"
5
- xmlns="http://www.w3.org/2000/svg"
6
- fill="none"
7
- stroke="currentColor"
8
- stroke-width="2"
9
- style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"
10
- >
11
- <path
12
- d="M12,2.5L2.5,12c-.7.7-.7,1.8,0,2.4l7.1,7.1c.7.7,1.8.7,2.4,0l9.5-9.5c.3-.3.5-.8.5-1.2V3.7c0-1-.8-1.7-1.7-1.7h-7.1c-.5,0-.9.2-1.2.5ZM7.3,14.1l4.7-4.7M9.9,16.7l2.2-2.2"
13
- />
14
- <path d="M18.5,6.3c0,.5-.4.9-.9.9s-.9-.4-.9-.9.4-.9.9-.9.9.4.9.9Z" />
15
- </svg>
 
1
+ <svg
2
+ width="100%"
3
+ height="100%"
4
+ viewBox="0 0 24 24"
5
+ xmlns="http://www.w3.org/2000/svg"
6
+ fill="none"
7
+ stroke="currentColor"
8
+ stroke-width="2"
9
+ style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"
10
+ >
11
+ <path
12
+ d="M12,2.5L2.5,12c-.7.7-.7,1.8,0,2.4l7.1,7.1c.7.7,1.8.7,2.4,0l9.5-9.5c.3-.3.5-.8.5-1.2V3.7c0-1-.8-1.7-1.7-1.7h-7.1c-.5,0-.9.2-1.2.5ZM7.3,14.1l4.7-4.7M9.9,16.7l2.2-2.2"
13
+ />
14
+ <path d="M18.5,6.3c0,.5-.4.9-.9.9s-.9-.4-.9-.9.4-.9.9-.9.9.4.9.9Z" />
15
+ </svg>
src/frontend/shared/icons/Lock.svelte CHANGED
@@ -1,14 +1,14 @@
1
- <svg
2
- width="100%"
3
- height="100%"
4
- viewBox="0 0 24 24"
5
- fill="none"
6
- stroke="currentColor"
7
- stroke-width="2"
8
- style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"
9
- xmlns="http://www.w3.org/2000/svg"
10
- >
11
- <path
12
- d="M7 10.0288C7.47142 10 8.05259 10 8.8 10H15.2C15.9474 10 16.5286 10 17 10.0288M7 10.0288C6.41168 10.0647 5.99429 10.1455 5.63803 10.327C5.07354 10.6146 4.6146 11.0735 4.32698 11.638C4 12.2798 4 13.1198 4 14.8V16.2C4 17.8802 4 18.7202 4.32698 19.362C4.6146 19.9265 5.07354 20.3854 5.63803 20.673C6.27976 21 7.11984 21 8.8 21H15.2C16.8802 21 17.7202 21 18.362 20.673C18.9265 20.3854 19.3854 19.9265 19.673 19.362C20 18.7202 20 17.8802 20 16.2V14.8C20 13.1198 20 12.2798 19.673 11.638C19.3854 11.0735 18.9265 10.6146 18.362 10.327C18.0057 10.1455 17.5883 10.0647 17 10.0288M7 10.0288V8C7 5.23858 9.23858 3 12 3C14.7614 3 17 5.23858 17 8V10.0288"
13
- ></path>
14
- </svg>
 
1
+ <svg
2
+ width="100%"
3
+ height="100%"
4
+ viewBox="0 0 24 24"
5
+ fill="none"
6
+ stroke="currentColor"
7
+ stroke-width="2"
8
+ style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"
9
+ xmlns="http://www.w3.org/2000/svg"
10
+ >
11
+ <path
12
+ d="M7 10.0288C7.47142 10 8.05259 10 8.8 10H15.2C15.9474 10 16.5286 10 17 10.0288M7 10.0288C6.41168 10.0647 5.99429 10.1455 5.63803 10.327C5.07354 10.6146 4.6146 11.0735 4.32698 11.638C4 12.2798 4 13.1198 4 14.8V16.2C4 17.8802 4 18.7202 4.32698 19.362C4.6146 19.9265 5.07354 20.3854 5.63803 20.673C6.27976 21 7.11984 21 8.8 21H15.2C16.8802 21 17.7202 21 18.362 20.673C18.9265 20.3854 19.3854 19.9265 19.673 19.362C20 18.7202 20 17.8802 20 16.2V14.8C20 13.1198 20 12.2798 19.673 11.638C19.3854 11.0735 18.9265 10.6146 18.362 10.327C18.0057 10.1455 17.5883 10.0647 17 10.0288M7 10.0288V8C7 5.23858 9.23858 3 12 3C14.7614 3 17 5.23858 17 8V10.0288"
13
+ ></path>
14
+ </svg>
src/frontend/shared/icons/Unlock.svelte CHANGED
@@ -1,14 +1,14 @@
1
- <svg
2
- width="100%"
3
- height="100%"
4
- viewBox="0 0 24 24"
5
- fill="none"
6
- stroke="currentColor"
7
- stroke-width="2"
8
- style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"
9
- xmlns="http://www.w3.org/2000/svg"
10
- >
11
- <path
12
- d="M16.584 6C15.8124 4.2341 14.0503 3 12 3C9.23858 3 7 5.23858 7 8V10.0288M7 10.0288C7.47142 10 8.05259 10 8.8 10H15.2C16.8802 10 17.7202 10 18.362 10.327C18.9265 10.6146 19.3854 11.0735 19.673 11.638C20 12.2798 20 13.1198 20 14.8V16.2C20 17.8802 20 18.7202 19.673 19.362C19.3854 19.9265 18.9265 20.3854 18.362 20.673C17.7202 21 16.8802 21 15.2 21H8.8C7.11984 21 6.27976 21 5.63803 20.673C5.07354 20.3854 4.6146 19.9265 4.32698 19.362C4 18.7202 4 17.8802 4 16.2V14.8C4 13.1198 4 12.2798 4.32698 11.638C4.6146 11.0735 5.07354 10.6146 5.63803 10.327C5.99429 10.1455 6.41168 10.0647 7 10.0288Z"
13
- ></path>
14
- </svg>
 
1
+ <svg
2
+ width="100%"
3
+ height="100%"
4
+ viewBox="0 0 24 24"
5
+ fill="none"
6
+ stroke="currentColor"
7
+ stroke-width="2"
8
+ style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"
9
+ xmlns="http://www.w3.org/2000/svg"
10
+ >
11
+ <path
12
+ d="M16.584 6C15.8124 4.2341 14.0503 3 12 3C9.23858 3 7 5.23858 7 8V10.0288M7 10.0288C7.47142 10 8.05259 10 8.8 10H15.2C16.8802 10 17.7202 10 18.362 10.327C18.9265 10.6146 19.3854 11.0735 19.673 11.638C20 12.2798 20 13.1198 20 14.8V16.2C20 17.8802 20 18.7202 19.673 19.362C19.3854 19.9265 18.9265 20.3854 18.362 20.673C17.7202 21 16.8802 21 15.2 21H8.8C7.11984 21 6.27976 21 5.63803 20.673C5.07354 20.3854 4.6146 19.9265 4.32698 19.362C4 18.7202 4 17.8802 4 16.2V14.8C4 13.1198 4 12.2798 4.32698 11.638C4.6146 11.0735 5.07354 10.6146 5.63803 10.327C5.99429 10.1455 6.41168 10.0647 7 10.0288Z"
13
+ ></path>
14
+ </svg>
src/frontend/shared/icons/index.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { default as Add } from "./Add.svelte";
2
- export { default as BoundingBox } from "./BoundingBox.svelte";
3
- export { default as Hand } from "./Hand.svelte";
4
- export { default as Trash } from "./Trash.svelte";
5
- export { default as Label } from "./Label.svelte";
6
- export { default as Lock } from "./Lock.svelte";
7
  export { default as Unlock } from "./Unlock.svelte";
 
1
+ export { default as Add } from "./Add.svelte";
2
+ export { default as BoundingBox } from "./BoundingBox.svelte";
3
+ export { default as Hand } from "./Hand.svelte";
4
+ export { default as Trash } from "./Trash.svelte";
5
+ export { default as Label } from "./Label.svelte";
6
+ export { default as Lock } from "./Lock.svelte";
7
  export { default as Unlock } from "./Unlock.svelte";
src/frontend/shared/index.ts CHANGED
@@ -1 +1 @@
1
- export { default as Image } from "./Image.svelte";
 
1
+ export { default as Image } from "./Image.svelte";
src/frontend/shared/patched_dropdown/CHANGELOG.md CHANGED
@@ -1,246 +1,246 @@
1
- # @gradio/dropdown
2
-
3
- ## 0.6.3
4
-
5
- ### Fixes
6
-
7
- - [#7567](https://github.com/gradio-app/gradio/pull/7567) [`e340894`](https://github.com/gradio-app/gradio/commit/e340894b1cf2f44dd45e597fd8d9e547f408fbb3) - Quick fix: custom dropdown value. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)!
8
-
9
- ## 0.6.2
10
-
11
- ### Patch Changes
12
-
13
- - Updated dependencies [[`98a2719`](https://github.com/gradio-app/gradio/commit/98a2719bfb9c64338caf9009891b6c6b0b33ea89)]:
14
- - @gradio/statustracker@0.4.8
15
-
16
- ## 0.6.1
17
-
18
- ### Features
19
-
20
- - [#7425](https://github.com/gradio-app/gradio/pull/7425) [`3e4e680`](https://github.com/gradio-app/gradio/commit/3e4e680a52ba5a73c108ef1b328dacd7b6e4b566) - Fixes to the `.key_up()` method to make it usable for a dynamic dropdown autocomplete. Thanks [@abidlabs](https://github.com/abidlabs)!
21
-
22
- ### Fixes
23
-
24
- - [#7431](https://github.com/gradio-app/gradio/pull/7431) [`6b8a7e5`](https://github.com/gradio-app/gradio/commit/6b8a7e5d36887cdfcfbfec1536a915128df0d6b2) - Ensure `gr.Dropdown` can have an empty initial value. Thanks [@hannahblair](https://github.com/hannahblair)!
25
-
26
- ## 0.6.0
27
-
28
- ### Fixes
29
-
30
- - [#7404](https://github.com/gradio-app/gradio/pull/7404) [`065c5b1`](https://github.com/gradio-app/gradio/commit/065c5b163c4badb9d9cbd06d627fb4ba086003e7) - Add `.key_up` event listener to `gr.Dropdown()`. Thanks [@abidlabs](https://github.com/abidlabs)!
31
- - [#7401](https://github.com/gradio-app/gradio/pull/7401) [`dff4109`](https://github.com/gradio-app/gradio/commit/dff410955e41145848376784c03fe28ba1c4fd85) - Retain dropdown value if choices have been changed. Thanks [@abidlabs](https://github.com/abidlabs)!
32
-
33
- ## 0.5.2
34
-
35
- ### Fixes
36
-
37
- - [#7192](https://github.com/gradio-app/gradio/pull/7192) [`8dd6f4b`](https://github.com/gradio-app/gradio/commit/8dd6f4bc1901792f05cd59e86df7b1dbab692739) - Handle the case where examples is `null` for all components. Thanks [@abidlabs](https://github.com/abidlabs)!
38
-
39
- ## 0.5.1
40
-
41
- ### Fixes
42
-
43
- - [#7081](https://github.com/gradio-app/gradio/pull/7081) [`44c53d9`](https://github.com/gradio-app/gradio/commit/44c53d9bde7cab605b7dbd16331683d13cae029e) - Fix dropdown refocusing due to `<label />` element. Thanks [@hannahblair](https://github.com/hannahblair)!
44
-
45
- ## 0.5.0
46
-
47
- ### Fixes
48
-
49
- - [#6933](https://github.com/gradio-app/gradio/pull/6933) [`9cefd2e`](https://github.com/gradio-app/gradio/commit/9cefd2e90a1d0cc4d3e4e953fc5b9b1a7afb68dd) - Refactor examples so they accept data in the same format as is returned by function, rename `.as_example()` to `.process_example()`. Thanks [@abidlabs](https://github.com/abidlabs)!
50
-
51
- ## 0.4.3
52
-
53
- ### Patch Changes
54
-
55
- - Updated dependencies [[`828fb9e`](https://github.com/gradio-app/gradio/commit/828fb9e6ce15b6ea08318675a2361117596a1b5d), [`73268ee`](https://github.com/gradio-app/gradio/commit/73268ee2e39f23ebdd1e927cb49b8d79c4b9a144)]:
56
- - @gradio/statustracker@0.4.3
57
- - @gradio/atoms@0.4.1
58
-
59
- ## 0.4.2
60
-
61
- ### Features
62
-
63
- - [#6399](https://github.com/gradio-app/gradio/pull/6399) [`053bec9`](https://github.com/gradio-app/gradio/commit/053bec98be1127e083414024e02cf0bebb0b5142) - Improve CSS token documentation in Storybook. Thanks [@hannahblair](https://github.com/hannahblair)!
64
-
65
- ### Fixes
66
-
67
- - [#6694](https://github.com/gradio-app/gradio/pull/6694) [`dfc61ec`](https://github.com/gradio-app/gradio/commit/dfc61ec4d09da72ddd6e7ab726820529621dbd38) - Fix dropdown blur bug when values are provided as tuples. Thanks [@abidlabs](https://github.com/abidlabs)!
68
-
69
- ## 0.4.1
70
-
71
- ### Patch Changes
72
-
73
- - Updated dependencies [[`206af31`](https://github.com/gradio-app/gradio/commit/206af31d7c1a31013364a44e9b40cf8df304ba50)]:
74
- - @gradio/icons@0.3.1
75
- - @gradio/atoms@0.3.1
76
- - @gradio/statustracker@0.4.1
77
-
78
- ## 0.4.0
79
-
80
- ### Features
81
-
82
- - [#6517](https://github.com/gradio-app/gradio/pull/6517) [`901f3eebd`](https://github.com/gradio-app/gradio/commit/901f3eebda0a67fa8f3050d80f7f7b5800c7f566) - Allow reselecting the original option in `gr.Dropdown` after value has changed programmatically. Thanks [@abidlabs](https://github.com/abidlabs)!
83
-
84
- ## 0.3.3
85
-
86
- ### Patch Changes
87
-
88
- - Updated dependencies [[`9caddc17b`](https://github.com/gradio-app/gradio/commit/9caddc17b1dea8da1af8ba724c6a5eab04ce0ed8)]:
89
- - @gradio/atoms@0.3.0
90
- - @gradio/icons@0.3.0
91
- - @gradio/statustracker@0.4.0
92
-
93
- ## 0.3.2
94
-
95
- ### Fixes
96
-
97
- - [#6425](https://github.com/gradio-app/gradio/pull/6425) [`b3ba17dd1`](https://github.com/gradio-app/gradio/commit/b3ba17dd1167d254756d93f1fb01e8be071819b6) - Update the selected indices in `Dropdown` when value changes programmatically. Thanks [@abidlabs](https://github.com/abidlabs)!
98
-
99
- ## 0.3.1
100
-
101
- ### Patch Changes
102
-
103
- - Updated dependencies [[`3cdeabc68`](https://github.com/gradio-app/gradio/commit/3cdeabc6843000310e1a9e1d17190ecbf3bbc780), [`fad92c29d`](https://github.com/gradio-app/gradio/commit/fad92c29dc1f5cd84341aae417c495b33e01245f)]:
104
- - @gradio/atoms@0.2.1
105
- - @gradio/statustracker@0.3.1
106
-
107
- ## 0.3.0
108
-
109
- ### Features
110
-
111
- - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Publish all components to npm. Thanks [@pngwn](https://github.com/pngwn)!
112
- - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Custom components. Thanks [@pngwn](https://github.com/pngwn)!
113
-
114
- ## 0.3.0-beta.8
115
-
116
- ### Features
117
-
118
- - [#6136](https://github.com/gradio-app/gradio/pull/6136) [`667802a6c`](https://github.com/gradio-app/gradio/commit/667802a6cdbfb2ce454a3be5a78e0990b194548a) - JS Component Documentation. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
119
- - [#6149](https://github.com/gradio-app/gradio/pull/6149) [`90318b1dd`](https://github.com/gradio-app/gradio/commit/90318b1dd118ae08a695a50e7c556226234ab6dc) - swap `mode` on the frontned to `interactive` to match the backend. Thanks [@pngwn](https://github.com/pngwn)!
120
-
121
- ### Fixes
122
-
123
- - [#6148](https://github.com/gradio-app/gradio/pull/6148) [`0000a1916`](https://github.com/gradio-app/gradio/commit/0000a191688c5480c977c80acdd0c9023865d57e) - fix dropdown arrow size. Thanks [@pngwn](https://github.com/pngwn)!
124
-
125
- ## 0.3.0-beta.7
126
-
127
- ### Features
128
-
129
- - [#6016](https://github.com/gradio-app/gradio/pull/6016) [`83e947676`](https://github.com/gradio-app/gradio/commit/83e947676d327ca2ab6ae2a2d710c78961c771a0) - Format js in v4 branch. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
130
-
131
- ### Fixes
132
-
133
- - [#6065](https://github.com/gradio-app/gradio/pull/6065) [`7d07001e8`](https://github.com/gradio-app/gradio/commit/7d07001e8e7ca9cbd2251632667b3a043de49f49) - fix storybook. Thanks [@pngwn](https://github.com/pngwn)!
134
-
135
- ## 0.3.0-beta.6
136
-
137
- ### Features
138
-
139
- - [#5960](https://github.com/gradio-app/gradio/pull/5960) [`319c30f3f`](https://github.com/gradio-app/gradio/commit/319c30f3fccf23bfe1da6c9b132a6a99d59652f7) - rererefactor frontend files. Thanks [@pngwn](https://github.com/pngwn)!
140
- - [#5938](https://github.com/gradio-app/gradio/pull/5938) [`13ed8a485`](https://github.com/gradio-app/gradio/commit/13ed8a485d5e31d7d75af87fe8654b661edcca93) - V4: Use beta release versions for '@gradio' packages. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
141
-
142
- ## 0.3.3
143
-
144
- ### Fixes
145
-
146
- - [#5839](https://github.com/gradio-app/gradio/pull/5839) [`b83064da0`](https://github.com/gradio-app/gradio/commit/b83064da0005ca055fc15ee478cf064bf91702a4) - Fix error when scrolling dropdown with scrollbar. Thanks [@Kit-p](https://github.com/Kit-p)!
147
-
148
- ## 0.3.2
149
-
150
- ### Patch Changes
151
-
152
- - Updated dependencies []:
153
- - @gradio/utils@0.1.2
154
- - @gradio/atoms@0.1.4
155
- - @gradio/statustracker@0.2.2
156
-
157
- ## 0.3.1
158
-
159
- ### Patch Changes
160
-
161
- - Updated dependencies [[`8f0fed857`](https://github.com/gradio-app/gradio/commit/8f0fed857d156830626eb48b469d54d211a582d2)]:
162
- - @gradio/icons@0.2.0
163
- - @gradio/atoms@0.1.3
164
- - @gradio/statustracker@0.2.1
165
-
166
- ## 0.3.0
167
-
168
- ### Features
169
-
170
- - [#5554](https://github.com/gradio-app/gradio/pull/5554) [`75ddeb390`](https://github.com/gradio-app/gradio/commit/75ddeb390d665d4484667390a97442081b49a423) - Accessibility Improvements. Thanks [@hannahblair](https://github.com/hannahblair)!
171
-
172
- ## 0.2.2
173
-
174
- ### Fixes
175
-
176
- - [#5544](https://github.com/gradio-app/gradio/pull/5544) [`a0cc9ac9`](https://github.com/gradio-app/gradio/commit/a0cc9ac931554e06dcb091158c9b9ac0cc580b6c) - Fixes dropdown breaking if a user types in invalid value and presses enter. Thanks [@abidlabs](https://github.com/abidlabs)!
177
-
178
- ## 0.2.1
179
-
180
- ### Fixes
181
-
182
- - [#5525](https://github.com/gradio-app/gradio/pull/5525) [`21f1db40`](https://github.com/gradio-app/gradio/commit/21f1db40de6d1717eba97a550e11422a457ba7e9) - Ensure input value saves on dropdown blur. Thanks [@hannahblair](https://github.com/hannahblair)!
183
-
184
- ## 0.2.0
185
-
186
- ### Features
187
-
188
- - [#5384](https://github.com/gradio-app/gradio/pull/5384) [`ddc02268`](https://github.com/gradio-app/gradio/commit/ddc02268f731bd2ed04b7a5854accf3383f9a0da) - Allows the `gr.Dropdown` to have separate names and values, as well as enables `allow_custom_value` for multiselect dropdown. Thanks [@abidlabs](https://github.com/abidlabs)!
189
-
190
- ### Fixes
191
-
192
- - [#5508](https://github.com/gradio-app/gradio/pull/5508) [`05715f55`](https://github.com/gradio-app/gradio/commit/05715f5599ae3e928d3183c7b0a7f5291f843a96) - Adds a `filterable` parameter to `gr.Dropdown` that controls whether user can type to filter choices. Thanks [@abidlabs](https://github.com/abidlabs)!
193
-
194
- ## 0.1.3
195
-
196
- ### Patch Changes
197
-
198
- - Updated dependencies [[`afac0006`](https://github.com/gradio-app/gradio/commit/afac0006337ce2840cf497cd65691f2f60ee5912)]:
199
- - @gradio/statustracker@0.2.0
200
- - @gradio/utils@0.1.1
201
- - @gradio/atoms@0.1.2
202
-
203
- ## 0.1.2
204
-
205
- ### Fixes
206
-
207
- - [#5360](https://github.com/gradio-app/gradio/pull/5360) [`64666525`](https://github.com/gradio-app/gradio/commit/6466652583e3c620df995fb865ef3511a34cb676) - Cancel Dropdown Filter. Thanks [@deckar01](https://github.com/deckar01)!
208
-
209
- ## 0.1.1
210
-
211
- ### Fixes
212
-
213
- - [#5323](https://github.com/gradio-app/gradio/pull/5323) [`e32b0928`](https://github.com/gradio-app/gradio/commit/e32b0928d2d00342ca917ebb10c379ffc2ec200d) - ensure dropdown stays open when identical data is passed in. Thanks [@pngwn](https://github.com/pngwn)!
214
-
215
- ## 0.1.0
216
-
217
- ### Highlights
218
-
219
- #### Improve startup performance and markdown support ([#5279](https://github.com/gradio-app/gradio/pull/5279) [`fe057300`](https://github.com/gradio-app/gradio/commit/fe057300f0672c62dab9d9b4501054ac5d45a4ec))
220
-
221
- ##### Improved markdown support
222
-
223
- We now have better support for markdown in `gr.Markdown` and `gr.Dataframe`. Including syntax highlighting and Github Flavoured Markdown. We also have more consistent markdown behaviour and styling.
224
-
225
- ##### Various performance improvements
226
-
227
- These improvements will be particularly beneficial to large applications.
228
-
229
- - Rather than attaching events manually, they are now delegated, leading to a significant performance improvement and addressing a performance regression introduced in a recent version of Gradio. App startup for large applications is now around twice as fast.
230
- - Optimised the mounting of individual components, leading to a modest performance improvement during startup (~30%).
231
- - Corrected an issue that was causing markdown to re-render infinitely.
232
- - Ensured that the `gr.3DModel` does re-render prematurely.
233
-
234
- Thanks [@pngwn](https://github.com/pngwn)!
235
-
236
- ### Features
237
-
238
- - [#5215](https://github.com/gradio-app/gradio/pull/5215) [`fbdad78a`](https://github.com/gradio-app/gradio/commit/fbdad78af4c47454cbb570f88cc14bf4479bbceb) - Lazy load interactive or static variants of a component individually, rather than loading both variants regardless. This change will improve performance for many applications. Thanks [@pngwn](https://github.com/pngwn)!
239
- - [#5216](https://github.com/gradio-app/gradio/pull/5216) [`4b58ea6d`](https://github.com/gradio-app/gradio/commit/4b58ea6d98e7a43b3f30d8a4cb6f379bc2eca6a8) - Update i18n tokens and locale files. Thanks [@hannahblair](https://github.com/hannahblair)!
240
-
241
- ## 0.0.2
242
-
243
- ### Fixes
244
-
245
- - [#5062](https://github.com/gradio-app/gradio/pull/5062) [`7d897165`](https://github.com/gradio-app/gradio/commit/7d89716519d0751072792c9bbda668ffeb597296) - `gr.Dropdown` now has correct behavior in static mode as well as when an option is selected. Thanks [@abidlabs](https://github.com/abidlabs)!
246
  - [#5039](https://github.com/gradio-app/gradio/pull/5039) [`620e4645`](https://github.com/gradio-app/gradio/commit/620e46452729d6d4877b3fab84a65daf2f2b7bc6) - `gr.Dropdown()` now supports values with arbitrary characters and doesn't clear value when re-focused. Thanks [@abidlabs](https://github.com/abidlabs)!
 
1
+ # @gradio/dropdown
2
+
3
+ ## 0.6.3
4
+
5
+ ### Fixes
6
+
7
+ - [#7567](https://github.com/gradio-app/gradio/pull/7567) [`e340894`](https://github.com/gradio-app/gradio/commit/e340894b1cf2f44dd45e597fd8d9e547f408fbb3) - Quick fix: custom dropdown value. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)!
8
+
9
+ ## 0.6.2
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [[`98a2719`](https://github.com/gradio-app/gradio/commit/98a2719bfb9c64338caf9009891b6c6b0b33ea89)]:
14
+ - @gradio/statustracker@0.4.8
15
+
16
+ ## 0.6.1
17
+
18
+ ### Features
19
+
20
+ - [#7425](https://github.com/gradio-app/gradio/pull/7425) [`3e4e680`](https://github.com/gradio-app/gradio/commit/3e4e680a52ba5a73c108ef1b328dacd7b6e4b566) - Fixes to the `.key_up()` method to make it usable for a dynamic dropdown autocomplete. Thanks [@abidlabs](https://github.com/abidlabs)!
21
+
22
+ ### Fixes
23
+
24
+ - [#7431](https://github.com/gradio-app/gradio/pull/7431) [`6b8a7e5`](https://github.com/gradio-app/gradio/commit/6b8a7e5d36887cdfcfbfec1536a915128df0d6b2) - Ensure `gr.Dropdown` can have an empty initial value. Thanks [@hannahblair](https://github.com/hannahblair)!
25
+
26
+ ## 0.6.0
27
+
28
+ ### Fixes
29
+
30
+ - [#7404](https://github.com/gradio-app/gradio/pull/7404) [`065c5b1`](https://github.com/gradio-app/gradio/commit/065c5b163c4badb9d9cbd06d627fb4ba086003e7) - Add `.key_up` event listener to `gr.Dropdown()`. Thanks [@abidlabs](https://github.com/abidlabs)!
31
+ - [#7401](https://github.com/gradio-app/gradio/pull/7401) [`dff4109`](https://github.com/gradio-app/gradio/commit/dff410955e41145848376784c03fe28ba1c4fd85) - Retain dropdown value if choices have been changed. Thanks [@abidlabs](https://github.com/abidlabs)!
32
+
33
+ ## 0.5.2
34
+
35
+ ### Fixes
36
+
37
+ - [#7192](https://github.com/gradio-app/gradio/pull/7192) [`8dd6f4b`](https://github.com/gradio-app/gradio/commit/8dd6f4bc1901792f05cd59e86df7b1dbab692739) - Handle the case where examples is `null` for all components. Thanks [@abidlabs](https://github.com/abidlabs)!
38
+
39
+ ## 0.5.1
40
+
41
+ ### Fixes
42
+
43
+ - [#7081](https://github.com/gradio-app/gradio/pull/7081) [`44c53d9`](https://github.com/gradio-app/gradio/commit/44c53d9bde7cab605b7dbd16331683d13cae029e) - Fix dropdown refocusing due to `<label />` element. Thanks [@hannahblair](https://github.com/hannahblair)!
44
+
45
+ ## 0.5.0
46
+
47
+ ### Fixes
48
+
49
+ - [#6933](https://github.com/gradio-app/gradio/pull/6933) [`9cefd2e`](https://github.com/gradio-app/gradio/commit/9cefd2e90a1d0cc4d3e4e953fc5b9b1a7afb68dd) - Refactor examples so they accept data in the same format as is returned by function, rename `.as_example()` to `.process_example()`. Thanks [@abidlabs](https://github.com/abidlabs)!
50
+
51
+ ## 0.4.3
52
+
53
+ ### Patch Changes
54
+
55
+ - Updated dependencies [[`828fb9e`](https://github.com/gradio-app/gradio/commit/828fb9e6ce15b6ea08318675a2361117596a1b5d), [`73268ee`](https://github.com/gradio-app/gradio/commit/73268ee2e39f23ebdd1e927cb49b8d79c4b9a144)]:
56
+ - @gradio/statustracker@0.4.3
57
+ - @gradio/atoms@0.4.1
58
+
59
+ ## 0.4.2
60
+
61
+ ### Features
62
+
63
+ - [#6399](https://github.com/gradio-app/gradio/pull/6399) [`053bec9`](https://github.com/gradio-app/gradio/commit/053bec98be1127e083414024e02cf0bebb0b5142) - Improve CSS token documentation in Storybook. Thanks [@hannahblair](https://github.com/hannahblair)!
64
+
65
+ ### Fixes
66
+
67
+ - [#6694](https://github.com/gradio-app/gradio/pull/6694) [`dfc61ec`](https://github.com/gradio-app/gradio/commit/dfc61ec4d09da72ddd6e7ab726820529621dbd38) - Fix dropdown blur bug when values are provided as tuples. Thanks [@abidlabs](https://github.com/abidlabs)!
68
+
69
+ ## 0.4.1
70
+
71
+ ### Patch Changes
72
+
73
+ - Updated dependencies [[`206af31`](https://github.com/gradio-app/gradio/commit/206af31d7c1a31013364a44e9b40cf8df304ba50)]:
74
+ - @gradio/icons@0.3.1
75
+ - @gradio/atoms@0.3.1
76
+ - @gradio/statustracker@0.4.1
77
+
78
+ ## 0.4.0
79
+
80
+ ### Features
81
+
82
+ - [#6517](https://github.com/gradio-app/gradio/pull/6517) [`901f3eebd`](https://github.com/gradio-app/gradio/commit/901f3eebda0a67fa8f3050d80f7f7b5800c7f566) - Allow reselecting the original option in `gr.Dropdown` after value has changed programmatically. Thanks [@abidlabs](https://github.com/abidlabs)!
83
+
84
+ ## 0.3.3
85
+
86
+ ### Patch Changes
87
+
88
+ - Updated dependencies [[`9caddc17b`](https://github.com/gradio-app/gradio/commit/9caddc17b1dea8da1af8ba724c6a5eab04ce0ed8)]:
89
+ - @gradio/atoms@0.3.0
90
+ - @gradio/icons@0.3.0
91
+ - @gradio/statustracker@0.4.0
92
+
93
+ ## 0.3.2
94
+
95
+ ### Fixes
96
+
97
+ - [#6425](https://github.com/gradio-app/gradio/pull/6425) [`b3ba17dd1`](https://github.com/gradio-app/gradio/commit/b3ba17dd1167d254756d93f1fb01e8be071819b6) - Update the selected indices in `Dropdown` when value changes programmatically. Thanks [@abidlabs](https://github.com/abidlabs)!
98
+
99
+ ## 0.3.1
100
+
101
+ ### Patch Changes
102
+
103
+ - Updated dependencies [[`3cdeabc68`](https://github.com/gradio-app/gradio/commit/3cdeabc6843000310e1a9e1d17190ecbf3bbc780), [`fad92c29d`](https://github.com/gradio-app/gradio/commit/fad92c29dc1f5cd84341aae417c495b33e01245f)]:
104
+ - @gradio/atoms@0.2.1
105
+ - @gradio/statustracker@0.3.1
106
+
107
+ ## 0.3.0
108
+
109
+ ### Features
110
+
111
+ - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Publish all components to npm. Thanks [@pngwn](https://github.com/pngwn)!
112
+ - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Custom components. Thanks [@pngwn](https://github.com/pngwn)!
113
+
114
+ ## 0.3.0-beta.8
115
+
116
+ ### Features
117
+
118
+ - [#6136](https://github.com/gradio-app/gradio/pull/6136) [`667802a6c`](https://github.com/gradio-app/gradio/commit/667802a6cdbfb2ce454a3be5a78e0990b194548a) - JS Component Documentation. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
119
+ - [#6149](https://github.com/gradio-app/gradio/pull/6149) [`90318b1dd`](https://github.com/gradio-app/gradio/commit/90318b1dd118ae08a695a50e7c556226234ab6dc) - swap `mode` on the frontned to `interactive` to match the backend. Thanks [@pngwn](https://github.com/pngwn)!
120
+
121
+ ### Fixes
122
+
123
+ - [#6148](https://github.com/gradio-app/gradio/pull/6148) [`0000a1916`](https://github.com/gradio-app/gradio/commit/0000a191688c5480c977c80acdd0c9023865d57e) - fix dropdown arrow size. Thanks [@pngwn](https://github.com/pngwn)!
124
+
125
+ ## 0.3.0-beta.7
126
+
127
+ ### Features
128
+
129
+ - [#6016](https://github.com/gradio-app/gradio/pull/6016) [`83e947676`](https://github.com/gradio-app/gradio/commit/83e947676d327ca2ab6ae2a2d710c78961c771a0) - Format js in v4 branch. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
130
+
131
+ ### Fixes
132
+
133
+ - [#6065](https://github.com/gradio-app/gradio/pull/6065) [`7d07001e8`](https://github.com/gradio-app/gradio/commit/7d07001e8e7ca9cbd2251632667b3a043de49f49) - fix storybook. Thanks [@pngwn](https://github.com/pngwn)!
134
+
135
+ ## 0.3.0-beta.6
136
+
137
+ ### Features
138
+
139
+ - [#5960](https://github.com/gradio-app/gradio/pull/5960) [`319c30f3f`](https://github.com/gradio-app/gradio/commit/319c30f3fccf23bfe1da6c9b132a6a99d59652f7) - rererefactor frontend files. Thanks [@pngwn](https://github.com/pngwn)!
140
+ - [#5938](https://github.com/gradio-app/gradio/pull/5938) [`13ed8a485`](https://github.com/gradio-app/gradio/commit/13ed8a485d5e31d7d75af87fe8654b661edcca93) - V4: Use beta release versions for '@gradio' packages. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
141
+
142
+ ## 0.3.3
143
+
144
+ ### Fixes
145
+
146
+ - [#5839](https://github.com/gradio-app/gradio/pull/5839) [`b83064da0`](https://github.com/gradio-app/gradio/commit/b83064da0005ca055fc15ee478cf064bf91702a4) - Fix error when scrolling dropdown with scrollbar. Thanks [@Kit-p](https://github.com/Kit-p)!
147
+
148
+ ## 0.3.2
149
+
150
+ ### Patch Changes
151
+
152
+ - Updated dependencies []:
153
+ - @gradio/utils@0.1.2
154
+ - @gradio/atoms@0.1.4
155
+ - @gradio/statustracker@0.2.2
156
+
157
+ ## 0.3.1
158
+
159
+ ### Patch Changes
160
+
161
+ - Updated dependencies [[`8f0fed857`](https://github.com/gradio-app/gradio/commit/8f0fed857d156830626eb48b469d54d211a582d2)]:
162
+ - @gradio/icons@0.2.0
163
+ - @gradio/atoms@0.1.3
164
+ - @gradio/statustracker@0.2.1
165
+
166
+ ## 0.3.0
167
+
168
+ ### Features
169
+
170
+ - [#5554](https://github.com/gradio-app/gradio/pull/5554) [`75ddeb390`](https://github.com/gradio-app/gradio/commit/75ddeb390d665d4484667390a97442081b49a423) - Accessibility Improvements. Thanks [@hannahblair](https://github.com/hannahblair)!
171
+
172
+ ## 0.2.2
173
+
174
+ ### Fixes
175
+
176
+ - [#5544](https://github.com/gradio-app/gradio/pull/5544) [`a0cc9ac9`](https://github.com/gradio-app/gradio/commit/a0cc9ac931554e06dcb091158c9b9ac0cc580b6c) - Fixes dropdown breaking if a user types in invalid value and presses enter. Thanks [@abidlabs](https://github.com/abidlabs)!
177
+
178
+ ## 0.2.1
179
+
180
+ ### Fixes
181
+
182
+ - [#5525](https://github.com/gradio-app/gradio/pull/5525) [`21f1db40`](https://github.com/gradio-app/gradio/commit/21f1db40de6d1717eba97a550e11422a457ba7e9) - Ensure input value saves on dropdown blur. Thanks [@hannahblair](https://github.com/hannahblair)!
183
+
184
+ ## 0.2.0
185
+
186
+ ### Features
187
+
188
+ - [#5384](https://github.com/gradio-app/gradio/pull/5384) [`ddc02268`](https://github.com/gradio-app/gradio/commit/ddc02268f731bd2ed04b7a5854accf3383f9a0da) - Allows the `gr.Dropdown` to have separate names and values, as well as enables `allow_custom_value` for multiselect dropdown. Thanks [@abidlabs](https://github.com/abidlabs)!
189
+
190
+ ### Fixes
191
+
192
+ - [#5508](https://github.com/gradio-app/gradio/pull/5508) [`05715f55`](https://github.com/gradio-app/gradio/commit/05715f5599ae3e928d3183c7b0a7f5291f843a96) - Adds a `filterable` parameter to `gr.Dropdown` that controls whether user can type to filter choices. Thanks [@abidlabs](https://github.com/abidlabs)!
193
+
194
+ ## 0.1.3
195
+
196
+ ### Patch Changes
197
+
198
+ - Updated dependencies [[`afac0006`](https://github.com/gradio-app/gradio/commit/afac0006337ce2840cf497cd65691f2f60ee5912)]:
199
+ - @gradio/statustracker@0.2.0
200
+ - @gradio/utils@0.1.1
201
+ - @gradio/atoms@0.1.2
202
+
203
+ ## 0.1.2
204
+
205
+ ### Fixes
206
+
207
+ - [#5360](https://github.com/gradio-app/gradio/pull/5360) [`64666525`](https://github.com/gradio-app/gradio/commit/6466652583e3c620df995fb865ef3511a34cb676) - Cancel Dropdown Filter. Thanks [@deckar01](https://github.com/deckar01)!
208
+
209
+ ## 0.1.1
210
+
211
+ ### Fixes
212
+
213
+ - [#5323](https://github.com/gradio-app/gradio/pull/5323) [`e32b0928`](https://github.com/gradio-app/gradio/commit/e32b0928d2d00342ca917ebb10c379ffc2ec200d) - ensure dropdown stays open when identical data is passed in. Thanks [@pngwn](https://github.com/pngwn)!
214
+
215
+ ## 0.1.0
216
+
217
+ ### Highlights
218
+
219
+ #### Improve startup performance and markdown support ([#5279](https://github.com/gradio-app/gradio/pull/5279) [`fe057300`](https://github.com/gradio-app/gradio/commit/fe057300f0672c62dab9d9b4501054ac5d45a4ec))
220
+
221
+ ##### Improved markdown support
222
+
223
+ We now have better support for markdown in `gr.Markdown` and `gr.Dataframe`. Including syntax highlighting and Github Flavoured Markdown. We also have more consistent markdown behaviour and styling.
224
+
225
+ ##### Various performance improvements
226
+
227
+ These improvements will be particularly beneficial to large applications.
228
+
229
+ - Rather than attaching events manually, they are now delegated, leading to a significant performance improvement and addressing a performance regression introduced in a recent version of Gradio. App startup for large applications is now around twice as fast.
230
+ - Optimised the mounting of individual components, leading to a modest performance improvement during startup (~30%).
231
+ - Corrected an issue that was causing markdown to re-render infinitely.
232
+ - Ensured that the `gr.3DModel` does re-render prematurely.
233
+
234
+ Thanks [@pngwn](https://github.com/pngwn)!
235
+
236
+ ### Features
237
+
238
+ - [#5215](https://github.com/gradio-app/gradio/pull/5215) [`fbdad78a`](https://github.com/gradio-app/gradio/commit/fbdad78af4c47454cbb570f88cc14bf4479bbceb) - Lazy load interactive or static variants of a component individually, rather than loading both variants regardless. This change will improve performance for many applications. Thanks [@pngwn](https://github.com/pngwn)!
239
+ - [#5216](https://github.com/gradio-app/gradio/pull/5216) [`4b58ea6d`](https://github.com/gradio-app/gradio/commit/4b58ea6d98e7a43b3f30d8a4cb6f379bc2eca6a8) - Update i18n tokens and locale files. Thanks [@hannahblair](https://github.com/hannahblair)!
240
+
241
+ ## 0.0.2
242
+
243
+ ### Fixes
244
+
245
+ - [#5062](https://github.com/gradio-app/gradio/pull/5062) [`7d897165`](https://github.com/gradio-app/gradio/commit/7d89716519d0751072792c9bbda668ffeb597296) - `gr.Dropdown` now has correct behavior in static mode as well as when an option is selected. Thanks [@abidlabs](https://github.com/abidlabs)!
246
  - [#5039](https://github.com/gradio-app/gradio/pull/5039) [`620e4645`](https://github.com/gradio-app/gradio/commit/620e46452729d6d4877b3fab84a65daf2f2b7bc6) - `gr.Dropdown()` now supports values with arbitrary characters and doesn't clear value when re-focused. Thanks [@abidlabs](https://github.com/abidlabs)!
src/frontend/shared/patched_dropdown/Dropdown.stories.svelte CHANGED
@@ -1,60 +1,60 @@
1
- <script lang="ts">
2
- import { Meta, Template, Story } from "@storybook/addon-svelte-csf";
3
- import Dropdown from "./shared/Dropdown.svelte";
4
- </script>
5
-
6
- <Meta
7
- title="Components/Dropdown"
8
- component={Dropdown}
9
- argTypes={{
10
- multiselect: {
11
- control: [true, false],
12
- description: "Whether to autoplay the video on load",
13
- name: "multiselect",
14
- value: false
15
- }
16
- }}
17
- />
18
-
19
- <Template let:args>
20
- <Dropdown {...args} />
21
- </Template>
22
-
23
- <Story
24
- name="Single-select"
25
- args={{
26
- value: "swim",
27
- choices: [
28
- ["run", "run"],
29
- ["swim", "swim"],
30
- ["jump", "jump"]
31
- ],
32
- label: "Single-select Dropdown"
33
- }}
34
- />
35
- <Story
36
- name="Single-select Static"
37
- args={{
38
- value: "swim",
39
- choices: [
40
- ["run", "run"],
41
- ["swim", "swim"],
42
- ["jump", "jump"]
43
- ],
44
- disabled: true,
45
- label: "Single-select Dropdown"
46
- }}
47
- />
48
-
49
- <Story
50
- name="Empty initial value"
51
- args={{
52
- interactive: true,
53
- choices: [
54
- ["run", "run"],
55
- ["swim", "swim"],
56
- ["jump", "jump"]
57
- ],
58
- label: "Empty Dropdown"
59
- }}
60
- />
 
1
+ <script lang="ts">
2
+ import { Meta, Template, Story } from "@storybook/addon-svelte-csf";
3
+ import Dropdown from "./shared/Dropdown.svelte";
4
+ </script>
5
+
6
+ <Meta
7
+ title="Components/Dropdown"
8
+ component={Dropdown}
9
+ argTypes={{
10
+ multiselect: {
11
+ control: [true, false],
12
+ description: "Whether to autoplay the video on load",
13
+ name: "multiselect",
14
+ value: false
15
+ }
16
+ }}
17
+ />
18
+
19
+ <Template let:args>
20
+ <Dropdown {...args} />
21
+ </Template>
22
+
23
+ <Story
24
+ name="Single-select"
25
+ args={{
26
+ value: "swim",
27
+ choices: [
28
+ ["run", "run"],
29
+ ["swim", "swim"],
30
+ ["jump", "jump"]
31
+ ],
32
+ label: "Single-select Dropdown"
33
+ }}
34
+ />
35
+ <Story
36
+ name="Single-select Static"
37
+ args={{
38
+ value: "swim",
39
+ choices: [
40
+ ["run", "run"],
41
+ ["swim", "swim"],
42
+ ["jump", "jump"]
43
+ ],
44
+ disabled: true,
45
+ label: "Single-select Dropdown"
46
+ }}
47
+ />
48
+
49
+ <Story
50
+ name="Empty initial value"
51
+ args={{
52
+ interactive: true,
53
+ choices: [
54
+ ["run", "run"],
55
+ ["swim", "swim"],
56
+ ["jump", "jump"]
57
+ ],
58
+ label: "Empty Dropdown"
59
+ }}
60
+ />
src/frontend/shared/patched_dropdown/Example.svelte CHANGED
@@ -1,33 +1,33 @@
1
- <script lang="ts">
2
- export let value: string | string[] | null;
3
- export let type: "gallery" | "table";
4
- export let selected = false;
5
- export let choices: [string, string | number][];
6
-
7
- let value_array = value ? (Array.isArray(value) ? value : [value]) : [];
8
- let names = value_array
9
- .map(
10
- (val) =>
11
- (
12
- choices.find((pair) => pair[1] === val) as
13
- | [string, string | number]
14
- | undefined
15
- )?.[0]
16
- )
17
- .filter((name) => name !== undefined);
18
- let names_string = names.join(", ");
19
- </script>
20
-
21
- <div
22
- class:table={type === "table"}
23
- class:gallery={type === "gallery"}
24
- class:selected
25
- >
26
- {names_string}
27
- </div>
28
-
29
- <style>
30
- .gallery {
31
- padding: var(--size-1) var(--size-2);
32
- }
33
- </style>
 
1
+ <script lang="ts">
2
+ export let value: string | string[] | null;
3
+ export let type: "gallery" | "table";
4
+ export let selected = false;
5
+ export let choices: [string, string | number][];
6
+
7
+ let value_array = value ? (Array.isArray(value) ? value : [value]) : [];
8
+ let names = value_array
9
+ .map(
10
+ (val) =>
11
+ (
12
+ choices.find((pair) => pair[1] === val) as
13
+ | [string, string | number]
14
+ | undefined
15
+ )?.[0]
16
+ )
17
+ .filter((name) => name !== undefined);
18
+ let names_string = names.join(", ");
19
+ </script>
20
+
21
+ <div
22
+ class:table={type === "table"}
23
+ class:gallery={type === "gallery"}
24
+ class:selected
25
+ >
26
+ {names_string}
27
+ </div>
28
+
29
+ <style>
30
+ .gallery {
31
+ padding: var(--size-1) var(--size-2);
32
+ }
33
+ </style>
src/frontend/shared/patched_dropdown/Index.svelte CHANGED
@@ -1,99 +1,99 @@
1
- <script context="module" lang="ts">
2
- export { default as BaseDropdown } from "./shared/Dropdown.svelte";
3
- export { default as BaseMultiselect } from "./shared/Multiselect.svelte";
4
- export { default as BaseExample } from "./Example.svelte";
5
- </script>
6
-
7
- <script lang="ts">
8
- import type { Gradio, KeyUpData, SelectData } from "@gradio/utils";
9
- import Multiselect from "./shared/Multiselect.svelte";
10
- import Dropdown from "./shared/Dropdown.svelte";
11
- import { Block } from "@gradio/atoms";
12
- import { StatusTracker } from "@gradio/statustracker";
13
- import type { LoadingStatus } from "@gradio/statustracker";
14
-
15
- export let label = "Dropdown";
16
- export let info: string | undefined = undefined;
17
- export let elem_id = "";
18
- export let elem_classes: string[] = [];
19
- export let visible = true;
20
- export let value: string | string[] | undefined = undefined;
21
- export let value_is_output = false;
22
- export let multiselect = false;
23
- export let max_choices: number | null = null;
24
- export let choices: [string, string | number][];
25
- export let show_label: boolean;
26
- export let filterable: boolean;
27
- export let container = true;
28
- export let scale: number | null = null;
29
- export let min_width: number | undefined = undefined;
30
- export let loading_status: LoadingStatus;
31
- export let allow_custom_value = false;
32
- export let gradio: Gradio<{
33
- change: never;
34
- input: never;
35
- select: SelectData;
36
- blur: never;
37
- focus: never;
38
- key_up: KeyUpData;
39
- }>;
40
- export let interactive: boolean;
41
- </script>
42
-
43
- <Block
44
- {visible}
45
- {elem_id}
46
- {elem_classes}
47
- padding={container}
48
- allow_overflow={false}
49
- {scale}
50
- {min_width}
51
- >
52
- <StatusTracker
53
- autoscroll={gradio.autoscroll}
54
- i18n={gradio.i18n}
55
- {...loading_status}
56
- />
57
-
58
- {#if multiselect}
59
- <Multiselect
60
- bind:value
61
- bind:value_is_output
62
- {choices}
63
- {max_choices}
64
- {label}
65
- {info}
66
- {show_label}
67
- {allow_custom_value}
68
- {filterable}
69
- {container}
70
- i18n={gradio.i18n}
71
- on:change={() => gradio.dispatch("change")}
72
- on:input={() => gradio.dispatch("input")}
73
- on:select={(e) => gradio.dispatch("select", e.detail)}
74
- on:blur={() => gradio.dispatch("blur")}
75
- on:focus={() => gradio.dispatch("focus")}
76
- on:key_up={() => gradio.dispatch("key_up")}
77
- disabled={!interactive}
78
- />
79
- {:else}
80
- <Dropdown
81
- bind:value
82
- bind:value_is_output
83
- {choices}
84
- {label}
85
- {info}
86
- {show_label}
87
- {filterable}
88
- {allow_custom_value}
89
- {container}
90
- on:change={() => gradio.dispatch("change")}
91
- on:input={() => gradio.dispatch("input")}
92
- on:select={(e) => gradio.dispatch("select", e.detail)}
93
- on:blur={() => gradio.dispatch("blur")}
94
- on:focus={() => gradio.dispatch("focus")}
95
- on:key_up={(e) => gradio.dispatch("key_up", e.detail)}
96
- disabled={!interactive}
97
- />
98
- {/if}
99
- </Block>
 
1
+ <script context="module" lang="ts">
2
+ export { default as BaseDropdown } from "./shared/Dropdown.svelte";
3
+ export { default as BaseMultiselect } from "./shared/Multiselect.svelte";
4
+ export { default as BaseExample } from "./Example.svelte";
5
+ </script>
6
+
7
+ <script lang="ts">
8
+ import type { Gradio, KeyUpData, SelectData } from "@gradio/utils";
9
+ import Multiselect from "./shared/Multiselect.svelte";
10
+ import Dropdown from "./shared/Dropdown.svelte";
11
+ import { Block } from "@gradio/atoms";
12
+ import { StatusTracker } from "@gradio/statustracker";
13
+ import type { LoadingStatus } from "@gradio/statustracker";
14
+
15
+ export let label = "Dropdown";
16
+ export let info: string | undefined = undefined;
17
+ export let elem_id = "";
18
+ export let elem_classes: string[] = [];
19
+ export let visible = true;
20
+ export let value: string | string[] | undefined = undefined;
21
+ export let value_is_output = false;
22
+ export let multiselect = false;
23
+ export let max_choices: number | null = null;
24
+ export let choices: [string, string | number][];
25
+ export let show_label: boolean;
26
+ export let filterable: boolean;
27
+ export let container = true;
28
+ export let scale: number | null = null;
29
+ export let min_width: number | undefined = undefined;
30
+ export let loading_status: LoadingStatus;
31
+ export let allow_custom_value = false;
32
+ export let gradio: Gradio<{
33
+ change: never;
34
+ input: never;
35
+ select: SelectData;
36
+ blur: never;
37
+ focus: never;
38
+ key_up: KeyUpData;
39
+ }>;
40
+ export let interactive: boolean;
41
+ </script>
42
+
43
+ <Block
44
+ {visible}
45
+ {elem_id}
46
+ {elem_classes}
47
+ padding={container}
48
+ allow_overflow={false}
49
+ {scale}
50
+ {min_width}
51
+ >
52
+ <StatusTracker
53
+ autoscroll={gradio.autoscroll}
54
+ i18n={gradio.i18n}
55
+ {...loading_status}
56
+ />
57
+
58
+ {#if multiselect}
59
+ <Multiselect
60
+ bind:value
61
+ bind:value_is_output
62
+ {choices}
63
+ {max_choices}
64
+ {label}
65
+ {info}
66
+ {show_label}
67
+ {allow_custom_value}
68
+ {filterable}
69
+ {container}
70
+ i18n={gradio.i18n}
71
+ on:change={() => gradio.dispatch("change")}
72
+ on:input={() => gradio.dispatch("input")}
73
+ on:select={(e) => gradio.dispatch("select", e.detail)}
74
+ on:blur={() => gradio.dispatch("blur")}
75
+ on:focus={() => gradio.dispatch("focus")}
76
+ on:key_up={() => gradio.dispatch("key_up")}
77
+ disabled={!interactive}
78
+ />
79
+ {:else}
80
+ <Dropdown
81
+ bind:value
82
+ bind:value_is_output
83
+ {choices}
84
+ {label}
85
+ {info}
86
+ {show_label}
87
+ {filterable}
88
+ {allow_custom_value}
89
+ {container}
90
+ on:change={() => gradio.dispatch("change")}
91
+ on:input={() => gradio.dispatch("input")}
92
+ on:select={(e) => gradio.dispatch("select", e.detail)}
93
+ on:blur={() => gradio.dispatch("blur")}
94
+ on:focus={() => gradio.dispatch("focus")}
95
+ on:key_up={(e) => gradio.dispatch("key_up", e.detail)}
96
+ disabled={!interactive}
97
+ />
98
+ {/if}
99
+ </Block>
src/frontend/shared/patched_dropdown/LICENSE CHANGED
@@ -1,201 +1,201 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
src/frontend/shared/patched_dropdown/Multiselect.stories.svelte CHANGED
@@ -1,48 +1,48 @@
1
- <script>
2
- import { Meta, Template, Story } from "@storybook/addon-svelte-csf";
3
- import Multiselect from "./shared/Multiselect.svelte";
4
- import { format } from "svelte-i18n";
5
- import { get } from "svelte/store";
6
- </script>
7
-
8
- <Meta
9
- title="Components/Multiselect"
10
- component={Multiselect}
11
- argTypes={{
12
- multiselect: {
13
- control: [true, false],
14
- name: "multiselect",
15
- value: false
16
- }
17
- }}
18
- />
19
-
20
- <Template let:args>
21
- <Multiselect {...args} i18n={get(format)} />
22
- </Template>
23
-
24
- <Story
25
- name="Multiselect Interactive"
26
- args={{
27
- value: ["swim", "run"],
28
- choices: [
29
- ["run", "run"],
30
- ["swim", "swim"],
31
- ["jump", "jump"]
32
- ],
33
- label: "Multiselect Dropdown"
34
- }}
35
- />
36
- <Story
37
- name="Multiselect Static"
38
- args={{
39
- value: ["swim", "run"],
40
- choices: [
41
- ["run", "run"],
42
- ["swim", "swim"],
43
- ["jump", "jump"]
44
- ],
45
- label: "Multiselect Dropdown",
46
- disabled: true
47
- }}
48
- />
 
1
+ <script>
2
+ import { Meta, Template, Story } from "@storybook/addon-svelte-csf";
3
+ import Multiselect from "./shared/Multiselect.svelte";
4
+ import { format } from "svelte-i18n";
5
+ import { get } from "svelte/store";
6
+ </script>
7
+
8
+ <Meta
9
+ title="Components/Multiselect"
10
+ component={Multiselect}
11
+ argTypes={{
12
+ multiselect: {
13
+ control: [true, false],
14
+ name: "multiselect",
15
+ value: false
16
+ }
17
+ }}
18
+ />
19
+
20
+ <Template let:args>
21
+ <Multiselect {...args} i18n={get(format)} />
22
+ </Template>
23
+
24
+ <Story
25
+ name="Multiselect Interactive"
26
+ args={{
27
+ value: ["swim", "run"],
28
+ choices: [
29
+ ["run", "run"],
30
+ ["swim", "swim"],
31
+ ["jump", "jump"]
32
+ ],
33
+ label: "Multiselect Dropdown"
34
+ }}
35
+ />
36
+ <Story
37
+ name="Multiselect Static"
38
+ args={{
39
+ value: ["swim", "run"],
40
+ choices: [
41
+ ["run", "run"],
42
+ ["swim", "swim"],
43
+ ["jump", "jump"]
44
+ ],
45
+ label: "Multiselect Dropdown",
46
+ disabled: true
47
+ }}
48
+ />
src/frontend/shared/patched_dropdown/README.md CHANGED
@@ -1,44 +1,44 @@
1
- # `@gradio/dropdown`
2
-
3
- ```html
4
- <script>
5
- import {BaseDropdown, BaseMultiselect, BaseExample } from "@gradio/dropdown";
6
- </script>
7
- ```
8
-
9
- BaseDropdown
10
- ```javascript
11
- export let label: string;
12
- export let info: string | undefined = undefined;
13
- export let value: string | number | (string | number)[] | undefined = [];
14
- export let value_is_output = false;
15
- export let choices: [string, string | number][];
16
- export let disabled = false;
17
- export let show_label: boolean;
18
- export let container = true;
19
- export let allow_custom_value = false;
20
- export let filterable = true;
21
- ```
22
-
23
- BaseMultiselect
24
- ```javascript
25
- export let label: string;
26
- export let info: string | undefined = undefined;
27
- export let value: string | number | (string | number)[] | undefined = [];
28
- export let value_is_output = false;
29
- export let max_choices: number | null = null;
30
- export let choices: [string, string | number][];
31
- export let disabled = false;
32
- export let show_label: boolean;
33
- export let container = true;
34
- export let allow_custom_value = false;
35
- export let filterable = true;
36
- export let i18n: I18nFormatter;
37
- ```
38
-
39
- BaseExample
40
- ```javascript
41
- export let value: string;
42
- export let type: "gallery" | "table";
43
- export let selected = false;
44
  ```
 
1
+ # `@gradio/dropdown`
2
+
3
+ ```html
4
+ <script>
5
+ import {BaseDropdown, BaseMultiselect, BaseExample } from "@gradio/dropdown";
6
+ </script>
7
+ ```
8
+
9
+ BaseDropdown
10
+ ```javascript
11
+ export let label: string;
12
+ export let info: string | undefined = undefined;
13
+ export let value: string | number | (string | number)[] | undefined = [];
14
+ export let value_is_output = false;
15
+ export let choices: [string, string | number][];
16
+ export let disabled = false;
17
+ export let show_label: boolean;
18
+ export let container = true;
19
+ export let allow_custom_value = false;
20
+ export let filterable = true;
21
+ ```
22
+
23
+ BaseMultiselect
24
+ ```javascript
25
+ export let label: string;
26
+ export let info: string | undefined = undefined;
27
+ export let value: string | number | (string | number)[] | undefined = [];
28
+ export let value_is_output = false;
29
+ export let max_choices: number | null = null;
30
+ export let choices: [string, string | number][];
31
+ export let disabled = false;
32
+ export let show_label: boolean;
33
+ export let container = true;
34
+ export let allow_custom_value = false;
35
+ export let filterable = true;
36
+ export let i18n: I18nFormatter;
37
+ ```
38
+
39
+ BaseExample
40
+ ```javascript
41
+ export let value: string;
42
+ export let type: "gallery" | "table";
43
+ export let selected = false;
44
  ```
src/frontend/shared/patched_dropdown/dropdown.test.ts CHANGED
@@ -1,515 +1,515 @@
1
- import { test, describe, assert, afterEach, vi } from "vitest";
2
- import { cleanup, render } from "@gradio/tootils";
3
- import event from "@testing-library/user-event";
4
- import { setupi18n } from "../app/src/i18n";
5
-
6
- import Dropdown from "./Index.svelte";
7
- import type { LoadingStatus } from "@gradio/statustracker";
8
-
9
- const loading_status: LoadingStatus = {
10
- eta: 0,
11
- queue_position: 1,
12
- queue_size: 1,
13
- status: "complete" as LoadingStatus["status"],
14
- scroll_to_output: false,
15
- visible: true,
16
- fn_index: 0,
17
- show_progress: "full"
18
- };
19
-
20
- describe("Dropdown", () => {
21
- afterEach(() => {
22
- cleanup();
23
- vi.useRealTimers();
24
- });
25
- beforeEach(() => {
26
- setupi18n();
27
- });
28
- test("renders provided value", async () => {
29
- const { getByLabelText } = await render(Dropdown, {
30
- show_label: true,
31
- loading_status,
32
- max_choices: null,
33
- value: "choice",
34
- label: "Dropdown",
35
- choices: [
36
- ["choice", "choice"],
37
- ["choice2", "choice2"]
38
- ],
39
- filterable: false,
40
- interactive: false
41
- });
42
-
43
- const item: HTMLInputElement = getByLabelText(
44
- "Dropdown"
45
- ) as HTMLInputElement;
46
- assert.equal(item.value, "choice");
47
- });
48
-
49
- test("selecting the textbox should show the options", async () => {
50
- const { getByLabelText, getAllByTestId } = await render(Dropdown, {
51
- show_label: true,
52
- loading_status,
53
- max_choices: 10,
54
- value: "choice",
55
- label: "Dropdown",
56
- choices: [
57
- ["choice", "choice"],
58
- ["name2", "choice2"]
59
- ],
60
- filterable: true,
61
- interactive: true
62
- });
63
-
64
- const item: HTMLInputElement = getByLabelText(
65
- "Dropdown"
66
- ) as HTMLInputElement;
67
-
68
- await item.focus();
69
-
70
- const options = getAllByTestId("dropdown-option");
71
-
72
- expect(options).toHaveLength(2);
73
- expect(options[0]).toContainHTML("choice");
74
- expect(options[1]).toContainHTML("name2");
75
- });
76
-
77
- test("editing the textbox value should trigger the type event and filter the options", async () => {
78
- const { getByLabelText, listen, getAllByTestId } = await render(Dropdown, {
79
- show_label: true,
80
- loading_status,
81
- max_choices: 10,
82
- value: "",
83
- label: "Dropdown",
84
- choices: [
85
- ["apple", "apple"],
86
- ["zebra", "zebra"]
87
- ],
88
- filterable: true,
89
- interactive: true
90
- });
91
-
92
- const key_up_event = listen("key_up");
93
-
94
- const item: HTMLInputElement = getByLabelText(
95
- "Dropdown"
96
- ) as HTMLInputElement;
97
-
98
- await item.focus();
99
- const options = getAllByTestId("dropdown-option");
100
-
101
- expect(options).toHaveLength(2);
102
-
103
- item.value = "";
104
- await event.keyboard("z");
105
-
106
- const options_new = getAllByTestId("dropdown-option");
107
-
108
- await expect(options_new).toHaveLength(1);
109
- await expect(options[0]).toContainHTML("zebra");
110
- await assert.equal(key_up_event.callCount, 1);
111
- });
112
-
113
- test("blurring the textbox should cancel the filter", async () => {
114
- const { getByLabelText, listen } = await render(Dropdown, {
115
- show_label: true,
116
- loading_status,
117
- value: "default",
118
- label: "Dropdown",
119
- max_choices: undefined,
120
- choices: [
121
- ["default", "default"],
122
- ["other", "other"]
123
- ],
124
- filterable: false,
125
- interactive: true
126
- });
127
-
128
- const item: HTMLInputElement = getByLabelText(
129
- "Dropdown"
130
- ) as HTMLInputElement;
131
-
132
- item.focus();
133
- await event.keyboard("other");
134
- });
135
-
136
- test("blurring the textbox should save the input value", async () => {
137
- const { getByLabelText, listen } = await render(Dropdown, {
138
- show_label: true,
139
- loading_status,
140
- value: "new ",
141
- label: "Dropdown",
142
- max_choices: undefined,
143
- allow_custom_value: true,
144
- choices: [
145
- ["dwight", "dwight"],
146
- ["michael", "michael"]
147
- ],
148
- filterable: true,
149
- interactive: true
150
- });
151
-
152
- const item: HTMLInputElement = getByLabelText(
153
- "Dropdown"
154
- ) as HTMLInputElement;
155
- const change_event = listen("change");
156
-
157
- item.focus();
158
- await event.keyboard("kevin");
159
- await item.blur();
160
-
161
- assert.equal(item.value, "new kevin");
162
- assert.equal(change_event.callCount, 1);
163
- });
164
-
165
- test("focusing the label should toggle the options", async () => {
166
- const { getByLabelText, listen } = await render(Dropdown, {
167
- show_label: true,
168
- loading_status,
169
- value: "default",
170
- label: "Dropdown",
171
- choices: [
172
- ["default", "default"],
173
- ["other", "other"]
174
- ],
175
- filterable: true,
176
- interactive: true
177
- });
178
-
179
- const item: HTMLInputElement = getByLabelText(
180
- "Dropdown"
181
- ) as HTMLInputElement;
182
- const blur_event = listen("blur");
183
- const focus_event = listen("focus");
184
-
185
- item.focus();
186
- item.blur();
187
-
188
- assert.equal(blur_event.callCount, 1);
189
- assert.equal(focus_event.callCount, 1);
190
- });
191
-
192
- test("deselecting and reselcting a filtered dropdown should show all options again", async () => {
193
- vi.useFakeTimers();
194
- const { getByLabelText, getAllByTestId } = await render(Dropdown, {
195
- show_label: true,
196
- loading_status,
197
- max_choices: 10,
198
- value: "",
199
- label: "Dropdown",
200
- choices: [
201
- ["apple", "apple"],
202
- ["zebra", "zebra"],
203
- ["pony", "pony"]
204
- ],
205
- filterable: true,
206
- interactive: true
207
- });
208
-
209
- const item: HTMLInputElement = getByLabelText(
210
- "Dropdown"
211
- ) as HTMLInputElement;
212
-
213
- item.focus();
214
- item.value = "";
215
- await event.keyboard("z");
216
- const options = getAllByTestId("dropdown-option");
217
-
218
- expect(options).toHaveLength(1);
219
-
220
- await item.blur();
221
- // Mock 100ms delay between interactions.
222
- vi.runAllTimers();
223
- await item.focus();
224
- const options_new = getAllByTestId("dropdown-option");
225
-
226
- expect(options_new).toHaveLength(3);
227
- });
228
-
229
- test("passing in a new set of identical choices when the dropdown is open should not filter the dropdown", async () => {
230
- const { getByLabelText, getAllByTestId, component } = await render(
231
- Dropdown,
232
- {
233
- show_label: true,
234
- loading_status,
235
- value: "",
236
- label: "Dropdown",
237
- choices: [
238
- ["apple", "apple"],
239
- ["zebra", "zebra"],
240
- ["pony", "pony"]
241
- ],
242
- filterable: true,
243
- interactive: true
244
- }
245
- );
246
-
247
- const item: HTMLInputElement = getByLabelText(
248
- "Dropdown"
249
- ) as HTMLInputElement;
250
-
251
- await item.focus();
252
-
253
- const options = getAllByTestId("dropdown-option");
254
-
255
- expect(options).toHaveLength(3);
256
-
257
- component.$set({
258
- value: "",
259
- choices: [
260
- ["apple", "apple"],
261
- ["zebra", "zebra"],
262
- ["pony", "pony"]
263
- ]
264
- });
265
-
266
- item.focus();
267
-
268
- const options_new = getAllByTestId("dropdown-option");
269
- expect(options_new).toHaveLength(3);
270
- });
271
-
272
- test("setting a custom value when allow_custom_choice is false should revert to the first valid choice", async () => {
273
- const { getByLabelText, getAllByTestId, component } = await render(
274
- Dropdown,
275
- {
276
- show_label: true,
277
- loading_status,
278
- value: "",
279
- allow_custom_value: false,
280
- label: "Dropdown",
281
- choices: [
282
- ["apple", "apple"],
283
- ["zebra", "zebra"],
284
- ["pony", "pony"]
285
- ],
286
- filterable: true,
287
- interactive: true
288
- }
289
- );
290
-
291
- const item: HTMLInputElement = getByLabelText(
292
- "Dropdown"
293
- ) as HTMLInputElement;
294
-
295
- await item.focus();
296
- await event.keyboard("pie");
297
- expect(item.value).toBe("applepie");
298
- await item.blur();
299
- expect(item.value).toBe("apple");
300
- });
301
-
302
- test("setting a custom value when allow_custom_choice is true should keep the value", async () => {
303
- const { getByLabelText, getAllByTestId, component } = await render(
304
- Dropdown,
305
- {
306
- show_label: true,
307
- loading_status,
308
- value: "",
309
- allow_custom_value: true,
310
- label: "Dropdown",
311
- choices: [
312
- ["apple", "apple"],
313
- ["zebra", "zebra"],
314
- ["pony", "pony"]
315
- ],
316
- filterable: true,
317
- interactive: true
318
- }
319
- );
320
-
321
- const item: HTMLInputElement = getByLabelText(
322
- "Dropdown"
323
- ) as HTMLInputElement;
324
-
325
- await item.focus();
326
- await event.keyboard("pie");
327
- expect(item.value).toBe("applepie");
328
- await item.blur();
329
- expect(item.value).toBe("applepie");
330
- });
331
-
332
- test("setting a value should update the displayed value and selected indices", async () => {
333
- const { getByLabelText, getAllByTestId, component } = await render(
334
- Dropdown,
335
- {
336
- show_label: true,
337
- loading_status,
338
- value: "",
339
- allow_custom_value: false,
340
- label: "Dropdown",
341
- choices: [
342
- ["apple", "apple"],
343
- ["zebra", "zebra"],
344
- ["pony", "pony"]
345
- ],
346
- filterable: true,
347
- interactive: true
348
- }
349
- );
350
-
351
- const item: HTMLInputElement = getByLabelText(
352
- "Dropdown"
353
- ) as HTMLInputElement;
354
-
355
- expect(item.value).toBe("apple");
356
- await item.focus();
357
- let options = getAllByTestId("dropdown-option");
358
- expect(options[0]).toHaveClass("selected");
359
-
360
- await component.$set({ value: "zebra" });
361
- expect(item.value).toBe("zebra");
362
- options = getAllByTestId("dropdown-option");
363
- expect(options[0]).toHaveClass("selected");
364
-
365
- await component.$set({ value: undefined });
366
- expect(item.value).toBe("");
367
- options = getAllByTestId("dropdown-option");
368
- expect(options[0]).not.toHaveClass("selected");
369
-
370
- await component.$set({ value: "zebra" });
371
- expect(item.value).toBe("zebra");
372
- options = getAllByTestId("dropdown-option");
373
- expect(options[0]).toHaveClass("selected");
374
- });
375
-
376
- test("blurring a dropdown should set the input text to the previously selected value", async () => {
377
- const { getByLabelText, getAllByTestId, component } = await render(
378
- Dropdown,
379
- {
380
- show_label: true,
381
- loading_status,
382
- value: "",
383
- allow_custom_value: false,
384
- label: "Dropdown",
385
- choices: [
386
- ["apple", "apple_internal_value"],
387
- ["zebra", "zebra_internal_value"],
388
- ["pony", "pony_internal_value"]
389
- ],
390
- filterable: true,
391
- interactive: true
392
- }
393
- );
394
-
395
- const item: HTMLInputElement = getByLabelText(
396
- "Dropdown"
397
- ) as HTMLInputElement;
398
-
399
- expect(item.value).toBe("apple");
400
- await item.focus();
401
- let options = getAllByTestId("dropdown-option");
402
- expect(options[0]).toHaveClass("selected");
403
- await item.blur();
404
- expect(item.value).toBe("apple");
405
-
406
- await item.focus();
407
- await event.keyboard("z");
408
- expect(item.value).toBe("applez");
409
- await item.blur();
410
- expect(item.value).toBe("apple");
411
- });
412
-
413
- test("updating choices should keep the dropdown focus-able and change the value appropriately if custom values are not allowed", async () => {
414
- const { getByLabelText, component } = await render(Dropdown, {
415
- show_label: true,
416
- loading_status,
417
- value: "apple_internal_value",
418
- allow_custom_value: false,
419
- label: "Dropdown",
420
- choices: [
421
- ["apple_choice", "apple_internal_value"],
422
- ["zebra_choice", "zebra_internal_value"]
423
- ],
424
- filterable: true,
425
- interactive: true
426
- });
427
-
428
- const item: HTMLInputElement = getByLabelText(
429
- "Dropdown"
430
- ) as HTMLInputElement;
431
-
432
- await expect(item.value).toBe("apple_choice");
433
-
434
- component.$set({
435
- choices: [
436
- ["apple_new_choice", "apple_internal_value"],
437
- ["zebra_new_choice", "zebra_internal_value"]
438
- ]
439
- });
440
-
441
- await item.focus();
442
- await item.blur();
443
- await expect(item.value).toBe("apple_new_choice");
444
- });
445
-
446
- test("updating choices should not reset the value if custom values are allowed", async () => {
447
- const { getByLabelText, component } = await render(Dropdown, {
448
- show_label: true,
449
- loading_status,
450
- value: "apple_internal_value",
451
- allow_custom_value: true,
452
- label: "Dropdown",
453
- choices: [
454
- ["apple_choice", "apple_internal_value"],
455
- ["zebra_choice", "zebra_internal_value"]
456
- ],
457
- filterable: true,
458
- interactive: true
459
- });
460
-
461
- const item: HTMLInputElement = getByLabelText(
462
- "Dropdown"
463
- ) as HTMLInputElement;
464
-
465
- await expect(item.value).toBe("apple_choice");
466
-
467
- component.$set({
468
- choices: [
469
- ["apple_new_choice", "apple_internal_value"],
470
- ["zebra_new_choice", "zebra_internal_value"]
471
- ]
472
- });
473
-
474
- await expect(item.value).toBe("apple_choice");
475
- });
476
-
477
- test("ensure dropdown can have an empty value", async () => {
478
- const { getByLabelText } = await render(Dropdown, {
479
- show_label: true,
480
- loading_status,
481
- allow_custom_value: false,
482
- label: "Dropdown",
483
- choices: [
484
- ["apple_choice", "apple_internal_value"],
485
- ["zebra_choice", "zebra_internal_value"]
486
- ],
487
- filterable: true,
488
- interactive: true
489
- });
490
- const item: HTMLInputElement = getByLabelText(
491
- "Dropdown"
492
- ) as HTMLInputElement;
493
- await expect(item.value).toBe("");
494
- });
495
-
496
- test("ensure dropdown works when initial value is undefined and allow custom value is set", async () => {
497
- const { getByLabelText } = await render(Dropdown, {
498
- show_label: true,
499
- loading_status,
500
- value: undefined,
501
- allow_custom_value: true,
502
- label: "Dropdown",
503
- choices: [
504
- ["apple_choice", "apple_internal_value"],
505
- ["zebra_choice", "zebra_internal_value"]
506
- ],
507
- filterable: true,
508
- interactive: true
509
- });
510
- const item: HTMLInputElement = getByLabelText(
511
- "Dropdown"
512
- ) as HTMLInputElement;
513
- await expect(item.value).toBe("");
514
- });
515
- });
 
1
+ import { test, describe, assert, afterEach, vi } from "vitest";
2
+ import { cleanup, render } from "@gradio/tootils";
3
+ import event from "@testing-library/user-event";
4
+ import { setupi18n } from "../app/src/i18n";
5
+
6
+ import Dropdown from "./Index.svelte";
7
+ import type { LoadingStatus } from "@gradio/statustracker";
8
+
9
+ const loading_status: LoadingStatus = {
10
+ eta: 0,
11
+ queue_position: 1,
12
+ queue_size: 1,
13
+ status: "complete" as LoadingStatus["status"],
14
+ scroll_to_output: false,
15
+ visible: true,
16
+ fn_index: 0,
17
+ show_progress: "full"
18
+ };
19
+
20
+ describe("Dropdown", () => {
21
+ afterEach(() => {
22
+ cleanup();
23
+ vi.useRealTimers();
24
+ });
25
+ beforeEach(() => {
26
+ setupi18n();
27
+ });
28
+ test("renders provided value", async () => {
29
+ const { getByLabelText } = await render(Dropdown, {
30
+ show_label: true,
31
+ loading_status,
32
+ max_choices: null,
33
+ value: "choice",
34
+ label: "Dropdown",
35
+ choices: [
36
+ ["choice", "choice"],
37
+ ["choice2", "choice2"]
38
+ ],
39
+ filterable: false,
40
+ interactive: false
41
+ });
42
+
43
+ const item: HTMLInputElement = getByLabelText(
44
+ "Dropdown"
45
+ ) as HTMLInputElement;
46
+ assert.equal(item.value, "choice");
47
+ });
48
+
49
+ test("selecting the textbox should show the options", async () => {
50
+ const { getByLabelText, getAllByTestId } = await render(Dropdown, {
51
+ show_label: true,
52
+ loading_status,
53
+ max_choices: 10,
54
+ value: "choice",
55
+ label: "Dropdown",
56
+ choices: [
57
+ ["choice", "choice"],
58
+ ["name2", "choice2"]
59
+ ],
60
+ filterable: true,
61
+ interactive: true
62
+ });
63
+
64
+ const item: HTMLInputElement = getByLabelText(
65
+ "Dropdown"
66
+ ) as HTMLInputElement;
67
+
68
+ await item.focus();
69
+
70
+ const options = getAllByTestId("dropdown-option");
71
+
72
+ expect(options).toHaveLength(2);
73
+ expect(options[0]).toContainHTML("choice");
74
+ expect(options[1]).toContainHTML("name2");
75
+ });
76
+
77
+ test("editing the textbox value should trigger the type event and filter the options", async () => {
78
+ const { getByLabelText, listen, getAllByTestId } = await render(Dropdown, {
79
+ show_label: true,
80
+ loading_status,
81
+ max_choices: 10,
82
+ value: "",
83
+ label: "Dropdown",
84
+ choices: [
85
+ ["apple", "apple"],
86
+ ["zebra", "zebra"]
87
+ ],
88
+ filterable: true,
89
+ interactive: true
90
+ });
91
+
92
+ const key_up_event = listen("key_up");
93
+
94
+ const item: HTMLInputElement = getByLabelText(
95
+ "Dropdown"
96
+ ) as HTMLInputElement;
97
+
98
+ await item.focus();
99
+ const options = getAllByTestId("dropdown-option");
100
+
101
+ expect(options).toHaveLength(2);
102
+
103
+ item.value = "";
104
+ await event.keyboard("z");
105
+
106
+ const options_new = getAllByTestId("dropdown-option");
107
+
108
+ await expect(options_new).toHaveLength(1);
109
+ await expect(options[0]).toContainHTML("zebra");
110
+ await assert.equal(key_up_event.callCount, 1);
111
+ });
112
+
113
+ test("blurring the textbox should cancel the filter", async () => {
114
+ const { getByLabelText, listen } = await render(Dropdown, {
115
+ show_label: true,
116
+ loading_status,
117
+ value: "default",
118
+ label: "Dropdown",
119
+ max_choices: undefined,
120
+ choices: [
121
+ ["default", "default"],
122
+ ["other", "other"]
123
+ ],
124
+ filterable: false,
125
+ interactive: true
126
+ });
127
+
128
+ const item: HTMLInputElement = getByLabelText(
129
+ "Dropdown"
130
+ ) as HTMLInputElement;
131
+
132
+ item.focus();
133
+ await event.keyboard("other");
134
+ });
135
+
136
+ test("blurring the textbox should save the input value", async () => {
137
+ const { getByLabelText, listen } = await render(Dropdown, {
138
+ show_label: true,
139
+ loading_status,
140
+ value: "new ",
141
+ label: "Dropdown",
142
+ max_choices: undefined,
143
+ allow_custom_value: true,
144
+ choices: [
145
+ ["dwight", "dwight"],
146
+ ["michael", "michael"]
147
+ ],
148
+ filterable: true,
149
+ interactive: true
150
+ });
151
+
152
+ const item: HTMLInputElement = getByLabelText(
153
+ "Dropdown"
154
+ ) as HTMLInputElement;
155
+ const change_event = listen("change");
156
+
157
+ item.focus();
158
+ await event.keyboard("kevin");
159
+ await item.blur();
160
+
161
+ assert.equal(item.value, "new kevin");
162
+ assert.equal(change_event.callCount, 1);
163
+ });
164
+
165
+ test("focusing the label should toggle the options", async () => {
166
+ const { getByLabelText, listen } = await render(Dropdown, {
167
+ show_label: true,
168
+ loading_status,
169
+ value: "default",
170
+ label: "Dropdown",
171
+ choices: [
172
+ ["default", "default"],
173
+ ["other", "other"]
174
+ ],
175
+ filterable: true,
176
+ interactive: true
177
+ });
178
+
179
+ const item: HTMLInputElement = getByLabelText(
180
+ "Dropdown"
181
+ ) as HTMLInputElement;
182
+ const blur_event = listen("blur");
183
+ const focus_event = listen("focus");
184
+
185
+ item.focus();
186
+ item.blur();
187
+
188
+ assert.equal(blur_event.callCount, 1);
189
+ assert.equal(focus_event.callCount, 1);
190
+ });
191
+
192
+ test("deselecting and reselcting a filtered dropdown should show all options again", async () => {
193
+ vi.useFakeTimers();
194
+ const { getByLabelText, getAllByTestId } = await render(Dropdown, {
195
+ show_label: true,
196
+ loading_status,
197
+ max_choices: 10,
198
+ value: "",
199
+ label: "Dropdown",
200
+ choices: [
201
+ ["apple", "apple"],
202
+ ["zebra", "zebra"],
203
+ ["pony", "pony"]
204
+ ],
205
+ filterable: true,
206
+ interactive: true
207
+ });
208
+
209
+ const item: HTMLInputElement = getByLabelText(
210
+ "Dropdown"
211
+ ) as HTMLInputElement;
212
+
213
+ item.focus();
214
+ item.value = "";
215
+ await event.keyboard("z");
216
+ const options = getAllByTestId("dropdown-option");
217
+
218
+ expect(options).toHaveLength(1);
219
+
220
+ await item.blur();
221
+ // Mock 100ms delay between interactions.
222
+ vi.runAllTimers();
223
+ await item.focus();
224
+ const options_new = getAllByTestId("dropdown-option");
225
+
226
+ expect(options_new).toHaveLength(3);
227
+ });
228
+
229
+ test("passing in a new set of identical choices when the dropdown is open should not filter the dropdown", async () => {
230
+ const { getByLabelText, getAllByTestId, component } = await render(
231
+ Dropdown,
232
+ {
233
+ show_label: true,
234
+ loading_status,
235
+ value: "",
236
+ label: "Dropdown",
237
+ choices: [
238
+ ["apple", "apple"],
239
+ ["zebra", "zebra"],
240
+ ["pony", "pony"]
241
+ ],
242
+ filterable: true,
243
+ interactive: true
244
+ }
245
+ );
246
+
247
+ const item: HTMLInputElement = getByLabelText(
248
+ "Dropdown"
249
+ ) as HTMLInputElement;
250
+
251
+ await item.focus();
252
+
253
+ const options = getAllByTestId("dropdown-option");
254
+
255
+ expect(options).toHaveLength(3);
256
+
257
+ component.$set({
258
+ value: "",
259
+ choices: [
260
+ ["apple", "apple"],
261
+ ["zebra", "zebra"],
262
+ ["pony", "pony"]
263
+ ]
264
+ });
265
+
266
+ item.focus();
267
+
268
+ const options_new = getAllByTestId("dropdown-option");
269
+ expect(options_new).toHaveLength(3);
270
+ });
271
+
272
+ test("setting a custom value when allow_custom_choice is false should revert to the first valid choice", async () => {
273
+ const { getByLabelText, getAllByTestId, component } = await render(
274
+ Dropdown,
275
+ {
276
+ show_label: true,
277
+ loading_status,
278
+ value: "",
279
+ allow_custom_value: false,
280
+ label: "Dropdown",
281
+ choices: [
282
+ ["apple", "apple"],
283
+ ["zebra", "zebra"],
284
+ ["pony", "pony"]
285
+ ],
286
+ filterable: true,
287
+ interactive: true
288
+ }
289
+ );
290
+
291
+ const item: HTMLInputElement = getByLabelText(
292
+ "Dropdown"
293
+ ) as HTMLInputElement;
294
+
295
+ await item.focus();
296
+ await event.keyboard("pie");
297
+ expect(item.value).toBe("applepie");
298
+ await item.blur();
299
+ expect(item.value).toBe("apple");
300
+ });
301
+
302
+ test("setting a custom value when allow_custom_choice is true should keep the value", async () => {
303
+ const { getByLabelText, getAllByTestId, component } = await render(
304
+ Dropdown,
305
+ {
306
+ show_label: true,
307
+ loading_status,
308
+ value: "",
309
+ allow_custom_value: true,
310
+ label: "Dropdown",
311
+ choices: [
312
+ ["apple", "apple"],
313
+ ["zebra", "zebra"],
314
+ ["pony", "pony"]
315
+ ],
316
+ filterable: true,
317
+ interactive: true
318
+ }
319
+ );
320
+
321
+ const item: HTMLInputElement = getByLabelText(
322
+ "Dropdown"
323
+ ) as HTMLInputElement;
324
+
325
+ await item.focus();
326
+ await event.keyboard("pie");
327
+ expect(item.value).toBe("applepie");
328
+ await item.blur();
329
+ expect(item.value).toBe("applepie");
330
+ });
331
+
332
+ test("setting a value should update the displayed value and selected indices", async () => {
333
+ const { getByLabelText, getAllByTestId, component } = await render(
334
+ Dropdown,
335
+ {
336
+ show_label: true,
337
+ loading_status,
338
+ value: "",
339
+ allow_custom_value: false,
340
+ label: "Dropdown",
341
+ choices: [
342
+ ["apple", "apple"],
343
+ ["zebra", "zebra"],
344
+ ["pony", "pony"]
345
+ ],
346
+ filterable: true,
347
+ interactive: true
348
+ }
349
+ );
350
+
351
+ const item: HTMLInputElement = getByLabelText(
352
+ "Dropdown"
353
+ ) as HTMLInputElement;
354
+
355
+ expect(item.value).toBe("apple");
356
+ await item.focus();
357
+ let options = getAllByTestId("dropdown-option");
358
+ expect(options[0]).toHaveClass("selected");
359
+
360
+ await component.$set({ value: "zebra" });
361
+ expect(item.value).toBe("zebra");
362
+ options = getAllByTestId("dropdown-option");
363
+ expect(options[0]).toHaveClass("selected");
364
+
365
+ await component.$set({ value: undefined });
366
+ expect(item.value).toBe("");
367
+ options = getAllByTestId("dropdown-option");
368
+ expect(options[0]).not.toHaveClass("selected");
369
+
370
+ await component.$set({ value: "zebra" });
371
+ expect(item.value).toBe("zebra");
372
+ options = getAllByTestId("dropdown-option");
373
+ expect(options[0]).toHaveClass("selected");
374
+ });
375
+
376
+ test("blurring a dropdown should set the input text to the previously selected value", async () => {
377
+ const { getByLabelText, getAllByTestId, component } = await render(
378
+ Dropdown,
379
+ {
380
+ show_label: true,
381
+ loading_status,
382
+ value: "",
383
+ allow_custom_value: false,
384
+ label: "Dropdown",
385
+ choices: [
386
+ ["apple", "apple_internal_value"],
387
+ ["zebra", "zebra_internal_value"],
388
+ ["pony", "pony_internal_value"]
389
+ ],
390
+ filterable: true,
391
+ interactive: true
392
+ }
393
+ );
394
+
395
+ const item: HTMLInputElement = getByLabelText(
396
+ "Dropdown"
397
+ ) as HTMLInputElement;
398
+
399
+ expect(item.value).toBe("apple");
400
+ await item.focus();
401
+ let options = getAllByTestId("dropdown-option");
402
+ expect(options[0]).toHaveClass("selected");
403
+ await item.blur();
404
+ expect(item.value).toBe("apple");
405
+
406
+ await item.focus();
407
+ await event.keyboard("z");
408
+ expect(item.value).toBe("applez");
409
+ await item.blur();
410
+ expect(item.value).toBe("apple");
411
+ });
412
+
413
+ test("updating choices should keep the dropdown focus-able and change the value appropriately if custom values are not allowed", async () => {
414
+ const { getByLabelText, component } = await render(Dropdown, {
415
+ show_label: true,
416
+ loading_status,
417
+ value: "apple_internal_value",
418
+ allow_custom_value: false,
419
+ label: "Dropdown",
420
+ choices: [
421
+ ["apple_choice", "apple_internal_value"],
422
+ ["zebra_choice", "zebra_internal_value"]
423
+ ],
424
+ filterable: true,
425
+ interactive: true
426
+ });
427
+
428
+ const item: HTMLInputElement = getByLabelText(
429
+ "Dropdown"
430
+ ) as HTMLInputElement;
431
+
432
+ await expect(item.value).toBe("apple_choice");
433
+
434
+ component.$set({
435
+ choices: [
436
+ ["apple_new_choice", "apple_internal_value"],
437
+ ["zebra_new_choice", "zebra_internal_value"]
438
+ ]
439
+ });
440
+
441
+ await item.focus();
442
+ await item.blur();
443
+ await expect(item.value).toBe("apple_new_choice");
444
+ });
445
+
446
+ test("updating choices should not reset the value if custom values are allowed", async () => {
447
+ const { getByLabelText, component } = await render(Dropdown, {
448
+ show_label: true,
449
+ loading_status,
450
+ value: "apple_internal_value",
451
+ allow_custom_value: true,
452
+ label: "Dropdown",
453
+ choices: [
454
+ ["apple_choice", "apple_internal_value"],
455
+ ["zebra_choice", "zebra_internal_value"]
456
+ ],
457
+ filterable: true,
458
+ interactive: true
459
+ });
460
+
461
+ const item: HTMLInputElement = getByLabelText(
462
+ "Dropdown"
463
+ ) as HTMLInputElement;
464
+
465
+ await expect(item.value).toBe("apple_choice");
466
+
467
+ component.$set({
468
+ choices: [
469
+ ["apple_new_choice", "apple_internal_value"],
470
+ ["zebra_new_choice", "zebra_internal_value"]
471
+ ]
472
+ });
473
+
474
+ await expect(item.value).toBe("apple_choice");
475
+ });
476
+
477
+ test("ensure dropdown can have an empty value", async () => {
478
+ const { getByLabelText } = await render(Dropdown, {
479
+ show_label: true,
480
+ loading_status,
481
+ allow_custom_value: false,
482
+ label: "Dropdown",
483
+ choices: [
484
+ ["apple_choice", "apple_internal_value"],
485
+ ["zebra_choice", "zebra_internal_value"]
486
+ ],
487
+ filterable: true,
488
+ interactive: true
489
+ });
490
+ const item: HTMLInputElement = getByLabelText(
491
+ "Dropdown"
492
+ ) as HTMLInputElement;
493
+ await expect(item.value).toBe("");
494
+ });
495
+
496
+ test("ensure dropdown works when initial value is undefined and allow custom value is set", async () => {
497
+ const { getByLabelText } = await render(Dropdown, {
498
+ show_label: true,
499
+ loading_status,
500
+ value: undefined,
501
+ allow_custom_value: true,
502
+ label: "Dropdown",
503
+ choices: [
504
+ ["apple_choice", "apple_internal_value"],
505
+ ["zebra_choice", "zebra_internal_value"]
506
+ ],
507
+ filterable: true,
508
+ interactive: true
509
+ });
510
+ const item: HTMLInputElement = getByLabelText(
511
+ "Dropdown"
512
+ ) as HTMLInputElement;
513
+ await expect(item.value).toBe("");
514
+ });
515
+ });
src/frontend/shared/patched_dropdown/package.json CHANGED
@@ -1,21 +1,21 @@
1
- {
2
- "name": "@gradio/dropdown",
3
- "version": "0.6.3",
4
- "description": "Gradio UI packages",
5
- "type": "module",
6
- "author": "",
7
- "license": "ISC",
8
- "private": false,
9
- "main_changeset": true,
10
- "exports": {
11
- ".": "./Index.svelte",
12
- "./example": "./Example.svelte",
13
- "./package.json": "./package.json"
14
- },
15
- "dependencies": {
16
- "@gradio/atoms": "^0.5.3",
17
- "@gradio/icons": "^0.3.3",
18
- "@gradio/statustracker": "^0.4.8",
19
- "@gradio/utils": "^0.3.0"
20
- }
21
  }
 
1
+ {
2
+ "name": "@gradio/dropdown",
3
+ "version": "0.6.3",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "main_changeset": true,
10
+ "exports": {
11
+ ".": "./Index.svelte",
12
+ "./example": "./Example.svelte",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "dependencies": {
16
+ "@gradio/atoms": "^0.5.3",
17
+ "@gradio/icons": "^0.3.3",
18
+ "@gradio/statustracker": "^0.4.8",
19
+ "@gradio/utils": "^0.3.0"
20
+ }
21
  }
src/frontend/shared/patched_dropdown/shared/Dropdown.svelte CHANGED
@@ -1,326 +1,326 @@
1
- <script lang="ts">
2
- import { onMount } from "svelte";
3
- import DropdownOptions from "./DropdownOptions.svelte";
4
- import { createEventDispatcher, afterUpdate } from "svelte";
5
- import { BlockTitle } from "@gradio/atoms";
6
- import { DropdownArrow } from "@gradio/icons";
7
- import type { SelectData, KeyUpData } from "@gradio/utils";
8
- import { handle_filter, handle_change, handle_shared_keys } from "./utils";
9
-
10
- export let label: string;
11
- export let info: string | undefined = undefined;
12
- export let value: string | number | (string | number)[] | undefined = [];
13
- let old_value: string | number | (string | number)[] | undefined = [];
14
- export let value_is_output = false;
15
- export let choices: [string, string | number][];
16
- let old_choices: [string, string | number][];
17
- export let disabled = false;
18
- export let show_label: boolean;
19
- export let container = true;
20
- export let allow_custom_value = false;
21
- export let filterable = true;
22
-
23
- let filter_input: HTMLElement;
24
-
25
- let show_options = false;
26
- let choices_names: string[];
27
- let choices_values: (string | number)[];
28
- let input_text = "";
29
- let old_input_text = "";
30
- let initialized = false;
31
-
32
- // All of these are indices with respect to the choices array
33
- let filtered_indices: number[] = [];
34
- let active_index: number | null = null;
35
- // selected_index is null if allow_custom_value is true and the input_text is not in choices_names
36
- let selected_index: number | null = null;
37
- let old_selected_index: number | null;
38
-
39
- const dispatch = createEventDispatcher<{
40
- change: string | undefined;
41
- input: undefined;
42
- select: SelectData;
43
- blur: undefined;
44
- focus: undefined;
45
- key_up: KeyUpData;
46
- enter: any;
47
- }>();
48
-
49
- // Setting the initial value of the dropdown
50
- if (value) {
51
- old_selected_index = choices.map((c) => c[1]).indexOf(value as string);
52
- selected_index = old_selected_index;
53
- if (selected_index === -1) {
54
- old_value = value;
55
- selected_index = null;
56
- } else {
57
- [input_text, old_value] = choices[selected_index];
58
- old_input_text = input_text;
59
- }
60
- set_input_text();
61
- } else if (choices.length > 0) {
62
- old_selected_index = 0;
63
- selected_index = 0;
64
- [input_text, value] = choices[selected_index];
65
- old_value = value;
66
- old_input_text = input_text;
67
- }
68
-
69
- $: {
70
- if (
71
- selected_index !== old_selected_index &&
72
- selected_index !== null &&
73
- initialized
74
- ) {
75
- [input_text, value] = choices[selected_index];
76
- old_selected_index = selected_index;
77
- dispatch("select", {
78
- index: selected_index,
79
- value: choices_values[selected_index],
80
- selected: true
81
- });
82
- }
83
- }
84
-
85
- $: {
86
- if (value != old_value) {
87
- set_input_text();
88
- handle_change(dispatch, value, value_is_output);
89
- old_value = value;
90
- }
91
- }
92
-
93
- function set_choice_names_values(): void {
94
- choices_names = choices.map((c) => c[0]);
95
- choices_values = choices.map((c) => c[1]);
96
- }
97
-
98
- $: choices, set_choice_names_values();
99
-
100
- $: {
101
- if (choices !== old_choices) {
102
- if (!allow_custom_value) {
103
- set_input_text();
104
- }
105
- old_choices = choices;
106
- filtered_indices = handle_filter(choices, input_text);
107
- if (!allow_custom_value && filtered_indices.length > 0) {
108
- active_index = filtered_indices[0];
109
- }
110
- if (filter_input == document.activeElement) {
111
- show_options = true;
112
- }
113
- }
114
- }
115
-
116
- $: {
117
- if (input_text !== old_input_text) {
118
- filtered_indices = handle_filter(choices, input_text);
119
- old_input_text = input_text;
120
- if (!allow_custom_value && filtered_indices.length > 0) {
121
- active_index = filtered_indices[0];
122
- }
123
- }
124
- }
125
-
126
- function set_input_text(): void {
127
- set_choice_names_values();
128
- if (value === undefined || (Array.isArray(value) && value.length === 0)) {
129
- input_text = "";
130
- selected_index = null;
131
- } else if (choices_values.includes(value as string)) {
132
- input_text = choices_names[choices_values.indexOf(value as string)];
133
- selected_index = choices_values.indexOf(value as string);
134
- } else if (allow_custom_value) {
135
- input_text = value as string;
136
- selected_index = null;
137
- } else {
138
- input_text = "";
139
- selected_index = null;
140
- }
141
- old_selected_index = selected_index;
142
- }
143
-
144
- function handle_option_selected(e: any): void {
145
- selected_index = parseInt(e.detail.target.dataset.index);
146
- if (isNaN(selected_index)) {
147
- // This is the case when the user clicks on the scrollbar
148
- selected_index = null;
149
- return;
150
- }
151
- show_options = false;
152
- active_index = null;
153
- filter_input.blur();
154
- }
155
-
156
- function handle_focus(e: FocusEvent): void {
157
- filtered_indices = choices.map((_, i) => i);
158
- show_options = true;
159
- dispatch("focus");
160
- }
161
-
162
- function handle_blur(): void {
163
- if (!allow_custom_value) {
164
- input_text = choices_names[choices_values.indexOf(value as string)];
165
- } else {
166
- value = input_text;
167
- }
168
- show_options = false;
169
- active_index = null;
170
- dispatch("blur");
171
- }
172
-
173
- function handle_key_down(e: KeyboardEvent): void {
174
- [show_options, active_index] = handle_shared_keys(
175
- e,
176
- active_index,
177
- filtered_indices
178
- );
179
- if (e.key === "Enter") {
180
- if (active_index !== null) {
181
- selected_index = active_index;
182
- show_options = false;
183
- filter_input.blur();
184
- active_index = null;
185
- } else if (choices_names.includes(input_text)) {
186
- selected_index = choices_names.indexOf(input_text);
187
- show_options = false;
188
- active_index = null;
189
- filter_input.blur();
190
- } else if (allow_custom_value) {
191
- value = input_text;
192
- selected_index = null;
193
- show_options = false;
194
- active_index = null;
195
- filter_input.blur();
196
- }
197
- dispatch("enter", value);
198
- }
199
- }
200
-
201
- afterUpdate(() => {
202
- value_is_output = false;
203
- initialized = true;
204
- });
205
-
206
- onMount(() => {
207
- filter_input.focus();
208
- });
209
- </script>
210
-
211
- <div class:container>
212
- <BlockTitle {show_label} {info}>{label}</BlockTitle>
213
-
214
- <div class="wrap">
215
- <div class="wrap-inner" class:show_options>
216
- <div class="secondary-wrap">
217
- <input
218
- role="listbox"
219
- aria-controls="dropdown-options"
220
- aria-expanded={show_options}
221
- aria-label={label}
222
- class="border-none"
223
- class:subdued={!choices_names.includes(input_text) &&
224
- !allow_custom_value}
225
- {disabled}
226
- autocomplete="off"
227
- bind:value={input_text}
228
- bind:this={filter_input}
229
- on:keydown={handle_key_down}
230
- on:keyup={(e) =>
231
- dispatch("key_up", {
232
- key: e.key,
233
- input_value: input_text
234
- })}
235
- on:blur={handle_blur}
236
- on:focus={handle_focus}
237
- readonly={!filterable}
238
- />
239
- {#if !disabled}
240
- <div class="icon-wrap">
241
- <DropdownArrow />
242
- </div>
243
- {/if}
244
- </div>
245
- </div>
246
- <DropdownOptions
247
- {show_options}
248
- {choices}
249
- {filtered_indices}
250
- {disabled}
251
- selected_indices={selected_index === null ? [] : [selected_index]}
252
- {active_index}
253
- on:change={handle_option_selected}
254
- />
255
- </div>
256
- </div>
257
-
258
- <style>
259
- .icon-wrap {
260
- color: var(--body-text-color);
261
- margin-right: var(--size-2);
262
- width: var(--size-5);
263
- }
264
- .container {
265
- height: 100%;
266
- }
267
- .container .wrap {
268
- box-shadow: var(--input-shadow);
269
- border: var(--input-border-width) solid var(--border-color-primary);
270
- }
271
-
272
- .wrap {
273
- position: relative;
274
- border-radius: var(--input-radius);
275
- background: var(--input-background-fill);
276
- }
277
-
278
- .wrap:focus-within {
279
- box-shadow: var(--input-shadow-focus);
280
- border-color: var(--input-border-color-focus);
281
- }
282
-
283
- .wrap-inner {
284
- display: flex;
285
- position: relative;
286
- flex-wrap: wrap;
287
- align-items: center;
288
- gap: var(--checkbox-label-gap);
289
- padding: var(--checkbox-label-padding);
290
- height: 100%;
291
- }
292
- .secondary-wrap {
293
- display: flex;
294
- flex: 1 1 0%;
295
- align-items: center;
296
- border: none;
297
- min-width: min-content;
298
- height: 100%;
299
- }
300
-
301
- input {
302
- margin: var(--spacing-sm);
303
- outline: none;
304
- border: none;
305
- background: inherit;
306
- width: var(--size-full);
307
- color: var(--body-text-color);
308
- font-size: var(--input-text-size);
309
- height: 100%;
310
- }
311
-
312
- input:disabled {
313
- -webkit-text-fill-color: var(--body-text-color);
314
- -webkit-opacity: 1;
315
- opacity: 1;
316
- cursor: not-allowed;
317
- }
318
-
319
- .subdued {
320
- color: var(--body-text-color-subdued);
321
- }
322
-
323
- input[readonly] {
324
- cursor: pointer;
325
- }
326
- </style>
 
1
+ <script lang="ts">
2
+ import { onMount } from "svelte";
3
+ import DropdownOptions from "./DropdownOptions.svelte";
4
+ import { createEventDispatcher, afterUpdate } from "svelte";
5
+ import { BlockTitle } from "@gradio/atoms";
6
+ import { DropdownArrow } from "@gradio/icons";
7
+ import type { SelectData, KeyUpData } from "@gradio/utils";
8
+ import { handle_filter, handle_change, handle_shared_keys } from "./utils";
9
+
10
+ export let label: string;
11
+ export let info: string | undefined = undefined;
12
+ export let value: string | number | (string | number)[] | undefined = [];
13
+ let old_value: string | number | (string | number)[] | undefined = [];
14
+ export let value_is_output = false;
15
+ export let choices: [string, string | number][];
16
+ let old_choices: [string, string | number][];
17
+ export let disabled = false;
18
+ export let show_label: boolean;
19
+ export let container = true;
20
+ export let allow_custom_value = false;
21
+ export let filterable = true;
22
+
23
+ let filter_input: HTMLElement;
24
+
25
+ let show_options = false;
26
+ let choices_names: string[];
27
+ let choices_values: (string | number)[];
28
+ let input_text = "";
29
+ let old_input_text = "";
30
+ let initialized = false;
31
+
32
+ // All of these are indices with respect to the choices array
33
+ let filtered_indices: number[] = [];
34
+ let active_index: number | null = null;
35
+ // selected_index is null if allow_custom_value is true and the input_text is not in choices_names
36
+ let selected_index: number | null = null;
37
+ let old_selected_index: number | null;
38
+
39
+ const dispatch = createEventDispatcher<{
40
+ change: string | undefined;
41
+ input: undefined;
42
+ select: SelectData;
43
+ blur: undefined;
44
+ focus: undefined;
45
+ key_up: KeyUpData;
46
+ enter: any;
47
+ }>();
48
+
49
+ // Setting the initial value of the dropdown
50
+ if (value) {
51
+ old_selected_index = choices.map((c) => c[1]).indexOf(value as string);
52
+ selected_index = old_selected_index;
53
+ if (selected_index === -1) {
54
+ old_value = value;
55
+ selected_index = null;
56
+ } else {
57
+ [input_text, old_value] = choices[selected_index];
58
+ old_input_text = input_text;
59
+ }
60
+ set_input_text();
61
+ } else if (choices.length > 0) {
62
+ old_selected_index = 0;
63
+ selected_index = 0;
64
+ [input_text, value] = choices[selected_index];
65
+ old_value = value;
66
+ old_input_text = input_text;
67
+ }
68
+
69
+ $: {
70
+ if (
71
+ selected_index !== old_selected_index &&
72
+ selected_index !== null &&
73
+ initialized
74
+ ) {
75
+ [input_text, value] = choices[selected_index];
76
+ old_selected_index = selected_index;
77
+ dispatch("select", {
78
+ index: selected_index,
79
+ value: choices_values[selected_index],
80
+ selected: true
81
+ });
82
+ }
83
+ }
84
+
85
+ $: {
86
+ if (value != old_value) {
87
+ set_input_text();
88
+ handle_change(dispatch, value, value_is_output);
89
+ old_value = value;
90
+ }
91
+ }
92
+
93
+ function set_choice_names_values(): void {
94
+ choices_names = choices.map((c) => c[0]);
95
+ choices_values = choices.map((c) => c[1]);
96
+ }
97
+
98
+ $: choices, set_choice_names_values();
99
+
100
+ $: {
101
+ if (choices !== old_choices) {
102
+ if (!allow_custom_value) {
103
+ set_input_text();
104
+ }
105
+ old_choices = choices;
106
+ filtered_indices = handle_filter(choices, input_text);
107
+ if (!allow_custom_value && filtered_indices.length > 0) {
108
+ active_index = filtered_indices[0];
109
+ }
110
+ if (filter_input == document.activeElement) {
111
+ show_options = true;
112
+ }
113
+ }
114
+ }
115
+
116
+ $: {
117
+ if (input_text !== old_input_text) {
118
+ filtered_indices = handle_filter(choices, input_text);
119
+ old_input_text = input_text;
120
+ if (!allow_custom_value && filtered_indices.length > 0) {
121
+ active_index = filtered_indices[0];
122
+ }
123
+ }
124
+ }
125
+
126
+ function set_input_text(): void {
127
+ set_choice_names_values();
128
+ if (value === undefined || (Array.isArray(value) && value.length === 0)) {
129
+ input_text = "";
130
+ selected_index = null;
131
+ } else if (choices_values.includes(value as string)) {
132
+ input_text = choices_names[choices_values.indexOf(value as string)];
133
+ selected_index = choices_values.indexOf(value as string);
134
+ } else if (allow_custom_value) {
135
+ input_text = value as string;
136
+ selected_index = null;
137
+ } else {
138
+ input_text = "";
139
+ selected_index = null;
140
+ }
141
+ old_selected_index = selected_index;
142
+ }
143
+
144
+ function handle_option_selected(e: any): void {
145
+ selected_index = parseInt(e.detail.target.dataset.index);
146
+ if (isNaN(selected_index)) {
147
+ // This is the case when the user clicks on the scrollbar
148
+ selected_index = null;
149
+ return;
150
+ }
151
+ show_options = false;
152
+ active_index = null;
153
+ filter_input.blur();
154
+ }
155
+
156
+ function handle_focus(e: FocusEvent): void {
157
+ filtered_indices = choices.map((_, i) => i);
158
+ show_options = true;
159
+ dispatch("focus");
160
+ }
161
+
162
+ function handle_blur(): void {
163
+ if (!allow_custom_value) {
164
+ input_text = choices_names[choices_values.indexOf(value as string)];
165
+ } else {
166
+ value = input_text;
167
+ }
168
+ show_options = false;
169
+ active_index = null;
170
+ dispatch("blur");
171
+ }
172
+
173
+ function handle_key_down(e: KeyboardEvent): void {
174
+ [show_options, active_index] = handle_shared_keys(
175
+ e,
176
+ active_index,
177
+ filtered_indices
178
+ );
179
+ if (e.key === "Enter") {
180
+ if (active_index !== null) {
181
+ selected_index = active_index;
182
+ show_options = false;
183
+ filter_input.blur();
184
+ active_index = null;
185
+ } else if (choices_names.includes(input_text)) {
186
+ selected_index = choices_names.indexOf(input_text);
187
+ show_options = false;
188
+ active_index = null;
189
+ filter_input.blur();
190
+ } else if (allow_custom_value) {
191
+ value = input_text;
192
+ selected_index = null;
193
+ show_options = false;
194
+ active_index = null;
195
+ filter_input.blur();
196
+ }
197
+ dispatch("enter", value);
198
+ }
199
+ }
200
+
201
+ afterUpdate(() => {
202
+ value_is_output = false;
203
+ initialized = true;
204
+ });
205
+
206
+ onMount(() => {
207
+ filter_input.focus();
208
+ });
209
+ </script>
210
+
211
+ <div class:container>
212
+ <BlockTitle {show_label} {info}>{label}</BlockTitle>
213
+
214
+ <div class="wrap">
215
+ <div class="wrap-inner" class:show_options>
216
+ <div class="secondary-wrap">
217
+ <input
218
+ role="listbox"
219
+ aria-controls="dropdown-options"
220
+ aria-expanded={show_options}
221
+ aria-label={label}
222
+ class="border-none"
223
+ class:subdued={!choices_names.includes(input_text) &&
224
+ !allow_custom_value}
225
+ {disabled}
226
+ autocomplete="off"
227
+ bind:value={input_text}
228
+ bind:this={filter_input}
229
+ on:keydown={handle_key_down}
230
+ on:keyup={(e) =>
231
+ dispatch("key_up", {
232
+ key: e.key,
233
+ input_value: input_text
234
+ })}
235
+ on:blur={handle_blur}
236
+ on:focus={handle_focus}
237
+ readonly={!filterable}
238
+ />
239
+ {#if !disabled}
240
+ <div class="icon-wrap">
241
+ <DropdownArrow />
242
+ </div>
243
+ {/if}
244
+ </div>
245
+ </div>
246
+ <DropdownOptions
247
+ {show_options}
248
+ {choices}
249
+ {filtered_indices}
250
+ {disabled}
251
+ selected_indices={selected_index === null ? [] : [selected_index]}
252
+ {active_index}
253
+ on:change={handle_option_selected}
254
+ />
255
+ </div>
256
+ </div>
257
+
258
+ <style>
259
+ .icon-wrap {
260
+ color: var(--body-text-color);
261
+ margin-right: var(--size-2);
262
+ width: var(--size-5);
263
+ }
264
+ .container {
265
+ height: 100%;
266
+ }
267
+ .container .wrap {
268
+ box-shadow: var(--input-shadow);
269
+ border: var(--input-border-width) solid var(--border-color-primary);
270
+ }
271
+
272
+ .wrap {
273
+ position: relative;
274
+ border-radius: var(--input-radius);
275
+ background: var(--input-background-fill);
276
+ }
277
+
278
+ .wrap:focus-within {
279
+ box-shadow: var(--input-shadow-focus);
280
+ border-color: var(--input-border-color-focus);
281
+ }
282
+
283
+ .wrap-inner {
284
+ display: flex;
285
+ position: relative;
286
+ flex-wrap: wrap;
287
+ align-items: center;
288
+ gap: var(--checkbox-label-gap);
289
+ padding: var(--checkbox-label-padding);
290
+ height: 100%;
291
+ }
292
+ .secondary-wrap {
293
+ display: flex;
294
+ flex: 1 1 0%;
295
+ align-items: center;
296
+ border: none;
297
+ min-width: min-content;
298
+ height: 100%;
299
+ }
300
+
301
+ input {
302
+ margin: var(--spacing-sm);
303
+ outline: none;
304
+ border: none;
305
+ background: inherit;
306
+ width: var(--size-full);
307
+ color: var(--body-text-color);
308
+ font-size: var(--input-text-size);
309
+ height: 100%;
310
+ }
311
+
312
+ input:disabled {
313
+ -webkit-text-fill-color: var(--body-text-color);
314
+ -webkit-opacity: 1;
315
+ opacity: 1;
316
+ cursor: not-allowed;
317
+ }
318
+
319
+ .subdued {
320
+ color: var(--body-text-color-subdued);
321
+ }
322
+
323
+ input[readonly] {
324
+ cursor: pointer;
325
+ }
326
+ </style>
src/frontend/shared/patched_dropdown/shared/DropdownOptions.svelte CHANGED
@@ -1,144 +1,144 @@
1
- <script lang="ts">
2
- import { fly } from "svelte/transition";
3
- import { createEventDispatcher } from "svelte";
4
- export let choices: [string, string | number][];
5
- export let filtered_indices: number[];
6
- export let show_options = false;
7
- export let disabled = false;
8
- export let selected_indices: (string | number)[] = [];
9
- export let active_index: number | null = null;
10
-
11
- let distance_from_top: number;
12
- let distance_from_bottom: number;
13
- let input_height: number;
14
- let input_width: number;
15
- let refElement: HTMLDivElement;
16
- let listElement: HTMLUListElement;
17
- let top: string | null, bottom: string | null, max_height: number;
18
- let innerHeight: number;
19
-
20
- function calculate_window_distance(): void {
21
- const { top: ref_top, bottom: ref_bottom } =
22
- refElement.getBoundingClientRect();
23
- distance_from_top = ref_top;
24
- distance_from_bottom = innerHeight - ref_bottom;
25
- }
26
-
27
- let scroll_timeout: NodeJS.Timeout | null = null;
28
- function scroll_listener(): void {
29
- if (!show_options) return;
30
- if (scroll_timeout !== null) {
31
- clearTimeout(scroll_timeout);
32
- }
33
-
34
- scroll_timeout = setTimeout(() => {
35
- calculate_window_distance();
36
- scroll_timeout = null;
37
- }, 10);
38
- }
39
-
40
- $: {
41
- if (show_options && refElement) {
42
- if (listElement && selected_indices.length > 0) {
43
- let elements = listElement.querySelectorAll("li");
44
- for (const element of Array.from(elements)) {
45
- if (
46
- element.getAttribute("data-index") ===
47
- selected_indices[0].toString()
48
- ) {
49
- listElement?.scrollTo?.(0, (element as HTMLLIElement).offsetTop);
50
- break;
51
- }
52
- }
53
- }
54
- calculate_window_distance();
55
- const rect = refElement.parentElement?.getBoundingClientRect();
56
- input_height = rect?.height || 0;
57
- input_width = rect?.width || 0;
58
- }
59
- if (distance_from_bottom > distance_from_top) {
60
- top = `${distance_from_top}px`;
61
- max_height = distance_from_bottom;
62
- bottom = null;
63
- } else {
64
- bottom = `${distance_from_bottom + input_height}px`;
65
- max_height = distance_from_top - input_height;
66
- top = null;
67
- }
68
- }
69
-
70
- const dispatch = createEventDispatcher();
71
- </script>
72
-
73
- <svelte:window on:scroll={scroll_listener} bind:innerHeight />
74
-
75
- <div class="reference" bind:this={refElement} />
76
- {#if show_options && !disabled}
77
- <ul
78
- class="options"
79
- transition:fly={{ duration: 200, y: 5 }}
80
- on:mousedown|preventDefault={(e) => dispatch("change", e)}
81
-
82
- style:bottom
83
- style:max-height={`calc(${max_height}px - var(--window-padding))`}
84
- style:width={input_width + "px"}
85
- bind:this={listElement}
86
- role="listbox"
87
- >
88
- {#each filtered_indices as index}
89
- <li
90
- class="item"
91
- class:selected={selected_indices.includes(index)}
92
- class:active={index === active_index}
93
- class:bg-gray-100={index === active_index}
94
- class:dark:bg-gray-600={index === active_index}
95
- data-index={index}
96
- aria-label={choices[index][0]}
97
- data-testid="dropdown-option"
98
- role="option"
99
- aria-selected={selected_indices.includes(index)}
100
- >
101
- <span class:hide={!selected_indices.includes(index)} class="inner-item">
102
-
103
- </span>
104
- {choices[index][0]}
105
- </li>
106
- {/each}
107
- </ul>
108
- {/if}
109
-
110
- <style>
111
- .options {
112
- --window-padding: var(--size-8);
113
- position: fixed;
114
- z-index: var(--layer-top);
115
- margin-left: 0;
116
- box-shadow: var(--shadow-drop-lg);
117
- border-radius: var(--container-radius);
118
- background: var(--background-fill-primary);
119
- min-width: fit-content;
120
- max-width: inherit;
121
- overflow: auto;
122
- color: var(--body-text-color);
123
- list-style: none;
124
- }
125
-
126
- .item {
127
- display: flex;
128
- cursor: pointer;
129
- padding: var(--size-2);
130
- }
131
-
132
- .item:hover,
133
- .active {
134
- background: var(--background-fill-secondary);
135
- }
136
-
137
- .inner-item {
138
- padding-right: var(--size-1);
139
- }
140
-
141
- .hide {
142
- visibility: hidden;
143
- }
144
- </style>
 
1
+ <script lang="ts">
2
+ import { fly } from "svelte/transition";
3
+ import { createEventDispatcher } from "svelte";
4
+ export let choices: [string, string | number][];
5
+ export let filtered_indices: number[];
6
+ export let show_options = false;
7
+ export let disabled = false;
8
+ export let selected_indices: (string | number)[] = [];
9
+ export let active_index: number | null = null;
10
+
11
+ let distance_from_top: number;
12
+ let distance_from_bottom: number;
13
+ let input_height: number;
14
+ let input_width: number;
15
+ let refElement: HTMLDivElement;
16
+ let listElement: HTMLUListElement;
17
+ let top: string | null, bottom: string | null, max_height: number;
18
+ let innerHeight: number;
19
+
20
+ function calculate_window_distance(): void {
21
+ const { top: ref_top, bottom: ref_bottom } =
22
+ refElement.getBoundingClientRect();
23
+ distance_from_top = ref_top;
24
+ distance_from_bottom = innerHeight - ref_bottom;
25
+ }
26
+
27
+ let scroll_timeout: NodeJS.Timeout | null = null;
28
+ function scroll_listener(): void {
29
+ if (!show_options) return;
30
+ if (scroll_timeout !== null) {
31
+ clearTimeout(scroll_timeout);
32
+ }
33
+
34
+ scroll_timeout = setTimeout(() => {
35
+ calculate_window_distance();
36
+ scroll_timeout = null;
37
+ }, 10);
38
+ }
39
+
40
+ $: {
41
+ if (show_options && refElement) {
42
+ if (listElement && selected_indices.length > 0) {
43
+ let elements = listElement.querySelectorAll("li");
44
+ for (const element of Array.from(elements)) {
45
+ if (
46
+ element.getAttribute("data-index") ===
47
+ selected_indices[0].toString()
48
+ ) {
49
+ listElement?.scrollTo?.(0, (element as HTMLLIElement).offsetTop);
50
+ break;
51
+ }
52
+ }
53
+ }
54
+ calculate_window_distance();
55
+ const rect = refElement.parentElement?.getBoundingClientRect();
56
+ input_height = rect?.height || 0;
57
+ input_width = rect?.width || 0;
58
+ }
59
+ if (distance_from_bottom > distance_from_top) {
60
+ top = `${distance_from_top}px`;
61
+ max_height = distance_from_bottom;
62
+ bottom = null;
63
+ } else {
64
+ bottom = `${distance_from_bottom + input_height}px`;
65
+ max_height = distance_from_top - input_height;
66
+ top = null;
67
+ }
68
+ }
69
+
70
+ const dispatch = createEventDispatcher();
71
+ </script>
72
+
73
+ <svelte:window on:scroll={scroll_listener} bind:innerHeight />
74
+
75
+ <div class="reference" bind:this={refElement} />
76
+ {#if show_options && !disabled}
77
+ <ul
78
+ class="options"
79
+ transition:fly={{ duration: 200, y: 5 }}
80
+ on:mousedown|preventDefault={(e) => dispatch("change", e)}
81
+
82
+ style:bottom
83
+ style:max-height={`calc(${max_height}px - var(--window-padding))`}
84
+ style:width={input_width + "px"}
85
+ bind:this={listElement}
86
+ role="listbox"
87
+ >
88
+ {#each filtered_indices as index}
89
+ <li
90
+ class="item"
91
+ class:selected={selected_indices.includes(index)}
92
+ class:active={index === active_index}
93
+ class:bg-gray-100={index === active_index}
94
+ class:dark:bg-gray-600={index === active_index}
95
+ data-index={index}
96
+ aria-label={choices[index][0]}
97
+ data-testid="dropdown-option"
98
+ role="option"
99
+ aria-selected={selected_indices.includes(index)}
100
+ >
101
+ <span class:hide={!selected_indices.includes(index)} class="inner-item">
102
+
103
+ </span>
104
+ {choices[index][0]}
105
+ </li>
106
+ {/each}
107
+ </ul>
108
+ {/if}
109
+
110
+ <style>
111
+ .options {
112
+ --window-padding: var(--size-8);
113
+ position: fixed;
114
+ z-index: var(--layer-top);
115
+ margin-left: 0;
116
+ box-shadow: var(--shadow-drop-lg);
117
+ border-radius: var(--container-radius);
118
+ background: var(--background-fill-primary);
119
+ min-width: fit-content;
120
+ max-width: inherit;
121
+ overflow: auto;
122
+ color: var(--body-text-color);
123
+ list-style: none;
124
+ }
125
+
126
+ .item {
127
+ display: flex;
128
+ cursor: pointer;
129
+ padding: var(--size-2);
130
+ }
131
+
132
+ .item:hover,
133
+ .active {
134
+ background: var(--background-fill-secondary);
135
+ }
136
+
137
+ .inner-item {
138
+ padding-right: var(--size-1);
139
+ }
140
+
141
+ .hide {
142
+ visibility: hidden;
143
+ }
144
+ </style>
src/frontend/shared/patched_dropdown/shared/Multiselect.svelte CHANGED
@@ -1,416 +1,416 @@
1
- <script lang="ts">
2
- import { afterUpdate, createEventDispatcher } from "svelte";
3
- import { _, number } from "svelte-i18n";
4
- import { BlockTitle } from "@gradio/atoms";
5
- import { Remove, DropdownArrow } from "@gradio/icons";
6
- import type { KeyUpData, SelectData, I18nFormatter } from "@gradio/utils";
7
- import DropdownOptions from "./DropdownOptions.svelte";
8
- import { handle_filter, handle_change, handle_shared_keys } from "./utils";
9
-
10
- export let label: string;
11
- export let info: string | undefined = undefined;
12
- export let value: string | number | (string | number)[] | undefined = [];
13
- let old_value: string | number | (string | number)[] | undefined = [];
14
- export let value_is_output = false;
15
- export let max_choices: number | null = null;
16
- export let choices: [string, string | number][];
17
- let old_choices: [string, string | number][];
18
- export let disabled = false;
19
- export let show_label: boolean;
20
- export let container = true;
21
- export let allow_custom_value = false;
22
- export let filterable = true;
23
- export let i18n: I18nFormatter;
24
-
25
- let filter_input: HTMLElement;
26
- let input_text = "";
27
- let old_input_text = "";
28
- let show_options = false;
29
- let choices_names: string[];
30
- let choices_values: (string | number)[];
31
-
32
- // All of these are indices with respect to the choices array
33
- let filtered_indices: number[] = [];
34
- let active_index: number | null = null;
35
- // selected_index consists of indices from choices or strings if allow_custom_value is true and user types in a custom value
36
- let selected_indices: (number | string)[] = [];
37
- let old_selected_index: (number | string)[] = [];
38
-
39
- const dispatch = createEventDispatcher<{
40
- change: string | string[] | undefined;
41
- input: undefined;
42
- select: SelectData;
43
- blur: undefined;
44
- focus: undefined;
45
- key_up: KeyUpData;
46
- }>();
47
-
48
- // Setting the initial value of the multiselect dropdown
49
- if (Array.isArray(value)) {
50
- value.forEach((element) => {
51
- const index = choices.map((c) => c[1]).indexOf(element);
52
- if (index !== -1) {
53
- selected_indices.push(index);
54
- } else {
55
- selected_indices.push(element);
56
- }
57
- });
58
- }
59
-
60
- $: {
61
- choices_names = choices.map((c) => c[0]);
62
- choices_values = choices.map((c) => c[1]);
63
- }
64
-
65
- $: {
66
- if (choices !== old_choices || input_text !== old_input_text) {
67
- filtered_indices = handle_filter(choices, input_text);
68
- old_choices = choices;
69
- old_input_text = input_text;
70
- if (!allow_custom_value) {
71
- active_index = filtered_indices[0];
72
- }
73
- }
74
- }
75
-
76
- $: {
77
- if (JSON.stringify(value) != JSON.stringify(old_value)) {
78
- handle_change(dispatch, value, value_is_output);
79
- old_value = Array.isArray(value) ? value.slice() : value;
80
- }
81
- }
82
-
83
- $: {
84
- if (
85
- JSON.stringify(selected_indices) != JSON.stringify(old_selected_index)
86
- ) {
87
- value = selected_indices.map((index) =>
88
- typeof index === "number" ? choices_values[index] : index
89
- );
90
- old_selected_index = selected_indices.slice();
91
- }
92
- }
93
-
94
- function handle_blur(): void {
95
- if (!allow_custom_value) {
96
- input_text = "";
97
- }
98
-
99
- if (allow_custom_value && input_text !== "") {
100
- add_selected_choice(input_text);
101
- input_text = "";
102
- }
103
-
104
- show_options = false;
105
- active_index = null;
106
- dispatch("blur");
107
- }
108
-
109
- function remove_selected_choice(option_index: number | string): void {
110
- selected_indices = selected_indices.filter((v) => v !== option_index);
111
- dispatch("select", {
112
- index: typeof option_index === "number" ? option_index : -1,
113
- value:
114
- typeof option_index === "number"
115
- ? choices_values[option_index]
116
- : option_index,
117
- selected: false
118
- });
119
- }
120
-
121
- function add_selected_choice(option_index: number | string): void {
122
- if (max_choices === null || selected_indices.length < max_choices) {
123
- selected_indices = [...selected_indices, option_index];
124
- dispatch("select", {
125
- index: typeof option_index === "number" ? option_index : -1,
126
- value:
127
- typeof option_index === "number"
128
- ? choices_values[option_index]
129
- : option_index,
130
- selected: true
131
- });
132
- }
133
- if (selected_indices.length === max_choices) {
134
- show_options = false;
135
- active_index = null;
136
- filter_input.blur();
137
- }
138
- }
139
-
140
- function handle_option_selected(e: any): void {
141
- const option_index = parseInt(e.detail.target.dataset.index);
142
- add_or_remove_index(option_index);
143
- }
144
-
145
- function add_or_remove_index(option_index: number): void {
146
- if (selected_indices.includes(option_index)) {
147
- remove_selected_choice(option_index);
148
- } else {
149
- add_selected_choice(option_index);
150
- }
151
- input_text = "";
152
- }
153
-
154
- function remove_all(e: any): void {
155
- selected_indices = [];
156
- input_text = "";
157
- e.preventDefault();
158
- }
159
-
160
- function handle_focus(e: FocusEvent): void {
161
- filtered_indices = choices.map((_, i) => i);
162
- if (max_choices === null || selected_indices.length < max_choices) {
163
- show_options = true;
164
- }
165
- dispatch("focus");
166
- }
167
-
168
- function handle_key_down(e: KeyboardEvent): void {
169
- [show_options, active_index] = handle_shared_keys(
170
- e,
171
- active_index,
172
- filtered_indices
173
- );
174
- if (e.key === "Enter") {
175
- if (active_index !== null) {
176
- add_or_remove_index(active_index);
177
- } else {
178
- if (allow_custom_value) {
179
- add_selected_choice(input_text);
180
- input_text = "";
181
- }
182
- }
183
- }
184
- if (e.key === "Backspace" && input_text === "") {
185
- selected_indices = [...selected_indices.slice(0, -1)];
186
- }
187
- if (selected_indices.length === max_choices) {
188
- show_options = false;
189
- active_index = null;
190
- }
191
- }
192
-
193
- function set_selected_indices(): void {
194
- if (value === undefined) {
195
- selected_indices = [];
196
- } else if (Array.isArray(value)) {
197
- selected_indices = value
198
- .map((v) => {
199
- const index = choices_values.indexOf(v);
200
- if (index !== -1) {
201
- return index;
202
- }
203
- if (allow_custom_value) {
204
- return v;
205
- }
206
- // Instead of returning null, skip this iteration
207
- return undefined;
208
- })
209
- .filter((val): val is string | number => val !== undefined);
210
- }
211
- }
212
-
213
- $: value, set_selected_indices();
214
-
215
- afterUpdate(() => {
216
- value_is_output = false;
217
- });
218
- </script>
219
-
220
- <label class:container>
221
- <BlockTitle {show_label} {info}>{label}</BlockTitle>
222
-
223
- <div class="wrap">
224
- <div class="wrap-inner" class:show_options>
225
- {#each selected_indices as s}
226
- <div class="token">
227
- <span>
228
- {#if typeof s === "number"}
229
- {choices_names[s]}
230
- {:else}
231
- {s}
232
- {/if}
233
- </span>
234
- {#if !disabled}
235
- <div
236
- class="token-remove"
237
- on:click|preventDefault={() => remove_selected_choice(s)}
238
- on:keydown|preventDefault={(event) => {
239
- if (event.key === "Enter") {
240
- remove_selected_choice(s);
241
- }
242
- }}
243
- role="button"
244
- tabindex="0"
245
- title={i18n("common.remove") + " " + s}
246
- >
247
- <Remove />
248
- </div>
249
- {/if}
250
- </div>
251
- {/each}
252
- <div class="secondary-wrap">
253
- <input
254
- class="border-none"
255
- class:subdued={(!choices_names.includes(input_text) &&
256
- !allow_custom_value) ||
257
- selected_indices.length === max_choices}
258
- {disabled}
259
- autocomplete="off"
260
- bind:value={input_text}
261
- bind:this={filter_input}
262
- on:keydown={handle_key_down}
263
- on:keyup={(e) =>
264
- dispatch("key_up", {
265
- key: e.key,
266
- input_value: input_text
267
- })}
268
- on:blur={handle_blur}
269
- on:focus={handle_focus}
270
- readonly={!filterable}
271
- />
272
-
273
- {#if !disabled}
274
- {#if selected_indices.length > 0}
275
- <div
276
- role="button"
277
- tabindex="0"
278
- class="token-remove remove-all"
279
- title={i18n("common.clear")}
280
- on:click={remove_all}
281
- on:keydown={(event) => {
282
- if (event.key === "Enter") {
283
- remove_all(event);
284
- }
285
- }}
286
- >
287
- <Remove />
288
- </div>
289
- {/if}
290
- <span class="icon-wrap"> <DropdownArrow /></span>
291
- {/if}
292
- </div>
293
- </div>
294
- <DropdownOptions
295
- {show_options}
296
- {choices}
297
- {filtered_indices}
298
- {disabled}
299
- {selected_indices}
300
- {active_index}
301
- on:change={handle_option_selected}
302
- />
303
- </div>
304
- </label>
305
-
306
- <style>
307
- .icon-wrap {
308
- color: var(--body-text-color);
309
- margin-right: var(--size-2);
310
- width: var(--size-5);
311
- }
312
- label:not(.container),
313
- label:not(.container) .wrap,
314
- label:not(.container) .wrap-inner,
315
- label:not(.container) .secondary-wrap,
316
- label:not(.container) .token,
317
- label:not(.container) input {
318
- height: 100%;
319
- }
320
- .container .wrap {
321
- box-shadow: var(--input-shadow);
322
- border: var(--input-border-width) solid var(--border-color-primary);
323
- }
324
-
325
- .wrap {
326
- position: relative;
327
- border-radius: var(--input-radius);
328
- background: var(--input-background-fill);
329
- }
330
-
331
- .wrap:focus-within {
332
- box-shadow: var(--input-shadow-focus);
333
- border-color: var(--input-border-color-focus);
334
- }
335
-
336
- .wrap-inner {
337
- display: flex;
338
- position: relative;
339
- flex-wrap: wrap;
340
- align-items: center;
341
- gap: var(--checkbox-label-gap);
342
- padding: var(--checkbox-label-padding);
343
- }
344
-
345
- .token {
346
- display: flex;
347
- align-items: center;
348
- transition: var(--button-transition);
349
- cursor: pointer;
350
- box-shadow: var(--checkbox-label-shadow);
351
- border: var(--checkbox-label-border-width) solid
352
- var(--checkbox-label-border-color);
353
- border-radius: var(--button-small-radius);
354
- background: var(--checkbox-label-background-fill);
355
- padding: var(--checkbox-label-padding);
356
- color: var(--checkbox-label-text-color);
357
- font-weight: var(--checkbox-label-text-weight);
358
- font-size: var(--checkbox-label-text-size);
359
- line-height: var(--line-md);
360
- }
361
-
362
- .token > * + * {
363
- margin-left: var(--size-2);
364
- }
365
-
366
- .token-remove {
367
- fill: var(--body-text-color);
368
- display: flex;
369
- justify-content: center;
370
- align-items: center;
371
- cursor: pointer;
372
- border: var(--checkbox-border-width) solid var(--border-color-primary);
373
- border-radius: var(--radius-full);
374
- background: var(--background-fill-primary);
375
- padding: var(--size-0-5);
376
- width: 16px;
377
- height: 16px;
378
- }
379
-
380
- .secondary-wrap {
381
- display: flex;
382
- flex: 1 1 0%;
383
- align-items: center;
384
- border: none;
385
- min-width: min-content;
386
- }
387
-
388
- input {
389
- margin: var(--spacing-sm);
390
- outline: none;
391
- border: none;
392
- background: inherit;
393
- width: var(--size-full);
394
- color: var(--body-text-color);
395
- font-size: var(--input-text-size);
396
- }
397
-
398
- input:disabled {
399
- -webkit-text-fill-color: var(--body-text-color);
400
- -webkit-opacity: 1;
401
- opacity: 1;
402
- cursor: not-allowed;
403
- }
404
-
405
- .remove-all {
406
- margin-left: var(--size-1);
407
- width: 20px;
408
- height: 20px;
409
- }
410
- .subdued {
411
- color: var(--body-text-color-subdued);
412
- }
413
- input[readonly] {
414
- cursor: pointer;
415
- }
416
- </style>
 
1
+ <script lang="ts">
2
+ import { afterUpdate, createEventDispatcher } from "svelte";
3
+ import { _, number } from "svelte-i18n";
4
+ import { BlockTitle } from "@gradio/atoms";
5
+ import { Remove, DropdownArrow } from "@gradio/icons";
6
+ import type { KeyUpData, SelectData, I18nFormatter } from "@gradio/utils";
7
+ import DropdownOptions from "./DropdownOptions.svelte";
8
+ import { handle_filter, handle_change, handle_shared_keys } from "./utils";
9
+
10
+ export let label: string;
11
+ export let info: string | undefined = undefined;
12
+ export let value: string | number | (string | number)[] | undefined = [];
13
+ let old_value: string | number | (string | number)[] | undefined = [];
14
+ export let value_is_output = false;
15
+ export let max_choices: number | null = null;
16
+ export let choices: [string, string | number][];
17
+ let old_choices: [string, string | number][];
18
+ export let disabled = false;
19
+ export let show_label: boolean;
20
+ export let container = true;
21
+ export let allow_custom_value = false;
22
+ export let filterable = true;
23
+ export let i18n: I18nFormatter;
24
+
25
+ let filter_input: HTMLElement;
26
+ let input_text = "";
27
+ let old_input_text = "";
28
+ let show_options = false;
29
+ let choices_names: string[];
30
+ let choices_values: (string | number)[];
31
+
32
+ // All of these are indices with respect to the choices array
33
+ let filtered_indices: number[] = [];
34
+ let active_index: number | null = null;
35
+ // selected_index consists of indices from choices or strings if allow_custom_value is true and user types in a custom value
36
+ let selected_indices: (number | string)[] = [];
37
+ let old_selected_index: (number | string)[] = [];
38
+
39
+ const dispatch = createEventDispatcher<{
40
+ change: string | string[] | undefined;
41
+ input: undefined;
42
+ select: SelectData;
43
+ blur: undefined;
44
+ focus: undefined;
45
+ key_up: KeyUpData;
46
+ }>();
47
+
48
+ // Setting the initial value of the multiselect dropdown
49
+ if (Array.isArray(value)) {
50
+ value.forEach((element) => {
51
+ const index = choices.map((c) => c[1]).indexOf(element);
52
+ if (index !== -1) {
53
+ selected_indices.push(index);
54
+ } else {
55
+ selected_indices.push(element);
56
+ }
57
+ });
58
+ }
59
+
60
+ $: {
61
+ choices_names = choices.map((c) => c[0]);
62
+ choices_values = choices.map((c) => c[1]);
63
+ }
64
+
65
+ $: {
66
+ if (choices !== old_choices || input_text !== old_input_text) {
67
+ filtered_indices = handle_filter(choices, input_text);
68
+ old_choices = choices;
69
+ old_input_text = input_text;
70
+ if (!allow_custom_value) {
71
+ active_index = filtered_indices[0];
72
+ }
73
+ }
74
+ }
75
+
76
+ $: {
77
+ if (JSON.stringify(value) != JSON.stringify(old_value)) {
78
+ handle_change(dispatch, value, value_is_output);
79
+ old_value = Array.isArray(value) ? value.slice() : value;
80
+ }
81
+ }
82
+
83
+ $: {
84
+ if (
85
+ JSON.stringify(selected_indices) != JSON.stringify(old_selected_index)
86
+ ) {
87
+ value = selected_indices.map((index) =>
88
+ typeof index === "number" ? choices_values[index] : index
89
+ );
90
+ old_selected_index = selected_indices.slice();
91
+ }
92
+ }
93
+
94
+ function handle_blur(): void {
95
+ if (!allow_custom_value) {
96
+ input_text = "";
97
+ }
98
+
99
+ if (allow_custom_value && input_text !== "") {
100
+ add_selected_choice(input_text);
101
+ input_text = "";
102
+ }
103
+
104
+ show_options = false;
105
+ active_index = null;
106
+ dispatch("blur");
107
+ }
108
+
109
+ function remove_selected_choice(option_index: number | string): void {
110
+ selected_indices = selected_indices.filter((v) => v !== option_index);
111
+ dispatch("select", {
112
+ index: typeof option_index === "number" ? option_index : -1,
113
+ value:
114
+ typeof option_index === "number"
115
+ ? choices_values[option_index]
116
+ : option_index,
117
+ selected: false
118
+ });
119
+ }
120
+
121
+ function add_selected_choice(option_index: number | string): void {
122
+ if (max_choices === null || selected_indices.length < max_choices) {
123
+ selected_indices = [...selected_indices, option_index];
124
+ dispatch("select", {
125
+ index: typeof option_index === "number" ? option_index : -1,
126
+ value:
127
+ typeof option_index === "number"
128
+ ? choices_values[option_index]
129
+ : option_index,
130
+ selected: true
131
+ });
132
+ }
133
+ if (selected_indices.length === max_choices) {
134
+ show_options = false;
135
+ active_index = null;
136
+ filter_input.blur();
137
+ }
138
+ }
139
+
140
+ function handle_option_selected(e: any): void {
141
+ const option_index = parseInt(e.detail.target.dataset.index);
142
+ add_or_remove_index(option_index);
143
+ }
144
+
145
+ function add_or_remove_index(option_index: number): void {
146
+ if (selected_indices.includes(option_index)) {
147
+ remove_selected_choice(option_index);
148
+ } else {
149
+ add_selected_choice(option_index);
150
+ }
151
+ input_text = "";
152
+ }
153
+
154
+ function remove_all(e: any): void {
155
+ selected_indices = [];
156
+ input_text = "";
157
+ e.preventDefault();
158
+ }
159
+
160
+ function handle_focus(e: FocusEvent): void {
161
+ filtered_indices = choices.map((_, i) => i);
162
+ if (max_choices === null || selected_indices.length < max_choices) {
163
+ show_options = true;
164
+ }
165
+ dispatch("focus");
166
+ }
167
+
168
+ function handle_key_down(e: KeyboardEvent): void {
169
+ [show_options, active_index] = handle_shared_keys(
170
+ e,
171
+ active_index,
172
+ filtered_indices
173
+ );
174
+ if (e.key === "Enter") {
175
+ if (active_index !== null) {
176
+ add_or_remove_index(active_index);
177
+ } else {
178
+ if (allow_custom_value) {
179
+ add_selected_choice(input_text);
180
+ input_text = "";
181
+ }
182
+ }
183
+ }
184
+ if (e.key === "Backspace" && input_text === "") {
185
+ selected_indices = [...selected_indices.slice(0, -1)];
186
+ }
187
+ if (selected_indices.length === max_choices) {
188
+ show_options = false;
189
+ active_index = null;
190
+ }
191
+ }
192
+
193
+ function set_selected_indices(): void {
194
+ if (value === undefined) {
195
+ selected_indices = [];
196
+ } else if (Array.isArray(value)) {
197
+ selected_indices = value
198
+ .map((v) => {
199
+ const index = choices_values.indexOf(v);
200
+ if (index !== -1) {
201
+ return index;
202
+ }
203
+ if (allow_custom_value) {
204
+ return v;
205
+ }
206
+ // Instead of returning null, skip this iteration
207
+ return undefined;
208
+ })
209
+ .filter((val): val is string | number => val !== undefined);
210
+ }
211
+ }
212
+
213
+ $: value, set_selected_indices();
214
+
215
+ afterUpdate(() => {
216
+ value_is_output = false;
217
+ });
218
+ </script>
219
+
220
+ <label class:container>
221
+ <BlockTitle {show_label} {info}>{label}</BlockTitle>
222
+
223
+ <div class="wrap">
224
+ <div class="wrap-inner" class:show_options>
225
+ {#each selected_indices as s}
226
+ <div class="token">
227
+ <span>
228
+ {#if typeof s === "number"}
229
+ {choices_names[s]}
230
+ {:else}
231
+ {s}
232
+ {/if}
233
+ </span>
234
+ {#if !disabled}
235
+ <div
236
+ class="token-remove"
237
+ on:click|preventDefault={() => remove_selected_choice(s)}
238
+ on:keydown|preventDefault={(event) => {
239
+ if (event.key === "Enter") {
240
+ remove_selected_choice(s);
241
+ }
242
+ }}
243
+ role="button"
244
+ tabindex="0"
245
+ title={i18n("common.remove") + " " + s}
246
+ >
247
+ <Remove />
248
+ </div>
249
+ {/if}
250
+ </div>
251
+ {/each}
252
+ <div class="secondary-wrap">
253
+ <input
254
+ class="border-none"
255
+ class:subdued={(!choices_names.includes(input_text) &&
256
+ !allow_custom_value) ||
257
+ selected_indices.length === max_choices}
258
+ {disabled}
259
+ autocomplete="off"
260
+ bind:value={input_text}
261
+ bind:this={filter_input}
262
+ on:keydown={handle_key_down}
263
+ on:keyup={(e) =>
264
+ dispatch("key_up", {
265
+ key: e.key,
266
+ input_value: input_text
267
+ })}
268
+ on:blur={handle_blur}
269
+ on:focus={handle_focus}
270
+ readonly={!filterable}
271
+ />
272
+
273
+ {#if !disabled}
274
+ {#if selected_indices.length > 0}
275
+ <div
276
+ role="button"
277
+ tabindex="0"
278
+ class="token-remove remove-all"
279
+ title={i18n("common.clear")}
280
+ on:click={remove_all}
281
+ on:keydown={(event) => {
282
+ if (event.key === "Enter") {
283
+ remove_all(event);
284
+ }
285
+ }}
286
+ >
287
+ <Remove />
288
+ </div>
289
+ {/if}
290
+ <span class="icon-wrap"> <DropdownArrow /></span>
291
+ {/if}
292
+ </div>
293
+ </div>
294
+ <DropdownOptions
295
+ {show_options}
296
+ {choices}
297
+ {filtered_indices}
298
+ {disabled}
299
+ {selected_indices}
300
+ {active_index}
301
+ on:change={handle_option_selected}
302
+ />
303
+ </div>
304
+ </label>
305
+
306
+ <style>
307
+ .icon-wrap {
308
+ color: var(--body-text-color);
309
+ margin-right: var(--size-2);
310
+ width: var(--size-5);
311
+ }
312
+ label:not(.container),
313
+ label:not(.container) .wrap,
314
+ label:not(.container) .wrap-inner,
315
+ label:not(.container) .secondary-wrap,
316
+ label:not(.container) .token,
317
+ label:not(.container) input {
318
+ height: 100%;
319
+ }
320
+ .container .wrap {
321
+ box-shadow: var(--input-shadow);
322
+ border: var(--input-border-width) solid var(--border-color-primary);
323
+ }
324
+
325
+ .wrap {
326
+ position: relative;
327
+ border-radius: var(--input-radius);
328
+ background: var(--input-background-fill);
329
+ }
330
+
331
+ .wrap:focus-within {
332
+ box-shadow: var(--input-shadow-focus);
333
+ border-color: var(--input-border-color-focus);
334
+ }
335
+
336
+ .wrap-inner {
337
+ display: flex;
338
+ position: relative;
339
+ flex-wrap: wrap;
340
+ align-items: center;
341
+ gap: var(--checkbox-label-gap);
342
+ padding: var(--checkbox-label-padding);
343
+ }
344
+
345
+ .token {
346
+ display: flex;
347
+ align-items: center;
348
+ transition: var(--button-transition);
349
+ cursor: pointer;
350
+ box-shadow: var(--checkbox-label-shadow);
351
+ border: var(--checkbox-label-border-width) solid
352
+ var(--checkbox-label-border-color);
353
+ border-radius: var(--button-small-radius);
354
+ background: var(--checkbox-label-background-fill);
355
+ padding: var(--checkbox-label-padding);
356
+ color: var(--checkbox-label-text-color);
357
+ font-weight: var(--checkbox-label-text-weight);
358
+ font-size: var(--checkbox-label-text-size);
359
+ line-height: var(--line-md);
360
+ }
361
+
362
+ .token > * + * {
363
+ margin-left: var(--size-2);
364
+ }
365
+
366
+ .token-remove {
367
+ fill: var(--body-text-color);
368
+ display: flex;
369
+ justify-content: center;
370
+ align-items: center;
371
+ cursor: pointer;
372
+ border: var(--checkbox-border-width) solid var(--border-color-primary);
373
+ border-radius: var(--radius-full);
374
+ background: var(--background-fill-primary);
375
+ padding: var(--size-0-5);
376
+ width: 16px;
377
+ height: 16px;
378
+ }
379
+
380
+ .secondary-wrap {
381
+ display: flex;
382
+ flex: 1 1 0%;
383
+ align-items: center;
384
+ border: none;
385
+ min-width: min-content;
386
+ }
387
+
388
+ input {
389
+ margin: var(--spacing-sm);
390
+ outline: none;
391
+ border: none;
392
+ background: inherit;
393
+ width: var(--size-full);
394
+ color: var(--body-text-color);
395
+ font-size: var(--input-text-size);
396
+ }
397
+
398
+ input:disabled {
399
+ -webkit-text-fill-color: var(--body-text-color);
400
+ -webkit-opacity: 1;
401
+ opacity: 1;
402
+ cursor: not-allowed;
403
+ }
404
+
405
+ .remove-all {
406
+ margin-left: var(--size-1);
407
+ width: 20px;
408
+ height: 20px;
409
+ }
410
+ .subdued {
411
+ color: var(--body-text-color-subdued);
412
+ }
413
+ input[readonly] {
414
+ cursor: pointer;
415
+ }
416
+ </style>
src/frontend/shared/patched_dropdown/shared/utils.ts CHANGED
@@ -1,56 +1,56 @@
1
- function positive_mod(n: number, m: number): number {
2
- return ((n % m) + m) % m;
3
- }
4
-
5
- export function handle_filter(
6
- choices: [string, string | number][],
7
- input_text: string
8
- ): number[] {
9
- return choices.reduce((filtered_indices, o, index) => {
10
- if (
11
- input_text ? o[0].toLowerCase().includes(input_text.toLowerCase()) : true
12
- ) {
13
- filtered_indices.push(index);
14
- }
15
- return filtered_indices;
16
- }, [] as number[]);
17
- }
18
-
19
- export function handle_change(
20
- dispatch: any,
21
- value: string | number | (string | number)[] | undefined,
22
- value_is_output: boolean
23
- ): void {
24
- dispatch("change", value);
25
- if (!value_is_output) {
26
- dispatch("input");
27
- }
28
- }
29
-
30
- export function handle_shared_keys(
31
- e: KeyboardEvent,
32
- active_index: number | null,
33
- filtered_indices: number[]
34
- ): [boolean, number | null] {
35
- if (e.key === "Escape") {
36
- return [false, active_index];
37
- }
38
- if (e.key === "ArrowDown" || e.key === "ArrowUp") {
39
- if (filtered_indices.length >= 0) {
40
- if (active_index === null) {
41
- active_index =
42
- e.key === "ArrowDown"
43
- ? filtered_indices[0]
44
- : filtered_indices[filtered_indices.length - 1];
45
- } else {
46
- const index_in_filtered = filtered_indices.indexOf(active_index);
47
- const increment = e.key === "ArrowUp" ? -1 : 1;
48
- active_index =
49
- filtered_indices[
50
- positive_mod(index_in_filtered + increment, filtered_indices.length)
51
- ];
52
- }
53
- }
54
- }
55
- return [true, active_index];
56
- }
 
1
+ function positive_mod(n: number, m: number): number {
2
+ return ((n % m) + m) % m;
3
+ }
4
+
5
+ export function handle_filter(
6
+ choices: [string, string | number][],
7
+ input_text: string
8
+ ): number[] {
9
+ return choices.reduce((filtered_indices, o, index) => {
10
+ if (
11
+ input_text ? o[0].toLowerCase().includes(input_text.toLowerCase()) : true
12
+ ) {
13
+ filtered_indices.push(index);
14
+ }
15
+ return filtered_indices;
16
+ }, [] as number[]);
17
+ }
18
+
19
+ export function handle_change(
20
+ dispatch: any,
21
+ value: string | number | (string | number)[] | undefined,
22
+ value_is_output: boolean
23
+ ): void {
24
+ dispatch("change", value);
25
+ if (!value_is_output) {
26
+ dispatch("input");
27
+ }
28
+ }
29
+
30
+ export function handle_shared_keys(
31
+ e: KeyboardEvent,
32
+ active_index: number | null,
33
+ filtered_indices: number[]
34
+ ): [boolean, number | null] {
35
+ if (e.key === "Escape") {
36
+ return [false, active_index];
37
+ }
38
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
39
+ if (filtered_indices.length >= 0) {
40
+ if (active_index === null) {
41
+ active_index =
42
+ e.key === "ArrowDown"
43
+ ? filtered_indices[0]
44
+ : filtered_indices[filtered_indices.length - 1];
45
+ } else {
46
+ const index_in_filtered = filtered_indices.indexOf(active_index);
47
+ const increment = e.key === "ArrowUp" ? -1 : 1;
48
+ active_index =
49
+ filtered_indices[
50
+ positive_mod(index_in_filtered + increment, filtered_indices.length)
51
+ ];
52
+ }
53
+ }
54
+ }
55
+ return [true, active_index];
56
+ }
src/frontend/shared/utils.ts CHANGED
@@ -1,29 +1,29 @@
1
- export const get_coordinates_of_clicked_image = (
2
- evt: MouseEvent
3
- ): [number, number] | null => {
4
- let image;
5
- if (evt.currentTarget instanceof Element) {
6
- image = evt.currentTarget.querySelector("img") as HTMLImageElement;
7
- } else {
8
- return [NaN, NaN];
9
- }
10
-
11
- const imageRect = image.getBoundingClientRect();
12
- const xScale = image.naturalWidth / imageRect.width;
13
- const yScale = image.naturalHeight / imageRect.height;
14
- if (xScale > yScale) {
15
- const displayed_height = image.naturalHeight / xScale;
16
- const y_offset = (imageRect.height - displayed_height) / 2;
17
- var x = Math.round((evt.clientX - imageRect.left) * xScale);
18
- var y = Math.round((evt.clientY - imageRect.top - y_offset) * xScale);
19
- } else {
20
- const displayed_width = image.naturalWidth / yScale;
21
- const x_offset = (imageRect.width - displayed_width) / 2;
22
- var x = Math.round((evt.clientX - imageRect.left - x_offset) * yScale);
23
- var y = Math.round((evt.clientY - imageRect.top) * yScale);
24
- }
25
- if (x < 0 || x >= image.naturalWidth || y < 0 || y >= image.naturalHeight) {
26
- return null;
27
- }
28
- return [x, y];
29
- };
 
1
+ export const get_coordinates_of_clicked_image = (
2
+ evt: MouseEvent
3
+ ): [number, number] | null => {
4
+ let image;
5
+ if (evt.currentTarget instanceof Element) {
6
+ image = evt.currentTarget.querySelector("img") as HTMLImageElement;
7
+ } else {
8
+ return [NaN, NaN];
9
+ }
10
+
11
+ const imageRect = image.getBoundingClientRect();
12
+ const xScale = image.naturalWidth / imageRect.width;
13
+ const yScale = image.naturalHeight / imageRect.height;
14
+ if (xScale > yScale) {
15
+ const displayed_height = image.naturalHeight / xScale;
16
+ const y_offset = (imageRect.height - displayed_height) / 2;
17
+ var x = Math.round((evt.clientX - imageRect.left) * xScale);
18
+ var y = Math.round((evt.clientY - imageRect.top - y_offset) * xScale);
19
+ } else {
20
+ const displayed_width = image.naturalWidth / yScale;
21
+ const x_offset = (imageRect.width - displayed_width) / 2;
22
+ var x = Math.round((evt.clientX - imageRect.left - x_offset) * yScale);
23
+ var y = Math.round((evt.clientY - imageRect.top) * yScale);
24
+ }
25
+ if (x < 0 || x >= image.naturalWidth || y < 0 || y >= image.naturalHeight) {
26
+ return null;
27
+ }
28
+ return [x, y];
29
+ };
src/package.json CHANGED
@@ -1,5 +1,5 @@
1
- {
2
- "devDependencies": {
3
- "@gradio/preview": "^0.9.0"
4
- }
5
- }
 
1
+ {
2
+ "devDependencies": {
3
+ "@gradio/preview": "^0.9.0"
4
+ }
5
+ }
src/pyproject.toml CHANGED
@@ -8,7 +8,7 @@ build-backend = "hatchling.build"
8
 
9
  [project]
10
  name = "gradio_image_annotation"
11
- version = "0.4.0"
12
  description = "A Gradio component that can be used to annotate images with bounding boxes."
13
  readme = "README.md"
14
  license = "MIT"
@@ -40,7 +40,7 @@ Issues = "https://github.com/edgarGracia/gradio_image_annotator/issues"
40
  dev = ["build", "twine"]
41
 
42
  [tool.hatch.build]
43
- artifacts = ["/backend/gradio_image_annotation/templates", "*.pyi", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates"]
44
 
45
  [tool.hatch.build.targets.wheel]
46
  packages = ["/backend/gradio_image_annotation"]
 
8
 
9
  [project]
10
  name = "gradio_image_annotation"
11
+ version = "0.4.1"
12
  description = "A Gradio component that can be used to annotate images with bounding boxes."
13
  readme = "README.md"
14
  license = "MIT"
 
40
  dev = ["build", "twine"]
41
 
42
  [tool.hatch.build]
43
+ artifacts = ["/backend/gradio_image_annotation/templates", "*.pyi", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "backend/gradio_image_annotation/templates", "/\\backend\\gradio_image_annotation\\templates"]
44
 
45
  [tool.hatch.build.targets.wheel]
46
  packages = ["/backend/gradio_image_annotation"]