diff --git a/lib/python3.11/site-packages/gradio/_vendor/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..359159433684a00a7420691eae3dc1f05afff03e Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__init__.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f62158ed47f905112bb2f594ba4de7e711551e8 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__init__.py @@ -0,0 +1,23 @@ +"""Utilities for asyncio-friendly file handling.""" + +from . import tempfile +from .threadpool import ( + open, + stderr, + stderr_bytes, + stdin, + stdin_bytes, + stdout, + stdout_bytes, +) + +__all__ = [ + "open", + "tempfile", + "stdin", + "stdout", + "stderr", + "stdin_bytes", + "stdout_bytes", + "stderr_bytes", +] diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..883872d205493ba3ffa93a4efc2a9298b4db7642 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/base.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..192e492516b7fed67202fd8da82d743d3aec1dfb Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/base.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/os.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/os.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b7164174aa0b54e23e33812ddb7edab910bb32 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/os.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/ospath.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/ospath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4df19ad0253e7f6bc307188439cbc480789c7e75 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/__pycache__/ospath.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/base.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/base.py new file mode 100644 index 0000000000000000000000000000000000000000..178bd21a2ecfe96d83f8fc8161bf3413b97bd559 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/base.py @@ -0,0 +1,70 @@ +"""Various base classes.""" + +from asyncio import get_running_loop +from collections.abc import Awaitable +from contextlib import AbstractAsyncContextManager + + +class AsyncBase: + def __init__(self, file, loop, executor): + self._file = file + self._executor = executor + self._ref_loop = loop + + @property + def _loop(self): + return self._ref_loop or get_running_loop() + + def __aiter__(self): + """We are our own iterator.""" + return self + + def __repr__(self): + return super().__repr__() + " wrapping " + repr(self._file) + + async def __anext__(self): + """Simulate normal file iteration.""" + line = await self.readline() + if line: + return line + else: + raise StopAsyncIteration + + +class AsyncIndirectBase(AsyncBase): + def __init__(self, name, loop, executor, indirect): + self._indirect = indirect + self._name = name + super().__init__(None, loop, executor) + + @property + def _file(self): + return self._indirect() + + @_file.setter + def _file(self, v): + pass # discard writes + + +class AiofilesContextManager(Awaitable, AbstractAsyncContextManager): + """An adjusted async context manager for aiofiles.""" + + __slots__ = ("_coro", "_obj") + + def __init__(self, coro): + self._coro = coro + self._obj = None + + def __await__(self): + if self._obj is None: + self._obj = yield from self._coro.__await__() + return self._obj + + async def __aenter__(self): + return await self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await get_running_loop().run_in_executor( + None, self._obj._file.__exit__, exc_type, exc_val, exc_tb + ) + self._obj = None diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/os.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/os.py new file mode 100644 index 0000000000000000000000000000000000000000..92243fa4d7e01174616d319cfa8fb79bc5a51986 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/os.py @@ -0,0 +1,58 @@ +"""Async executor versions of file functions from the os module.""" + +import os + +from . import ospath as path +from .ospath import wrap + +__all__ = [ + "path", + "stat", + "rename", + "renames", + "replace", + "remove", + "unlink", + "mkdir", + "makedirs", + "rmdir", + "removedirs", + "symlink", + "readlink", + "listdir", + "scandir", + "access", + "wrap", + "getcwd", +] +if hasattr(os, "link"): + __all__ += ["link"] +if hasattr(os, "sendfile"): + __all__ += ["sendfile"] +if hasattr(os, "statvfs"): + __all__ += ["statvfs"] + + +stat = wrap(os.stat) +rename = wrap(os.rename) +renames = wrap(os.renames) +replace = wrap(os.replace) +remove = wrap(os.remove) +unlink = wrap(os.unlink) +mkdir = wrap(os.mkdir) +makedirs = wrap(os.makedirs) +rmdir = wrap(os.rmdir) +removedirs = wrap(os.removedirs) +symlink = wrap(os.symlink) +readlink = wrap(os.readlink) +listdir = wrap(os.listdir) +scandir = wrap(os.scandir) +access = wrap(os.access) +getcwd = wrap(os.getcwd) + +if hasattr(os, "link"): + link = wrap(os.link) +if hasattr(os, "sendfile"): + sendfile = wrap(os.sendfile) +if hasattr(os, "statvfs"): + statvfs = wrap(os.statvfs) diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/ospath.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/ospath.py new file mode 100644 index 0000000000000000000000000000000000000000..387d68d57197365217902c8768d865ca9d18bdf4 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/ospath.py @@ -0,0 +1,30 @@ +"""Async executor versions of file functions from the os.path module.""" + +import asyncio +from functools import partial, wraps +from os import path + + +def wrap(func): + @wraps(func) + async def run(*args, loop=None, executor=None, **kwargs): + if loop is None: + loop = asyncio.get_running_loop() + pfunc = partial(func, *args, **kwargs) + return await loop.run_in_executor(executor, pfunc) + + return run + + +exists = wrap(path.exists) +isfile = wrap(path.isfile) +isdir = wrap(path.isdir) +islink = wrap(path.islink) +ismount = wrap(path.ismount) +getsize = wrap(path.getsize) +getmtime = wrap(path.getmtime) +getatime = wrap(path.getatime) +getctime = wrap(path.getctime) +samefile = wrap(path.samefile) +sameopenfile = wrap(path.sameopenfile) +abspath = wrap(path.abspath) diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__init__.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c0db0af88f7906aaf32f644689151ad639fcef --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__init__.py @@ -0,0 +1,357 @@ +import asyncio +import sys +from functools import partial, singledispatch +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOBase +from tempfile import NamedTemporaryFile as syncNamedTemporaryFile +from tempfile import SpooledTemporaryFile as syncSpooledTemporaryFile +from tempfile import TemporaryDirectory as syncTemporaryDirectory +from tempfile import TemporaryFile as syncTemporaryFile +from tempfile import _TemporaryFileWrapper as syncTemporaryFileWrapper + +from ..base import AiofilesContextManager +from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO +from ..threadpool.text import AsyncTextIOWrapper +from .temptypes import AsyncSpooledTemporaryFile, AsyncTemporaryDirectory + +__all__ = [ + "NamedTemporaryFile", + "TemporaryFile", + "SpooledTemporaryFile", + "TemporaryDirectory", +] + + +# ================================================================ +# Public methods for async open and return of temp file/directory +# objects with async interface +# ================================================================ +if sys.version_info >= (3, 12): + + def NamedTemporaryFile( + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + delete_on_close=True, + loop=None, + executor=None, + ): + """Async open a named temporary file""" + return AiofilesContextManager( + _temporary_file( + named=True, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + delete_on_close=delete_on_close, + loop=loop, + executor=executor, + ) + ) + +else: + + def NamedTemporaryFile( + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + loop=None, + executor=None, + ): + """Async open a named temporary file""" + return AiofilesContextManager( + _temporary_file( + named=True, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + loop=loop, + executor=executor, + ) + ) + + +def TemporaryFile( + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + loop=None, + executor=None, +): + """Async open an unnamed temporary file""" + return AiofilesContextManager( + _temporary_file( + named=False, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + loop=loop, + executor=executor, + ) + ) + + +def SpooledTemporaryFile( + max_size=0, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + loop=None, + executor=None, +): + """Async open a spooled temporary file""" + return AiofilesContextManager( + _spooled_temporary_file( + max_size=max_size, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + loop=loop, + executor=executor, + ) + ) + + +def TemporaryDirectory(suffix=None, prefix=None, dir=None, loop=None, executor=None): + """Async open a temporary directory""" + return AiofilesContextManagerTempDir( + _temporary_directory( + suffix=suffix, prefix=prefix, dir=dir, loop=loop, executor=executor + ) + ) + + +# ========================================================= +# Internal coroutines to open new temp files/directories +# ========================================================= +if sys.version_info >= (3, 12): + + async def _temporary_file( + named=True, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + delete_on_close=True, + loop=None, + executor=None, + max_size=0, + ): + """Async method to open a temporary file with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + if named: + cb = partial( + syncNamedTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + delete_on_close=delete_on_close, + ) + else: + cb = partial( + syncTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + ) + + f = await loop.run_in_executor(executor, cb) + + # Wrap based on type of underlying IO object + if type(f) is syncTemporaryFileWrapper: + # _TemporaryFileWrapper was used (named files) + result = wrap(f.file, f, loop=loop, executor=executor) + result._closer = f._closer + return result + else: + # IO object was returned directly without wrapper + return wrap(f, f, loop=loop, executor=executor) + +else: + + async def _temporary_file( + named=True, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + loop=None, + executor=None, + max_size=0, + ): + """Async method to open a temporary file with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + if named: + cb = partial( + syncNamedTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + ) + else: + cb = partial( + syncTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + ) + + f = await loop.run_in_executor(executor, cb) + + # Wrap based on type of underlying IO object + if type(f) is syncTemporaryFileWrapper: + # _TemporaryFileWrapper was used (named files) + result = wrap(f.file, f, loop=loop, executor=executor) + # add delete property + result.delete = f.delete + return result + else: + # IO object was returned directly without wrapper + return wrap(f, f, loop=loop, executor=executor) + + +async def _spooled_temporary_file( + max_size=0, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + loop=None, + executor=None, +): + """Open a spooled temporary file with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + cb = partial( + syncSpooledTemporaryFile, + max_size=max_size, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + ) + + f = await loop.run_in_executor(executor, cb) + + # Single interface provided by SpooledTemporaryFile for all modes + return AsyncSpooledTemporaryFile(f, loop=loop, executor=executor) + + +async def _temporary_directory( + suffix=None, prefix=None, dir=None, loop=None, executor=None +): + """Async method to open a temporary directory with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + cb = partial(syncTemporaryDirectory, suffix, prefix, dir) + f = await loop.run_in_executor(executor, cb) + + return AsyncTemporaryDirectory(f, loop=loop, executor=executor) + + +class AiofilesContextManagerTempDir(AiofilesContextManager): + """With returns the directory location, not the object (matching sync lib)""" + + async def __aenter__(self): + self._obj = await self._coro + return self._obj.name + + +@singledispatch +def wrap(base_io_obj, file, *, loop=None, executor=None): + """Wrap the object with interface based on type of underlying IO""" + raise TypeError(f"Unsupported IO type: {base_io_obj}") + + +@wrap.register(TextIOBase) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncTextIOWrapper(file, loop=loop, executor=executor) + + +@wrap.register(BufferedWriter) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncBufferedIOBase(file, loop=loop, executor=executor) + + +@wrap.register(BufferedReader) +@wrap.register(BufferedRandom) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncBufferedReader(file, loop=loop, executor=executor) + + +@wrap.register(FileIO) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncFileIO(file, loop=loop, executor=executor) diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80af3aaed0b8075f43d4bfa2732df930d25218dd Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13b87eff17d6fb5e4e5d58ebaef605fe264dcbfa Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/temptypes.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/temptypes.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d29ca8bc269ca38dcbe2999d43aefa2cf66e86 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/tempfile/temptypes.py @@ -0,0 +1,70 @@ +"""Async wrappers for spooled temp files and temp directory objects""" + +from functools import partial + +from ..base import AsyncBase +from ..threadpool.utils import ( + cond_delegate_to_executor, + delegate_to_executor, + proxy_property_directly, +) + + +@delegate_to_executor("fileno", "rollover") +@cond_delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readline", + "readlines", + "seek", + "tell", + "truncate", +) +@proxy_property_directly("closed", "encoding", "mode", "name", "newlines") +class AsyncSpooledTemporaryFile(AsyncBase): + """Async wrapper for SpooledTemporaryFile class""" + + async def _check(self): + if self._file._rolled: + return + max_size = self._file._max_size + if max_size and self._file.tell() > max_size: + await self.rollover() + + async def write(self, s): + """Implementation to anticipate rollover""" + if self._file._rolled: + cb = partial(self._file.write, s) + return await self._loop.run_in_executor(self._executor, cb) + else: + file = self._file._file # reference underlying base IO object + rv = file.write(s) + await self._check() + return rv + + async def writelines(self, iterable): + """Implementation to anticipate rollover""" + if self._file._rolled: + cb = partial(self._file.writelines, iterable) + return await self._loop.run_in_executor(self._executor, cb) + else: + file = self._file._file # reference underlying base IO object + rv = file.writelines(iterable) + await self._check() + return rv + + +@delegate_to_executor("cleanup") +@proxy_property_directly("name") +class AsyncTemporaryDirectory: + """Async wrapper for TemporaryDirectory class""" + + def __init__(self, file, loop, executor): + self._file = file + self._loop = loop + self._executor = executor + + async def close(self): + await self.cleanup() diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__init__.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebbc480d4a69eb31ea3d105b8607f5ab2b6ec8a --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__init__.py @@ -0,0 +1,140 @@ +"""Handle files using a thread pool executor.""" + +import asyncio +import sys +from functools import partial, singledispatch +from io import ( + BufferedIOBase, + BufferedRandom, + BufferedReader, + BufferedWriter, + FileIO, + TextIOBase, +) + +from ..base import AiofilesContextManager +from .binary import ( + AsyncBufferedIOBase, + AsyncBufferedReader, + AsyncFileIO, + AsyncIndirectBufferedIOBase, +) +from .text import AsyncTextIndirectIOWrapper, AsyncTextIOWrapper + +sync_open = open + +__all__ = ( + "open", + "stdin", + "stdout", + "stderr", + "stdin_bytes", + "stdout_bytes", + "stderr_bytes", +) + + +def open( + file, + mode="r", + buffering=-1, + encoding=None, + errors=None, + newline=None, + closefd=True, + opener=None, + *, + loop=None, + executor=None, +): + return AiofilesContextManager( + _open( + file, + mode=mode, + buffering=buffering, + encoding=encoding, + errors=errors, + newline=newline, + closefd=closefd, + opener=opener, + loop=loop, + executor=executor, + ) + ) + + +async def _open( + file, + mode="r", + buffering=-1, + encoding=None, + errors=None, + newline=None, + closefd=True, + opener=None, + *, + loop=None, + executor=None, +): + """Open an asyncio file.""" + if loop is None: + loop = asyncio.get_running_loop() + cb = partial( + sync_open, + file, + mode=mode, + buffering=buffering, + encoding=encoding, + errors=errors, + newline=newline, + closefd=closefd, + opener=opener, + ) + f = await loop.run_in_executor(executor, cb) + + return wrap(f, loop=loop, executor=executor) + + +@singledispatch +def wrap(file, *, loop=None, executor=None): + raise TypeError(f"Unsupported io type: {file}.") + + +@wrap.register(TextIOBase) +def _(file, *, loop=None, executor=None): + return AsyncTextIOWrapper(file, loop=loop, executor=executor) + + +@wrap.register(BufferedWriter) +@wrap.register(BufferedIOBase) +def _(file, *, loop=None, executor=None): + return AsyncBufferedIOBase(file, loop=loop, executor=executor) + + +@wrap.register(BufferedReader) +@wrap.register(BufferedRandom) +def _(file, *, loop=None, executor=None): + return AsyncBufferedReader(file, loop=loop, executor=executor) + + +@wrap.register(FileIO) +def _(file, *, loop=None, executor=None): + return AsyncFileIO(file, loop=loop, executor=executor) + + +stdin = AsyncTextIndirectIOWrapper("sys.stdin", None, None, indirect=lambda: sys.stdin) +stdout = AsyncTextIndirectIOWrapper( + "sys.stdout", None, None, indirect=lambda: sys.stdout +) +stderr = AsyncTextIndirectIOWrapper( + "sys.stderr", None, None, indirect=lambda: sys.stderr +) +stdin_bytes = AsyncIndirectBufferedIOBase( + "sys.stdin.buffer", None, None, indirect=lambda: sys.stdin.buffer +) +stdout_bytes = AsyncIndirectBufferedIOBase( + "sys.stdout.buffer", None, None, indirect=lambda: sys.stdout.buffer +) +stderr_bytes = AsyncIndirectBufferedIOBase( + "sys.stderr.buffer", None, None, indirect=lambda: sys.stderr.buffer +) diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a4a9bc6188c4326281f07960eedc17d1d1c2bca Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa542d8fde3cce4759d1c6ad6da0eb9ada1c419f Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/text.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a37bf94317f171a0c0e4a06a6ad329872e838932 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/text.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3259f1617d1302b80c13493d27cf2cb139e04f59 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/binary.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..63fcaff25959472c3282674a0c9e95160a8210b7 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/binary.py @@ -0,0 +1,104 @@ +from ..base import AsyncBase, AsyncIndirectBase +from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "read1", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly("closed", "raw", "name", "mode") +class AsyncBufferedIOBase(AsyncBase): + """The asyncio executor version of io.BufferedWriter and BufferedIOBase.""" + + +@delegate_to_executor("peek") +class AsyncBufferedReader(AsyncBufferedIOBase): + """The asyncio executor version of io.BufferedReader and Random.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readall", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("fileno", "readable") +@proxy_property_directly("closed", "name", "mode") +class AsyncFileIO(AsyncBase): + """The asyncio executor version of io.FileIO.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "read1", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly("closed", "raw", "name", "mode") +class AsyncIndirectBufferedIOBase(AsyncIndirectBase): + """The indirect asyncio executor version of io.BufferedWriter and BufferedIOBase.""" + + +@delegate_to_executor("peek") +class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase): + """The indirect asyncio executor version of io.BufferedReader and Random.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readall", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("fileno", "readable") +@proxy_property_directly("closed", "name", "mode") +class AsyncIndirectFileIO(AsyncIndirectBase): + """The indirect asyncio executor version of io.FileIO.""" diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/text.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/text.py new file mode 100644 index 0000000000000000000000000000000000000000..0e625909b6c960ebed4a0ed99941b28156fbf2d1 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/text.py @@ -0,0 +1,64 @@ +from ..base import AsyncBase, AsyncIndirectBase +from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readable", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "write", + "writable", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly( + "buffer", + "closed", + "encoding", + "errors", + "line_buffering", + "newlines", + "name", + "mode", +) +class AsyncTextIOWrapper(AsyncBase): + """The asyncio executor version of io.TextIOWrapper.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readable", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "write", + "writable", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly( + "buffer", + "closed", + "encoding", + "errors", + "line_buffering", + "newlines", + "name", + "mode", +) +class AsyncTextIndirectIOWrapper(AsyncIndirectBase): + """The indirect asyncio executor version of io.TextIOWrapper.""" diff --git a/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/utils.py b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd3bb992e51b54225d53edb5f8e50f575997f81 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/aiofiles/threadpool/utils.py @@ -0,0 +1,72 @@ +import functools + + +def delegate_to_executor(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_delegate_method(attr_name)) + return cls + + return cls_builder + + +def proxy_method_directly(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_proxy_method(attr_name)) + return cls + + return cls_builder + + +def proxy_property_directly(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_proxy_property(attr_name)) + return cls + + return cls_builder + + +def cond_delegate_to_executor(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_cond_delegate_method(attr_name)) + return cls + + return cls_builder + + +def _make_delegate_method(attr_name): + async def method(self, *args, **kwargs): + cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs) + return await self._loop.run_in_executor(self._executor, cb) + + return method + + +def _make_proxy_method(attr_name): + def method(self, *args, **kwargs): + return getattr(self._file, attr_name)(*args, **kwargs) + + return method + + +def _make_proxy_property(attr_name): + def proxy_property(self): + return getattr(self._file, attr_name) + + return property(proxy_property) + + +def _make_cond_delegate_method(attr_name): + """For spooled temp files, delegate only if rolled to file object""" + + async def method(self, *args, **kwargs): + if self._file._rolled: + cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs) + return await self._loop.run_in_executor(self._executor, cb) + else: + return getattr(self._file, attr_name)(*args, **kwargs) + + return method diff --git a/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__init__.py b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc682bb56e86da5b1f7940122fe4cde38865cbdc --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__init__.py @@ -0,0 +1,3 @@ +from .ffmpy import FFExecutableNotFoundError, FFmpeg, FFprobe, FFRuntimeError + +__all__ = ["FFmpeg", "FFprobe", "FFExecutableNotFoundError", "FFRuntimeError"] diff --git a/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23958e0fd15afecf48a6ba9fa993ba3ae096b5a0 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__pycache__/ffmpy.cpython-311.pyc b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__pycache__/ffmpy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a49f77d0b56ad8df9c2f92724532c3750768c235 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/__pycache__/ffmpy.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/_vendor/ffmpy/ffmpy.py b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/ffmpy.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f4c79e7e4a7fff1ea32f3d2350e49efbb8842c --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/ffmpy.py @@ -0,0 +1,251 @@ +from __future__ import annotations + +import errno +import itertools +import shlex +import subprocess +from collections.abc import Mapping, Sequence +from typing import IO, Any + +try: + from psutil import Popen # noqa: F401 + + popen: type[subprocess.Popen | Popen] +except ImportError: + popen = subprocess.Popen +else: + popen = Popen + + +class FFmpeg: + """Wrapper for various `FFmpeg `_ related applications (ffmpeg, + ffprobe). + """ + + def __init__( + self, + executable: str = "ffmpeg", + global_options: Sequence[str] | str | None = None, + inputs: Mapping[str, Sequence[str] | str | None] | None = None, + outputs: Mapping[str, Sequence[str] | str | None] | None = None, + ) -> None: + """Initialize FFmpeg command line wrapper. + + Compiles FFmpeg command line from passed arguments (executable path, options, inputs and + outputs). ``inputs`` and ``outputs`` are dictionares containing inputs/outputs as keys and + their respective options as values. One dictionary value (set of options) must be either a + single space separated string, or a list or strings without spaces (i.e. each part of the + option is a separate item of the list, the result of calling ``split()`` on the options + string). If the value is a list, it cannot be mixed, i.e. cannot contain items with spaces. + An exception are complex FFmpeg command lines that contain quotes: the quoted part must be + one string, even if it contains spaces (see *Examples* for more info). + For more info about FFmpeg command line format see `here + `_. + + :param str executable: path to ffmpeg executable; by default the ``ffmpeg`` command will be + searched for in the ``PATH``, but can be overridden with an absolute path to ``ffmpeg`` + executable + :param iterable global_options: global options passed to ``ffmpeg`` executable (e.g. + ``-y``, ``-v`` etc.); can be specified either as a list/tuple/set of strings, or one + space-separated string; by default no global options are passed + :param dict inputs: a dictionary specifying one or more input arguments as keys with their + corresponding options (either as a list of strings or a single space separated string) as + values + :param dict outputs: a dictionary specifying one or more output arguments as keys with their + corresponding options (either as a list of strings or a single space separated string) as + values + """ + self.executable = executable + self._cmd = [executable] + self._cmd += _normalize_options(global_options, split_mixed=True) + + if inputs is not None: + self._cmd += _merge_args_opts(inputs, add_minus_i_option=True) + + if outputs is not None: + self._cmd += _merge_args_opts(outputs) + + self.cmd = subprocess.list2cmdline(self._cmd) + self.process: subprocess.Popen | Popen | None = None + + def __repr__(self) -> str: + return f"<{self.__class__.__name__!r} {self.cmd!r}>" + + def run( + self, + input_data: bytes | None = None, + stdout: IO | int | None = None, + stderr: IO | int | None = None, + env: Mapping[str, str] | None = None, + **kwargs: Any, + ) -> tuple[bytes | None, bytes | None]: + """Execute FFmpeg command line. + + ``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input. + ``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the + process. By default no redirection is done, which means all output goes to running shell + (this mode should normally only be used for debugging purposes). If FFmpeg ``pipe`` protocol + is used for output, ``stdout`` must be redirected to a pipe by passing `subprocess.PIPE` as + ``stdout`` argument. You can pass custom environment to ffmpeg process with ``env``. + + Returns a 2-tuple containing ``stdout`` and ``stderr`` of the process. If there was no + redirection or if the output was redirected to e.g. `os.devnull`, the value returned will + be a tuple of two `None` values, otherwise it will contain the actual ``stdout`` and + ``stderr`` data returned by ffmpeg process. + + More info about ``pipe`` protocol `here `_. + + :param str input_data: input data for FFmpeg to deal with (audio, video etc.) as bytes (e.g. + the result of reading a file in binary mode) + :param stdout: redirect FFmpeg ``stdout`` there (default is `None` which means no + redirection) + :param stderr: redirect FFmpeg ``stderr`` there (default is `None` which means no + redirection) + :param env: custom environment for ffmpeg process + :param kwargs: any other keyword arguments to be forwarded to `subprocess.Popen + `_ + :return: a 2-tuple containing ``stdout`` and ``stderr`` of the process + :rtype: tuple + :raise: `FFRuntimeError` in case FFmpeg command exits with a non-zero code; + `FFExecutableNotFoundError` in case the executable path passed was not valid + """ + try: + self.process = popen( + self._cmd, + stdin=subprocess.PIPE, + stdout=stdout, + stderr=stderr, + env=env, + **kwargs, + ) + except OSError as e: + if e.errno == errno.ENOENT: + raise FFExecutableNotFoundError( + f"Executable '{self.executable}' not found" + ) + else: + raise + + o_stdout, o_stderr = self.process.communicate(input=input_data) + if self.process.returncode != 0: + raise FFRuntimeError(self.cmd, self.process.returncode, o_stdout, o_stderr) + + return o_stdout, o_stderr + + +class FFprobe(FFmpeg): + """Wrapper for `ffprobe `_.""" + + def __init__( + self, + executable: str = "ffprobe", + global_options: Sequence[str] | str | None = None, + inputs: Mapping[str, Sequence[str] | str | None] | None = None, + ) -> None: + """Create an instance of FFprobe. + + Compiles FFprobe command line from passed arguments (executable path, options, inputs). + FFprobe executable by default is taken from ``PATH`` but can be overridden with an + absolute path. For more info about FFprobe command line format see + `here `_. + + :param str executable: absolute path to ffprobe executable + :param iterable global_options: global options passed to ffmpeg executable; can be specified + either as a list/tuple of strings or a space-separated string + :param dict inputs: a dictionary specifying one or more inputs as keys with their + corresponding options as values + """ + super().__init__( + executable=executable, global_options=global_options, inputs=inputs + ) + + +class FFExecutableNotFoundError(Exception): + """Raise when FFmpeg/FFprobe executable was not found.""" + + +class FFRuntimeError(Exception): + """Raise when FFmpeg/FFprobe command line execution returns a non-zero exit code. + + The resulting exception object will contain the attributes relates to command line execution: + ``cmd``, ``exit_code``, ``stdout``, ``stderr``. + """ + + def __init__( + self, + cmd: str, + exit_code: int, + stdout: bytes | str | None, + stderr: bytes | str | None, + ) -> None: + self.cmd = cmd + self.exit_code = exit_code + self.stdout = stdout + self.stderr = stderr + + stdout_display = _safe_decode(stdout) + stderr_display = _safe_decode(stderr) + + message = f"`{self.cmd}` exited with status {exit_code}\n\nSTDOUT:\n{stdout_display}\n\nSTDERR:\n{stderr_display}" + + super().__init__(message) + + +def _merge_args_opts( + args_opts_dict: Mapping[str, Sequence[str] | str | None], + add_minus_i_option: bool = False, +) -> list[str]: + """Merge options with their corresponding arguments. + + Iterates over the dictionary holding arguments (keys) and options (values). Merges each + options string with its corresponding argument. + + :param dict args_opts_dict: a dictionary of arguments and options + :param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument + :return: merged list of strings with arguments and their corresponding options + :rtype: list + """ + merged: list[str] = [] + + for arg, opt in args_opts_dict.items(): + merged += _normalize_options(opt) + + if not arg: + continue + + if add_minus_i_option: + merged.append("-i") + + merged.append(arg) + + return merged + + +def _normalize_options( + options: Sequence[str] | str | None, split_mixed: bool = False +) -> list[str]: + """Normalize options string or list of strings. + + Splits `options` into a list of strings. If `split_mixed` is `True`, splits (flattens) mixed + options (i.e. list of strings with spaces) into separate items. + + :param options: options string or list of strings + :param bool split_mixed: whether to split mixed options into separate items + """ + if options is None: + return [] + elif isinstance(options, str): + return shlex.split(options) + elif split_mixed: + return list(itertools.chain(*[shlex.split(o) for o in options])) + else: + return list(options) + + +def _safe_decode(stream_data: bytes | str | None) -> str: + """Convert FFmpeg output to text for error messages.""" + if stream_data is None: + return "" + if isinstance(stream_data, bytes): + return stream_data.decode(errors="replace") + return stream_data diff --git a/lib/python3.11/site-packages/gradio/_vendor/ffmpy/py.typed b/lib/python3.11/site-packages/gradio/_vendor/ffmpy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/gradio/_vendor/licenses/aiofiles.LICENSE b/lib/python3.11/site-packages/gradio/_vendor/licenses/aiofiles.LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e06d2081865a766a8668acc12878f98b27fc9ea0 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/licenses/aiofiles.LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/lib/python3.11/site-packages/gradio/_vendor/licenses/aiofiles.NOTICE b/lib/python3.11/site-packages/gradio/_vendor/licenses/aiofiles.NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..d134f281ef732a3697f32b24b42ce8c4c07f9019 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/licenses/aiofiles.NOTICE @@ -0,0 +1,2 @@ +Asyncio support for files +Copyright 2016 Tin Tvrtkovic diff --git a/lib/python3.11/site-packages/gradio/_vendor/licenses/ffmpy.LICENSE b/lib/python3.11/site-packages/gradio/_vendor/licenses/ffmpy.LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eda4fa42c6aac7cb96cb4cbd8919a07d32da2bd7 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/_vendor/licenses/ffmpy.LICENSE @@ -0,0 +1,18 @@ +Copyright 2016-2024 Andrii Yurchuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/python3.11/site-packages/gradio/cli/__init__.py b/lib/python3.11/site-packages/gradio/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34f6d59065faf2e637175948f791c055559ba4ec --- /dev/null +++ b/lib/python3.11/site-packages/gradio/cli/__init__.py @@ -0,0 +1,4 @@ +from .cli import cli, deploy +from .commands import custom_component, sketch + +__all__ = ["cli", "deploy", "custom_component", "sketch"] diff --git a/lib/python3.11/site-packages/gradio/cli/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf31aa99e2d5829fa98b600fa948e5c32db43df Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/__pycache__/cli.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/__pycache__/cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a84e28fbf54c1da0057c0083194416ad6cd4870 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/__pycache__/cli.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/cli.py b/lib/python3.11/site-packages/gradio/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..b53b8376da8a5997511bb0312dd34eb838948d66 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/cli/cli.py @@ -0,0 +1,99 @@ +import sys + +import typer +from rich.console import Console + +from gradio import analytics + +from .commands import ( + custom_component, + deploy, + hf_login, + info, + load_app, + predict, + print_environment_info, + reload, + sketch, + skills_app, + upload_mcp, +) + +app = typer.Typer() +app.add_typer(load_app, name="load") +app.add_typer(skills_app, name="skills") +app.command("environment", help="Print Gradio environment information.")( + print_environment_info +) +app.command( + "deploy", + help="Deploy a Gradio app to Spaces or Google Cloud Run. Must be called within the directory you would like to deploy.", +)(deploy) +app.command("sketch", help="Open the Sketch app to design a Gradio app.")(sketch) +app.command( + "info", + help="Fetches the expected JSON payload for all of a Gradio app's endpoints.", +)(info) +app.command( + "predict", + help="Sends a prediction request to a Gradio app endpoint.", +)(predict) + + +def cli(): + args = sys.argv[1:] + if len(args) == 0: + raise ValueError("No file specified.") + if args[0] in { + "deploy", + "environment", + "deploy-discord", + "sketch", + "load", + "skills", + "info", + "predict", + }: + app() + elif args[0] in {"cc", "component"}: + sys.argv = sys.argv[1:] + custom_component() + elif args[0] in {"build", "dev", "create", "show", "publish", "install"}: + try: + error = f"gradio {args[0]} is not a valid command. Did you mean `gradio cc {args[0]}` or `gradio component {args[0]}`?." + raise ValueError(error) + except ValueError: + console = Console() + console.print_exception() + elif args[0] in {"upload-mcp"}: + upload_mcp(args[1], args[2]) + elif args[0] == "--vibe": + import os + from pathlib import Path + + os.environ["GRADIO_VIBE_MODE"] = "1" + analytics.vibe_analytics() + + demo_path = Path("demo.py") if len(args) == 1 else Path(args[1]) + + if not demo_path.exists(): + template_content = """import gradio as gr + +with gr.Blocks() as demo: + pass + +demo.launch()""" + with open(demo_path, "w") as f: + f.write(template_content) + print(f"Created {demo_path} with default Gradio template.") + + print( + "\n⚠️ WARNING: Vibe editor mode is enabled. Anyone who can access the Gradio endpoint can modify files and run arbitrary code on the host machine. Use with caution!\n" + ) + + hf_login() + + sys.argv = ["gradio", str(demo_path)] + typer.run(reload) + else: + typer.run(reload) diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__init__.py b/lib/python3.11/site-packages/gradio/cli/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..616eb76bbcd4a7cae9d290a3ab81481038e08907 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/cli/commands/__init__.py @@ -0,0 +1,25 @@ +from hf_gradio.cli import info, predict + +from .cli_env_info import print_environment_info +from .components import app as custom_component +from .deploy_space import deploy +from .hf_login import hf_login +from .load import load_app +from .reload import main as reload +from .sketch import launch as sketch +from .skills import skills_app +from .upload_mcp import main as upload_mcp + +__all__ = [ + "deploy", + "reload", + "print_environment_info", + "custom_component", + "sketch", + "upload_mcp", + "hf_login", + "load_app", + "skills_app", + "info", + "predict", +] diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0324de65d295e6534e651c482a01976711b8bbdb Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/cli_env_info.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/cli_env_info.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d79b177f66e96e44f2cee076ee3398999baf22e Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/cli_env_info.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/deploy_space.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/deploy_space.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d69da8fd32d4c200cf54e5fd3f27b38e3455959c Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/deploy_space.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/display.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/display.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb0656e611e3940903524b5431375dab11ed4d09 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/display.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/hf_login.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/hf_login.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9fc65a430a1fb7aa0844abf95a4bb3369fc9b0d Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/hf_login.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/load.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/load.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6ebdf293e4a23505d20e54a6e3b6cbfbf1a6ce2 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/load.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/load_chat.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/load_chat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dc1fa8f511d9da7ecdec35ac9b041a55b071532 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/load_chat.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/reload.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/reload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4258ddfade6a1bdaffd98fa4ab01f82b914113e1 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/reload.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/sketch.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/sketch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8648bf2c1c0dec7e2bcf910e6f9031362588208d Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/sketch.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/skills.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/skills.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1602c251c44ecbf94909f2ccfc725fe691f7b95e Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/skills.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/upload_mcp.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/upload_mcp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74bd5e3a9d9d78f437871544ac7d45f5d28dc9f1 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/upload_mcp.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/utils.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7fae99e2bdd64579dd78f54f03dca5bf46e242f Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/__pycache__/utils.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/cli_env_info.py b/lib/python3.11/site-packages/gradio/cli/commands/cli_env_info.py new file mode 100644 index 0000000000000000000000000000000000000000..6259868f44fa4f76314d8c01fd4c9ae385da81cd --- /dev/null +++ b/lib/python3.11/site-packages/gradio/cli/commands/cli_env_info.py @@ -0,0 +1,39 @@ +"""This file is the part of 'gradio/cli.py' for printing the environment info +for the cli command 'gradio environment' +""" + +from __future__ import annotations + +import platform +from importlib import metadata + +from packaging.requirements import Requirement +from rich import print + + +def print_environment_info(): + """Print Gradio environment information.""" + print("Gradio Environment Information:\n------------------------------") + print("Operating System:", platform.system()) + + for package_name in ["gradio", "gradio_client"]: + try: + package_version = metadata.version(package_name) + print(f"{package_name} version:", package_version) + except metadata.PackageNotFoundError: + print(f"{package_name} package is not installed.") + print("\n------------------------------------------------") + for package_name in ["gradio", "gradio_client"]: + try: + dist = metadata.distribution(package_name) + print(f"{package_name} dependencies in your environment:\n") + if dist.requires is not None: + for req in dist.requires: + req_obj = Requirement(req) + try: + print(f"{req_obj.name}: {metadata.version(req_obj.name)}") + except metadata.PackageNotFoundError: + print(f"{req_obj.name} is not installed.") + print("\n") + except metadata.PackageNotFoundError: + print(f"{package_name} package is not installed.") diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__init__.py b/lib/python3.11/site-packages/gradio/cli/commands/components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34f275ed3c9d7894766f1b188d9d5e13327f24bb --- /dev/null +++ b/lib/python3.11/site-packages/gradio/cli/commands/components/__init__.py @@ -0,0 +1,3 @@ +from .app import app + +__all__ = ["app"] diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef08a5857eb59cf0c45f714889fe2447f5b9be93 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_create_utils.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_create_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d244ee47ccd856c694fe24caa3394086d94ef4 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_create_utils.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_docs_assets.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_docs_assets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b61c446cc132f05bbff8a13adb20e7e8c4688ba9 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_docs_assets.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_docs_utils.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_docs_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26f29c182656ab264006962d86026627836a4a0 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/_docs_utils.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/app.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c030b4bd7dbfedf87eaa46267814da97695371c1 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/app.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/build.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/build.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb71b282ff1767408ea8cffa129f72f0516700e9 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/build.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/create.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/create.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30703e964ff76110b44b769baa9bd99ad1f3e371 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/create.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/dev.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/dev.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bbcebaccb3401f15f5c47c9835524ca9ec96636 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/dev.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/docs.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/docs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c3e4d39c0cc383945e00fd8394ce6b459f11469 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/docs.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/install_component.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/install_component.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50587d54b09706b190d7be5259aa0e7c85c0eb37 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/install_component.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/publish.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/publish.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d67156156d0df6a9411cf477495e7a5b4beb7f1a Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/publish.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/show.cpython-311.pyc b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/show.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58a9aad7d098f97264037c3f9ed0ed8c3ac496f3 Binary files /dev/null and b/lib/python3.11/site-packages/gradio/cli/commands/components/__pycache__/show.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/gradio/cli/commands/components/_create_utils.py b/lib/python3.11/site-packages/gradio/cli/commands/components/_create_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb3b2c3e4559ad3c3919a9a2e6ceae474ac82d7 --- /dev/null +++ b/lib/python3.11/site-packages/gradio/cli/commands/components/_create_utils.py @@ -0,0 +1,483 @@ +from __future__ import annotations + +import dataclasses +import inspect +import json +import re +import shutil +import textwrap +from pathlib import Path +from typing import Literal + +from huggingface_hub import snapshot_download + +import gradio + + +def _in_test_dir(): + """Check if the current working directory ends with gradio/js/preview/test.""" + return Path.cwd().parts[-4:] == ("gradio", "js", "preview", "test") + + +default_demo_code = """ +example = {name}().example_value() + +demo = gr.Interface( + lambda x:x, + {name}(), # interactive version of your component + {name}(), # static version of your component + # examples=[[example]], # uncomment this line to view the "example version" of your component +) +""" + +static_only_demo_code = """ +example = {name}().example_value() + +with gr.Blocks() as demo: + with gr.Row(): + {name}(label="Blank"), # blank component + {name}(value=example, label="Populated"), # populated component +""" + +layout_demo_code = """ +with gr.Blocks() as demo: + with {name}(): + gr.Textbox(value="foo", interactive=True) + gr.Number(value=10, interactive=True) +""" + +fallback_code = """ +with gr.Blocks() as demo: + gr.Markdown("# Change the value (keep it JSON) and the front-end will update automatically.") + {name}(value={{"message": "Hello from Gradio!"}}, label="Static") +""" + + +PATTERN_RE = r"gradio-template-\w+" +PATTERN = "gradio-template-{template}" + + +@dataclasses.dataclass +class ComponentFiles: + template: str + demo_code: str = default_demo_code + python_file_name: str = "" + js_dir: str = "" + + def __post_init__(self): + self.js_dir = self.js_dir or self.template.lower() + self.python_file_name = self.python_file_name or f"{self.template.lower()}.py" + + +OVERRIDES = { + "AnnotatedImage": ComponentFiles( + template="AnnotatedImage", + python_file_name="annotated_image.py", + demo_code=static_only_demo_code, + ), + "HighlightedText": ComponentFiles( + template="HighlightedText", + python_file_name="highlighted_text.py", + demo_code=static_only_demo_code, + ), + "Chatbot": ComponentFiles(template="Chatbot", demo_code=static_only_demo_code), + "Gallery": ComponentFiles(template="Gallery", demo_code=static_only_demo_code), + "HTML": ComponentFiles(template="HTML", demo_code=static_only_demo_code), + "Label": ComponentFiles(template="Label", demo_code=static_only_demo_code), + "Markdown": ComponentFiles(template="Markdown", demo_code=static_only_demo_code), + "Fallback": ComponentFiles(template="Fallback", demo_code=fallback_code), + "Plot": ComponentFiles(template="Plot", demo_code=static_only_demo_code), + "BarPlot": ComponentFiles( + template="BarPlot", + python_file_name="native_plot.py", + js_dir="plot", + demo_code=static_only_demo_code, + ), + "ClearButton": ComponentFiles( + template="ClearButton", + python_file_name="clear_button.py", + js_dir="button", + demo_code=static_only_demo_code, + ), + "ColorPicker": ComponentFiles( + template="ColorPicker", python_file_name="color_picker.py" + ), + "DuplicateButton": ComponentFiles( + template="DuplicateButton", + python_file_name="duplicate_button.py", + js_dir="button", + demo_code=static_only_demo_code, + ), + "FileExplorer": ComponentFiles( + template="FileExplorer", + python_file_name="file_explorer.py", + js_dir="fileexplorer", + demo_code=textwrap.dedent( + """ + import os + + with gr.Blocks() as demo: + {name}(value=os.path.dirname(__file__).split(os.sep)) + """ + ), + ), + "LinePlot": ComponentFiles( + template="LinePlot", + python_file_name="native_plot.py", + js_dir="plot", + demo_code=static_only_demo_code, + ), + "LogoutButton": ComponentFiles( + template="LogoutButton", + python_file_name="logout_button.py", + js_dir="button", + demo_code=static_only_demo_code, + ), + "LoginButton": ComponentFiles( + template="LoginButton", + python_file_name="login_button.py", + js_dir="button", + demo_code=static_only_demo_code, + ), + "ScatterPlot": ComponentFiles( + template="ScatterPlot", + python_file_name="native_plot.py", + js_dir="plot", + demo_code=static_only_demo_code, + ), + "UploadButton": ComponentFiles( + template="UploadButton", + python_file_name="upload_button.py", + demo_code=static_only_demo_code, + ), + "JSON": ComponentFiles( + template="JSON", + python_file_name="json_component.py", + demo_code=static_only_demo_code, + ), + "Row": ComponentFiles( + template="Row", + demo_code=layout_demo_code, + ), + "Column": ComponentFiles( + template="Column", + demo_code=layout_demo_code, + ), + "Tabs": ComponentFiles( + template="Tabs", + demo_code=textwrap.dedent( + """ + with gr.Blocks() as demo: + with {name}(): + with gr.Tab("Tab 1"): + gr.Textbox(value="foo", interactive=True) + with gr.Tab("Tab 2"): + gr.Number(value=10, interactive=True) + """ + ), + ), + "Group": ComponentFiles( + template="Group", + demo_code=layout_demo_code, + ), + "Accordion": ComponentFiles( + template="Accordion", + demo_code=textwrap.dedent( + """ + with gr.Blocks() as demo: + with {name}(label="Accordion"): + gr.Textbox(value="foo", interactive=True) + gr.Number(value=10, interactive=True) + """ + ), + ), + "Model3D": ComponentFiles( + template="Model3D", + js_dir="model3D", + demo_code=textwrap.dedent( + """ + with gr.Blocks() as demo: + {name}() + """ + ), + ), + "ImageEditor": ComponentFiles( + template="ImageEditor", + python_file_name="image_editor.py", + js_dir="imageeditor", + ), + "MultimodalTextbox": ComponentFiles( + template="MultimodalTextbox", + python_file_name="multimodal_textbox.py", + js_dir="multimodaltextbox", + ), + "DownloadButton": ComponentFiles( + template="DownloadButton", + python_file_name="download_button.py", + js_dir="downloadbutton", + ), + "Walkthrough": ComponentFiles( + template="Walkthrough", + js_dir="tabs", + demo_code=textwrap.dedent( + """ + with gr.Blocks() as demo: + with {name}(): + with gr.Tab("Tab 1"): + gr.Textbox(value="foo", interactive=True) + with gr.Tab("Tab 2"): + gr.Number(value=10, interactive=True) + """ + ), + ), + "Step": ComponentFiles( + template="Step", + js_dir="tabitem", + python_file_name="walkthrough.py", + demo_code=textwrap.dedent( + """ + with gr.Blocks() as demo: + with {name}(): + gr.Textbox(value="foo", interactive=True) + """ + ), + ), +} + + +def _get_component_code(template: str | None) -> ComponentFiles: + template = template or "Fallback" + if template in OVERRIDES: + return OVERRIDES[template] + else: + return ComponentFiles( + python_file_name=f"{template.lower()}.py", + js_dir=template.lower(), + template=template, + ) + + +def _get_js_dependency_version(name: str, local_js_dir: Path) -> str: + package_json = json.loads( + Path(local_js_dir / name.split("/")[1] / "package.json").read_text() + ) + return package_json["version"] + + +def copy_svelte_to_deps(package_json: dict): + svelte_version = package_json.get("peerDependencies", {}).get("svelte", "latest") + package_json["dependencies"]["svelte"] = svelte_version + return package_json + + +def _modify_js_deps( + package_json: dict, + key: Literal["dependencies", "devDependencies"], + gradio_dir: Path, +): + for dep in package_json.get(key, []): + # if curent working directory is the gradio repo, use the local version of the dependency' + if not _in_test_dir() and dep.startswith("@gradio/"): + package_json[key][dep] = _get_js_dependency_version( + dep, gradio_dir / "_frontend_code" / gradio.__version__ + ) + return package_json + + +def delete_contents(directory: str | Path) -> None: + """Delete all contents of a directory, but not the directory itself.""" + path = Path(directory) + for child in path.glob("*"): + if child.is_file(): + child.unlink() + elif child.is_dir(): + shutil.rmtree(child) + + +def _download_from_hub(destination: Path): + version = gradio.__version__ + + snapshot_download( + repo_id="gradio/frontend", + allow_patterns=f"{version}/**", + local_dir=destination, + repo_type="dataset", + ) + + +def _create_frontend( + name: str, # noqa: ARG001 + component: ComponentFiles, + directory: Path, + package_name: str, +): + frontend = directory / "frontend" + frontend.mkdir(exist_ok=True) + + p = Path(inspect.getfile(gradio)).parent + + component_source = p / "_frontend_code" + if not component_source.exists(): + component_source.mkdir(exist_ok=True) + _download_from_hub(component_source) + + def ignore(_src, names): + ignored = [] + for n in names: + if ( + n.startswith("CHANGELOG") + or n.startswith("README.md") + or ".test." in n + or ".stories." in n + or ".spec." in n + ): + ignored.append(n) + return ignored + + # Replace once we figure out bug with svelte-package + shutil.copytree( + str(p / "_frontend_code" / gradio.__version__ / component.js_dir), + frontend, + dirs_exist_ok=True, + ignore=ignore, + ) + source_package_json = json.loads(Path(frontend / "package.json").read_text()) + source_package_json["name"] = package_name + source_package_json = _modify_js_deps(source_package_json, "dependencies", p) + source_package_json = _modify_js_deps(source_package_json, "devDependencies", p) + source_package_json = copy_svelte_to_deps(source_package_json) + + (frontend / "package.json").write_text(json.dumps(source_package_json, indent=2)) + shutil.copy( + str(Path(__file__).parent / "files" / "gradio.config.js"), + frontend / "gradio.config.js", + ) + shutil.copy( + str(Path(__file__).parent / "files" / "tsconfig.json"), + frontend / "tsconfig.json", + ) + + +def _replace_old_class_name(old_class_name: str, new_class_name: str, content: str): + pattern = rf"(?<=\b)(?>", package_name).replace( + "<