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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
"""Included for backwards compatibility with 3.x spaces/apps."""
from __future__ import annotations

import json
import os
import secrets
import tempfile
import uuid
from pathlib import Path
from typing import Any

from gradio_client import media_data, utils
from gradio_client.data_classes import FileData

with open(Path(__file__).parent / "types.json") as f:
    serializer_types = json.load(f)


class Serializable:
    def serialized_info(self):
        """
        The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description].
        Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output
        """
        return self.api_info()

    def api_info(self) -> dict[str, list[str]]:
        """
        The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description].
        Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output
        """
        raise NotImplementedError()

    def example_inputs(self) -> dict[str, Any]:
        """
        The example inputs for this component as a dictionary whose values are example inputs compatible with this component.
        Keys of the dictionary are: raw, serialized
        """
        raise NotImplementedError()

    # For backwards compatibility
    def input_api_info(self) -> tuple[str, str]:
        api_info = self.api_info()
        types = api_info.get("serialized_input", [api_info["info"]["type"]] * 2)  # type: ignore
        return (types[0], types[1])

    # For backwards compatibility
    def output_api_info(self) -> tuple[str, str]:
        api_info = self.api_info()
        types = api_info.get("serialized_output", [api_info["info"]["type"]] * 2)  # type: ignore
        return (types[0], types[1])

    def serialize(self, x: Any, load_dir: str | Path = "", allow_links: bool = False):
        """
        Convert data from human-readable format to serialized format for a browser.
        """
        return x

    def deserialize(
        self,
        x: Any,
        save_dir: str | Path | None = None,
        root_url: str | None = None,
        hf_token: str | None = None,
    ):
        """
        Convert data from serialized format for a browser to human-readable format.
        """
        return x


class SimpleSerializable(Serializable):
    """General class that does not perform any serialization or deserialization."""

    def api_info(self) -> dict[str, bool | dict]:
        return {
            "info": serializer_types["SimpleSerializable"],
            "serialized_info": False,
        }

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": None,
            "serialized": None,
        }


class StringSerializable(Serializable):
    """Expects a string as input/output but performs no serialization."""

    def api_info(self) -> dict[str, bool | dict]:
        return {
            "info": serializer_types["StringSerializable"],
            "serialized_info": False,
        }

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": "Howdy!",
            "serialized": "Howdy!",
        }


class ListStringSerializable(Serializable):
    """Expects a list of strings as input/output but performs no serialization."""

    def api_info(self) -> dict[str, bool | dict]:
        return {
            "info": serializer_types["ListStringSerializable"],
            "serialized_info": False,
        }

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": ["Howdy!", "Merhaba"],
            "serialized": ["Howdy!", "Merhaba"],
        }


class BooleanSerializable(Serializable):
    """Expects a boolean as input/output but performs no serialization."""

    def api_info(self) -> dict[str, bool | dict]:
        return {
            "info": serializer_types["BooleanSerializable"],
            "serialized_info": False,
        }

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": True,
            "serialized": True,
        }


class NumberSerializable(Serializable):
    """Expects a number (int/float) as input/output but performs no serialization."""

    def api_info(self) -> dict[str, bool | dict]:
        return {
            "info": serializer_types["NumberSerializable"],
            "serialized_info": False,
        }

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": 5,
            "serialized": 5,
        }


class ImgSerializable(Serializable):
    """Expects a base64 string as input/output which is serialized to a filepath."""

    def serialized_info(self):
        return {
            "type": "string",
            "description": "filepath on your computer (or URL) of image",
        }

    def api_info(self) -> dict[str, bool | dict]:
        return {"info": serializer_types["ImgSerializable"], "serialized_info": True}

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": media_data.BASE64_IMAGE,
            "serialized": "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png",
        }

    def serialize(
        self,
        x: str | None,
        load_dir: str | Path = "",
        allow_links: bool = False,
    ) -> str | None:
        """
        Convert from human-friendly version of a file (string filepath) to a serialized
        representation (base64).
        Parameters:
            x: String path to file to serialize
            load_dir: Path to directory containing x
        """
        if not x:
            return None
        if utils.is_http_url_like(x):
            return utils.encode_url_to_base64(x)
        return utils.encode_file_to_base64(Path(load_dir) / x)

    def deserialize(
        self,
        x: str | None,
        save_dir: str | Path | None = None,
        root_url: str | None = None,
        hf_token: str | None = None,
    ) -> str | None:
        """
        Convert from serialized representation of a file (base64) to a human-friendly
        version (string filepath). Optionally, save the file to the directory specified by save_dir
        Parameters:
            x: Base64 representation of image to deserialize into a string filepath
            save_dir: Path to directory to save the deserialized image to
            root_url: Ignored
            hf_token: Ignored
        """
        if x is None or x == "":
            return None
        file = utils.decode_base64_to_file(x, dir=save_dir)
        return file.name


class FileSerializable(Serializable):
    """Expects a dict with base64 representation of object as input/output which is serialized to a filepath."""

    def __init__(self) -> None:
        self.stream = None
        self.stream_name = None
        super().__init__()

    def serialized_info(self):
        return self._single_file_serialized_info()

    def _single_file_api_info(self):
        return {
            "info": serializer_types["SingleFileSerializable"],
            "serialized_info": True,
        }

    def _single_file_serialized_info(self):
        return {
            "type": "string",
            "description": "filepath on your computer (or URL) of file",
        }

    def _multiple_file_serialized_info(self):
        return {
            "type": "array",
            "description": "List of filepath(s) or URL(s) to files",
            "items": {
                "type": "string",
                "description": "filepath on your computer (or URL) of file",
            },
        }

    def _multiple_file_api_info(self):
        return {
            "info": serializer_types["MultipleFileSerializable"],
            "serialized_info": True,
        }

    def api_info(self) -> dict[str, dict | bool]:
        return self._single_file_api_info()

    def example_inputs(self) -> dict[str, Any]:
        return self._single_file_example_inputs()

    def _single_file_example_inputs(self) -> dict[str, Any]:
        return {
            "raw": {"is_file": False, "data": media_data.BASE64_FILE},
            "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf",
        }

    def _multiple_file_example_inputs(self) -> dict[str, Any]:
        return {
            "raw": [{"is_file": False, "data": media_data.BASE64_FILE}],
            "serialized": [
                "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf"
            ],
        }

    def _serialize_single(
        self,
        x: str | FileData | None,
        load_dir: str | Path = "",
        allow_links: bool = False,
    ) -> FileData | None:
        if x is None or isinstance(x, dict):
            return x
        if utils.is_http_url_like(x):
            filename = x
            size = None
        else:
            filename = str(Path(load_dir) / x)
            size = Path(filename).stat().st_size
        return {
            "name": filename or None,
            "data": None
            if allow_links
            else utils.encode_url_or_file_to_base64(filename),
            "orig_name": Path(filename).name,
            "size": size,
        }

    def _setup_stream(self, url, hf_token):
        return utils.download_byte_stream(url, hf_token)

    def _deserialize_single(
        self,
        x: str | FileData | None,
        save_dir: str | None = None,
        root_url: str | None = None,
        hf_token: str | None = None,
    ) -> str | None:
        if x is None:
            return None
        if isinstance(x, str):
            file_name = utils.decode_base64_to_file(x, dir=save_dir).name
        elif isinstance(x, dict):
            if x.get("is_file"):
                filepath = x.get("name")
                if filepath is None:
                    raise ValueError(f"The 'name' field is missing in {x}")
                if root_url is not None:
                    file_name = utils.download_tmp_copy_of_file(
                        root_url + "file=" + filepath,
                        hf_token=hf_token,
                        dir=save_dir,
                    )
                else:
                    file_name = utils.create_tmp_copy_of_file(filepath, dir=save_dir)
            elif x.get("is_stream"):
                assert x["name"] and root_url and save_dir
                if not self.stream or self.stream_name != x["name"]:
                    self.stream = self._setup_stream(
                        root_url + "stream/" + x["name"], hf_token=hf_token
                    )
                    self.stream_name = x["name"]
                chunk = next(self.stream)
                path = Path(save_dir or tempfile.gettempdir()) / secrets.token_hex(20)
                path.mkdir(parents=True, exist_ok=True)
                path = path / x.get("orig_name", "output")
                path.write_bytes(chunk)
                file_name = str(path)
            else:
                data = x.get("data")
                if data is None:
                    raise ValueError(f"The 'data' field is missing in {x}")
                file_name = utils.decode_base64_to_file(data, dir=save_dir).name
        else:
            raise ValueError(
                f"A FileSerializable component can only deserialize a string or a dict, not a {type(x)}: {x}"
            )
        return file_name

    def serialize(
        self,
        x: str | FileData | None | list[str | FileData | None],
        load_dir: str | Path = "",
        allow_links: bool = False,
    ) -> FileData | None | list[FileData | None]:
        """
        Convert from human-friendly version of a file (string filepath) to a
        serialized representation (base64)
        Parameters:
            x: String path to file to serialize
            load_dir: Path to directory containing x
            allow_links: Will allow path returns instead of raw file content
        """
        if x is None or x == "":
            return None
        if isinstance(x, list):
            return [self._serialize_single(f, load_dir, allow_links) for f in x]
        else:
            return self._serialize_single(x, load_dir, allow_links)

    def deserialize(
        self,
        x: str | FileData | None | list[str | FileData | None],
        save_dir: Path | str | None = None,
        root_url: str | None = None,
        hf_token: str | None = None,
    ) -> str | None | list[str | None]:
        """
        Convert from serialized representation of a file (base64) to a human-friendly
        version (string filepath). Optionally, save the file to the directory specified by `save_dir`
        Parameters:
            x: Base64 representation of file to deserialize into a string filepath
            save_dir: Path to directory to save the deserialized file to
            root_url: If this component is loaded from an external Space, this is the URL of the Space.
            hf_token: If this component is loaded from an external private Space, this is the access token for the Space
        """
        if x is None:
            return None
        if isinstance(save_dir, Path):
            save_dir = str(save_dir)
        if isinstance(x, list):
            return [
                self._deserialize_single(
                    f, save_dir=save_dir, root_url=root_url, hf_token=hf_token
                )
                for f in x
            ]
        else:
            return self._deserialize_single(
                x, save_dir=save_dir, root_url=root_url, hf_token=hf_token
            )


class VideoSerializable(FileSerializable):
    def serialized_info(self):
        return {
            "type": "string",
            "description": "filepath on your computer (or URL) of video file",
        }

    def api_info(self) -> dict[str, dict | bool]:
        return {"info": serializer_types["FileSerializable"], "serialized_info": True}

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": {"is_file": False, "data": media_data.BASE64_VIDEO},
            "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/video_sample.mp4",
        }

    def serialize(
        self, x: str | None, load_dir: str | Path = "", allow_links: bool = False
    ) -> tuple[FileData | None, None]:
        return (super().serialize(x, load_dir, allow_links), None)  # type: ignore

    def deserialize(
        self,
        x: tuple[FileData | None, FileData | None] | None,
        save_dir: Path | str | None = None,
        root_url: str | None = None,
        hf_token: str | None = None,
    ) -> str | tuple[str | None, str | None] | None:
        """
        Convert from serialized representation of a file (base64) to a human-friendly
        version (string filepath). Optionally, save the file to the directory specified by `save_dir`
        """
        if isinstance(x, (tuple, list)):
            if len(x) != 2:
                raise ValueError(f"Expected tuple of length 2. Received: {x}")
            x_as_list = [x[0], x[1]]
        else:
            raise ValueError(f"Expected tuple of length 2. Received: {x}")
        deserialized_file = super().deserialize(x_as_list, save_dir, root_url, hf_token)  # type: ignore
        if isinstance(deserialized_file, list):
            return deserialized_file[0]  # ignore subtitles


class JSONSerializable(Serializable):
    def serialized_info(self):
        return {"type": "string", "description": "filepath to JSON file"}

    def api_info(self) -> dict[str, dict | bool]:
        return {"info": serializer_types["JSONSerializable"], "serialized_info": True}

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": {"a": 1, "b": 2},
            "serialized": None,
        }

    def serialize(
        self,
        x: str | None,
        load_dir: str | Path = "",
        allow_links: bool = False,
    ) -> dict | list | None:
        """
        Convert from a a human-friendly version (string path to json file) to a
        serialized representation (json string)
        Parameters:
            x: String path to json file to read to get json string
            load_dir: Path to directory containing x
        """
        if x is None or x == "":
            return None
        return utils.file_to_json(Path(load_dir) / x)

    def deserialize(
        self,
        x: str | dict | list,
        save_dir: str | Path | None = None,
        root_url: str | None = None,
        hf_token: str | None = None,
    ) -> str | None:
        """
        Convert from serialized representation (json string) to a human-friendly
        version (string path to json file).  Optionally, save the file to the directory specified by `save_dir`
        Parameters:
            x: Json string
            save_dir: Path to save the deserialized json file to
            root_url: Ignored
            hf_token: Ignored
        """
        if x is None:
            return None
        return utils.dict_or_str_to_json_file(x, dir=save_dir).name


class GallerySerializable(Serializable):
    def serialized_info(self):
        return {
            "type": "string",
            "description": "path to directory with images and a file associating images with captions called captions.json",
        }

    def api_info(self) -> dict[str, dict | bool]:
        return {
            "info": serializer_types["GallerySerializable"],
            "serialized_info": True,
        }

    def example_inputs(self) -> dict[str, Any]:
        return {
            "raw": [media_data.BASE64_IMAGE] * 2,
            "serialized": [
                "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png",
            ]
            * 2,
        }

    def serialize(
        self, x: str | None, load_dir: str | Path = "", allow_links: bool = False
    ) -> list[list[str | None]] | None:
        if x is None or x == "":
            return None
        files = []
        captions_file = Path(x) / "captions.json"
        with captions_file.open("r") as captions_json:
            captions = json.load(captions_json)
        for file_name, caption in captions.items():
            img = FileSerializable().serialize(file_name, allow_links=allow_links)
            files.append([img, caption])
        return files

    def deserialize(
        self,
        x: list[list[str | None]] | None,
        save_dir: str = "",
        root_url: str | None = None,
        hf_token: str | None = None,
    ) -> None | str:
        if x is None:
            return None
        gallery_path = Path(save_dir) / str(uuid.uuid4())
        gallery_path.mkdir(exist_ok=True, parents=True)
        captions = {}
        for img_data in x:
            if isinstance(img_data, (list, tuple)):
                img_data, caption = img_data
            else:
                caption = None
            name = FileSerializable().deserialize(
                img_data, gallery_path, root_url=root_url, hf_token=hf_token
            )
            captions[name] = caption
            captions_file = gallery_path / "captions.json"
            with captions_file.open("w") as captions_json:
                json.dump(captions, captions_json)
        return os.path.abspath(gallery_path)


SERIALIZER_MAPPING = {}
for cls in Serializable.__subclasses__():
    SERIALIZER_MAPPING[cls.__name__] = cls
    for subcls in cls.__subclasses__():
        SERIALIZER_MAPPING[subcls.__name__] = subcls

SERIALIZER_MAPPING["Serializable"] = SimpleSerializable
SERIALIZER_MAPPING["File"] = FileSerializable
SERIALIZER_MAPPING["UploadButton"] = FileSerializable

COMPONENT_MAPPING: dict[str, type] = {
    "textbox": StringSerializable,
    "number": NumberSerializable,
    "slider": NumberSerializable,
    "checkbox": BooleanSerializable,
    "checkboxgroup": ListStringSerializable,
    "radio": StringSerializable,
    "dropdown": SimpleSerializable,
    "image": ImgSerializable,
    "video": FileSerializable,
    "audio": FileSerializable,
    "file": FileSerializable,
    "dataframe": JSONSerializable,
    "timeseries": JSONSerializable,
    "fileexplorer": JSONSerializable,
    "state": SimpleSerializable,
    "button": StringSerializable,
    "uploadbutton": FileSerializable,
    "colorpicker": StringSerializable,
    "label": JSONSerializable,
    "highlightedtext": JSONSerializable,
    "json": JSONSerializable,
    "html": StringSerializable,
    "gallery": GallerySerializable,
    "chatbot": JSONSerializable,
    "model3d": FileSerializable,
    "plot": JSONSerializable,
    "barplot": JSONSerializable,
    "lineplot": JSONSerializable,
    "scatterplot": JSONSerializable,
    "markdown": StringSerializable,
    "code": StringSerializable,
    "annotatedimage": JSONSerializable,
}