Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- falcon/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so +3 -0
- falcon/lib/python3.10/site-packages/beautifulsoup4-4.12.3.dist-info/licenses/AUTHORS +49 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/__init__.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_catch.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_exceptions.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_formatting.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_suppress.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_version.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/_catch.py +138 -0
- falcon/lib/python3.10/site-packages/exceptiongroup/_version.py +16 -0
- falcon/lib/python3.10/site-packages/gradio/.dockerignore +2 -0
- falcon/lib/python3.10/site-packages/gradio/__init__.py +97 -0
- falcon/lib/python3.10/site-packages/gradio/analytics.py +190 -0
- falcon/lib/python3.10/site-packages/gradio/cli.py +14 -0
- falcon/lib/python3.10/site-packages/gradio/context.py +16 -0
- falcon/lib/python3.10/site-packages/gradio/deploy_space.py +175 -0
- falcon/lib/python3.10/site-packages/gradio/deprecation.py +46 -0
- falcon/lib/python3.10/site-packages/gradio/events.py +351 -0
- falcon/lib/python3.10/site-packages/gradio/exceptions.py +42 -0
- falcon/lib/python3.10/site-packages/gradio/external_utils.py +140 -0
- falcon/lib/python3.10/site-packages/gradio/flagging.py +518 -0
- falcon/lib/python3.10/site-packages/gradio/interface.py +899 -0
- falcon/lib/python3.10/site-packages/gradio/interpretation.py +328 -0
- falcon/lib/python3.10/site-packages/gradio/mix.py +129 -0
- falcon/lib/python3.10/site-packages/gradio/processing_utils.py +530 -0
- falcon/lib/python3.10/site-packages/gradio/queueing.py +462 -0
- falcon/lib/python3.10/site-packages/gradio/ranged_response.py +185 -0
- falcon/lib/python3.10/site-packages/gradio/reload.py +91 -0
- falcon/lib/python3.10/site-packages/gradio/routes.py +824 -0
- falcon/lib/python3.10/site-packages/gradio/strings.py +45 -0
- falcon/lib/python3.10/site-packages/gradio/templates.py +574 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Column-2853eb31.css +1 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Copy-143d56db.js +2 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Form-68b374ed.js +2 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Info-b7dfbb56.js.map +1 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Caligraphic-Regular-3398dd02.woff +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Fraktur-Regular-5e28753b.woff +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Main-Bold-c76c5d69.woff +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Main-Italic-0d85ae7c.ttf +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Main-Italic-97479ca6.woff2 +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Math-BoldItalic-850c0af5.woff +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Math-Italic-8a8d2445.woff +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Size3-Regular-500e04d5.ttf +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Size4-Regular-99f9c675.woff +0 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Model3D-98fc2b2c.css +1 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/TabItem.svelte_svelte_type_style_lang-f9698472.js.map +1 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/UploadText-2a4d151d.js.map +1 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/dsv-576afacd.js +6 -0
- falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/index-0008c077.js.map +1 -0
.gitattributes
CHANGED
|
@@ -565,3 +565,4 @@ falcon/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-3
|
|
| 565 |
falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 566 |
evalkit_tf437/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 567 |
falcon/lib/python3.10/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 565 |
falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 566 |
evalkit_tf437/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 567 |
falcon/lib/python3.10/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 568 |
+
falcon/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
falcon/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:44e15dd58778dd4993847079c1f46572f7a73ca58d636b212c887b181351c10c
|
| 3 |
+
size 155456
|
falcon/lib/python3.10/site-packages/beautifulsoup4-4.12.3.dist-info/licenses/AUTHORS
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Behold, mortal, the origins of Beautiful Soup...
|
| 2 |
+
================================================
|
| 3 |
+
|
| 4 |
+
Leonard Richardson is the primary maintainer.
|
| 5 |
+
|
| 6 |
+
Aaron DeVore and Isaac Muse have made significant contributions to the
|
| 7 |
+
code base.
|
| 8 |
+
|
| 9 |
+
Mark Pilgrim provided the encoding detection code that forms the base
|
| 10 |
+
of UnicodeDammit.
|
| 11 |
+
|
| 12 |
+
Thomas Kluyver and Ezio Melotti finished the work of getting Beautiful
|
| 13 |
+
Soup 4 working under Python 3.
|
| 14 |
+
|
| 15 |
+
Simon Willison wrote soupselect, which was used to make Beautiful Soup
|
| 16 |
+
support CSS selectors. Isaac Muse wrote SoupSieve, which made it
|
| 17 |
+
possible to _remove_ the CSS selector code from Beautiful Soup.
|
| 18 |
+
|
| 19 |
+
Sam Ruby helped with a lot of edge cases.
|
| 20 |
+
|
| 21 |
+
Jonathan Ellis was awarded the prestigious Beau Potage D'Or for his
|
| 22 |
+
work in solving the nestable tags conundrum.
|
| 23 |
+
|
| 24 |
+
An incomplete list of people have contributed patches to Beautiful
|
| 25 |
+
Soup:
|
| 26 |
+
|
| 27 |
+
Istvan Albert, Andrew Lin, Anthony Baxter, Oliver Beattie, Andrew
|
| 28 |
+
Boyko, Tony Chang, Francisco Canas, "Delong", Zephyr Fang, Fuzzy,
|
| 29 |
+
Roman Gaufman, Yoni Gilad, Richie Hindle, Toshihiro Kamiya, Peteris
|
| 30 |
+
Krumins, Kent Johnson, Marek Kapolka, Andreas Kostyrka, Roel Kramer,
|
| 31 |
+
Ben Last, Robert Leftwich, Stefaan Lippens, "liquider", Staffan
|
| 32 |
+
Malmgren, Ksenia Marasanova, JP Moins, Adam Monsen, John Nagle, "Jon",
|
| 33 |
+
Ed Oskiewicz, Martijn Peters, Greg Phillips, Giles Radford, Stefano
|
| 34 |
+
Revera, Arthur Rudolph, Marko Samastur, James Salter, Jouni Sepp�nen,
|
| 35 |
+
Alexander Schmolck, Tim Shirley, Geoffrey Sneddon, Ville Skytt�,
|
| 36 |
+
"Vikas", Jens Svalgaard, Andy Theyers, Eric Weiser, Glyn Webster, John
|
| 37 |
+
Wiseman, Paul Wright, Danny Yoo
|
| 38 |
+
|
| 39 |
+
An incomplete list of people who made suggestions or found bugs or
|
| 40 |
+
found ways to break Beautiful Soup:
|
| 41 |
+
|
| 42 |
+
Hanno B�ck, Matteo Bertini, Chris Curvey, Simon Cusack, Bruce Eckel,
|
| 43 |
+
Matt Ernst, Michael Foord, Tom Harris, Bill de hOra, Donald Howes,
|
| 44 |
+
Matt Patterson, Scott Roberts, Steve Strassmann, Mike Williams,
|
| 45 |
+
warchild at redho dot com, Sami Kuisma, Carlos Rocha, Bob Hutchison,
|
| 46 |
+
Joren Mc, Michal Migurski, John Kleven, Tim Heaney, Tripp Lilley, Ed
|
| 47 |
+
Summers, Dennis Sutch, Chris Smith, Aaron Swartz, Stuart
|
| 48 |
+
Turner, Greg Edwards, Kevin J Kalupson, Nikos Kouremenos, Artur de
|
| 49 |
+
Sousa Rocha, Yichun Wei, Per Vognsen
|
falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (862 Bytes). View file
|
|
|
falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_catch.cpython-310.pyc
ADDED
|
Binary file (3.25 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_exceptions.cpython-310.pyc
ADDED
|
Binary file (9.84 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_formatting.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_suppress.cpython-310.pyc
ADDED
|
Binary file (1.55 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/exceptiongroup/__pycache__/_version.cpython-310.pyc
ADDED
|
Binary file (489 Bytes). View file
|
|
|
falcon/lib/python3.10/site-packages/exceptiongroup/_catch.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import sys
|
| 5 |
+
from collections.abc import Callable, Iterable, Mapping
|
| 6 |
+
from contextlib import AbstractContextManager
|
| 7 |
+
from types import TracebackType
|
| 8 |
+
from typing import TYPE_CHECKING, Any
|
| 9 |
+
|
| 10 |
+
if sys.version_info < (3, 11):
|
| 11 |
+
from ._exceptions import BaseExceptionGroup
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
_Handler = Callable[[BaseExceptionGroup[Any]], Any]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _Catcher:
|
| 18 |
+
def __init__(self, handler_map: Mapping[tuple[type[BaseException], ...], _Handler]):
|
| 19 |
+
self._handler_map = handler_map
|
| 20 |
+
|
| 21 |
+
def __enter__(self) -> None:
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
def __exit__(
|
| 25 |
+
self,
|
| 26 |
+
etype: type[BaseException] | None,
|
| 27 |
+
exc: BaseException | None,
|
| 28 |
+
tb: TracebackType | None,
|
| 29 |
+
) -> bool:
|
| 30 |
+
if exc is not None:
|
| 31 |
+
unhandled = self.handle_exception(exc)
|
| 32 |
+
if unhandled is exc:
|
| 33 |
+
return False
|
| 34 |
+
elif unhandled is None:
|
| 35 |
+
return True
|
| 36 |
+
else:
|
| 37 |
+
if isinstance(exc, BaseExceptionGroup):
|
| 38 |
+
try:
|
| 39 |
+
raise unhandled from exc.__cause__
|
| 40 |
+
except BaseExceptionGroup:
|
| 41 |
+
# Change __context__ to __cause__ because Python 3.11 does this
|
| 42 |
+
# too
|
| 43 |
+
unhandled.__context__ = exc.__cause__
|
| 44 |
+
raise
|
| 45 |
+
|
| 46 |
+
raise unhandled from exc
|
| 47 |
+
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
def handle_exception(self, exc: BaseException) -> BaseException | None:
|
| 51 |
+
excgroup: BaseExceptionGroup | None
|
| 52 |
+
if isinstance(exc, BaseExceptionGroup):
|
| 53 |
+
excgroup = exc
|
| 54 |
+
else:
|
| 55 |
+
excgroup = BaseExceptionGroup("", [exc])
|
| 56 |
+
|
| 57 |
+
new_exceptions: list[BaseException] = []
|
| 58 |
+
for exc_types, handler in self._handler_map.items():
|
| 59 |
+
matched, excgroup = excgroup.split(exc_types)
|
| 60 |
+
if matched:
|
| 61 |
+
try:
|
| 62 |
+
try:
|
| 63 |
+
raise matched
|
| 64 |
+
except BaseExceptionGroup:
|
| 65 |
+
result = handler(matched)
|
| 66 |
+
except BaseExceptionGroup as new_exc:
|
| 67 |
+
if new_exc is matched:
|
| 68 |
+
new_exceptions.append(new_exc)
|
| 69 |
+
else:
|
| 70 |
+
new_exceptions.extend(new_exc.exceptions)
|
| 71 |
+
except BaseException as new_exc:
|
| 72 |
+
new_exceptions.append(new_exc)
|
| 73 |
+
else:
|
| 74 |
+
if inspect.iscoroutine(result):
|
| 75 |
+
raise TypeError(
|
| 76 |
+
f"Error trying to handle {matched!r} with {handler!r}. "
|
| 77 |
+
"Exception handler must be a sync function."
|
| 78 |
+
) from exc
|
| 79 |
+
|
| 80 |
+
if not excgroup:
|
| 81 |
+
break
|
| 82 |
+
|
| 83 |
+
if new_exceptions:
|
| 84 |
+
if len(new_exceptions) == 1:
|
| 85 |
+
return new_exceptions[0]
|
| 86 |
+
|
| 87 |
+
return BaseExceptionGroup("", new_exceptions)
|
| 88 |
+
elif (
|
| 89 |
+
excgroup and len(excgroup.exceptions) == 1 and excgroup.exceptions[0] is exc
|
| 90 |
+
):
|
| 91 |
+
return exc
|
| 92 |
+
else:
|
| 93 |
+
return excgroup
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def catch(
|
| 97 |
+
__handlers: Mapping[type[BaseException] | Iterable[type[BaseException]], _Handler],
|
| 98 |
+
) -> AbstractContextManager[None]:
|
| 99 |
+
if not isinstance(__handlers, Mapping):
|
| 100 |
+
raise TypeError("the argument must be a mapping")
|
| 101 |
+
|
| 102 |
+
handler_map: dict[
|
| 103 |
+
tuple[type[BaseException], ...], Callable[[BaseExceptionGroup]]
|
| 104 |
+
] = {}
|
| 105 |
+
for type_or_iterable, handler in __handlers.items():
|
| 106 |
+
iterable: tuple[type[BaseException]]
|
| 107 |
+
if isinstance(type_or_iterable, type) and issubclass(
|
| 108 |
+
type_or_iterable, BaseException
|
| 109 |
+
):
|
| 110 |
+
iterable = (type_or_iterable,)
|
| 111 |
+
elif isinstance(type_or_iterable, Iterable):
|
| 112 |
+
iterable = tuple(type_or_iterable)
|
| 113 |
+
else:
|
| 114 |
+
raise TypeError(
|
| 115 |
+
"each key must be either an exception classes or an iterable thereof"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if not callable(handler):
|
| 119 |
+
raise TypeError("handlers must be callable")
|
| 120 |
+
|
| 121 |
+
for exc_type in iterable:
|
| 122 |
+
if not isinstance(exc_type, type) or not issubclass(
|
| 123 |
+
exc_type, BaseException
|
| 124 |
+
):
|
| 125 |
+
raise TypeError(
|
| 126 |
+
"each key must be either an exception classes or an iterable "
|
| 127 |
+
"thereof"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if issubclass(exc_type, BaseExceptionGroup):
|
| 131 |
+
raise TypeError(
|
| 132 |
+
"catching ExceptionGroup with catch() is not allowed. "
|
| 133 |
+
"Use except instead."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
handler_map[iterable] = handler
|
| 137 |
+
|
| 138 |
+
return _Catcher(handler_map)
|
falcon/lib/python3.10/site-packages/exceptiongroup/_version.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# file generated by setuptools_scm
|
| 2 |
+
# don't change, don't track in version control
|
| 3 |
+
TYPE_CHECKING = False
|
| 4 |
+
if TYPE_CHECKING:
|
| 5 |
+
from typing import Tuple, Union
|
| 6 |
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
| 7 |
+
else:
|
| 8 |
+
VERSION_TUPLE = object
|
| 9 |
+
|
| 10 |
+
version: str
|
| 11 |
+
__version__: str
|
| 12 |
+
__version_tuple__: VERSION_TUPLE
|
| 13 |
+
version_tuple: VERSION_TUPLE
|
| 14 |
+
|
| 15 |
+
__version__ = version = '1.2.2'
|
| 16 |
+
__version_tuple__ = version_tuple = (1, 2, 2)
|
falcon/lib/python3.10/site-packages/gradio/.dockerignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
templates/frontend
|
| 2 |
+
templates/frontend/**/*
|
falcon/lib/python3.10/site-packages/gradio/__init__.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pkgutil
|
| 2 |
+
|
| 3 |
+
import gradio.components as components
|
| 4 |
+
import gradio.inputs as inputs
|
| 5 |
+
import gradio.outputs as outputs
|
| 6 |
+
import gradio.processing_utils
|
| 7 |
+
import gradio.templates
|
| 8 |
+
import gradio.themes as themes
|
| 9 |
+
from gradio.blocks import Blocks
|
| 10 |
+
from gradio.components import (
|
| 11 |
+
HTML,
|
| 12 |
+
JSON,
|
| 13 |
+
AnnotatedImage,
|
| 14 |
+
Annotatedimage,
|
| 15 |
+
Audio,
|
| 16 |
+
BarPlot,
|
| 17 |
+
Button,
|
| 18 |
+
Carousel,
|
| 19 |
+
Chatbot,
|
| 20 |
+
Checkbox,
|
| 21 |
+
CheckboxGroup,
|
| 22 |
+
Checkboxgroup,
|
| 23 |
+
ClearButton,
|
| 24 |
+
Code,
|
| 25 |
+
ColorPicker,
|
| 26 |
+
DataFrame,
|
| 27 |
+
Dataframe,
|
| 28 |
+
Dataset,
|
| 29 |
+
Dropdown,
|
| 30 |
+
File,
|
| 31 |
+
Gallery,
|
| 32 |
+
Highlight,
|
| 33 |
+
HighlightedText,
|
| 34 |
+
Highlightedtext,
|
| 35 |
+
Image,
|
| 36 |
+
Interpretation,
|
| 37 |
+
Json,
|
| 38 |
+
Label,
|
| 39 |
+
LinePlot,
|
| 40 |
+
Markdown,
|
| 41 |
+
Model3D,
|
| 42 |
+
Number,
|
| 43 |
+
Plot,
|
| 44 |
+
Radio,
|
| 45 |
+
ScatterPlot,
|
| 46 |
+
Slider,
|
| 47 |
+
State,
|
| 48 |
+
StatusTracker,
|
| 49 |
+
Text,
|
| 50 |
+
Textbox,
|
| 51 |
+
TimeSeries,
|
| 52 |
+
Timeseries,
|
| 53 |
+
UploadButton,
|
| 54 |
+
Variable,
|
| 55 |
+
Video,
|
| 56 |
+
component,
|
| 57 |
+
)
|
| 58 |
+
from gradio.deploy_space import deploy
|
| 59 |
+
from gradio.events import SelectData
|
| 60 |
+
from gradio.exceptions import Error
|
| 61 |
+
from gradio.external import load
|
| 62 |
+
from gradio.flagging import (
|
| 63 |
+
CSVLogger,
|
| 64 |
+
FlaggingCallback,
|
| 65 |
+
HuggingFaceDatasetJSONSaver,
|
| 66 |
+
HuggingFaceDatasetSaver,
|
| 67 |
+
SimpleCSVLogger,
|
| 68 |
+
)
|
| 69 |
+
from gradio.helpers import EventData, Progress, make_waveform, skip, update
|
| 70 |
+
from gradio.helpers import create_examples as Examples # noqa: N812
|
| 71 |
+
from gradio.interface import Interface, TabbedInterface, close_all
|
| 72 |
+
from gradio.ipython_ext import load_ipython_extension
|
| 73 |
+
from gradio.layouts import Accordion, Box, Column, Group, Row, Tab, TabItem, Tabs
|
| 74 |
+
from gradio.mix import Parallel, Series
|
| 75 |
+
from gradio.routes import Request, mount_gradio_app
|
| 76 |
+
from gradio.templates import (
|
| 77 |
+
Files,
|
| 78 |
+
ImageMask,
|
| 79 |
+
ImagePaint,
|
| 80 |
+
List,
|
| 81 |
+
Matrix,
|
| 82 |
+
Mic,
|
| 83 |
+
Microphone,
|
| 84 |
+
Numpy,
|
| 85 |
+
Paint,
|
| 86 |
+
Pil,
|
| 87 |
+
PlayableVideo,
|
| 88 |
+
Sketchpad,
|
| 89 |
+
TextArea,
|
| 90 |
+
Webcam,
|
| 91 |
+
)
|
| 92 |
+
from gradio.themes import Base as Theme
|
| 93 |
+
|
| 94 |
+
current_pkg_version = (
|
| 95 |
+
(pkgutil.get_data(__name__, "version.txt") or b"").decode("ascii").strip()
|
| 96 |
+
)
|
| 97 |
+
__version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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Functions related to analytics and telemetry. """
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import pkgutil
|
| 7 |
+
import threading
|
| 8 |
+
import warnings
|
| 9 |
+
from distutils.version import StrictVersion
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
import gradio
|
| 15 |
+
from gradio.context import Context
|
| 16 |
+
from gradio.utils import GRADIO_VERSION
|
| 17 |
+
|
| 18 |
+
ANALYTICS_URL = "https://api.gradio.app/"
|
| 19 |
+
PKG_VERSION_URL = "https://api.gradio.app/pkg-version"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def analytics_enabled() -> bool:
|
| 23 |
+
"""
|
| 24 |
+
Returns: True if analytics are enabled, False otherwise.
|
| 25 |
+
"""
|
| 26 |
+
return os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _do_analytics_request(url: str, data: dict[str, Any]) -> None:
|
| 30 |
+
try:
|
| 31 |
+
requests.post(url, data=data, timeout=5)
|
| 32 |
+
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
|
| 33 |
+
pass # do not push analytics if no network
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def version_check():
|
| 37 |
+
if not analytics_enabled():
|
| 38 |
+
return
|
| 39 |
+
try:
|
| 40 |
+
version_data = pkgutil.get_data(__name__, "version.txt")
|
| 41 |
+
if not version_data:
|
| 42 |
+
raise FileNotFoundError
|
| 43 |
+
current_pkg_version = version_data.decode("ascii").strip()
|
| 44 |
+
latest_pkg_version = requests.get(url=PKG_VERSION_URL, timeout=3).json()[
|
| 45 |
+
"version"
|
| 46 |
+
]
|
| 47 |
+
if StrictVersion(latest_pkg_version) > StrictVersion(current_pkg_version):
|
| 48 |
+
print(
|
| 49 |
+
f"IMPORTANT: You are using gradio version {current_pkg_version}, "
|
| 50 |
+
f"however version {latest_pkg_version} is available, please upgrade."
|
| 51 |
+
)
|
| 52 |
+
print("--------")
|
| 53 |
+
except json.decoder.JSONDecodeError:
|
| 54 |
+
warnings.warn("unable to parse version details from package URL.")
|
| 55 |
+
except KeyError:
|
| 56 |
+
warnings.warn("package URL does not contain version info.")
|
| 57 |
+
except Exception:
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_local_ip_address() -> str:
|
| 62 |
+
"""
|
| 63 |
+
Gets the public IP address or returns the string "No internet connection" if unable
|
| 64 |
+
to obtain it or the string "Analytics disabled" if a user has disabled analytics.
|
| 65 |
+
Does not make a new request if the IP address has already been obtained in the
|
| 66 |
+
same Python session.
|
| 67 |
+
"""
|
| 68 |
+
if not analytics_enabled():
|
| 69 |
+
return "Analytics disabled"
|
| 70 |
+
|
| 71 |
+
if Context.ip_address is None:
|
| 72 |
+
try:
|
| 73 |
+
ip_address = requests.get(
|
| 74 |
+
"https://checkip.amazonaws.com/", timeout=3
|
| 75 |
+
).text.strip()
|
| 76 |
+
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
|
| 77 |
+
ip_address = "No internet connection"
|
| 78 |
+
Context.ip_address = ip_address
|
| 79 |
+
else:
|
| 80 |
+
ip_address = Context.ip_address
|
| 81 |
+
return ip_address
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def initiated_analytics(data: dict[str, Any]) -> None:
|
| 85 |
+
if not analytics_enabled():
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
threading.Thread(
|
| 89 |
+
target=_do_analytics_request,
|
| 90 |
+
kwargs={
|
| 91 |
+
"url": f"{ANALYTICS_URL}gradio-initiated-analytics/",
|
| 92 |
+
"data": {**data, "ip_address": get_local_ip_address()},
|
| 93 |
+
},
|
| 94 |
+
).start()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def launched_analytics(blocks: gradio.Blocks, data: dict[str, Any]) -> None:
|
| 98 |
+
if not analytics_enabled():
|
| 99 |
+
return
|
| 100 |
+
|
| 101 |
+
blocks_telemetry, inputs_telemetry, outputs_telemetry, targets_telemetry = (
|
| 102 |
+
[],
|
| 103 |
+
[],
|
| 104 |
+
[],
|
| 105 |
+
[],
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
from gradio.blocks import BlockContext
|
| 109 |
+
|
| 110 |
+
for x in list(blocks.blocks.values()):
|
| 111 |
+
blocks_telemetry.append(x.get_block_name()) if isinstance(
|
| 112 |
+
x, BlockContext
|
| 113 |
+
) else blocks_telemetry.append(str(x))
|
| 114 |
+
|
| 115 |
+
for x in blocks.dependencies:
|
| 116 |
+
targets_telemetry = targets_telemetry + [
|
| 117 |
+
# Sometimes the target can be the Blocks object itself, so we need to check if its in blocks.blocks
|
| 118 |
+
str(blocks.blocks[y])
|
| 119 |
+
for y in x["targets"]
|
| 120 |
+
if y in blocks.blocks
|
| 121 |
+
]
|
| 122 |
+
inputs_telemetry = inputs_telemetry + [
|
| 123 |
+
str(blocks.blocks[y]) for y in x["inputs"]
|
| 124 |
+
]
|
| 125 |
+
outputs_telemetry = outputs_telemetry + [
|
| 126 |
+
str(blocks.blocks[y]) for y in x["outputs"]
|
| 127 |
+
]
|
| 128 |
+
additional_data = {
|
| 129 |
+
"version": GRADIO_VERSION,
|
| 130 |
+
"is_kaggle": blocks.is_kaggle,
|
| 131 |
+
"is_sagemaker": blocks.is_sagemaker,
|
| 132 |
+
"using_auth": blocks.auth is not None,
|
| 133 |
+
"dev_mode": blocks.dev_mode,
|
| 134 |
+
"show_api": blocks.show_api,
|
| 135 |
+
"show_error": blocks.show_error,
|
| 136 |
+
"title": blocks.title,
|
| 137 |
+
"inputs": blocks.input_components
|
| 138 |
+
if blocks.mode == "interface"
|
| 139 |
+
else inputs_telemetry,
|
| 140 |
+
"outputs": blocks.output_components
|
| 141 |
+
if blocks.mode == "interface"
|
| 142 |
+
else outputs_telemetry,
|
| 143 |
+
"targets": targets_telemetry,
|
| 144 |
+
"blocks": blocks_telemetry,
|
| 145 |
+
"events": [str(x["trigger"]) for x in blocks.dependencies],
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
data.update(additional_data)
|
| 149 |
+
data.update({"ip_address": get_local_ip_address()})
|
| 150 |
+
|
| 151 |
+
threading.Thread(
|
| 152 |
+
target=_do_analytics_request,
|
| 153 |
+
kwargs={
|
| 154 |
+
"url": f"{ANALYTICS_URL}gradio-launched-telemetry/",
|
| 155 |
+
"data": data,
|
| 156 |
+
},
|
| 157 |
+
).start()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def integration_analytics(data: dict[str, Any]) -> None:
|
| 161 |
+
if not analytics_enabled():
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
threading.Thread(
|
| 165 |
+
target=_do_analytics_request,
|
| 166 |
+
kwargs={
|
| 167 |
+
"url": f"{ANALYTICS_URL}gradio-integration-analytics/",
|
| 168 |
+
"data": {**data, "ip_address": get_local_ip_address()},
|
| 169 |
+
},
|
| 170 |
+
).start()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def error_analytics(message: str) -> None:
|
| 174 |
+
"""
|
| 175 |
+
Send error analytics if there is network
|
| 176 |
+
Parameters:
|
| 177 |
+
message: Details about error
|
| 178 |
+
"""
|
| 179 |
+
if not analytics_enabled():
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
data = {"ip_address": get_local_ip_address(), "error": message}
|
| 183 |
+
|
| 184 |
+
threading.Thread(
|
| 185 |
+
target=_do_analytics_request,
|
| 186 |
+
kwargs={
|
| 187 |
+
"url": f"{ANALYTICS_URL}gradio-error-analytics/",
|
| 188 |
+
"data": data,
|
| 189 |
+
},
|
| 190 |
+
).start()
|
falcon/lib/python3.10/site-packages/gradio/cli.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
import gradio.deploy_space
|
| 4 |
+
import gradio.reload
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def cli():
|
| 8 |
+
args = sys.argv[1:]
|
| 9 |
+
if len(args) == 0:
|
| 10 |
+
raise ValueError("No file specified.")
|
| 11 |
+
if args[0] == "deploy":
|
| 12 |
+
gradio.deploy_space.deploy()
|
| 13 |
+
else:
|
| 14 |
+
gradio.reload.main()
|
falcon/lib/python3.10/site-packages/gradio/context.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defines the Context class, which is used to store the state of all Blocks that are being rendered.
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import TYPE_CHECKING
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
|
| 8 |
+
from gradio.blocks import BlockContext, Blocks
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Context:
|
| 12 |
+
root_block: Blocks | None = None # The current root block that holds all blocks.
|
| 13 |
+
block: BlockContext | None = None # The current block that children are added to.
|
| 14 |
+
id: int = 0 # Running id to uniquely refer to any block that gets defined
|
| 15 |
+
ip_address: str | None = None # The IP address of the user.
|
| 16 |
+
hf_token: str | None = None # The token provided when loading private HF repos
|
falcon/lib/python3.10/site-packages/gradio/deploy_space.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import huggingface_hub
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
|
| 11 |
+
repo_directory = os.getcwd()
|
| 12 |
+
readme_file = os.path.join(repo_directory, "README.md")
|
| 13 |
+
github_action_template = os.path.join(
|
| 14 |
+
os.path.dirname(__file__), "deploy_space_action.yaml"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def add_configuration_to_readme(
|
| 19 |
+
title: str | None,
|
| 20 |
+
app_file: str | None,
|
| 21 |
+
) -> dict:
|
| 22 |
+
configuration = {}
|
| 23 |
+
|
| 24 |
+
dir_name = os.path.basename(repo_directory)
|
| 25 |
+
if title is None:
|
| 26 |
+
title = input(f"Enter Spaces app title [{dir_name}]: ") or dir_name
|
| 27 |
+
formatted_title = format_title(title)
|
| 28 |
+
if formatted_title != title:
|
| 29 |
+
print(f"Formatted to {formatted_title}. ")
|
| 30 |
+
configuration["title"] = formatted_title
|
| 31 |
+
|
| 32 |
+
if app_file is None:
|
| 33 |
+
for file in os.listdir(repo_directory):
|
| 34 |
+
file_path = os.path.join(repo_directory, file)
|
| 35 |
+
if not os.path.isfile(file_path) or not file.endswith(".py"):
|
| 36 |
+
continue
|
| 37 |
+
|
| 38 |
+
with open(file_path, encoding="utf-8", errors="ignore") as f:
|
| 39 |
+
content = f.read()
|
| 40 |
+
if "import gradio" in content:
|
| 41 |
+
app_file = file
|
| 42 |
+
break
|
| 43 |
+
|
| 44 |
+
app_file = (
|
| 45 |
+
input(f"Enter Gradio app file {f'[{app_file}]' if app_file else ''}: ")
|
| 46 |
+
or app_file
|
| 47 |
+
)
|
| 48 |
+
if not app_file or not os.path.exists(app_file):
|
| 49 |
+
raise FileNotFoundError("Failed to find Gradio app file.")
|
| 50 |
+
configuration["app_file"] = app_file
|
| 51 |
+
|
| 52 |
+
configuration["sdk"] = "gradio"
|
| 53 |
+
configuration["sdk_version"] = gr.__version__
|
| 54 |
+
huggingface_hub.metadata_save(readme_file, configuration)
|
| 55 |
+
|
| 56 |
+
configuration["hardware"] = (
|
| 57 |
+
input(
|
| 58 |
+
f"Enter Spaces hardware ({', '.join(hardware.value for hardware in huggingface_hub.SpaceHardware)}) [cpu-basic]: "
|
| 59 |
+
)
|
| 60 |
+
or "cpu-basic"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
secrets = {}
|
| 64 |
+
if input("Any Spaces secrets (y/n) [n]: ") == "y":
|
| 65 |
+
while True:
|
| 66 |
+
secret_name = input("Enter secret name (leave blank to end): ")
|
| 67 |
+
if not secret_name:
|
| 68 |
+
break
|
| 69 |
+
secret_value = input(f"Enter secret value for {secret_name}: ")
|
| 70 |
+
secrets[secret_name] = secret_value
|
| 71 |
+
configuration["secrets"] = secrets
|
| 72 |
+
|
| 73 |
+
requirements_file = os.path.join(repo_directory, "requirements.txt")
|
| 74 |
+
if (
|
| 75 |
+
not os.path.exists(requirements_file)
|
| 76 |
+
and input("Create requirements.txt file? (y/n) [n]: ").lower() == "y"
|
| 77 |
+
):
|
| 78 |
+
while True:
|
| 79 |
+
requirement = input("Enter a dependency (leave blank to end): ")
|
| 80 |
+
if not requirement:
|
| 81 |
+
break
|
| 82 |
+
with open(requirements_file, "a") as f:
|
| 83 |
+
f.write(requirement + "\n")
|
| 84 |
+
|
| 85 |
+
if (
|
| 86 |
+
input(
|
| 87 |
+
"Create Github Action to automatically update Space on 'git push'? [n]: "
|
| 88 |
+
).lower()
|
| 89 |
+
== "y"
|
| 90 |
+
):
|
| 91 |
+
track_branch = input("Enter branch to track [main]: ") or "main"
|
| 92 |
+
github_action_file = os.path.join(
|
| 93 |
+
repo_directory, ".github/workflows/update_space.yml"
|
| 94 |
+
)
|
| 95 |
+
os.makedirs(os.path.dirname(github_action_file), exist_ok=True)
|
| 96 |
+
with open(github_action_template) as f:
|
| 97 |
+
github_action_content = f.read()
|
| 98 |
+
github_action_content = github_action_content.replace("$branch", track_branch)
|
| 99 |
+
with open(github_action_file, "w") as f:
|
| 100 |
+
f.write(github_action_content)
|
| 101 |
+
|
| 102 |
+
print(
|
| 103 |
+
"Github Action created. Add your Hugging Face write token (from https://huggingface.co/settings/tokens) as an Actions Secret named 'hf_token' to your GitHub repository. This can be set in your repository's settings page."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
return configuration
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def format_title(title: str):
|
| 110 |
+
title = title.replace(" ", "_")
|
| 111 |
+
title = re.sub(r"[^a-zA-Z0-9\-._]", "", title)
|
| 112 |
+
title = re.sub("-+", "-", title)
|
| 113 |
+
while title.startswith("."):
|
| 114 |
+
title = title[1:]
|
| 115 |
+
return title
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def deploy():
|
| 119 |
+
if (
|
| 120 |
+
os.getenv("SYSTEM") == "spaces"
|
| 121 |
+
): # in case a repo with this function is uploaded to spaces
|
| 122 |
+
return
|
| 123 |
+
parser = argparse.ArgumentParser(description="Deploy to Spaces")
|
| 124 |
+
parser.add_argument("deploy")
|
| 125 |
+
parser.add_argument("--title", type=str, help="Spaces app title")
|
| 126 |
+
parser.add_argument("--app-file", type=str, help="File containing the Gradio app")
|
| 127 |
+
|
| 128 |
+
args = parser.parse_args()
|
| 129 |
+
|
| 130 |
+
hf_api = huggingface_hub.HfApi()
|
| 131 |
+
whoami = None
|
| 132 |
+
login = False
|
| 133 |
+
try:
|
| 134 |
+
whoami = hf_api.whoami()
|
| 135 |
+
if whoami["auth"]["accessToken"]["role"] != "write":
|
| 136 |
+
login = True
|
| 137 |
+
except OSError:
|
| 138 |
+
login = True
|
| 139 |
+
if login:
|
| 140 |
+
print("Need 'write' access token to create a Spaces repo.")
|
| 141 |
+
huggingface_hub.login(add_to_git_credential=False)
|
| 142 |
+
whoami = hf_api.whoami()
|
| 143 |
+
|
| 144 |
+
configuration: None | dict = None
|
| 145 |
+
if os.path.exists(readme_file):
|
| 146 |
+
try:
|
| 147 |
+
configuration = huggingface_hub.metadata_load(readme_file)
|
| 148 |
+
except ValueError:
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
if configuration is None:
|
| 152 |
+
print(
|
| 153 |
+
f"Creating new Spaces Repo in '{repo_directory}'. Collecting metadata, press Enter to accept default value."
|
| 154 |
+
)
|
| 155 |
+
configuration = add_configuration_to_readme(
|
| 156 |
+
args.title,
|
| 157 |
+
args.app_file,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
space_id = huggingface_hub.create_repo(
|
| 161 |
+
configuration["title"],
|
| 162 |
+
space_sdk="gradio",
|
| 163 |
+
repo_type="space",
|
| 164 |
+
exist_ok=True,
|
| 165 |
+
space_hardware=configuration.get("hardware"),
|
| 166 |
+
).repo_id
|
| 167 |
+
hf_api.upload_folder(
|
| 168 |
+
repo_id=space_id,
|
| 169 |
+
repo_type="space",
|
| 170 |
+
folder_path=repo_directory,
|
| 171 |
+
)
|
| 172 |
+
if configuration.get("secrets"):
|
| 173 |
+
for secret_name, secret_value in configuration["secrets"].items():
|
| 174 |
+
huggingface_hub.add_space_secret(space_id, secret_name, secret_value)
|
| 175 |
+
print(f"Space available at https://huggingface.co/spaces/{space_id}")
|
falcon/lib/python3.10/site-packages/gradio/deprecation.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def simple_deprecated_notice(term: str) -> str:
|
| 5 |
+
return f"`{term}` parameter is deprecated, and it has no effect"
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def use_in_launch(term: str) -> str:
|
| 9 |
+
return f"`{term}` is deprecated in `Interface()`, please use it within `launch()` instead."
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
DEPRECATION_MESSAGE = {
|
| 13 |
+
"optional": simple_deprecated_notice("optional"),
|
| 14 |
+
"keep_filename": simple_deprecated_notice("keep_filename"),
|
| 15 |
+
"numeric": simple_deprecated_notice("numeric"),
|
| 16 |
+
"verbose": simple_deprecated_notice("verbose"),
|
| 17 |
+
"allow_screenshot": simple_deprecated_notice("allow_screenshot"),
|
| 18 |
+
"layout": simple_deprecated_notice("layout"),
|
| 19 |
+
"show_input": simple_deprecated_notice("show_input"),
|
| 20 |
+
"show_output": simple_deprecated_notice("show_output"),
|
| 21 |
+
"capture_session": simple_deprecated_notice("capture_session"),
|
| 22 |
+
"api_mode": simple_deprecated_notice("api_mode"),
|
| 23 |
+
"show_tips": use_in_launch("show_tips"),
|
| 24 |
+
"encrypt": simple_deprecated_notice("encrypt"),
|
| 25 |
+
"enable_queue": use_in_launch("enable_queue"),
|
| 26 |
+
"server_name": use_in_launch("server_name"),
|
| 27 |
+
"server_port": use_in_launch("server_port"),
|
| 28 |
+
"width": use_in_launch("width"),
|
| 29 |
+
"height": use_in_launch("height"),
|
| 30 |
+
"plot": "The 'plot' parameter has been deprecated. Use the new Plot component instead",
|
| 31 |
+
"type": "The 'type' parameter has been deprecated. Use the Number component instead.",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def check_deprecated_parameters(cls: str, *, stacklevel: int = 2, kwargs) -> None:
|
| 36 |
+
for key, value in DEPRECATION_MESSAGE.items():
|
| 37 |
+
if key in kwargs:
|
| 38 |
+
kwargs.pop(key)
|
| 39 |
+
# Interestingly, using DeprecationWarning causes warning to not appear.
|
| 40 |
+
warnings.warn(value, stacklevel=stacklevel)
|
| 41 |
+
|
| 42 |
+
if kwargs:
|
| 43 |
+
warnings.warn(
|
| 44 |
+
f"You have unused kwarg parameters in {cls}, please remove them: {kwargs}",
|
| 45 |
+
stacklevel=stacklevel,
|
| 46 |
+
)
|
falcon/lib/python3.10/site-packages/gradio/events.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contains all of the events that can be triggered in a gr.Blocks() app, with the exception
|
| 2 |
+
of the on-page-load event, which is defined in gr.Blocks().load()."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Callable, Literal
|
| 8 |
+
|
| 9 |
+
from gradio_client.documentation import document, set_documentation_group
|
| 10 |
+
|
| 11 |
+
from gradio.blocks import Block
|
| 12 |
+
from gradio.helpers import EventData
|
| 13 |
+
from gradio.utils import get_cancel_function
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
|
| 16 |
+
from gradio.components import Component
|
| 17 |
+
|
| 18 |
+
set_documentation_group("events")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def set_cancel_events(
|
| 22 |
+
block: Block, event_name: str, cancels: None | dict[str, Any] | list[dict[str, Any]]
|
| 23 |
+
):
|
| 24 |
+
if cancels:
|
| 25 |
+
if not isinstance(cancels, list):
|
| 26 |
+
cancels = [cancels]
|
| 27 |
+
cancel_fn, fn_indices_to_cancel = get_cancel_function(cancels)
|
| 28 |
+
block.set_event_trigger(
|
| 29 |
+
event_name,
|
| 30 |
+
cancel_fn,
|
| 31 |
+
inputs=None,
|
| 32 |
+
outputs=None,
|
| 33 |
+
queue=False,
|
| 34 |
+
preprocess=False,
|
| 35 |
+
cancels=fn_indices_to_cancel,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class EventListener(Block):
|
| 40 |
+
def __init__(self: Any):
|
| 41 |
+
for event_listener_class in EventListener.__subclasses__():
|
| 42 |
+
if isinstance(self, event_listener_class):
|
| 43 |
+
event_listener_class.__init__(self)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Dependency(dict):
|
| 47 |
+
def __init__(self, trigger, key_vals, dep_index):
|
| 48 |
+
super().__init__(key_vals)
|
| 49 |
+
self.trigger = trigger
|
| 50 |
+
self.then = EventListenerMethod(
|
| 51 |
+
self.trigger,
|
| 52 |
+
"then",
|
| 53 |
+
trigger_after=dep_index,
|
| 54 |
+
trigger_only_on_success=False,
|
| 55 |
+
)
|
| 56 |
+
"""
|
| 57 |
+
Triggered after directly preceding event is completed, regardless of success or failure.
|
| 58 |
+
"""
|
| 59 |
+
self.success = EventListenerMethod(
|
| 60 |
+
self.trigger,
|
| 61 |
+
"success",
|
| 62 |
+
trigger_after=dep_index,
|
| 63 |
+
trigger_only_on_success=True,
|
| 64 |
+
)
|
| 65 |
+
"""
|
| 66 |
+
Triggered after directly preceding event is completed, if it was successful.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class EventListenerMethod:
|
| 71 |
+
"""
|
| 72 |
+
Triggered on an event deployment.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
trigger: Block,
|
| 78 |
+
event_name: str,
|
| 79 |
+
show_progress: Literal["full"]
|
| 80 |
+
| Literal["minimal"]
|
| 81 |
+
| Literal["hidden"] = "full",
|
| 82 |
+
callback: Callable | None = None,
|
| 83 |
+
trigger_after: int | None = None,
|
| 84 |
+
trigger_only_on_success: bool = False,
|
| 85 |
+
):
|
| 86 |
+
self.trigger = trigger
|
| 87 |
+
self.event_name = event_name
|
| 88 |
+
self.show_progress = show_progress
|
| 89 |
+
self.callback = callback
|
| 90 |
+
self.trigger_after = trigger_after
|
| 91 |
+
self.trigger_only_on_success = trigger_only_on_success
|
| 92 |
+
|
| 93 |
+
def __call__(
|
| 94 |
+
self,
|
| 95 |
+
fn: Callable | None,
|
| 96 |
+
inputs: Component | list[Component] | set[Component] | None = None,
|
| 97 |
+
outputs: Component | list[Component] | None = None,
|
| 98 |
+
api_name: str | None = None,
|
| 99 |
+
status_tracker: None = None,
|
| 100 |
+
scroll_to_output: bool = False,
|
| 101 |
+
show_progress: Literal["full"]
|
| 102 |
+
| Literal["minimal"]
|
| 103 |
+
| Literal["hidden"] = "full",
|
| 104 |
+
queue: bool | None = None,
|
| 105 |
+
batch: bool = False,
|
| 106 |
+
max_batch_size: int = 4,
|
| 107 |
+
preprocess: bool = True,
|
| 108 |
+
postprocess: bool = True,
|
| 109 |
+
cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
|
| 110 |
+
every: float | None = None,
|
| 111 |
+
_js: str | None = None,
|
| 112 |
+
) -> Dependency:
|
| 113 |
+
"""
|
| 114 |
+
Parameters:
|
| 115 |
+
fn: the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
|
| 116 |
+
inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
|
| 117 |
+
outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
|
| 118 |
+
api_name: Defining this parameter exposes the endpoint in the api docs
|
| 119 |
+
scroll_to_output: If True, will scroll to output component on completion
|
| 120 |
+
show_progress: If True, will show progress animation while pending
|
| 121 |
+
queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
|
| 122 |
+
batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
|
| 123 |
+
max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
|
| 124 |
+
preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
|
| 125 |
+
postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
|
| 126 |
+
cancels: A list of other events to cancel when This listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
|
| 127 |
+
every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
|
| 128 |
+
"""
|
| 129 |
+
if status_tracker:
|
| 130 |
+
warnings.warn(
|
| 131 |
+
"The 'status_tracker' parameter has been deprecated and has no effect."
|
| 132 |
+
)
|
| 133 |
+
if self.event_name == "stop":
|
| 134 |
+
warnings.warn(
|
| 135 |
+
"The `stop` event on Video and Audio has been deprecated and will be remove in a future version. Use `ended` instead."
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
if isinstance(self, Streamable):
|
| 139 |
+
self.check_streamable()
|
| 140 |
+
if isinstance(show_progress, bool):
|
| 141 |
+
show_progress = "full" if show_progress else "hidden"
|
| 142 |
+
|
| 143 |
+
dep, dep_index = self.trigger.set_event_trigger(
|
| 144 |
+
self.event_name,
|
| 145 |
+
fn,
|
| 146 |
+
inputs,
|
| 147 |
+
outputs,
|
| 148 |
+
preprocess=preprocess,
|
| 149 |
+
postprocess=postprocess,
|
| 150 |
+
scroll_to_output=scroll_to_output,
|
| 151 |
+
show_progress=show_progress
|
| 152 |
+
if show_progress is not None
|
| 153 |
+
else self.show_progress,
|
| 154 |
+
api_name=api_name,
|
| 155 |
+
js=_js,
|
| 156 |
+
queue=queue,
|
| 157 |
+
batch=batch,
|
| 158 |
+
max_batch_size=max_batch_size,
|
| 159 |
+
every=every,
|
| 160 |
+
trigger_after=self.trigger_after,
|
| 161 |
+
trigger_only_on_success=self.trigger_only_on_success,
|
| 162 |
+
)
|
| 163 |
+
set_cancel_events(self.trigger, self.event_name, cancels)
|
| 164 |
+
if self.callback:
|
| 165 |
+
self.callback()
|
| 166 |
+
return Dependency(self.trigger, dep, dep_index)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@document("*change", inherit=True)
|
| 170 |
+
class Changeable(EventListener):
|
| 171 |
+
def __init__(self):
|
| 172 |
+
self.change = EventListenerMethod(self, "change")
|
| 173 |
+
"""
|
| 174 |
+
This listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger).
|
| 175 |
+
See `.input()` for a listener that is only triggered by user input.
|
| 176 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@document("*input", inherit=True)
|
| 181 |
+
class Inputable(EventListener):
|
| 182 |
+
def __init__(self):
|
| 183 |
+
self.input = EventListenerMethod(self, "input")
|
| 184 |
+
"""
|
| 185 |
+
This listener is triggered when the user changes the value of the component.
|
| 186 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@document("*click", inherit=True)
|
| 191 |
+
class Clickable(EventListener):
|
| 192 |
+
def __init__(self):
|
| 193 |
+
self.click = EventListenerMethod(self, "click")
|
| 194 |
+
"""
|
| 195 |
+
This listener is triggered when the component (e.g. a button) is clicked.
|
| 196 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@document("*submit", inherit=True)
|
| 201 |
+
class Submittable(EventListener):
|
| 202 |
+
def __init__(self):
|
| 203 |
+
self.submit = EventListenerMethod(self, "submit")
|
| 204 |
+
"""
|
| 205 |
+
This listener is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused.
|
| 206 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@document("*edit", inherit=True)
|
| 211 |
+
class Editable(EventListener):
|
| 212 |
+
def __init__(self):
|
| 213 |
+
self.edit = EventListenerMethod(self, "edit")
|
| 214 |
+
"""
|
| 215 |
+
This listener is triggered when the user edits the component (e.g. image) using the
|
| 216 |
+
built-in editor. This method can be used when this component is in a Gradio Blocks.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@document("*clear", inherit=True)
|
| 221 |
+
class Clearable(EventListener):
|
| 222 |
+
def __init__(self):
|
| 223 |
+
self.clear = EventListenerMethod(self, "clear")
|
| 224 |
+
"""
|
| 225 |
+
This listener is triggered when the user clears the component (e.g. image or audio)
|
| 226 |
+
using the X button for the component. This method can be used when this component is in a Gradio Blocks.
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@document("*play", "*pause", "*stop", inherit=True)
|
| 231 |
+
class Playable(EventListener):
|
| 232 |
+
def __init__(self):
|
| 233 |
+
self.play = EventListenerMethod(self, "play")
|
| 234 |
+
"""
|
| 235 |
+
This listener is triggered when the user plays the component (e.g. audio or video).
|
| 236 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
self.pause = EventListenerMethod(self, "pause")
|
| 240 |
+
"""
|
| 241 |
+
This listener is triggered when the media stops playing for any reason (e.g. audio or video).
|
| 242 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
self.stop = EventListenerMethod(self, "stop")
|
| 246 |
+
"""
|
| 247 |
+
This listener is triggered when the user reaches the end of the media track (e.g. audio or video).
|
| 248 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
self.end = EventListenerMethod(self, "end")
|
| 252 |
+
"""
|
| 253 |
+
This listener is triggered when the user reaches the end of the media track (e.g. audio or video).
|
| 254 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 255 |
+
"""
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@document("*stream", inherit=True)
|
| 259 |
+
class Streamable(EventListener):
|
| 260 |
+
def __init__(self):
|
| 261 |
+
self.streaming: bool
|
| 262 |
+
self.stream = EventListenerMethod(
|
| 263 |
+
self,
|
| 264 |
+
"stream",
|
| 265 |
+
show_progress="hidden",
|
| 266 |
+
callback=lambda: setattr(self, "streaming", True),
|
| 267 |
+
)
|
| 268 |
+
"""
|
| 269 |
+
This listener is triggered when the user streams the component (e.g. a live webcam
|
| 270 |
+
component). This method can be used when this component is in a Gradio Blocks.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def check_streamable(self):
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@document("*start_recording", "*stop_recording", inherit=True)
|
| 278 |
+
class Recordable(EventListener):
|
| 279 |
+
def __init__(self):
|
| 280 |
+
self.start_recording = EventListenerMethod(self, "start_recording")
|
| 281 |
+
"""
|
| 282 |
+
This listener is triggered when the user starts recording with the component (e.g. audio or video).
|
| 283 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
self.stop_recording = EventListenerMethod(self, "stop_recording")
|
| 287 |
+
"""
|
| 288 |
+
This listener is triggered when the user stops recording with the component (e.g. audio or video).
|
| 289 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@document("*blur", inherit=True)
|
| 294 |
+
class Blurrable(EventListener):
|
| 295 |
+
def __init__(self):
|
| 296 |
+
self.blur = EventListenerMethod(self, "blur")
|
| 297 |
+
"""
|
| 298 |
+
This listener is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox).
|
| 299 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@document("*upload", inherit=True)
|
| 304 |
+
class Uploadable(EventListener):
|
| 305 |
+
def __init__(self):
|
| 306 |
+
self.upload = EventListenerMethod(self, "upload")
|
| 307 |
+
"""
|
| 308 |
+
This listener is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component).
|
| 309 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 310 |
+
"""
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@document("*release", inherit=True)
|
| 314 |
+
class Releaseable(EventListener):
|
| 315 |
+
def __init__(self):
|
| 316 |
+
self.release = EventListenerMethod(self, "release")
|
| 317 |
+
"""
|
| 318 |
+
This listener is triggered when the user releases the mouse on this component (e.g. when the user releases the slider).
|
| 319 |
+
This method can be used when this component is in a Gradio Blocks.
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@document("*select", inherit=True)
|
| 324 |
+
class Selectable(EventListener):
|
| 325 |
+
def __init__(self):
|
| 326 |
+
self.selectable: bool = False
|
| 327 |
+
self.select = EventListenerMethod(
|
| 328 |
+
self, "select", callback=lambda: setattr(self, "selectable", True)
|
| 329 |
+
)
|
| 330 |
+
"""
|
| 331 |
+
This listener is triggered when the user selects from within the Component.
|
| 332 |
+
This event has EventData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value.
|
| 333 |
+
See EventData documentation on how to use this event data.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class SelectData(EventData):
|
| 338 |
+
def __init__(self, target: Block | None, data: Any):
|
| 339 |
+
super().__init__(target, data)
|
| 340 |
+
self.index: int | tuple[int, int] = data["index"]
|
| 341 |
+
"""
|
| 342 |
+
The index of the selected item. Is a tuple if the component is two dimensional or selection is a range.
|
| 343 |
+
"""
|
| 344 |
+
self.value: Any = data["value"]
|
| 345 |
+
"""
|
| 346 |
+
The value of the selected item.
|
| 347 |
+
"""
|
| 348 |
+
self.selected: bool = data.get("selected", True)
|
| 349 |
+
"""
|
| 350 |
+
True if the item was selected, False if deselected.
|
| 351 |
+
"""
|
falcon/lib/python3.10/site-packages/gradio/exceptions.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from gradio_client.documentation import document, set_documentation_group
|
| 2 |
+
|
| 3 |
+
set_documentation_group("helpers")
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DuplicateBlockError(ValueError):
|
| 7 |
+
"""Raised when a Blocks contains more than one Block with the same id"""
|
| 8 |
+
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TooManyRequestsError(Exception):
|
| 13 |
+
"""Raised when the Hugging Face API returns a 429 status code."""
|
| 14 |
+
|
| 15 |
+
pass
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class InvalidApiNameError(ValueError):
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
InvalidApiName = InvalidApiNameError # backwards compatibility
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@document()
|
| 26 |
+
class Error(Exception):
|
| 27 |
+
"""
|
| 28 |
+
This class allows you to pass custom error messages to the user. You can do so by raising a gr.Error("custom message") anywhere in the code, and when that line is executed the custom message will appear in a modal on the demo.
|
| 29 |
+
|
| 30 |
+
Demos: calculator
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, message: str):
|
| 34 |
+
"""
|
| 35 |
+
Parameters:
|
| 36 |
+
message: The error message to be displayed to the user.
|
| 37 |
+
"""
|
| 38 |
+
self.message = message
|
| 39 |
+
super().__init__(self.message)
|
| 40 |
+
|
| 41 |
+
def __str__(self):
|
| 42 |
+
return repr(self.message)
|
falcon/lib/python3.10/site-packages/gradio/external_utils.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utility function for gradio/external.py"""
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import math
|
| 5 |
+
import operator
|
| 6 |
+
import re
|
| 7 |
+
import warnings
|
| 8 |
+
from typing import Dict, List, Tuple
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
import yaml
|
| 12 |
+
|
| 13 |
+
from gradio import components
|
| 14 |
+
|
| 15 |
+
##################
|
| 16 |
+
# Helper functions for processing tabular data
|
| 17 |
+
##################
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_tabular_examples(model_name: str) -> Dict[str, List[float]]:
|
| 21 |
+
readme = requests.get(f"https://huggingface.co/{model_name}/resolve/main/README.md")
|
| 22 |
+
if readme.status_code != 200:
|
| 23 |
+
warnings.warn(f"Cannot load examples from README for {model_name}", UserWarning)
|
| 24 |
+
example_data = {}
|
| 25 |
+
else:
|
| 26 |
+
yaml_regex = re.search(
|
| 27 |
+
"(?:^|[\r\n])---[\n\r]+([\\S\\s]*?)[\n\r]+---([\n\r]|$)", readme.text
|
| 28 |
+
)
|
| 29 |
+
if yaml_regex is None:
|
| 30 |
+
example_data = {}
|
| 31 |
+
else:
|
| 32 |
+
example_yaml = next(
|
| 33 |
+
yaml.safe_load_all(readme.text[: yaml_regex.span()[-1]])
|
| 34 |
+
)
|
| 35 |
+
example_data = example_yaml.get("widget", {}).get("structuredData", {})
|
| 36 |
+
if not example_data:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
f"No example data found in README.md of {model_name} - Cannot build gradio demo. "
|
| 39 |
+
"See the README.md here: https://huggingface.co/scikit-learn/tabular-playground/blob/main/README.md "
|
| 40 |
+
"for a reference on how to provide example data to your model."
|
| 41 |
+
)
|
| 42 |
+
# replace nan with string NaN for inference API
|
| 43 |
+
for data in example_data.values():
|
| 44 |
+
for i, val in enumerate(data):
|
| 45 |
+
if isinstance(val, float) and math.isnan(val):
|
| 46 |
+
data[i] = "NaN"
|
| 47 |
+
return example_data
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def cols_to_rows(
|
| 51 |
+
example_data: Dict[str, List[float]]
|
| 52 |
+
) -> Tuple[List[str], List[List[float]]]:
|
| 53 |
+
headers = list(example_data.keys())
|
| 54 |
+
n_rows = max(len(example_data[header] or []) for header in headers)
|
| 55 |
+
data = []
|
| 56 |
+
for row_index in range(n_rows):
|
| 57 |
+
row_data = []
|
| 58 |
+
for header in headers:
|
| 59 |
+
col = example_data[header] or []
|
| 60 |
+
if row_index >= len(col):
|
| 61 |
+
row_data.append("NaN")
|
| 62 |
+
else:
|
| 63 |
+
row_data.append(col[row_index])
|
| 64 |
+
data.append(row_data)
|
| 65 |
+
return headers, data
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def rows_to_cols(incoming_data: Dict) -> Dict[str, Dict[str, Dict[str, List[str]]]]:
|
| 69 |
+
data_column_wise = {}
|
| 70 |
+
for i, header in enumerate(incoming_data["headers"]):
|
| 71 |
+
data_column_wise[header] = [str(row[i]) for row in incoming_data["data"]]
|
| 72 |
+
return {"inputs": {"data": data_column_wise}}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
##################
|
| 76 |
+
# Helper functions for processing other kinds of data
|
| 77 |
+
##################
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def postprocess_label(scores: Dict) -> Dict:
|
| 81 |
+
sorted_pred = sorted(scores.items(), key=operator.itemgetter(1), reverse=True)
|
| 82 |
+
return {
|
| 83 |
+
"label": sorted_pred[0][0],
|
| 84 |
+
"confidences": [
|
| 85 |
+
{"label": pred[0], "confidence": pred[1]} for pred in sorted_pred
|
| 86 |
+
],
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def encode_to_base64(r: requests.Response) -> str:
|
| 91 |
+
# Handles the different ways HF API returns the prediction
|
| 92 |
+
base64_repr = base64.b64encode(r.content).decode("utf-8")
|
| 93 |
+
data_prefix = ";base64,"
|
| 94 |
+
# Case 1: base64 representation already includes data prefix
|
| 95 |
+
if data_prefix in base64_repr:
|
| 96 |
+
return base64_repr
|
| 97 |
+
else:
|
| 98 |
+
content_type = r.headers.get("content-type")
|
| 99 |
+
# Case 2: the data prefix is a key in the response
|
| 100 |
+
if content_type == "application/json":
|
| 101 |
+
try:
|
| 102 |
+
data = r.json()[0]
|
| 103 |
+
content_type = data["content-type"]
|
| 104 |
+
base64_repr = data["blob"]
|
| 105 |
+
except KeyError as ke:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"Cannot determine content type returned by external API."
|
| 108 |
+
) from ke
|
| 109 |
+
# Case 3: the data prefix is included in the response headers
|
| 110 |
+
else:
|
| 111 |
+
pass
|
| 112 |
+
new_base64 = f"data:{content_type};base64,{base64_repr}"
|
| 113 |
+
return new_base64
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
##################
|
| 117 |
+
# Helper function for cleaning up an Interface loaded from HF Spaces
|
| 118 |
+
##################
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def streamline_spaces_interface(config: Dict) -> Dict:
|
| 122 |
+
"""Streamlines the interface config dictionary to remove unnecessary keys."""
|
| 123 |
+
config["inputs"] = [
|
| 124 |
+
components.get_component_instance(component)
|
| 125 |
+
for component in config["input_components"]
|
| 126 |
+
]
|
| 127 |
+
config["outputs"] = [
|
| 128 |
+
components.get_component_instance(component)
|
| 129 |
+
for component in config["output_components"]
|
| 130 |
+
]
|
| 131 |
+
parameters = {
|
| 132 |
+
"article",
|
| 133 |
+
"description",
|
| 134 |
+
"flagging_options",
|
| 135 |
+
"inputs",
|
| 136 |
+
"outputs",
|
| 137 |
+
"title",
|
| 138 |
+
}
|
| 139 |
+
config = {k: config[k] for k in parameters}
|
| 140 |
+
return config
|
falcon/lib/python3.10/site-packages/gradio/flagging.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import datetime
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
import warnings
|
| 10 |
+
from abc import ABC, abstractmethod
|
| 11 |
+
from collections import OrderedDict
|
| 12 |
+
from distutils.version import StrictVersion
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import TYPE_CHECKING, Any
|
| 15 |
+
|
| 16 |
+
import filelock
|
| 17 |
+
import huggingface_hub
|
| 18 |
+
import pkg_resources
|
| 19 |
+
from gradio_client import utils as client_utils
|
| 20 |
+
from gradio_client.documentation import document, set_documentation_group
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
from gradio import utils
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from gradio.components import IOComponent
|
| 27 |
+
|
| 28 |
+
set_documentation_group("flagging")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class FlaggingCallback(ABC):
|
| 32 |
+
"""
|
| 33 |
+
An abstract class for defining the methods that any FlaggingCallback should have.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
@abstractmethod
|
| 37 |
+
def setup(self, components: list[IOComponent], flagging_dir: str):
|
| 38 |
+
"""
|
| 39 |
+
This method should be overridden and ensure that everything is set up correctly for flag().
|
| 40 |
+
This method gets called once at the beginning of the Interface.launch() method.
|
| 41 |
+
Parameters:
|
| 42 |
+
components: Set of components that will provide flagged data.
|
| 43 |
+
flagging_dir: A string, typically containing the path to the directory where the flagging file should be storied (provided as an argument to Interface.__init__()).
|
| 44 |
+
"""
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
@abstractmethod
|
| 48 |
+
def flag(
|
| 49 |
+
self,
|
| 50 |
+
flag_data: list[Any],
|
| 51 |
+
flag_option: str = "",
|
| 52 |
+
username: str | None = None,
|
| 53 |
+
) -> int:
|
| 54 |
+
"""
|
| 55 |
+
This method should be overridden by the FlaggingCallback subclass and may contain optional additional arguments.
|
| 56 |
+
This gets called every time the <flag> button is pressed.
|
| 57 |
+
Parameters:
|
| 58 |
+
interface: The Interface object that is being used to launch the flagging interface.
|
| 59 |
+
flag_data: The data to be flagged.
|
| 60 |
+
flag_option (optional): In the case that flagging_options are provided, the flag option that is being used.
|
| 61 |
+
username (optional): The username of the user that is flagging the data, if logged in.
|
| 62 |
+
Returns:
|
| 63 |
+
(int) The total number of samples that have been flagged.
|
| 64 |
+
"""
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@document()
|
| 69 |
+
class SimpleCSVLogger(FlaggingCallback):
|
| 70 |
+
"""
|
| 71 |
+
A simplified implementation of the FlaggingCallback abstract class
|
| 72 |
+
provided for illustrative purposes. Each flagged sample (both the input and output data)
|
| 73 |
+
is logged to a CSV file on the machine running the gradio app.
|
| 74 |
+
Example:
|
| 75 |
+
import gradio as gr
|
| 76 |
+
def image_classifier(inp):
|
| 77 |
+
return {'cat': 0.3, 'dog': 0.7}
|
| 78 |
+
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
|
| 79 |
+
flagging_callback=SimpleCSVLogger())
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self):
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
def setup(self, components: list[IOComponent], flagging_dir: str | Path):
|
| 86 |
+
self.components = components
|
| 87 |
+
self.flagging_dir = flagging_dir
|
| 88 |
+
os.makedirs(flagging_dir, exist_ok=True)
|
| 89 |
+
|
| 90 |
+
def flag(
|
| 91 |
+
self,
|
| 92 |
+
flag_data: list[Any],
|
| 93 |
+
flag_option: str = "",
|
| 94 |
+
username: str | None = None,
|
| 95 |
+
) -> int:
|
| 96 |
+
flagging_dir = self.flagging_dir
|
| 97 |
+
log_filepath = Path(flagging_dir) / "log.csv"
|
| 98 |
+
|
| 99 |
+
csv_data = []
|
| 100 |
+
for component, sample in zip(self.components, flag_data):
|
| 101 |
+
save_dir = Path(
|
| 102 |
+
flagging_dir
|
| 103 |
+
) / client_utils.strip_invalid_filename_characters(component.label or "")
|
| 104 |
+
csv_data.append(
|
| 105 |
+
component.deserialize(
|
| 106 |
+
sample,
|
| 107 |
+
save_dir,
|
| 108 |
+
None,
|
| 109 |
+
)
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
with open(log_filepath, "a", newline="") as csvfile:
|
| 113 |
+
writer = csv.writer(csvfile)
|
| 114 |
+
writer.writerow(utils.sanitize_list_for_csv(csv_data))
|
| 115 |
+
|
| 116 |
+
with open(log_filepath) as csvfile:
|
| 117 |
+
line_count = len(list(csv.reader(csvfile))) - 1
|
| 118 |
+
return line_count
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@document()
|
| 122 |
+
class CSVLogger(FlaggingCallback):
|
| 123 |
+
"""
|
| 124 |
+
The default implementation of the FlaggingCallback abstract class. Each flagged
|
| 125 |
+
sample (both the input and output data) is logged to a CSV file with headers on the machine running the gradio app.
|
| 126 |
+
Example:
|
| 127 |
+
import gradio as gr
|
| 128 |
+
def image_classifier(inp):
|
| 129 |
+
return {'cat': 0.3, 'dog': 0.7}
|
| 130 |
+
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
|
| 131 |
+
flagging_callback=CSVLogger())
|
| 132 |
+
Guides: using-flagging
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
def __init__(self):
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
def setup(
|
| 139 |
+
self,
|
| 140 |
+
components: list[IOComponent],
|
| 141 |
+
flagging_dir: str | Path,
|
| 142 |
+
):
|
| 143 |
+
self.components = components
|
| 144 |
+
self.flagging_dir = flagging_dir
|
| 145 |
+
os.makedirs(flagging_dir, exist_ok=True)
|
| 146 |
+
|
| 147 |
+
def flag(
|
| 148 |
+
self,
|
| 149 |
+
flag_data: list[Any],
|
| 150 |
+
flag_option: str = "",
|
| 151 |
+
username: str | None = None,
|
| 152 |
+
) -> int:
|
| 153 |
+
flagging_dir = self.flagging_dir
|
| 154 |
+
log_filepath = Path(flagging_dir) / "log.csv"
|
| 155 |
+
is_new = not Path(log_filepath).exists()
|
| 156 |
+
headers = [
|
| 157 |
+
getattr(component, "label", None) or f"component {idx}"
|
| 158 |
+
for idx, component in enumerate(self.components)
|
| 159 |
+
] + [
|
| 160 |
+
"flag",
|
| 161 |
+
"username",
|
| 162 |
+
"timestamp",
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
csv_data = []
|
| 166 |
+
for idx, (component, sample) in enumerate(zip(self.components, flag_data)):
|
| 167 |
+
save_dir = Path(
|
| 168 |
+
flagging_dir
|
| 169 |
+
) / client_utils.strip_invalid_filename_characters(
|
| 170 |
+
getattr(component, "label", None) or f"component {idx}"
|
| 171 |
+
)
|
| 172 |
+
if utils.is_update(sample):
|
| 173 |
+
csv_data.append(str(sample))
|
| 174 |
+
else:
|
| 175 |
+
csv_data.append(
|
| 176 |
+
component.deserialize(sample, save_dir=save_dir)
|
| 177 |
+
if sample is not None
|
| 178 |
+
else ""
|
| 179 |
+
)
|
| 180 |
+
csv_data.append(flag_option)
|
| 181 |
+
csv_data.append(username if username is not None else "")
|
| 182 |
+
csv_data.append(str(datetime.datetime.now()))
|
| 183 |
+
|
| 184 |
+
with open(log_filepath, "a", newline="", encoding="utf-8") as csvfile:
|
| 185 |
+
writer = csv.writer(csvfile)
|
| 186 |
+
if is_new:
|
| 187 |
+
writer.writerow(utils.sanitize_list_for_csv(headers))
|
| 188 |
+
writer.writerow(utils.sanitize_list_for_csv(csv_data))
|
| 189 |
+
|
| 190 |
+
with open(log_filepath, encoding="utf-8") as csvfile:
|
| 191 |
+
line_count = len(list(csv.reader(csvfile))) - 1
|
| 192 |
+
return line_count
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@document()
|
| 196 |
+
class HuggingFaceDatasetSaver(FlaggingCallback):
|
| 197 |
+
"""
|
| 198 |
+
A callback that saves each flagged sample (both the input and output data) to a HuggingFace dataset.
|
| 199 |
+
|
| 200 |
+
Example:
|
| 201 |
+
import gradio as gr
|
| 202 |
+
hf_writer = gr.HuggingFaceDatasetSaver(HF_API_TOKEN, "image-classification-mistakes")
|
| 203 |
+
def image_classifier(inp):
|
| 204 |
+
return {'cat': 0.3, 'dog': 0.7}
|
| 205 |
+
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
|
| 206 |
+
allow_flagging="manual", flagging_callback=hf_writer)
|
| 207 |
+
Guides: using-flagging
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
def __init__(
|
| 211 |
+
self,
|
| 212 |
+
hf_token: str,
|
| 213 |
+
dataset_name: str,
|
| 214 |
+
organization: str | None = None,
|
| 215 |
+
private: bool = False,
|
| 216 |
+
info_filename: str = "dataset_info.json",
|
| 217 |
+
separate_dirs: bool = False,
|
| 218 |
+
verbose: bool = True, # silently ignored. TODO: remove it?
|
| 219 |
+
):
|
| 220 |
+
"""
|
| 221 |
+
Parameters:
|
| 222 |
+
hf_token: The HuggingFace token to use to create (and write the flagged sample to) the HuggingFace dataset (defaults to the registered one).
|
| 223 |
+
dataset_name: The repo_id of the dataset to save the data to, e.g. "image-classifier-1" or "username/image-classifier-1".
|
| 224 |
+
organization: Deprecated argument. Please pass a full dataset id (e.g. 'username/dataset_name') to `dataset_name` instead.
|
| 225 |
+
private: Whether the dataset should be private (defaults to False).
|
| 226 |
+
info_filename: The name of the file to save the dataset info (defaults to "dataset_infos.json").
|
| 227 |
+
separate_dirs: If True, each flagged item will be saved in a separate directory. This makes the flagging more robust to concurrent editing, but may be less convenient to use.
|
| 228 |
+
"""
|
| 229 |
+
if organization is not None:
|
| 230 |
+
warnings.warn(
|
| 231 |
+
"Parameter `organization` is not used anymore. Please pass a full dataset id (e.g. 'username/dataset_name') to `dataset_name` instead."
|
| 232 |
+
)
|
| 233 |
+
self.hf_token = hf_token
|
| 234 |
+
self.dataset_id = dataset_name # TODO: rename parameter (but ensure backward compatibility somehow)
|
| 235 |
+
self.dataset_private = private
|
| 236 |
+
self.info_filename = info_filename
|
| 237 |
+
self.separate_dirs = separate_dirs
|
| 238 |
+
|
| 239 |
+
def setup(self, components: list[IOComponent], flagging_dir: str):
|
| 240 |
+
"""
|
| 241 |
+
Params:
|
| 242 |
+
flagging_dir (str): local directory where the dataset is cloned,
|
| 243 |
+
updated, and pushed from.
|
| 244 |
+
"""
|
| 245 |
+
hh_version = pkg_resources.get_distribution("huggingface_hub").version
|
| 246 |
+
try:
|
| 247 |
+
if StrictVersion(hh_version) < StrictVersion("0.12.0"):
|
| 248 |
+
raise ImportError(
|
| 249 |
+
"The `huggingface_hub` package must be version 0.12.0 or higher"
|
| 250 |
+
"for HuggingFaceDatasetSaver. Try 'pip install huggingface_hub --upgrade'."
|
| 251 |
+
)
|
| 252 |
+
except ValueError:
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
# Setup dataset on the Hub
|
| 256 |
+
self.dataset_id = huggingface_hub.create_repo(
|
| 257 |
+
repo_id=self.dataset_id,
|
| 258 |
+
token=self.hf_token,
|
| 259 |
+
private=self.dataset_private,
|
| 260 |
+
repo_type="dataset",
|
| 261 |
+
exist_ok=True,
|
| 262 |
+
).repo_id
|
| 263 |
+
|
| 264 |
+
# Setup flagging dir
|
| 265 |
+
self.components = components
|
| 266 |
+
self.dataset_dir = (
|
| 267 |
+
Path(flagging_dir).absolute() / self.dataset_id.split("/")[-1]
|
| 268 |
+
)
|
| 269 |
+
self.dataset_dir.mkdir(parents=True, exist_ok=True)
|
| 270 |
+
self.infos_file = self.dataset_dir / self.info_filename
|
| 271 |
+
|
| 272 |
+
# Download remote files to local
|
| 273 |
+
remote_files = [self.info_filename]
|
| 274 |
+
if not self.separate_dirs:
|
| 275 |
+
# No separate dirs => means all data is in the same CSV file => download it to get its current content
|
| 276 |
+
remote_files.append("data.csv")
|
| 277 |
+
|
| 278 |
+
for filename in remote_files:
|
| 279 |
+
try:
|
| 280 |
+
huggingface_hub.hf_hub_download(
|
| 281 |
+
repo_id=self.dataset_id,
|
| 282 |
+
repo_type="dataset",
|
| 283 |
+
filename=filename,
|
| 284 |
+
local_dir=self.dataset_dir,
|
| 285 |
+
token=self.hf_token,
|
| 286 |
+
)
|
| 287 |
+
except huggingface_hub.utils.EntryNotFoundError:
|
| 288 |
+
pass
|
| 289 |
+
|
| 290 |
+
def flag(
|
| 291 |
+
self,
|
| 292 |
+
flag_data: list[Any],
|
| 293 |
+
flag_option: str = "",
|
| 294 |
+
username: str | None = None,
|
| 295 |
+
) -> int:
|
| 296 |
+
if self.separate_dirs:
|
| 297 |
+
# JSONL files to support dataset preview on the Hub
|
| 298 |
+
unique_id = str(uuid.uuid4())
|
| 299 |
+
components_dir = self.dataset_dir / str(uuid.uuid4())
|
| 300 |
+
data_file = components_dir / "metadata.jsonl"
|
| 301 |
+
path_in_repo = unique_id # upload in sub folder (safer for concurrency)
|
| 302 |
+
else:
|
| 303 |
+
# Unique CSV file
|
| 304 |
+
components_dir = self.dataset_dir
|
| 305 |
+
data_file = components_dir / "data.csv"
|
| 306 |
+
path_in_repo = None # upload at root level
|
| 307 |
+
|
| 308 |
+
return self._flag_in_dir(
|
| 309 |
+
data_file=data_file,
|
| 310 |
+
components_dir=components_dir,
|
| 311 |
+
path_in_repo=path_in_repo,
|
| 312 |
+
flag_data=flag_data,
|
| 313 |
+
flag_option=flag_option,
|
| 314 |
+
username=username or "",
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
def _flag_in_dir(
|
| 318 |
+
self,
|
| 319 |
+
data_file: Path,
|
| 320 |
+
components_dir: Path,
|
| 321 |
+
path_in_repo: str | None,
|
| 322 |
+
flag_data: list[Any],
|
| 323 |
+
flag_option: str = "",
|
| 324 |
+
username: str = "",
|
| 325 |
+
) -> int:
|
| 326 |
+
# Deserialize components (write images/audio to files)
|
| 327 |
+
features, row = self._deserialize_components(
|
| 328 |
+
components_dir, flag_data, flag_option, username
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
# Write generic info to dataset_infos.json + upload
|
| 332 |
+
with filelock.FileLock(str(self.infos_file) + ".lock"):
|
| 333 |
+
if not self.infos_file.exists():
|
| 334 |
+
self.infos_file.write_text(
|
| 335 |
+
json.dumps({"flagged": {"features": features}})
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
huggingface_hub.upload_file(
|
| 339 |
+
repo_id=self.dataset_id,
|
| 340 |
+
repo_type="dataset",
|
| 341 |
+
token=self.hf_token,
|
| 342 |
+
path_in_repo=self.infos_file.name,
|
| 343 |
+
path_or_fileobj=self.infos_file,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
headers = list(features.keys())
|
| 347 |
+
|
| 348 |
+
if not self.separate_dirs:
|
| 349 |
+
with filelock.FileLock(components_dir / ".lock"):
|
| 350 |
+
sample_nb = self._save_as_csv(data_file, headers=headers, row=row)
|
| 351 |
+
sample_name = str(sample_nb)
|
| 352 |
+
huggingface_hub.upload_folder(
|
| 353 |
+
repo_id=self.dataset_id,
|
| 354 |
+
repo_type="dataset",
|
| 355 |
+
commit_message=f"Flagged sample #{sample_name}",
|
| 356 |
+
path_in_repo=path_in_repo,
|
| 357 |
+
ignore_patterns="*.lock",
|
| 358 |
+
folder_path=components_dir,
|
| 359 |
+
token=self.hf_token,
|
| 360 |
+
)
|
| 361 |
+
else:
|
| 362 |
+
sample_name = self._save_as_jsonl(data_file, headers=headers, row=row)
|
| 363 |
+
sample_nb = len(
|
| 364 |
+
[path for path in self.dataset_dir.iterdir() if path.is_dir()]
|
| 365 |
+
)
|
| 366 |
+
huggingface_hub.upload_folder(
|
| 367 |
+
repo_id=self.dataset_id,
|
| 368 |
+
repo_type="dataset",
|
| 369 |
+
commit_message=f"Flagged sample #{sample_name}",
|
| 370 |
+
path_in_repo=path_in_repo,
|
| 371 |
+
ignore_patterns="*.lock",
|
| 372 |
+
folder_path=components_dir,
|
| 373 |
+
token=self.hf_token,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
return sample_nb
|
| 377 |
+
|
| 378 |
+
@staticmethod
|
| 379 |
+
def _save_as_csv(data_file: Path, headers: list[str], row: list[Any]) -> int:
|
| 380 |
+
"""Save data as CSV and return the sample name (row number)."""
|
| 381 |
+
is_new = not data_file.exists()
|
| 382 |
+
|
| 383 |
+
with data_file.open("a", newline="", encoding="utf-8") as csvfile:
|
| 384 |
+
writer = csv.writer(csvfile)
|
| 385 |
+
|
| 386 |
+
# Write CSV headers if new file
|
| 387 |
+
if is_new:
|
| 388 |
+
writer.writerow(utils.sanitize_list_for_csv(headers))
|
| 389 |
+
|
| 390 |
+
# Write CSV row for flagged sample
|
| 391 |
+
writer.writerow(utils.sanitize_list_for_csv(row))
|
| 392 |
+
|
| 393 |
+
with data_file.open(encoding="utf-8") as csvfile:
|
| 394 |
+
return sum(1 for _ in csv.reader(csvfile)) - 1
|
| 395 |
+
|
| 396 |
+
@staticmethod
|
| 397 |
+
def _save_as_jsonl(data_file: Path, headers: list[str], row: list[Any]) -> str:
|
| 398 |
+
"""Save data as JSONL and return the sample name (uuid)."""
|
| 399 |
+
Path.mkdir(data_file.parent, parents=True, exist_ok=True)
|
| 400 |
+
with open(data_file, "w") as f:
|
| 401 |
+
json.dump(dict(zip(headers, row)), f)
|
| 402 |
+
return data_file.parent.name
|
| 403 |
+
|
| 404 |
+
def _deserialize_components(
|
| 405 |
+
self,
|
| 406 |
+
data_dir: Path,
|
| 407 |
+
flag_data: list[Any],
|
| 408 |
+
flag_option: str = "",
|
| 409 |
+
username: str = "",
|
| 410 |
+
) -> tuple[dict[Any, Any], list[Any]]:
|
| 411 |
+
"""Deserialize components and return the corresponding row for the flagged sample.
|
| 412 |
+
|
| 413 |
+
Images/audio are saved to disk as individual files.
|
| 414 |
+
"""
|
| 415 |
+
# Components that can have a preview on dataset repos
|
| 416 |
+
file_preview_types = {gr.Audio: "Audio", gr.Image: "Image"}
|
| 417 |
+
|
| 418 |
+
# Generate the row corresponding to the flagged sample
|
| 419 |
+
features = OrderedDict()
|
| 420 |
+
row = []
|
| 421 |
+
for component, sample in zip(self.components, flag_data):
|
| 422 |
+
# Get deserialized object (will save sample to disk if applicable -file, audio, image,...-)
|
| 423 |
+
label = component.label or ""
|
| 424 |
+
save_dir = data_dir / client_utils.strip_invalid_filename_characters(label)
|
| 425 |
+
deserialized = component.deserialize(sample, save_dir, None)
|
| 426 |
+
|
| 427 |
+
# Add deserialized object to row
|
| 428 |
+
features[label] = {"dtype": "string", "_type": "Value"}
|
| 429 |
+
try:
|
| 430 |
+
assert Path(deserialized).exists()
|
| 431 |
+
row.append(Path(deserialized).name)
|
| 432 |
+
except (AssertionError, TypeError, ValueError):
|
| 433 |
+
row.append(str(deserialized))
|
| 434 |
+
|
| 435 |
+
# If component is eligible for a preview, add the URL of the file
|
| 436 |
+
if isinstance(component, tuple(file_preview_types)): # type: ignore
|
| 437 |
+
for _component, _type in file_preview_types.items():
|
| 438 |
+
if isinstance(component, _component):
|
| 439 |
+
features[label + " file"] = {"_type": _type}
|
| 440 |
+
break
|
| 441 |
+
path_in_repo = str( # returned filepath is absolute, we want it relative to compute URL
|
| 442 |
+
Path(deserialized).relative_to(self.dataset_dir)
|
| 443 |
+
).replace(
|
| 444 |
+
"\\", "/"
|
| 445 |
+
)
|
| 446 |
+
row.append(
|
| 447 |
+
huggingface_hub.hf_hub_url(
|
| 448 |
+
repo_id=self.dataset_id,
|
| 449 |
+
filename=path_in_repo,
|
| 450 |
+
repo_type="dataset",
|
| 451 |
+
)
|
| 452 |
+
)
|
| 453 |
+
features["flag"] = {"dtype": "string", "_type": "Value"}
|
| 454 |
+
features["username"] = {"dtype": "string", "_type": "Value"}
|
| 455 |
+
row.append(flag_option)
|
| 456 |
+
row.append(username)
|
| 457 |
+
return features, row
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class HuggingFaceDatasetJSONSaver(HuggingFaceDatasetSaver):
|
| 461 |
+
def __init__(
|
| 462 |
+
self,
|
| 463 |
+
hf_token: str,
|
| 464 |
+
dataset_name: str,
|
| 465 |
+
organization: str | None = None,
|
| 466 |
+
private: bool = False,
|
| 467 |
+
info_filename: str = "dataset_info.json",
|
| 468 |
+
verbose: bool = True, # silently ignored. TODO: remove it?
|
| 469 |
+
):
|
| 470 |
+
warnings.warn(
|
| 471 |
+
"Callback `HuggingFaceDatasetJSONSaver` is deprecated in favor of using"
|
| 472 |
+
" `HuggingFaceDatasetSaver` and passing `separate_dirs=True` as parameter."
|
| 473 |
+
)
|
| 474 |
+
super().__init__(
|
| 475 |
+
hf_token=hf_token,
|
| 476 |
+
dataset_name=dataset_name,
|
| 477 |
+
organization=organization,
|
| 478 |
+
private=private,
|
| 479 |
+
info_filename=info_filename,
|
| 480 |
+
separate_dirs=True,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
class FlagMethod:
|
| 485 |
+
"""
|
| 486 |
+
Helper class that contains the flagging options and calls the flagging method. Also
|
| 487 |
+
provides visual feedback to the user when flag is clicked.
|
| 488 |
+
"""
|
| 489 |
+
|
| 490 |
+
def __init__(
|
| 491 |
+
self,
|
| 492 |
+
flagging_callback: FlaggingCallback,
|
| 493 |
+
label: str,
|
| 494 |
+
value: str,
|
| 495 |
+
visual_feedback: bool = True,
|
| 496 |
+
):
|
| 497 |
+
self.flagging_callback = flagging_callback
|
| 498 |
+
self.label = label
|
| 499 |
+
self.value = value
|
| 500 |
+
self.__name__ = "Flag"
|
| 501 |
+
self.visual_feedback = visual_feedback
|
| 502 |
+
|
| 503 |
+
def __call__(self, request: gr.Request, *flag_data):
|
| 504 |
+
try:
|
| 505 |
+
self.flagging_callback.flag(
|
| 506 |
+
list(flag_data), flag_option=self.value, username=request.username
|
| 507 |
+
)
|
| 508 |
+
except Exception as e:
|
| 509 |
+
print(f"Error while flagging: {e}")
|
| 510 |
+
if self.visual_feedback:
|
| 511 |
+
return "Error!"
|
| 512 |
+
if not self.visual_feedback:
|
| 513 |
+
return
|
| 514 |
+
time.sleep(0.8) # to provide enough time for the user to observe button change
|
| 515 |
+
return self.reset()
|
| 516 |
+
|
| 517 |
+
def reset(self):
|
| 518 |
+
return gr.Button.update(value=self.label, interactive=True)
|
falcon/lib/python3.10/site-packages/gradio/interface.py
ADDED
|
@@ -0,0 +1,899 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This is the core file in the `gradio` package, and defines the Interface class,
|
| 3 |
+
including various methods for constructing an interface and then launching it.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import inspect
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import warnings
|
| 12 |
+
import weakref
|
| 13 |
+
from typing import TYPE_CHECKING, Any, Callable
|
| 14 |
+
|
| 15 |
+
from gradio_client.documentation import document, set_documentation_group
|
| 16 |
+
|
| 17 |
+
from gradio import Examples, analytics, external, interpretation, utils
|
| 18 |
+
from gradio.blocks import Blocks
|
| 19 |
+
from gradio.components import (
|
| 20 |
+
Button,
|
| 21 |
+
ClearButton,
|
| 22 |
+
Interpretation,
|
| 23 |
+
IOComponent,
|
| 24 |
+
Markdown,
|
| 25 |
+
State,
|
| 26 |
+
get_component_instance,
|
| 27 |
+
)
|
| 28 |
+
from gradio.data_classes import InterfaceTypes
|
| 29 |
+
from gradio.events import Changeable, Streamable, Submittable
|
| 30 |
+
from gradio.flagging import CSVLogger, FlaggingCallback, FlagMethod
|
| 31 |
+
from gradio.layouts import Column, Row, Tab, Tabs
|
| 32 |
+
from gradio.pipelines import load_from_pipeline
|
| 33 |
+
from gradio.themes import ThemeClass as Theme
|
| 34 |
+
|
| 35 |
+
set_documentation_group("interface")
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
|
| 38 |
+
from transformers.pipelines.base import Pipeline
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@document("launch", "load", "from_pipeline", "integrate", "queue")
|
| 42 |
+
class Interface(Blocks):
|
| 43 |
+
"""
|
| 44 |
+
Interface is Gradio's main high-level class, and allows you to create a web-based GUI / demo
|
| 45 |
+
around a machine learning model (or any Python function) in a few lines of code.
|
| 46 |
+
You must specify three parameters: (1) the function to create a GUI for (2) the desired input components and
|
| 47 |
+
(3) the desired output components. Additional parameters can be used to control the appearance
|
| 48 |
+
and behavior of the demo.
|
| 49 |
+
|
| 50 |
+
Example:
|
| 51 |
+
import gradio as gr
|
| 52 |
+
|
| 53 |
+
def image_classifier(inp):
|
| 54 |
+
return {'cat': 0.3, 'dog': 0.7}
|
| 55 |
+
|
| 56 |
+
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label")
|
| 57 |
+
demo.launch()
|
| 58 |
+
Demos: hello_world, hello_world_3, gpt_j
|
| 59 |
+
Guides: quickstart, key-features, sharing-your-app, interface-state, reactive-interfaces, advanced-interface-features, setting-up-a-gradio-demo-for-maximum-performance
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
# stores references to all currently existing Interface instances
|
| 63 |
+
instances: weakref.WeakSet = weakref.WeakSet()
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def get_instances(cls) -> list[Interface]:
|
| 67 |
+
"""
|
| 68 |
+
:return: list of all current instances.
|
| 69 |
+
"""
|
| 70 |
+
return list(Interface.instances)
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def load(
|
| 74 |
+
cls,
|
| 75 |
+
name: str,
|
| 76 |
+
src: str | None = None,
|
| 77 |
+
api_key: str | None = None,
|
| 78 |
+
alias: str | None = None,
|
| 79 |
+
**kwargs,
|
| 80 |
+
) -> Blocks:
|
| 81 |
+
"""
|
| 82 |
+
Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead. This is a class
|
| 83 |
+
method that constructs a Blocks from a Hugging Face repo. Can accept
|
| 84 |
+
model repos (if src is "models") or Space repos (if src is "spaces"). The input
|
| 85 |
+
and output components are automatically loaded from the repo.
|
| 86 |
+
Parameters:
|
| 87 |
+
name: the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
|
| 88 |
+
src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
|
| 89 |
+
api_key: optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.
|
| 90 |
+
alias: optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
|
| 91 |
+
Returns:
|
| 92 |
+
a Gradio Interface object for the given model
|
| 93 |
+
"""
|
| 94 |
+
warnings.warn("gr.Interface.load() will be deprecated. Use gr.load() instead.")
|
| 95 |
+
return external.load(
|
| 96 |
+
name=name, src=src, hf_token=api_key, alias=alias, **kwargs
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
@classmethod
|
| 100 |
+
def from_pipeline(cls, pipeline: Pipeline, **kwargs) -> Interface:
|
| 101 |
+
"""
|
| 102 |
+
Class method that constructs an Interface from a Hugging Face transformers.Pipeline object.
|
| 103 |
+
The input and output components are automatically determined from the pipeline.
|
| 104 |
+
Parameters:
|
| 105 |
+
pipeline: the pipeline object to use.
|
| 106 |
+
Returns:
|
| 107 |
+
a Gradio Interface object from the given Pipeline
|
| 108 |
+
Example:
|
| 109 |
+
import gradio as gr
|
| 110 |
+
from transformers import pipeline
|
| 111 |
+
pipe = pipeline("image-classification")
|
| 112 |
+
gr.Interface.from_pipeline(pipe).launch()
|
| 113 |
+
"""
|
| 114 |
+
interface_info = load_from_pipeline(pipeline)
|
| 115 |
+
kwargs = dict(interface_info, **kwargs)
|
| 116 |
+
interface = cls(**kwargs)
|
| 117 |
+
return interface
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
fn: Callable,
|
| 122 |
+
inputs: str | IOComponent | list[str | IOComponent] | None,
|
| 123 |
+
outputs: str | IOComponent | list[str | IOComponent] | None,
|
| 124 |
+
examples: list[Any] | list[list[Any]] | str | None = None,
|
| 125 |
+
cache_examples: bool | None = None,
|
| 126 |
+
examples_per_page: int = 10,
|
| 127 |
+
live: bool = False,
|
| 128 |
+
interpretation: Callable | str | None = None,
|
| 129 |
+
num_shap: float = 2.0,
|
| 130 |
+
title: str | None = None,
|
| 131 |
+
description: str | None = None,
|
| 132 |
+
article: str | None = None,
|
| 133 |
+
thumbnail: str | None = None,
|
| 134 |
+
theme: Theme | str | None = None,
|
| 135 |
+
css: str | None = None,
|
| 136 |
+
allow_flagging: str | None = None,
|
| 137 |
+
flagging_options: list[str] | list[tuple[str, str]] | None = None,
|
| 138 |
+
flagging_dir: str = "flagged",
|
| 139 |
+
flagging_callback: FlaggingCallback = CSVLogger(),
|
| 140 |
+
analytics_enabled: bool | None = None,
|
| 141 |
+
batch: bool = False,
|
| 142 |
+
max_batch_size: int = 4,
|
| 143 |
+
_api_mode: bool = False,
|
| 144 |
+
**kwargs,
|
| 145 |
+
):
|
| 146 |
+
"""
|
| 147 |
+
Parameters:
|
| 148 |
+
fn: the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
|
| 149 |
+
inputs: a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of input components should match the number of parameters in fn. If set to None, then only the output components will be displayed.
|
| 150 |
+
outputs: a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of output components should match the number of values returned by fn. If set to None, then only the input components will be displayed.
|
| 151 |
+
examples: sample inputs for the function; if provided, appear below the UI components and can be clicked to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided, but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.
|
| 152 |
+
cache_examples: If True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
|
| 153 |
+
examples_per_page: If examples are provided, how many to display per page.
|
| 154 |
+
live: whether the interface should automatically rerun if any of the inputs change.
|
| 155 |
+
interpretation: function that provides interpretation explaining prediction output. Pass "default" to use simple built-in interpreter, "shap" to use a built-in shapley-based interpreter, or your own custom interpretation function. For more information on the different interpretation methods, see the Advanced Interface Features guide.
|
| 156 |
+
num_shap: a multiplier that determines how many examples are computed for shap-based interpretation. Increasing this value will increase shap runtime, but improve results. Only applies if interpretation is "shap".
|
| 157 |
+
title: a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window.
|
| 158 |
+
description: a description for the interface; if provided, appears above the input and output components and beneath the title in regular font. Accepts Markdown and HTML content.
|
| 159 |
+
article: an expanded article explaining the interface; if provided, appears below the input and output components in regular font. Accepts Markdown and HTML content.
|
| 160 |
+
thumbnail: path or url to image to use as display image when the web demo is shared on social media.
|
| 161 |
+
theme: Theme to use, loaded from gradio.themes.
|
| 162 |
+
css: custom css or path to custom css file to use with interface.
|
| 163 |
+
allow_flagging: one of "never", "auto", or "manual". If "never" or "auto", users will not see a button to flag an input and output. If "manual", users will see a button to flag. If "auto", every input the user submits will be automatically flagged (outputs are not flagged). If "manual", both the input and outputs are flagged when the user clicks flag button. This parameter can be set with environmental variable GRADIO_ALLOW_FLAGGING; otherwise defaults to "manual".
|
| 164 |
+
flagging_options: if provided, allows user to select from the list of options when flagging. Only applies if allow_flagging is "manual". Can either be a list of tuples of the form (label, value), where label is the string that will be displayed on the button and value is the string that will be stored in the flagging CSV; or it can be a list of strings ["X", "Y"], in which case the values will be the list of strings and the labels will ["Flag as X", "Flag as Y"], etc.
|
| 165 |
+
flagging_dir: what to name the directory where flagged data is stored.
|
| 166 |
+
flagging_callback: An instance of a subclass of FlaggingCallback which will be called when a sample is flagged. By default logs to a local CSV file.
|
| 167 |
+
analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
|
| 168 |
+
batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
|
| 169 |
+
max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
|
| 170 |
+
"""
|
| 171 |
+
super().__init__(
|
| 172 |
+
analytics_enabled=analytics_enabled,
|
| 173 |
+
mode="interface",
|
| 174 |
+
css=css,
|
| 175 |
+
title=title or "Gradio",
|
| 176 |
+
theme=theme,
|
| 177 |
+
**kwargs,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if isinstance(fn, list):
|
| 181 |
+
raise DeprecationWarning(
|
| 182 |
+
"The `fn` parameter only accepts a single function, support for a list "
|
| 183 |
+
"of functions has been deprecated. Please use gradio.mix.Parallel "
|
| 184 |
+
"instead."
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
self.interface_type = InterfaceTypes.STANDARD
|
| 188 |
+
if (inputs is None or inputs == []) and (outputs is None or outputs == []):
|
| 189 |
+
raise ValueError("Must provide at least one of `inputs` or `outputs`")
|
| 190 |
+
elif outputs is None or outputs == []:
|
| 191 |
+
outputs = []
|
| 192 |
+
self.interface_type = InterfaceTypes.INPUT_ONLY
|
| 193 |
+
elif inputs is None or inputs == []:
|
| 194 |
+
inputs = []
|
| 195 |
+
self.interface_type = InterfaceTypes.OUTPUT_ONLY
|
| 196 |
+
|
| 197 |
+
assert isinstance(inputs, (str, list, IOComponent))
|
| 198 |
+
assert isinstance(outputs, (str, list, IOComponent))
|
| 199 |
+
|
| 200 |
+
if not isinstance(inputs, list):
|
| 201 |
+
inputs = [inputs]
|
| 202 |
+
if not isinstance(outputs, list):
|
| 203 |
+
outputs = [outputs]
|
| 204 |
+
|
| 205 |
+
if self.is_space and cache_examples is None:
|
| 206 |
+
self.cache_examples = True
|
| 207 |
+
else:
|
| 208 |
+
self.cache_examples = cache_examples or False
|
| 209 |
+
|
| 210 |
+
state_input_indexes = [
|
| 211 |
+
idx for idx, i in enumerate(inputs) if i == "state" or isinstance(i, State)
|
| 212 |
+
]
|
| 213 |
+
state_output_indexes = [
|
| 214 |
+
idx for idx, o in enumerate(outputs) if o == "state" or isinstance(o, State)
|
| 215 |
+
]
|
| 216 |
+
|
| 217 |
+
if len(state_input_indexes) == 0 and len(state_output_indexes) == 0:
|
| 218 |
+
pass
|
| 219 |
+
elif len(state_input_indexes) != 1 or len(state_output_indexes) != 1:
|
| 220 |
+
raise ValueError(
|
| 221 |
+
"If using 'state', there must be exactly one state input and one state output."
|
| 222 |
+
)
|
| 223 |
+
else:
|
| 224 |
+
state_input_index = state_input_indexes[0]
|
| 225 |
+
state_output_index = state_output_indexes[0]
|
| 226 |
+
if inputs[state_input_index] == "state":
|
| 227 |
+
default = utils.get_default_args(fn)[state_input_index]
|
| 228 |
+
state_variable = State(value=default) # type: ignore
|
| 229 |
+
else:
|
| 230 |
+
state_variable = inputs[state_input_index]
|
| 231 |
+
|
| 232 |
+
inputs[state_input_index] = state_variable
|
| 233 |
+
outputs[state_output_index] = state_variable
|
| 234 |
+
|
| 235 |
+
if cache_examples:
|
| 236 |
+
warnings.warn(
|
| 237 |
+
"Cache examples cannot be used with state inputs and outputs."
|
| 238 |
+
"Setting cache_examples to False."
|
| 239 |
+
)
|
| 240 |
+
self.cache_examples = False
|
| 241 |
+
|
| 242 |
+
self.input_components = [
|
| 243 |
+
get_component_instance(i, render=False) for i in inputs # type: ignore
|
| 244 |
+
]
|
| 245 |
+
self.output_components = [
|
| 246 |
+
get_component_instance(o, render=False) for o in outputs # type: ignore
|
| 247 |
+
]
|
| 248 |
+
|
| 249 |
+
for component in self.input_components + self.output_components:
|
| 250 |
+
if not (isinstance(component, IOComponent)):
|
| 251 |
+
raise ValueError(
|
| 252 |
+
f"{component} is not a valid input/output component for Interface."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
if len(self.input_components) == len(self.output_components):
|
| 256 |
+
same_components = [
|
| 257 |
+
i is o for i, o in zip(self.input_components, self.output_components)
|
| 258 |
+
]
|
| 259 |
+
if all(same_components):
|
| 260 |
+
self.interface_type = InterfaceTypes.UNIFIED
|
| 261 |
+
|
| 262 |
+
if self.interface_type in [
|
| 263 |
+
InterfaceTypes.STANDARD,
|
| 264 |
+
InterfaceTypes.OUTPUT_ONLY,
|
| 265 |
+
]:
|
| 266 |
+
for o in self.output_components:
|
| 267 |
+
assert isinstance(o, IOComponent)
|
| 268 |
+
if o.interactive is None:
|
| 269 |
+
# Unless explicitly otherwise specified, force output components to
|
| 270 |
+
# be non-interactive
|
| 271 |
+
o.interactive = False
|
| 272 |
+
if (
|
| 273 |
+
interpretation is None
|
| 274 |
+
or isinstance(interpretation, list)
|
| 275 |
+
or callable(interpretation)
|
| 276 |
+
):
|
| 277 |
+
self.interpretation = interpretation
|
| 278 |
+
elif isinstance(interpretation, str):
|
| 279 |
+
self.interpretation = [
|
| 280 |
+
interpretation.lower() for _ in self.input_components
|
| 281 |
+
]
|
| 282 |
+
else:
|
| 283 |
+
raise ValueError("Invalid value for parameter: interpretation")
|
| 284 |
+
|
| 285 |
+
self.api_mode = _api_mode
|
| 286 |
+
self.fn = fn
|
| 287 |
+
self.fn_durations = [0, 0]
|
| 288 |
+
self.__name__ = getattr(fn, "__name__", "fn")
|
| 289 |
+
self.live = live
|
| 290 |
+
self.title = title
|
| 291 |
+
|
| 292 |
+
md = utils.get_markdown_parser()
|
| 293 |
+
simple_description: str | None = None
|
| 294 |
+
if description is not None:
|
| 295 |
+
description = md.render(description)
|
| 296 |
+
simple_description = utils.remove_html_tags(description)
|
| 297 |
+
self.simple_description = simple_description
|
| 298 |
+
self.description = description
|
| 299 |
+
if article is not None:
|
| 300 |
+
article = utils.readme_to_html(article)
|
| 301 |
+
article = md.render(article)
|
| 302 |
+
self.article = article
|
| 303 |
+
|
| 304 |
+
self.thumbnail = thumbnail
|
| 305 |
+
|
| 306 |
+
self.examples = examples
|
| 307 |
+
self.num_shap = num_shap
|
| 308 |
+
self.examples_per_page = examples_per_page
|
| 309 |
+
|
| 310 |
+
self.simple_server = None
|
| 311 |
+
|
| 312 |
+
# For allow_flagging: (1) first check for parameter,
|
| 313 |
+
# (2) check for env variable, (3) default to True/"manual"
|
| 314 |
+
if allow_flagging is None:
|
| 315 |
+
allow_flagging = os.getenv("GRADIO_ALLOW_FLAGGING", "manual")
|
| 316 |
+
if allow_flagging is True:
|
| 317 |
+
warnings.warn(
|
| 318 |
+
"The `allow_flagging` parameter in `Interface` now"
|
| 319 |
+
"takes a string value ('auto', 'manual', or 'never')"
|
| 320 |
+
", not a boolean. Setting parameter to: 'manual'."
|
| 321 |
+
)
|
| 322 |
+
self.allow_flagging = "manual"
|
| 323 |
+
elif allow_flagging == "manual":
|
| 324 |
+
self.allow_flagging = "manual"
|
| 325 |
+
elif allow_flagging is False:
|
| 326 |
+
warnings.warn(
|
| 327 |
+
"The `allow_flagging` parameter in `Interface` now"
|
| 328 |
+
"takes a string value ('auto', 'manual', or 'never')"
|
| 329 |
+
", not a boolean. Setting parameter to: 'never'."
|
| 330 |
+
)
|
| 331 |
+
self.allow_flagging = "never"
|
| 332 |
+
elif allow_flagging == "never":
|
| 333 |
+
self.allow_flagging = "never"
|
| 334 |
+
elif allow_flagging == "auto":
|
| 335 |
+
self.allow_flagging = "auto"
|
| 336 |
+
else:
|
| 337 |
+
raise ValueError(
|
| 338 |
+
"Invalid value for `allow_flagging` parameter."
|
| 339 |
+
"Must be: 'auto', 'manual', or 'never'."
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
if flagging_options is None:
|
| 343 |
+
self.flagging_options = [("Flag", "")]
|
| 344 |
+
elif not (isinstance(flagging_options, list)):
|
| 345 |
+
raise ValueError(
|
| 346 |
+
"flagging_options must be a list of strings or list of (string, string) tuples."
|
| 347 |
+
)
|
| 348 |
+
elif all(isinstance(x, str) for x in flagging_options):
|
| 349 |
+
self.flagging_options = [(f"Flag as {x}", x) for x in flagging_options]
|
| 350 |
+
elif all(isinstance(x, tuple) for x in flagging_options):
|
| 351 |
+
self.flagging_options = flagging_options
|
| 352 |
+
else:
|
| 353 |
+
raise ValueError(
|
| 354 |
+
"flagging_options must be a list of strings or list of (string, string) tuples."
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
self.flagging_callback = flagging_callback
|
| 358 |
+
self.flagging_dir = flagging_dir
|
| 359 |
+
self.batch = batch
|
| 360 |
+
self.max_batch_size = max_batch_size
|
| 361 |
+
|
| 362 |
+
self.save_to = None # Used for selenium tests
|
| 363 |
+
self.share = None
|
| 364 |
+
self.share_url = None
|
| 365 |
+
self.local_url = None
|
| 366 |
+
|
| 367 |
+
self.favicon_path = None
|
| 368 |
+
analytics.version_check()
|
| 369 |
+
Interface.instances.add(self)
|
| 370 |
+
|
| 371 |
+
param_names = inspect.getfullargspec(self.fn)[0]
|
| 372 |
+
if len(param_names) > 0 and inspect.ismethod(self.fn):
|
| 373 |
+
param_names = param_names[1:]
|
| 374 |
+
for component, param_name in zip(self.input_components, param_names):
|
| 375 |
+
assert isinstance(component, IOComponent)
|
| 376 |
+
if component.label is None:
|
| 377 |
+
component.label = param_name
|
| 378 |
+
for i, component in enumerate(self.output_components):
|
| 379 |
+
assert isinstance(component, IOComponent)
|
| 380 |
+
if component.label is None:
|
| 381 |
+
if len(self.output_components) == 1:
|
| 382 |
+
component.label = "output"
|
| 383 |
+
else:
|
| 384 |
+
component.label = f"output {i}"
|
| 385 |
+
|
| 386 |
+
if self.allow_flagging != "never":
|
| 387 |
+
if (
|
| 388 |
+
self.interface_type == InterfaceTypes.UNIFIED
|
| 389 |
+
or self.allow_flagging == "auto"
|
| 390 |
+
):
|
| 391 |
+
self.flagging_callback.setup(self.input_components, self.flagging_dir) # type: ignore
|
| 392 |
+
elif self.interface_type == InterfaceTypes.INPUT_ONLY:
|
| 393 |
+
pass
|
| 394 |
+
else:
|
| 395 |
+
self.flagging_callback.setup(
|
| 396 |
+
self.input_components + self.output_components, self.flagging_dir # type: ignore
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# Render the Gradio UI
|
| 400 |
+
with self:
|
| 401 |
+
self.render_title_description()
|
| 402 |
+
|
| 403 |
+
submit_btn, clear_btn, stop_btn, flag_btns = None, None, None, None
|
| 404 |
+
interpretation_btn, interpretation_set = None, None
|
| 405 |
+
input_component_column, interpret_component_column = None, None
|
| 406 |
+
|
| 407 |
+
with Row(equal_height=False):
|
| 408 |
+
if self.interface_type in [
|
| 409 |
+
InterfaceTypes.STANDARD,
|
| 410 |
+
InterfaceTypes.INPUT_ONLY,
|
| 411 |
+
InterfaceTypes.UNIFIED,
|
| 412 |
+
]:
|
| 413 |
+
(
|
| 414 |
+
submit_btn,
|
| 415 |
+
clear_btn,
|
| 416 |
+
stop_btn,
|
| 417 |
+
flag_btns,
|
| 418 |
+
input_component_column,
|
| 419 |
+
interpret_component_column,
|
| 420 |
+
interpretation_set,
|
| 421 |
+
) = self.render_input_column()
|
| 422 |
+
if self.interface_type in [
|
| 423 |
+
InterfaceTypes.STANDARD,
|
| 424 |
+
InterfaceTypes.OUTPUT_ONLY,
|
| 425 |
+
]:
|
| 426 |
+
(
|
| 427 |
+
submit_btn_out,
|
| 428 |
+
clear_btn_2_out,
|
| 429 |
+
stop_btn_2_out,
|
| 430 |
+
flag_btns_out,
|
| 431 |
+
interpretation_btn,
|
| 432 |
+
) = self.render_output_column(submit_btn)
|
| 433 |
+
submit_btn = submit_btn or submit_btn_out
|
| 434 |
+
clear_btn = clear_btn or clear_btn_2_out
|
| 435 |
+
stop_btn = stop_btn or stop_btn_2_out
|
| 436 |
+
flag_btns = flag_btns or flag_btns_out
|
| 437 |
+
|
| 438 |
+
assert clear_btn is not None, "Clear button not rendered"
|
| 439 |
+
|
| 440 |
+
self.attach_submit_events(submit_btn, stop_btn)
|
| 441 |
+
self.attach_clear_events(
|
| 442 |
+
clear_btn, input_component_column, interpret_component_column
|
| 443 |
+
)
|
| 444 |
+
self.attach_interpretation_events(
|
| 445 |
+
interpretation_btn,
|
| 446 |
+
interpretation_set,
|
| 447 |
+
input_component_column,
|
| 448 |
+
interpret_component_column,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
self.attach_flagging_events(flag_btns, clear_btn)
|
| 452 |
+
self.render_examples()
|
| 453 |
+
self.render_article()
|
| 454 |
+
|
| 455 |
+
self.config = self.get_config_file()
|
| 456 |
+
|
| 457 |
+
def render_title_description(self) -> None:
|
| 458 |
+
if self.title:
|
| 459 |
+
Markdown(
|
| 460 |
+
f"<h1 style='text-align: center; margin-bottom: 1rem'>{self.title}</h1>"
|
| 461 |
+
)
|
| 462 |
+
if self.description:
|
| 463 |
+
Markdown(self.description)
|
| 464 |
+
|
| 465 |
+
def render_flag_btns(self) -> list[Button]:
|
| 466 |
+
return [Button(label) for label, _ in self.flagging_options]
|
| 467 |
+
|
| 468 |
+
def render_input_column(
|
| 469 |
+
self,
|
| 470 |
+
) -> tuple[
|
| 471 |
+
Button | None,
|
| 472 |
+
ClearButton | None,
|
| 473 |
+
Button | None,
|
| 474 |
+
list[Button] | None,
|
| 475 |
+
Column,
|
| 476 |
+
Column | None,
|
| 477 |
+
list[Interpretation] | None,
|
| 478 |
+
]:
|
| 479 |
+
submit_btn, clear_btn, stop_btn, flag_btns = None, None, None, None
|
| 480 |
+
interpret_component_column, interpretation_set = None, None
|
| 481 |
+
|
| 482 |
+
with Column(variant="panel"):
|
| 483 |
+
input_component_column = Column()
|
| 484 |
+
with input_component_column:
|
| 485 |
+
for component in self.input_components:
|
| 486 |
+
component.render()
|
| 487 |
+
if self.interpretation:
|
| 488 |
+
interpret_component_column = Column(visible=False)
|
| 489 |
+
interpretation_set = []
|
| 490 |
+
with interpret_component_column:
|
| 491 |
+
for component in self.input_components:
|
| 492 |
+
interpretation_set.append(Interpretation(component))
|
| 493 |
+
with Row():
|
| 494 |
+
if self.interface_type in [
|
| 495 |
+
InterfaceTypes.STANDARD,
|
| 496 |
+
InterfaceTypes.INPUT_ONLY,
|
| 497 |
+
]:
|
| 498 |
+
clear_btn = ClearButton()
|
| 499 |
+
if not self.live:
|
| 500 |
+
submit_btn = Button("Submit", variant="primary")
|
| 501 |
+
# Stopping jobs only works if the queue is enabled
|
| 502 |
+
# We don't know if the queue is enabled when the interface
|
| 503 |
+
# is created. We use whether a generator function is provided
|
| 504 |
+
# as a proxy of whether the queue will be enabled.
|
| 505 |
+
# Using a generator function without the queue will raise an error.
|
| 506 |
+
if inspect.isgeneratorfunction(
|
| 507 |
+
self.fn
|
| 508 |
+
) or inspect.isasyncgenfunction(self.fn):
|
| 509 |
+
stop_btn = Button("Stop", variant="stop", visible=False)
|
| 510 |
+
elif self.interface_type == InterfaceTypes.UNIFIED:
|
| 511 |
+
clear_btn = ClearButton()
|
| 512 |
+
submit_btn = Button("Submit", variant="primary")
|
| 513 |
+
if (
|
| 514 |
+
inspect.isgeneratorfunction(self.fn)
|
| 515 |
+
or inspect.isasyncgenfunction(self.fn)
|
| 516 |
+
) and not self.live:
|
| 517 |
+
stop_btn = Button("Stop", variant="stop")
|
| 518 |
+
if self.allow_flagging == "manual":
|
| 519 |
+
flag_btns = self.render_flag_btns()
|
| 520 |
+
elif self.allow_flagging == "auto":
|
| 521 |
+
flag_btns = [submit_btn]
|
| 522 |
+
return (
|
| 523 |
+
submit_btn,
|
| 524 |
+
clear_btn,
|
| 525 |
+
stop_btn,
|
| 526 |
+
flag_btns,
|
| 527 |
+
input_component_column,
|
| 528 |
+
interpret_component_column,
|
| 529 |
+
interpretation_set,
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
def render_output_column(
|
| 533 |
+
self,
|
| 534 |
+
submit_btn_in: Button | None,
|
| 535 |
+
) -> tuple[
|
| 536 |
+
Button | None, ClearButton | None, Button | None, list | None, Button | None
|
| 537 |
+
]:
|
| 538 |
+
submit_btn = submit_btn_in
|
| 539 |
+
interpretation_btn, clear_btn, flag_btns, stop_btn = None, None, None, None
|
| 540 |
+
|
| 541 |
+
with Column(variant="panel"):
|
| 542 |
+
for component in self.output_components:
|
| 543 |
+
if not (isinstance(component, State)):
|
| 544 |
+
component.render()
|
| 545 |
+
with Row():
|
| 546 |
+
if self.interface_type == InterfaceTypes.OUTPUT_ONLY:
|
| 547 |
+
clear_btn = ClearButton()
|
| 548 |
+
submit_btn = Button("Generate", variant="primary")
|
| 549 |
+
if (
|
| 550 |
+
inspect.isgeneratorfunction(self.fn)
|
| 551 |
+
or inspect.isasyncgenfunction(self.fn)
|
| 552 |
+
) and not self.live:
|
| 553 |
+
# Stopping jobs only works if the queue is enabled
|
| 554 |
+
# We don't know if the queue is enabled when the interface
|
| 555 |
+
# is created. We use whether a generator function is provided
|
| 556 |
+
# as a proxy of whether the queue will be enabled.
|
| 557 |
+
# Using a generator function without the queue will raise an error.
|
| 558 |
+
stop_btn = Button("Stop", variant="stop", visible=False)
|
| 559 |
+
if self.allow_flagging == "manual":
|
| 560 |
+
flag_btns = self.render_flag_btns()
|
| 561 |
+
elif self.allow_flagging == "auto":
|
| 562 |
+
assert submit_btn is not None, "Submit button not rendered"
|
| 563 |
+
flag_btns = [submit_btn]
|
| 564 |
+
if self.interpretation:
|
| 565 |
+
interpretation_btn = Button("Interpret")
|
| 566 |
+
|
| 567 |
+
return submit_btn, clear_btn, stop_btn, flag_btns, interpretation_btn
|
| 568 |
+
|
| 569 |
+
def render_article(self):
|
| 570 |
+
if self.article:
|
| 571 |
+
Markdown(self.article)
|
| 572 |
+
|
| 573 |
+
def attach_submit_events(self, submit_btn: Button | None, stop_btn: Button | None):
|
| 574 |
+
if self.live:
|
| 575 |
+
if self.interface_type == InterfaceTypes.OUTPUT_ONLY:
|
| 576 |
+
assert submit_btn is not None, "Submit button not rendered"
|
| 577 |
+
super().load(self.fn, None, self.output_components)
|
| 578 |
+
# For output-only interfaces, the user probably still want a "generate"
|
| 579 |
+
# button even if the Interface is live
|
| 580 |
+
submit_btn.click(
|
| 581 |
+
self.fn,
|
| 582 |
+
None,
|
| 583 |
+
self.output_components,
|
| 584 |
+
api_name="predict",
|
| 585 |
+
preprocess=not (self.api_mode),
|
| 586 |
+
postprocess=not (self.api_mode),
|
| 587 |
+
batch=self.batch,
|
| 588 |
+
max_batch_size=self.max_batch_size,
|
| 589 |
+
)
|
| 590 |
+
else:
|
| 591 |
+
for component in self.input_components:
|
| 592 |
+
if isinstance(component, Streamable) and component.streaming:
|
| 593 |
+
component.stream(
|
| 594 |
+
self.fn,
|
| 595 |
+
self.input_components,
|
| 596 |
+
self.output_components,
|
| 597 |
+
api_name="predict",
|
| 598 |
+
preprocess=not (self.api_mode),
|
| 599 |
+
postprocess=not (self.api_mode),
|
| 600 |
+
)
|
| 601 |
+
continue
|
| 602 |
+
if isinstance(component, Changeable):
|
| 603 |
+
component.change(
|
| 604 |
+
self.fn,
|
| 605 |
+
self.input_components,
|
| 606 |
+
self.output_components,
|
| 607 |
+
api_name="predict",
|
| 608 |
+
preprocess=not (self.api_mode),
|
| 609 |
+
postprocess=not (self.api_mode),
|
| 610 |
+
)
|
| 611 |
+
else:
|
| 612 |
+
assert submit_btn is not None, "Submit button not rendered"
|
| 613 |
+
fn = self.fn
|
| 614 |
+
extra_output = []
|
| 615 |
+
|
| 616 |
+
triggers = [submit_btn.click] + [
|
| 617 |
+
component.submit
|
| 618 |
+
for component in self.input_components
|
| 619 |
+
if isinstance(component, Submittable)
|
| 620 |
+
]
|
| 621 |
+
predict_events = []
|
| 622 |
+
|
| 623 |
+
if stop_btn:
|
| 624 |
+
# Wrap the original function to show/hide the "Stop" button
|
| 625 |
+
async def fn(*args):
|
| 626 |
+
# The main idea here is to call the original function
|
| 627 |
+
# and append some updates to keep the "Submit" button
|
| 628 |
+
# hidden and the "Stop" button visible
|
| 629 |
+
|
| 630 |
+
if inspect.isasyncgenfunction(self.fn):
|
| 631 |
+
iterator = self.fn(*args)
|
| 632 |
+
else:
|
| 633 |
+
iterator = utils.SyncToAsyncIterator(
|
| 634 |
+
self.fn(*args), limiter=self.limiter
|
| 635 |
+
)
|
| 636 |
+
async for output in iterator:
|
| 637 |
+
yield output
|
| 638 |
+
|
| 639 |
+
extra_output = [submit_btn, stop_btn]
|
| 640 |
+
|
| 641 |
+
def cleanup():
|
| 642 |
+
return [Button.update(visible=True), Button.update(visible=False)]
|
| 643 |
+
|
| 644 |
+
for i, trigger in enumerate(triggers):
|
| 645 |
+
predict_event = trigger(
|
| 646 |
+
lambda: (
|
| 647 |
+
submit_btn.update(visible=False),
|
| 648 |
+
stop_btn.update(visible=True),
|
| 649 |
+
),
|
| 650 |
+
inputs=None,
|
| 651 |
+
outputs=[submit_btn, stop_btn],
|
| 652 |
+
queue=False,
|
| 653 |
+
).then(
|
| 654 |
+
fn,
|
| 655 |
+
self.input_components,
|
| 656 |
+
self.output_components,
|
| 657 |
+
api_name="predict" if i == 0 else None,
|
| 658 |
+
scroll_to_output=True,
|
| 659 |
+
preprocess=not (self.api_mode),
|
| 660 |
+
postprocess=not (self.api_mode),
|
| 661 |
+
batch=self.batch,
|
| 662 |
+
max_batch_size=self.max_batch_size,
|
| 663 |
+
)
|
| 664 |
+
predict_events.append(predict_event)
|
| 665 |
+
|
| 666 |
+
predict_event.then(
|
| 667 |
+
cleanup,
|
| 668 |
+
inputs=None,
|
| 669 |
+
outputs=extra_output, # type: ignore
|
| 670 |
+
queue=False,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
stop_btn.click(
|
| 674 |
+
cleanup,
|
| 675 |
+
inputs=None,
|
| 676 |
+
outputs=[submit_btn, stop_btn],
|
| 677 |
+
cancels=predict_events,
|
| 678 |
+
queue=False,
|
| 679 |
+
)
|
| 680 |
+
else:
|
| 681 |
+
for i, trigger in enumerate(triggers):
|
| 682 |
+
predict_events.append(
|
| 683 |
+
trigger(
|
| 684 |
+
fn,
|
| 685 |
+
self.input_components,
|
| 686 |
+
self.output_components,
|
| 687 |
+
api_name="predict" if i == 0 else None,
|
| 688 |
+
scroll_to_output=True,
|
| 689 |
+
preprocess=not (self.api_mode),
|
| 690 |
+
postprocess=not (self.api_mode),
|
| 691 |
+
batch=self.batch,
|
| 692 |
+
max_batch_size=self.max_batch_size,
|
| 693 |
+
)
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
def attach_clear_events(
|
| 697 |
+
self,
|
| 698 |
+
clear_btn: ClearButton,
|
| 699 |
+
input_component_column: Column | None,
|
| 700 |
+
interpret_component_column: Column | None,
|
| 701 |
+
):
|
| 702 |
+
clear_btn.add(self.input_components + self.output_components)
|
| 703 |
+
clear_btn.click(
|
| 704 |
+
None,
|
| 705 |
+
[],
|
| 706 |
+
(
|
| 707 |
+
([input_component_column] if input_component_column else [])
|
| 708 |
+
+ ([interpret_component_column] if self.interpretation else [])
|
| 709 |
+
), # type: ignore
|
| 710 |
+
_js=f"""() => {json.dumps(
|
| 711 |
+
(
|
| 712 |
+
[Column.update(visible=True)]
|
| 713 |
+
if self.interface_type
|
| 714 |
+
in [
|
| 715 |
+
InterfaceTypes.STANDARD,
|
| 716 |
+
InterfaceTypes.INPUT_ONLY,
|
| 717 |
+
InterfaceTypes.UNIFIED,
|
| 718 |
+
]
|
| 719 |
+
else []
|
| 720 |
+
)
|
| 721 |
+
+ ([Column.update(visible=False)] if self.interpretation else [])
|
| 722 |
+
)}
|
| 723 |
+
""",
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
def attach_interpretation_events(
|
| 727 |
+
self,
|
| 728 |
+
interpretation_btn: Button | None,
|
| 729 |
+
interpretation_set: list[Interpretation] | None,
|
| 730 |
+
input_component_column: Column | None,
|
| 731 |
+
interpret_component_column: Column | None,
|
| 732 |
+
):
|
| 733 |
+
if interpretation_btn:
|
| 734 |
+
interpretation_btn.click(
|
| 735 |
+
self.interpret_func,
|
| 736 |
+
inputs=self.input_components + self.output_components,
|
| 737 |
+
outputs=(interpretation_set or []) + [input_component_column, interpret_component_column], # type: ignore
|
| 738 |
+
preprocess=False,
|
| 739 |
+
)
|
| 740 |
+
|
| 741 |
+
def attach_flagging_events(
|
| 742 |
+
self, flag_btns: list[Button] | None, clear_btn: ClearButton
|
| 743 |
+
):
|
| 744 |
+
if not (
|
| 745 |
+
flag_btns
|
| 746 |
+
and self.interface_type
|
| 747 |
+
in (
|
| 748 |
+
InterfaceTypes.STANDARD,
|
| 749 |
+
InterfaceTypes.OUTPUT_ONLY,
|
| 750 |
+
InterfaceTypes.UNIFIED,
|
| 751 |
+
)
|
| 752 |
+
):
|
| 753 |
+
return
|
| 754 |
+
|
| 755 |
+
if self.allow_flagging == "auto":
|
| 756 |
+
flag_method = FlagMethod(
|
| 757 |
+
self.flagging_callback, "", "", visual_feedback=False
|
| 758 |
+
)
|
| 759 |
+
flag_btns[0].click( # flag_btns[0] is just the "Submit" button
|
| 760 |
+
flag_method,
|
| 761 |
+
inputs=self.input_components,
|
| 762 |
+
outputs=None,
|
| 763 |
+
preprocess=False,
|
| 764 |
+
queue=False,
|
| 765 |
+
)
|
| 766 |
+
return
|
| 767 |
+
|
| 768 |
+
if self.interface_type == InterfaceTypes.UNIFIED:
|
| 769 |
+
flag_components = self.input_components
|
| 770 |
+
else:
|
| 771 |
+
flag_components = self.input_components + self.output_components
|
| 772 |
+
|
| 773 |
+
for flag_btn, (label, value) in zip(flag_btns, self.flagging_options):
|
| 774 |
+
assert isinstance(value, str)
|
| 775 |
+
flag_method = FlagMethod(self.flagging_callback, label, value)
|
| 776 |
+
flag_btn.click(
|
| 777 |
+
lambda: Button.update(value="Saving...", interactive=False),
|
| 778 |
+
None,
|
| 779 |
+
flag_btn,
|
| 780 |
+
queue=False,
|
| 781 |
+
)
|
| 782 |
+
flag_btn.click(
|
| 783 |
+
flag_method,
|
| 784 |
+
inputs=flag_components,
|
| 785 |
+
outputs=flag_btn,
|
| 786 |
+
preprocess=False,
|
| 787 |
+
queue=False,
|
| 788 |
+
)
|
| 789 |
+
clear_btn.click(
|
| 790 |
+
flag_method.reset,
|
| 791 |
+
None,
|
| 792 |
+
flag_btn,
|
| 793 |
+
queue=False,
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
def render_examples(self):
|
| 797 |
+
if self.examples:
|
| 798 |
+
non_state_inputs = [
|
| 799 |
+
c for c in self.input_components if not isinstance(c, State)
|
| 800 |
+
]
|
| 801 |
+
non_state_outputs = [
|
| 802 |
+
c for c in self.output_components if not isinstance(c, State)
|
| 803 |
+
]
|
| 804 |
+
self.examples_handler = Examples(
|
| 805 |
+
examples=self.examples,
|
| 806 |
+
inputs=non_state_inputs, # type: ignore
|
| 807 |
+
outputs=non_state_outputs, # type: ignore
|
| 808 |
+
fn=self.fn,
|
| 809 |
+
cache_examples=self.cache_examples,
|
| 810 |
+
examples_per_page=self.examples_per_page,
|
| 811 |
+
_api_mode=self.api_mode,
|
| 812 |
+
batch=self.batch,
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
def __str__(self):
|
| 816 |
+
return self.__repr__()
|
| 817 |
+
|
| 818 |
+
def __repr__(self):
|
| 819 |
+
repr = f"Gradio Interface for: {self.__name__}"
|
| 820 |
+
repr += f"\n{'-' * len(repr)}"
|
| 821 |
+
repr += "\ninputs:"
|
| 822 |
+
for component in self.input_components:
|
| 823 |
+
repr += f"\n|-{component}"
|
| 824 |
+
repr += "\noutputs:"
|
| 825 |
+
for component in self.output_components:
|
| 826 |
+
repr += f"\n|-{component}"
|
| 827 |
+
return repr
|
| 828 |
+
|
| 829 |
+
async def interpret_func(self, *args):
|
| 830 |
+
return await self.interpret(list(args)) + [
|
| 831 |
+
Column.update(visible=False),
|
| 832 |
+
Column.update(visible=True),
|
| 833 |
+
]
|
| 834 |
+
|
| 835 |
+
async def interpret(self, raw_input: list[Any]) -> list[Any]:
|
| 836 |
+
return [
|
| 837 |
+
{"original": raw_value, "interpretation": interpretation}
|
| 838 |
+
for interpretation, raw_value in zip(
|
| 839 |
+
(await interpretation.run_interpret(self, raw_input))[0], raw_input
|
| 840 |
+
)
|
| 841 |
+
]
|
| 842 |
+
|
| 843 |
+
def test_launch(self) -> None:
|
| 844 |
+
"""
|
| 845 |
+
Deprecated.
|
| 846 |
+
"""
|
| 847 |
+
warnings.warn("The Interface.test_launch() function is deprecated.")
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
@document()
|
| 851 |
+
class TabbedInterface(Blocks):
|
| 852 |
+
"""
|
| 853 |
+
A TabbedInterface is created by providing a list of Interfaces, each of which gets
|
| 854 |
+
rendered in a separate tab.
|
| 855 |
+
Demos: stt_or_tts
|
| 856 |
+
"""
|
| 857 |
+
|
| 858 |
+
def __init__(
|
| 859 |
+
self,
|
| 860 |
+
interface_list: list[Interface],
|
| 861 |
+
tab_names: list[str] | None = None,
|
| 862 |
+
title: str | None = None,
|
| 863 |
+
theme: Theme | None = None,
|
| 864 |
+
analytics_enabled: bool | None = None,
|
| 865 |
+
css: str | None = None,
|
| 866 |
+
):
|
| 867 |
+
"""
|
| 868 |
+
Parameters:
|
| 869 |
+
interface_list: a list of interfaces to be rendered in tabs.
|
| 870 |
+
tab_names: a list of tab names. If None, the tab names will be "Tab 1", "Tab 2", etc.
|
| 871 |
+
title: a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window.
|
| 872 |
+
analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
|
| 873 |
+
css: custom css or path to custom css file to apply to entire Blocks
|
| 874 |
+
Returns:
|
| 875 |
+
a Gradio Tabbed Interface for the given interfaces
|
| 876 |
+
"""
|
| 877 |
+
super().__init__(
|
| 878 |
+
title=title or "Gradio",
|
| 879 |
+
theme=theme,
|
| 880 |
+
analytics_enabled=analytics_enabled,
|
| 881 |
+
mode="tabbed_interface",
|
| 882 |
+
css=css,
|
| 883 |
+
)
|
| 884 |
+
if tab_names is None:
|
| 885 |
+
tab_names = [f"Tab {i}" for i in range(len(interface_list))]
|
| 886 |
+
with self:
|
| 887 |
+
if title:
|
| 888 |
+
Markdown(
|
| 889 |
+
f"<h1 style='text-align: center; margin-bottom: 1rem'>{title}</h1>"
|
| 890 |
+
)
|
| 891 |
+
with Tabs():
|
| 892 |
+
for interface, tab_name in zip(interface_list, tab_names):
|
| 893 |
+
with Tab(label=tab_name):
|
| 894 |
+
interface.render()
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
def close_all(verbose: bool = True) -> None:
|
| 898 |
+
for io in Interface.get_instances():
|
| 899 |
+
io.close(verbose)
|
falcon/lib/python3.10/site-packages/gradio/interpretation.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contains classes and methods related to interpretation for components in Gradio."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import math
|
| 7 |
+
from abc import ABC, abstractmethod
|
| 8 |
+
from typing import TYPE_CHECKING, Any
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from gradio_client import utils as client_utils
|
| 12 |
+
|
| 13 |
+
from gradio import components
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
|
| 16 |
+
from gradio import Interface
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Interpretable(ABC): # noqa: B024
|
| 20 |
+
def __init__(self) -> None:
|
| 21 |
+
self.set_interpret_parameters()
|
| 22 |
+
|
| 23 |
+
def set_interpret_parameters(self): # noqa: B027
|
| 24 |
+
"""
|
| 25 |
+
Set any parameters for interpretation. Properties can be set here to be
|
| 26 |
+
used in get_interpretation_neighbors and get_interpretation_scores.
|
| 27 |
+
"""
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
def get_interpretation_scores(
|
| 31 |
+
self, x: Any, neighbors: list[Any] | None, scores: list[float], **kwargs
|
| 32 |
+
) -> list:
|
| 33 |
+
"""
|
| 34 |
+
Arrange the output values from the neighbors into interpretation scores for the interface to render.
|
| 35 |
+
Parameters:
|
| 36 |
+
x: Input to interface
|
| 37 |
+
neighbors: Neighboring values to input x used for interpretation.
|
| 38 |
+
scores: Output value corresponding to each neighbor in neighbors
|
| 39 |
+
Returns:
|
| 40 |
+
Arrangement of interpretation scores for interfaces to render.
|
| 41 |
+
"""
|
| 42 |
+
return scores
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TokenInterpretable(Interpretable, ABC):
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def tokenize(self, x: Any) -> tuple[list, list, None]:
|
| 48 |
+
"""
|
| 49 |
+
Interprets an input data point x by splitting it into a list of tokens (e.g
|
| 50 |
+
a string into words or an image into super-pixels).
|
| 51 |
+
"""
|
| 52 |
+
return [], [], None
|
| 53 |
+
|
| 54 |
+
@abstractmethod
|
| 55 |
+
def get_masked_inputs(self, tokens: list, binary_mask_matrix: list[list]) -> list:
|
| 56 |
+
return []
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class NeighborInterpretable(Interpretable, ABC):
|
| 60 |
+
@abstractmethod
|
| 61 |
+
def get_interpretation_neighbors(self, x: Any) -> tuple[list, dict]:
|
| 62 |
+
"""
|
| 63 |
+
Generates values similar to input to be used to interpret the significance of the input in the final output.
|
| 64 |
+
Parameters:
|
| 65 |
+
x: Input to interface
|
| 66 |
+
Returns: (neighbor_values, interpret_kwargs, interpret_by_removal)
|
| 67 |
+
neighbor_values: Neighboring values to input x to compute for interpretation
|
| 68 |
+
interpret_kwargs: Keyword arguments to be passed to get_interpretation_scores
|
| 69 |
+
"""
|
| 70 |
+
return [], {}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
async def run_interpret(interface: Interface, raw_input: list):
|
| 74 |
+
"""
|
| 75 |
+
Runs the interpretation command for the machine learning model. Handles both the "default" out-of-the-box
|
| 76 |
+
interpretation for a certain set of UI component types, as well as the custom interpretation case.
|
| 77 |
+
Parameters:
|
| 78 |
+
raw_input: a list of raw inputs to apply the interpretation(s) on.
|
| 79 |
+
"""
|
| 80 |
+
if isinstance(interface.interpretation, list): # Either "default" or "shap"
|
| 81 |
+
processed_input = [
|
| 82 |
+
input_component.preprocess(raw_input[i])
|
| 83 |
+
for i, input_component in enumerate(interface.input_components)
|
| 84 |
+
]
|
| 85 |
+
original_output = await interface.call_function(0, processed_input)
|
| 86 |
+
original_output = original_output["prediction"]
|
| 87 |
+
|
| 88 |
+
if len(interface.output_components) == 1:
|
| 89 |
+
original_output = [original_output]
|
| 90 |
+
|
| 91 |
+
scores, alternative_outputs = [], []
|
| 92 |
+
|
| 93 |
+
for i, (x, interp) in enumerate(zip(raw_input, interface.interpretation)):
|
| 94 |
+
if interp == "default":
|
| 95 |
+
input_component = interface.input_components[i]
|
| 96 |
+
neighbor_raw_input = list(raw_input)
|
| 97 |
+
if isinstance(input_component, TokenInterpretable):
|
| 98 |
+
tokens, neighbor_values, masks = input_component.tokenize(x)
|
| 99 |
+
interface_scores = []
|
| 100 |
+
alternative_output = []
|
| 101 |
+
for neighbor_input in neighbor_values:
|
| 102 |
+
neighbor_raw_input[i] = neighbor_input
|
| 103 |
+
processed_neighbor_input = [
|
| 104 |
+
input_component.preprocess(neighbor_raw_input[i])
|
| 105 |
+
for i, input_component in enumerate(
|
| 106 |
+
interface.input_components
|
| 107 |
+
)
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
neighbor_output = await interface.call_function(
|
| 111 |
+
0, processed_neighbor_input
|
| 112 |
+
)
|
| 113 |
+
neighbor_output = neighbor_output["prediction"]
|
| 114 |
+
if len(interface.output_components) == 1:
|
| 115 |
+
neighbor_output = [neighbor_output]
|
| 116 |
+
processed_neighbor_output = [
|
| 117 |
+
output_component.postprocess(neighbor_output[i])
|
| 118 |
+
for i, output_component in enumerate(
|
| 119 |
+
interface.output_components
|
| 120 |
+
)
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
alternative_output.append(processed_neighbor_output)
|
| 124 |
+
interface_scores.append(
|
| 125 |
+
quantify_difference_in_label(
|
| 126 |
+
interface, original_output, neighbor_output
|
| 127 |
+
)
|
| 128 |
+
)
|
| 129 |
+
alternative_outputs.append(alternative_output)
|
| 130 |
+
scores.append(
|
| 131 |
+
input_component.get_interpretation_scores(
|
| 132 |
+
raw_input[i],
|
| 133 |
+
neighbor_values,
|
| 134 |
+
interface_scores,
|
| 135 |
+
masks=masks,
|
| 136 |
+
tokens=tokens,
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
elif isinstance(input_component, NeighborInterpretable):
|
| 140 |
+
(
|
| 141 |
+
neighbor_values,
|
| 142 |
+
interpret_kwargs,
|
| 143 |
+
) = input_component.get_interpretation_neighbors(
|
| 144 |
+
x
|
| 145 |
+
) # type: ignore
|
| 146 |
+
interface_scores = []
|
| 147 |
+
alternative_output = []
|
| 148 |
+
for neighbor_input in neighbor_values:
|
| 149 |
+
neighbor_raw_input[i] = neighbor_input
|
| 150 |
+
processed_neighbor_input = [
|
| 151 |
+
input_component.preprocess(neighbor_raw_input[i])
|
| 152 |
+
for i, input_component in enumerate(
|
| 153 |
+
interface.input_components
|
| 154 |
+
)
|
| 155 |
+
]
|
| 156 |
+
neighbor_output = await interface.call_function(
|
| 157 |
+
0, processed_neighbor_input
|
| 158 |
+
)
|
| 159 |
+
neighbor_output = neighbor_output["prediction"]
|
| 160 |
+
if len(interface.output_components) == 1:
|
| 161 |
+
neighbor_output = [neighbor_output]
|
| 162 |
+
processed_neighbor_output = [
|
| 163 |
+
output_component.postprocess(neighbor_output[i])
|
| 164 |
+
for i, output_component in enumerate(
|
| 165 |
+
interface.output_components
|
| 166 |
+
)
|
| 167 |
+
]
|
| 168 |
+
|
| 169 |
+
alternative_output.append(processed_neighbor_output)
|
| 170 |
+
interface_scores.append(
|
| 171 |
+
quantify_difference_in_label(
|
| 172 |
+
interface, original_output, neighbor_output
|
| 173 |
+
)
|
| 174 |
+
)
|
| 175 |
+
alternative_outputs.append(alternative_output)
|
| 176 |
+
interface_scores = [-score for score in interface_scores]
|
| 177 |
+
scores.append(
|
| 178 |
+
input_component.get_interpretation_scores(
|
| 179 |
+
raw_input[i],
|
| 180 |
+
neighbor_values,
|
| 181 |
+
interface_scores,
|
| 182 |
+
**interpret_kwargs,
|
| 183 |
+
)
|
| 184 |
+
)
|
| 185 |
+
else:
|
| 186 |
+
raise ValueError(
|
| 187 |
+
f"Component {input_component} does not support interpretation"
|
| 188 |
+
)
|
| 189 |
+
elif interp == "shap" or interp == "shapley":
|
| 190 |
+
try:
|
| 191 |
+
import shap # type: ignore
|
| 192 |
+
except (ImportError, ModuleNotFoundError) as err:
|
| 193 |
+
raise ValueError(
|
| 194 |
+
"The package `shap` is required for this interpretation method. Try: `pip install shap`"
|
| 195 |
+
) from err
|
| 196 |
+
input_component = interface.input_components[i]
|
| 197 |
+
if not isinstance(input_component, TokenInterpretable):
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"Input component {input_component} does not support `shap` interpretation"
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
tokens, _, masks = input_component.tokenize(x)
|
| 203 |
+
|
| 204 |
+
# construct a masked version of the input
|
| 205 |
+
def get_masked_prediction(binary_mask):
|
| 206 |
+
assert isinstance(input_component, TokenInterpretable)
|
| 207 |
+
masked_xs = input_component.get_masked_inputs(tokens, binary_mask)
|
| 208 |
+
preds = []
|
| 209 |
+
for masked_x in masked_xs:
|
| 210 |
+
processed_masked_input = copy.deepcopy(processed_input)
|
| 211 |
+
processed_masked_input[i] = input_component.preprocess(masked_x)
|
| 212 |
+
new_output = client_utils.synchronize_async(
|
| 213 |
+
interface.call_function, 0, processed_masked_input
|
| 214 |
+
)
|
| 215 |
+
new_output = new_output["prediction"]
|
| 216 |
+
if len(interface.output_components) == 1:
|
| 217 |
+
new_output = [new_output]
|
| 218 |
+
pred = get_regression_or_classification_value(
|
| 219 |
+
interface, original_output, new_output
|
| 220 |
+
)
|
| 221 |
+
preds.append(pred)
|
| 222 |
+
return np.array(preds)
|
| 223 |
+
|
| 224 |
+
num_total_segments = len(tokens)
|
| 225 |
+
explainer = shap.KernelExplainer(
|
| 226 |
+
get_masked_prediction, np.zeros((1, num_total_segments))
|
| 227 |
+
)
|
| 228 |
+
shap_values = explainer.shap_values(
|
| 229 |
+
np.ones((1, num_total_segments)),
|
| 230 |
+
nsamples=int(interface.num_shap * num_total_segments),
|
| 231 |
+
silent=True,
|
| 232 |
+
)
|
| 233 |
+
assert shap_values is not None, "SHAP values could not be calculated"
|
| 234 |
+
scores.append(
|
| 235 |
+
input_component.get_interpretation_scores(
|
| 236 |
+
raw_input[i],
|
| 237 |
+
None,
|
| 238 |
+
shap_values[0].tolist(),
|
| 239 |
+
masks=masks,
|
| 240 |
+
tokens=tokens,
|
| 241 |
+
)
|
| 242 |
+
)
|
| 243 |
+
alternative_outputs.append([])
|
| 244 |
+
elif interp is None:
|
| 245 |
+
scores.append(None)
|
| 246 |
+
alternative_outputs.append([])
|
| 247 |
+
else:
|
| 248 |
+
raise ValueError(f"Unknown interpretation method: {interp}")
|
| 249 |
+
return scores, alternative_outputs
|
| 250 |
+
elif interface.interpretation: # custom interpretation function
|
| 251 |
+
processed_input = [
|
| 252 |
+
input_component.preprocess(raw_input[i])
|
| 253 |
+
for i, input_component in enumerate(interface.input_components)
|
| 254 |
+
]
|
| 255 |
+
interpreter = interface.interpretation
|
| 256 |
+
interpretation = interpreter(*processed_input)
|
| 257 |
+
if len(raw_input) == 1:
|
| 258 |
+
interpretation = [interpretation]
|
| 259 |
+
return interpretation, []
|
| 260 |
+
else:
|
| 261 |
+
raise ValueError("No interpretation method specified.")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def diff(original: Any, perturbed: Any) -> int | float:
|
| 265 |
+
try: # try computing numerical difference
|
| 266 |
+
score = float(original) - float(perturbed)
|
| 267 |
+
except ValueError: # otherwise, look at strict difference in label
|
| 268 |
+
score = int(original != perturbed)
|
| 269 |
+
return score
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def quantify_difference_in_label(
|
| 273 |
+
interface: Interface, original_output: list, perturbed_output: list
|
| 274 |
+
) -> int | float:
|
| 275 |
+
output_component = interface.output_components[0]
|
| 276 |
+
post_original_output = output_component.postprocess(original_output[0])
|
| 277 |
+
post_perturbed_output = output_component.postprocess(perturbed_output[0])
|
| 278 |
+
|
| 279 |
+
if isinstance(output_component, components.Label):
|
| 280 |
+
original_label = post_original_output["label"]
|
| 281 |
+
perturbed_label = post_perturbed_output["label"]
|
| 282 |
+
|
| 283 |
+
# Handle different return types of Label interface
|
| 284 |
+
if "confidences" in post_original_output:
|
| 285 |
+
original_confidence = original_output[0][original_label]
|
| 286 |
+
perturbed_confidence = perturbed_output[0][original_label]
|
| 287 |
+
score = original_confidence - perturbed_confidence
|
| 288 |
+
else:
|
| 289 |
+
score = diff(original_label, perturbed_label)
|
| 290 |
+
return score
|
| 291 |
+
|
| 292 |
+
elif isinstance(output_component, components.Number):
|
| 293 |
+
score = diff(post_original_output, post_perturbed_output)
|
| 294 |
+
return score
|
| 295 |
+
|
| 296 |
+
else:
|
| 297 |
+
raise ValueError(
|
| 298 |
+
f"This interpretation method doesn't support the Output component: {output_component}"
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def get_regression_or_classification_value(
|
| 303 |
+
interface: Interface, original_output: list, perturbed_output: list
|
| 304 |
+
) -> int | float:
|
| 305 |
+
"""Used to combine regression/classification for Shap interpretation method."""
|
| 306 |
+
output_component = interface.output_components[0]
|
| 307 |
+
post_original_output = output_component.postprocess(original_output[0])
|
| 308 |
+
post_perturbed_output = output_component.postprocess(perturbed_output[0])
|
| 309 |
+
|
| 310 |
+
if isinstance(output_component, components.Label):
|
| 311 |
+
original_label = post_original_output["label"]
|
| 312 |
+
perturbed_label = post_perturbed_output["label"]
|
| 313 |
+
|
| 314 |
+
# Handle different return types of Label interface
|
| 315 |
+
if "confidences" in post_original_output:
|
| 316 |
+
if math.isnan(perturbed_output[0][original_label]):
|
| 317 |
+
return 0
|
| 318 |
+
return perturbed_output[0][original_label]
|
| 319 |
+
else:
|
| 320 |
+
score = diff(
|
| 321 |
+
perturbed_label, original_label
|
| 322 |
+
) # Intentionally inverted order of arguments.
|
| 323 |
+
return score
|
| 324 |
+
|
| 325 |
+
else:
|
| 326 |
+
raise ValueError(
|
| 327 |
+
f"This interpretation method doesn't support the Output component: {output_component}"
|
| 328 |
+
)
|
falcon/lib/python3.10/site-packages/gradio/mix.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ways to transform interfaces to produce new interfaces
|
| 3 |
+
"""
|
| 4 |
+
import asyncio
|
| 5 |
+
import warnings
|
| 6 |
+
|
| 7 |
+
from gradio_client.documentation import document, set_documentation_group
|
| 8 |
+
|
| 9 |
+
import gradio
|
| 10 |
+
|
| 11 |
+
set_documentation_group("mix_interface")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@document()
|
| 15 |
+
class Parallel(gradio.Interface):
|
| 16 |
+
"""
|
| 17 |
+
Creates a new Interface consisting of multiple Interfaces in parallel (comparing their outputs).
|
| 18 |
+
The Interfaces to put in Parallel must share the same input components (but can have different output components).
|
| 19 |
+
|
| 20 |
+
Demos: interface_parallel, interface_parallel_load
|
| 21 |
+
Guides: advanced-interface-features
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, *interfaces: gradio.Interface, **options):
|
| 25 |
+
"""
|
| 26 |
+
Parameters:
|
| 27 |
+
interfaces: any number of Interface objects that are to be compared in parallel
|
| 28 |
+
options: additional kwargs that are passed into the new Interface object to customize it
|
| 29 |
+
Returns:
|
| 30 |
+
an Interface object comparing the given models
|
| 31 |
+
"""
|
| 32 |
+
outputs = []
|
| 33 |
+
|
| 34 |
+
for interface in interfaces:
|
| 35 |
+
if not (isinstance(interface, gradio.Interface)):
|
| 36 |
+
warnings.warn(
|
| 37 |
+
"Parallel requires all inputs to be of type Interface. "
|
| 38 |
+
"May not work as expected."
|
| 39 |
+
)
|
| 40 |
+
outputs.extend(interface.output_components)
|
| 41 |
+
|
| 42 |
+
async def parallel_fn(*args):
|
| 43 |
+
return_values_with_durations = await asyncio.gather(
|
| 44 |
+
*[interface.call_function(0, list(args)) for interface in interfaces]
|
| 45 |
+
)
|
| 46 |
+
return_values = [rv["prediction"] for rv in return_values_with_durations]
|
| 47 |
+
combined_list = []
|
| 48 |
+
for interface, return_value in zip(interfaces, return_values):
|
| 49 |
+
if len(interface.output_components) == 1:
|
| 50 |
+
combined_list.append(return_value)
|
| 51 |
+
else:
|
| 52 |
+
combined_list.extend(return_value)
|
| 53 |
+
if len(outputs) == 1:
|
| 54 |
+
return combined_list[0]
|
| 55 |
+
return combined_list
|
| 56 |
+
|
| 57 |
+
parallel_fn.__name__ = " | ".join([io.__name__ for io in interfaces])
|
| 58 |
+
|
| 59 |
+
kwargs = {
|
| 60 |
+
"fn": parallel_fn,
|
| 61 |
+
"inputs": interfaces[0].input_components,
|
| 62 |
+
"outputs": outputs,
|
| 63 |
+
}
|
| 64 |
+
kwargs.update(options)
|
| 65 |
+
super().__init__(**kwargs)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@document()
|
| 69 |
+
class Series(gradio.Interface):
|
| 70 |
+
"""
|
| 71 |
+
Creates a new Interface from multiple Interfaces in series (the output of one is fed as the input to the next,
|
| 72 |
+
and so the input and output components must agree between the interfaces).
|
| 73 |
+
|
| 74 |
+
Demos: interface_series, interface_series_load
|
| 75 |
+
Guides: advanced-interface-features
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, *interfaces: gradio.Interface, **options):
|
| 79 |
+
"""
|
| 80 |
+
Parameters:
|
| 81 |
+
interfaces: any number of Interface objects that are to be connected in series
|
| 82 |
+
options: additional kwargs that are passed into the new Interface object to customize it
|
| 83 |
+
Returns:
|
| 84 |
+
an Interface object connecting the given models
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
async def connected_fn(*data):
|
| 88 |
+
for idx, interface in enumerate(interfaces):
|
| 89 |
+
# skip preprocessing for first interface since the Series interface will include it
|
| 90 |
+
if idx > 0 and not (interface.api_mode):
|
| 91 |
+
data = [
|
| 92 |
+
input_component.preprocess(data[i])
|
| 93 |
+
for i, input_component in enumerate(interface.input_components)
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
# run all of predictions sequentially
|
| 97 |
+
data = (await interface.call_function(0, list(data)))["prediction"]
|
| 98 |
+
if len(interface.output_components) == 1:
|
| 99 |
+
data = [data]
|
| 100 |
+
|
| 101 |
+
# skip postprocessing for final interface since the Series interface will include it
|
| 102 |
+
if idx < len(interfaces) - 1 and not (interface.api_mode):
|
| 103 |
+
data = [
|
| 104 |
+
output_component.postprocess(data[i])
|
| 105 |
+
for i, output_component in enumerate(
|
| 106 |
+
interface.output_components
|
| 107 |
+
)
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
if len(interface.output_components) == 1: # type: ignore
|
| 111 |
+
return data[0]
|
| 112 |
+
return data
|
| 113 |
+
|
| 114 |
+
for interface in interfaces:
|
| 115 |
+
if not (isinstance(interface, gradio.Interface)):
|
| 116 |
+
warnings.warn(
|
| 117 |
+
"Series requires all inputs to be of type Interface. May "
|
| 118 |
+
"not work as expected."
|
| 119 |
+
)
|
| 120 |
+
connected_fn.__name__ = " => ".join([io.__name__ for io in interfaces])
|
| 121 |
+
|
| 122 |
+
kwargs = {
|
| 123 |
+
"fn": connected_fn,
|
| 124 |
+
"inputs": interfaces[0].input_components,
|
| 125 |
+
"outputs": interfaces[-1].output_components,
|
| 126 |
+
"_api_mode": interfaces[0].api_mode, # TODO: set api_mode per-interface
|
| 127 |
+
}
|
| 128 |
+
kwargs.update(options)
|
| 129 |
+
super().__init__(**kwargs)
|
falcon/lib/python3.10/site-packages/gradio/processing_utils.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
import tempfile
|
| 9 |
+
import warnings
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from ffmpy import FFmpeg, FFprobe, FFRuntimeError
|
| 15 |
+
from gradio_client import utils as client_utils
|
| 16 |
+
from PIL import Image, ImageOps, PngImagePlugin
|
| 17 |
+
|
| 18 |
+
with warnings.catch_warnings():
|
| 19 |
+
warnings.simplefilter("ignore") # Ignore pydub warning if ffmpeg is not installed
|
| 20 |
+
from pydub import AudioSegment
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
#########################
|
| 24 |
+
# GENERAL
|
| 25 |
+
#########################
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def to_binary(x: str | dict) -> bytes:
|
| 29 |
+
"""Converts a base64 string or dictionary to a binary string that can be sent in a POST."""
|
| 30 |
+
if isinstance(x, dict):
|
| 31 |
+
if x.get("data"):
|
| 32 |
+
base64str = x["data"]
|
| 33 |
+
else:
|
| 34 |
+
base64str = client_utils.encode_url_or_file_to_base64(x["name"])
|
| 35 |
+
else:
|
| 36 |
+
base64str = x
|
| 37 |
+
return base64.b64decode(extract_base64_data(base64str))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def extract_base64_data(x: str) -> str:
|
| 41 |
+
"""Just extracts the base64 data from a general base64 string."""
|
| 42 |
+
return x.rsplit(",", 1)[-1]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
#########################
|
| 46 |
+
# IMAGE PRE-PROCESSING
|
| 47 |
+
#########################
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def decode_base64_to_image(encoding: str) -> Image.Image:
|
| 51 |
+
image_encoded = extract_base64_data(encoding)
|
| 52 |
+
img = Image.open(BytesIO(base64.b64decode(image_encoded)))
|
| 53 |
+
exif = img.getexif()
|
| 54 |
+
# 274 is the code for image rotation and 1 means "correct orientation"
|
| 55 |
+
if exif.get(274, 1) != 1 and hasattr(ImageOps, "exif_transpose"):
|
| 56 |
+
img = ImageOps.exif_transpose(img)
|
| 57 |
+
return img
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def encode_plot_to_base64(plt):
|
| 61 |
+
with BytesIO() as output_bytes:
|
| 62 |
+
plt.savefig(output_bytes, format="png")
|
| 63 |
+
bytes_data = output_bytes.getvalue()
|
| 64 |
+
base64_str = str(base64.b64encode(bytes_data), "utf-8")
|
| 65 |
+
return "data:image/png;base64," + base64_str
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def get_pil_metadata(pil_image):
|
| 69 |
+
# Copy any text-only metadata
|
| 70 |
+
metadata = PngImagePlugin.PngInfo()
|
| 71 |
+
for key, value in pil_image.info.items():
|
| 72 |
+
if isinstance(key, str) and isinstance(value, str):
|
| 73 |
+
metadata.add_text(key, value)
|
| 74 |
+
|
| 75 |
+
return metadata
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def encode_pil_to_bytes(pil_image, format="png"):
|
| 79 |
+
with BytesIO() as output_bytes:
|
| 80 |
+
pil_image.save(output_bytes, format, pnginfo=get_pil_metadata(pil_image))
|
| 81 |
+
return output_bytes.getvalue()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def encode_pil_to_base64(pil_image):
|
| 85 |
+
bytes_data = encode_pil_to_bytes(pil_image)
|
| 86 |
+
base64_str = str(base64.b64encode(bytes_data), "utf-8")
|
| 87 |
+
return "data:image/png;base64," + base64_str
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def encode_array_to_base64(image_array):
|
| 91 |
+
with BytesIO() as output_bytes:
|
| 92 |
+
pil_image = Image.fromarray(_convert(image_array, np.uint8, force_copy=False))
|
| 93 |
+
pil_image.save(output_bytes, "PNG")
|
| 94 |
+
bytes_data = output_bytes.getvalue()
|
| 95 |
+
base64_str = str(base64.b64encode(bytes_data), "utf-8")
|
| 96 |
+
return "data:image/png;base64," + base64_str
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def resize_and_crop(img, size, crop_type="center"):
|
| 100 |
+
"""
|
| 101 |
+
Resize and crop an image to fit the specified size.
|
| 102 |
+
args:
|
| 103 |
+
size: `(width, height)` tuple. Pass `None` for either width or height
|
| 104 |
+
to only crop and resize the other.
|
| 105 |
+
crop_type: can be 'top', 'middle' or 'bottom', depending on this
|
| 106 |
+
value, the image will cropped getting the 'top/left', 'middle' or
|
| 107 |
+
'bottom/right' of the image to fit the size.
|
| 108 |
+
raises:
|
| 109 |
+
ValueError: if an invalid `crop_type` is provided.
|
| 110 |
+
"""
|
| 111 |
+
if crop_type == "top":
|
| 112 |
+
center = (0, 0)
|
| 113 |
+
elif crop_type == "center":
|
| 114 |
+
center = (0.5, 0.5)
|
| 115 |
+
else:
|
| 116 |
+
raise ValueError
|
| 117 |
+
|
| 118 |
+
resize = list(size)
|
| 119 |
+
if size[0] is None:
|
| 120 |
+
resize[0] = img.size[0]
|
| 121 |
+
if size[1] is None:
|
| 122 |
+
resize[1] = img.size[1]
|
| 123 |
+
return ImageOps.fit(img, resize, centering=center) # type: ignore
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
##################
|
| 127 |
+
# Audio
|
| 128 |
+
##################
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def audio_from_file(filename, crop_min=0, crop_max=100):
|
| 132 |
+
try:
|
| 133 |
+
audio = AudioSegment.from_file(filename)
|
| 134 |
+
except FileNotFoundError as e:
|
| 135 |
+
isfile = Path(filename).is_file()
|
| 136 |
+
msg = (
|
| 137 |
+
f"Cannot load audio from file: `{'ffprobe' if isfile else filename}` not found."
|
| 138 |
+
+ " Please install `ffmpeg` in your system to use non-WAV audio file formats"
|
| 139 |
+
" and make sure `ffprobe` is in your PATH."
|
| 140 |
+
if isfile
|
| 141 |
+
else ""
|
| 142 |
+
)
|
| 143 |
+
raise RuntimeError(msg) from e
|
| 144 |
+
if crop_min != 0 or crop_max != 100:
|
| 145 |
+
audio_start = len(audio) * crop_min / 100
|
| 146 |
+
audio_end = len(audio) * crop_max / 100
|
| 147 |
+
audio = audio[audio_start:audio_end]
|
| 148 |
+
data = np.array(audio.get_array_of_samples())
|
| 149 |
+
if audio.channels > 1:
|
| 150 |
+
data = data.reshape(-1, audio.channels)
|
| 151 |
+
return audio.frame_rate, data
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def audio_to_file(sample_rate, data, filename, format="wav"):
|
| 155 |
+
if format == "wav":
|
| 156 |
+
data = convert_to_16_bit_wav(data)
|
| 157 |
+
audio = AudioSegment(
|
| 158 |
+
data.tobytes(),
|
| 159 |
+
frame_rate=sample_rate,
|
| 160 |
+
sample_width=data.dtype.itemsize,
|
| 161 |
+
channels=(1 if len(data.shape) == 1 else data.shape[1]),
|
| 162 |
+
)
|
| 163 |
+
file = audio.export(filename, format=format)
|
| 164 |
+
file.close() # type: ignore
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def convert_to_16_bit_wav(data):
|
| 168 |
+
# Based on: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.write.html
|
| 169 |
+
warning = "Trying to convert audio automatically from {} to 16-bit int format."
|
| 170 |
+
if data.dtype in [np.float64, np.float32, np.float16]:
|
| 171 |
+
warnings.warn(warning.format(data.dtype))
|
| 172 |
+
data = data / np.abs(data).max()
|
| 173 |
+
data = data * 32767
|
| 174 |
+
data = data.astype(np.int16)
|
| 175 |
+
elif data.dtype == np.int32:
|
| 176 |
+
warnings.warn(warning.format(data.dtype))
|
| 177 |
+
data = data / 65538
|
| 178 |
+
data = data.astype(np.int16)
|
| 179 |
+
elif data.dtype == np.int16:
|
| 180 |
+
pass
|
| 181 |
+
elif data.dtype == np.uint16:
|
| 182 |
+
warnings.warn(warning.format(data.dtype))
|
| 183 |
+
data = data - 32768
|
| 184 |
+
data = data.astype(np.int16)
|
| 185 |
+
elif data.dtype == np.uint8:
|
| 186 |
+
warnings.warn(warning.format(data.dtype))
|
| 187 |
+
data = data * 257 - 32768
|
| 188 |
+
data = data.astype(np.int16)
|
| 189 |
+
else:
|
| 190 |
+
raise ValueError(
|
| 191 |
+
"Audio data cannot be converted automatically from "
|
| 192 |
+
f"{data.dtype} to 16-bit int format."
|
| 193 |
+
)
|
| 194 |
+
return data
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
##################
|
| 198 |
+
# OUTPUT
|
| 199 |
+
##################
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _convert(image, dtype, force_copy=False, uniform=False):
|
| 203 |
+
"""
|
| 204 |
+
Adapted from: https://github.com/scikit-image/scikit-image/blob/main/skimage/util/dtype.py#L510-L531
|
| 205 |
+
|
| 206 |
+
Convert an image to the requested data-type.
|
| 207 |
+
Warnings are issued in case of precision loss, or when negative values
|
| 208 |
+
are clipped during conversion to unsigned integer types (sign loss).
|
| 209 |
+
Floating point values are expected to be normalized and will be clipped
|
| 210 |
+
to the range [0.0, 1.0] or [-1.0, 1.0] when converting to unsigned or
|
| 211 |
+
signed integers respectively.
|
| 212 |
+
Numbers are not shifted to the negative side when converting from
|
| 213 |
+
unsigned to signed integer types. Negative values will be clipped when
|
| 214 |
+
converting to unsigned integers.
|
| 215 |
+
Parameters
|
| 216 |
+
----------
|
| 217 |
+
image : ndarray
|
| 218 |
+
Input image.
|
| 219 |
+
dtype : dtype
|
| 220 |
+
Target data-type.
|
| 221 |
+
force_copy : bool, optional
|
| 222 |
+
Force a copy of the data, irrespective of its current dtype.
|
| 223 |
+
uniform : bool, optional
|
| 224 |
+
Uniformly quantize the floating point range to the integer range.
|
| 225 |
+
By default (uniform=False) floating point values are scaled and
|
| 226 |
+
rounded to the nearest integers, which minimizes back and forth
|
| 227 |
+
conversion errors.
|
| 228 |
+
.. versionchanged :: 0.15
|
| 229 |
+
``_convert`` no longer warns about possible precision or sign
|
| 230 |
+
information loss. See discussions on these warnings at:
|
| 231 |
+
https://github.com/scikit-image/scikit-image/issues/2602
|
| 232 |
+
https://github.com/scikit-image/scikit-image/issues/543#issuecomment-208202228
|
| 233 |
+
https://github.com/scikit-image/scikit-image/pull/3575
|
| 234 |
+
References
|
| 235 |
+
----------
|
| 236 |
+
.. [1] DirectX data conversion rules.
|
| 237 |
+
https://msdn.microsoft.com/en-us/library/windows/desktop/dd607323%28v=vs.85%29.aspx
|
| 238 |
+
.. [2] Data Conversions. In "OpenGL ES 2.0 Specification v2.0.25",
|
| 239 |
+
pp 7-8. Khronos Group, 2010.
|
| 240 |
+
.. [3] Proper treatment of pixels as integers. A.W. Paeth.
|
| 241 |
+
In "Graphics Gems I", pp 249-256. Morgan Kaufmann, 1990.
|
| 242 |
+
.. [4] Dirty Pixels. J. Blinn. In "Jim Blinn's corner: Dirty Pixels",
|
| 243 |
+
pp 47-57. Morgan Kaufmann, 1998.
|
| 244 |
+
"""
|
| 245 |
+
dtype_range = {
|
| 246 |
+
bool: (False, True),
|
| 247 |
+
np.bool_: (False, True),
|
| 248 |
+
np.bool8: (False, True),
|
| 249 |
+
float: (-1, 1),
|
| 250 |
+
np.float_: (-1, 1),
|
| 251 |
+
np.float16: (-1, 1),
|
| 252 |
+
np.float32: (-1, 1),
|
| 253 |
+
np.float64: (-1, 1),
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
def _dtype_itemsize(itemsize, *dtypes):
|
| 257 |
+
"""Return first of `dtypes` with itemsize greater than `itemsize`
|
| 258 |
+
Parameters
|
| 259 |
+
----------
|
| 260 |
+
itemsize: int
|
| 261 |
+
The data type object element size.
|
| 262 |
+
Other Parameters
|
| 263 |
+
----------------
|
| 264 |
+
*dtypes:
|
| 265 |
+
Any Object accepted by `np.dtype` to be converted to a data
|
| 266 |
+
type object
|
| 267 |
+
Returns
|
| 268 |
+
-------
|
| 269 |
+
dtype: data type object
|
| 270 |
+
First of `dtypes` with itemsize greater than `itemsize`.
|
| 271 |
+
"""
|
| 272 |
+
return next(dt for dt in dtypes if np.dtype(dt).itemsize >= itemsize)
|
| 273 |
+
|
| 274 |
+
def _dtype_bits(kind, bits, itemsize=1):
|
| 275 |
+
"""Return dtype of `kind` that can store a `bits` wide unsigned int
|
| 276 |
+
Parameters:
|
| 277 |
+
kind: str
|
| 278 |
+
Data type kind.
|
| 279 |
+
bits: int
|
| 280 |
+
Desired number of bits.
|
| 281 |
+
itemsize: int
|
| 282 |
+
The data type object element size.
|
| 283 |
+
Returns
|
| 284 |
+
-------
|
| 285 |
+
dtype: data type object
|
| 286 |
+
Data type of `kind` that can store a `bits` wide unsigned int
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
s = next(
|
| 290 |
+
i
|
| 291 |
+
for i in (itemsize,) + (2, 4, 8)
|
| 292 |
+
if bits < (i * 8) or (bits == (i * 8) and kind == "u")
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
return np.dtype(kind + str(s))
|
| 296 |
+
|
| 297 |
+
def _scale(a, n, m, copy=True):
|
| 298 |
+
"""Scale an array of unsigned/positive integers from `n` to `m` bits.
|
| 299 |
+
Numbers can be represented exactly only if `m` is a multiple of `n`.
|
| 300 |
+
Parameters
|
| 301 |
+
----------
|
| 302 |
+
a : ndarray
|
| 303 |
+
Input image array.
|
| 304 |
+
n : int
|
| 305 |
+
Number of bits currently used to encode the values in `a`.
|
| 306 |
+
m : int
|
| 307 |
+
Desired number of bits to encode the values in `out`.
|
| 308 |
+
copy : bool, optional
|
| 309 |
+
If True, allocates and returns new array. Otherwise, modifies
|
| 310 |
+
`a` in place.
|
| 311 |
+
Returns
|
| 312 |
+
-------
|
| 313 |
+
out : array
|
| 314 |
+
Output image array. Has the same kind as `a`.
|
| 315 |
+
"""
|
| 316 |
+
kind = a.dtype.kind
|
| 317 |
+
if n > m and a.max() < 2**m:
|
| 318 |
+
return a.astype(_dtype_bits(kind, m))
|
| 319 |
+
elif n == m:
|
| 320 |
+
return a.copy() if copy else a
|
| 321 |
+
elif n > m:
|
| 322 |
+
# downscale with precision loss
|
| 323 |
+
if copy:
|
| 324 |
+
b = np.empty(a.shape, _dtype_bits(kind, m))
|
| 325 |
+
np.floor_divide(a, 2 ** (n - m), out=b, dtype=a.dtype, casting="unsafe")
|
| 326 |
+
return b
|
| 327 |
+
else:
|
| 328 |
+
a //= 2 ** (n - m)
|
| 329 |
+
return a
|
| 330 |
+
elif m % n == 0:
|
| 331 |
+
# exact upscale to a multiple of `n` bits
|
| 332 |
+
if copy:
|
| 333 |
+
b = np.empty(a.shape, _dtype_bits(kind, m))
|
| 334 |
+
np.multiply(a, (2**m - 1) // (2**n - 1), out=b, dtype=b.dtype)
|
| 335 |
+
return b
|
| 336 |
+
else:
|
| 337 |
+
a = a.astype(_dtype_bits(kind, m, a.dtype.itemsize), copy=False)
|
| 338 |
+
a *= (2**m - 1) // (2**n - 1)
|
| 339 |
+
return a
|
| 340 |
+
else:
|
| 341 |
+
# upscale to a multiple of `n` bits,
|
| 342 |
+
# then downscale with precision loss
|
| 343 |
+
o = (m // n + 1) * n
|
| 344 |
+
if copy:
|
| 345 |
+
b = np.empty(a.shape, _dtype_bits(kind, o))
|
| 346 |
+
np.multiply(a, (2**o - 1) // (2**n - 1), out=b, dtype=b.dtype)
|
| 347 |
+
b //= 2 ** (o - m)
|
| 348 |
+
return b
|
| 349 |
+
else:
|
| 350 |
+
a = a.astype(_dtype_bits(kind, o, a.dtype.itemsize), copy=False)
|
| 351 |
+
a *= (2**o - 1) // (2**n - 1)
|
| 352 |
+
a //= 2 ** (o - m)
|
| 353 |
+
return a
|
| 354 |
+
|
| 355 |
+
image = np.asarray(image)
|
| 356 |
+
dtypeobj_in = image.dtype
|
| 357 |
+
dtypeobj_out = np.dtype("float64") if dtype is np.floating else np.dtype(dtype)
|
| 358 |
+
dtype_in = dtypeobj_in.type
|
| 359 |
+
dtype_out = dtypeobj_out.type
|
| 360 |
+
kind_in = dtypeobj_in.kind
|
| 361 |
+
kind_out = dtypeobj_out.kind
|
| 362 |
+
itemsize_in = dtypeobj_in.itemsize
|
| 363 |
+
itemsize_out = dtypeobj_out.itemsize
|
| 364 |
+
|
| 365 |
+
# Below, we do an `issubdtype` check. Its purpose is to find out
|
| 366 |
+
# whether we can get away without doing any image conversion. This happens
|
| 367 |
+
# when:
|
| 368 |
+
#
|
| 369 |
+
# - the output and input dtypes are the same or
|
| 370 |
+
# - when the output is specified as a type, and the input dtype
|
| 371 |
+
# is a subclass of that type (e.g. `np.floating` will allow
|
| 372 |
+
# `float32` and `float64` arrays through)
|
| 373 |
+
|
| 374 |
+
if np.issubdtype(dtype_in, np.obj2sctype(dtype)):
|
| 375 |
+
if force_copy:
|
| 376 |
+
image = image.copy()
|
| 377 |
+
return image
|
| 378 |
+
|
| 379 |
+
if kind_in in "ui":
|
| 380 |
+
imin_in = np.iinfo(dtype_in).min
|
| 381 |
+
imax_in = np.iinfo(dtype_in).max
|
| 382 |
+
if kind_out in "ui":
|
| 383 |
+
imin_out = np.iinfo(dtype_out).min # type: ignore
|
| 384 |
+
imax_out = np.iinfo(dtype_out).max # type: ignore
|
| 385 |
+
|
| 386 |
+
# any -> binary
|
| 387 |
+
if kind_out == "b":
|
| 388 |
+
return image > dtype_in(dtype_range[dtype_in][1] / 2)
|
| 389 |
+
|
| 390 |
+
# binary -> any
|
| 391 |
+
if kind_in == "b":
|
| 392 |
+
result = image.astype(dtype_out)
|
| 393 |
+
if kind_out != "f":
|
| 394 |
+
result *= dtype_out(dtype_range[dtype_out][1])
|
| 395 |
+
return result
|
| 396 |
+
|
| 397 |
+
# float -> any
|
| 398 |
+
if kind_in == "f":
|
| 399 |
+
if kind_out == "f":
|
| 400 |
+
# float -> float
|
| 401 |
+
return image.astype(dtype_out)
|
| 402 |
+
|
| 403 |
+
if np.min(image) < -1.0 or np.max(image) > 1.0:
|
| 404 |
+
raise ValueError("Images of type float must be between -1 and 1.")
|
| 405 |
+
# floating point -> integer
|
| 406 |
+
# use float type that can represent output integer type
|
| 407 |
+
computation_type = _dtype_itemsize(
|
| 408 |
+
itemsize_out, dtype_in, np.float32, np.float64
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if not uniform:
|
| 412 |
+
if kind_out == "u":
|
| 413 |
+
image_out = np.multiply(image, imax_out, dtype=computation_type) # type: ignore
|
| 414 |
+
else:
|
| 415 |
+
image_out = np.multiply(
|
| 416 |
+
image, (imax_out - imin_out) / 2, dtype=computation_type # type: ignore
|
| 417 |
+
)
|
| 418 |
+
image_out -= 1.0 / 2.0
|
| 419 |
+
np.rint(image_out, out=image_out)
|
| 420 |
+
np.clip(image_out, imin_out, imax_out, out=image_out) # type: ignore
|
| 421 |
+
elif kind_out == "u":
|
| 422 |
+
image_out = np.multiply(image, imax_out + 1, dtype=computation_type) # type: ignore
|
| 423 |
+
np.clip(image_out, 0, imax_out, out=image_out) # type: ignore
|
| 424 |
+
else:
|
| 425 |
+
image_out = np.multiply(
|
| 426 |
+
image, (imax_out - imin_out + 1.0) / 2.0, dtype=computation_type # type: ignore
|
| 427 |
+
)
|
| 428 |
+
np.floor(image_out, out=image_out)
|
| 429 |
+
np.clip(image_out, imin_out, imax_out, out=image_out) # type: ignore
|
| 430 |
+
return image_out.astype(dtype_out)
|
| 431 |
+
|
| 432 |
+
# signed/unsigned int -> float
|
| 433 |
+
if kind_out == "f":
|
| 434 |
+
# use float type that can exactly represent input integers
|
| 435 |
+
computation_type = _dtype_itemsize(
|
| 436 |
+
itemsize_in, dtype_out, np.float32, np.float64
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
if kind_in == "u":
|
| 440 |
+
# using np.divide or np.multiply doesn't copy the data
|
| 441 |
+
# until the computation time
|
| 442 |
+
image = np.multiply(image, 1.0 / imax_in, dtype=computation_type) # type: ignore
|
| 443 |
+
# DirectX uses this conversion also for signed ints
|
| 444 |
+
# if imin_in:
|
| 445 |
+
# np.maximum(image, -1.0, out=image)
|
| 446 |
+
else:
|
| 447 |
+
image = np.add(image, 0.5, dtype=computation_type)
|
| 448 |
+
image *= 2 / (imax_in - imin_in) # type: ignore
|
| 449 |
+
|
| 450 |
+
return np.asarray(image, dtype_out)
|
| 451 |
+
|
| 452 |
+
# unsigned int -> signed/unsigned int
|
| 453 |
+
if kind_in == "u":
|
| 454 |
+
if kind_out == "i":
|
| 455 |
+
# unsigned int -> signed int
|
| 456 |
+
image = _scale(image, 8 * itemsize_in, 8 * itemsize_out - 1)
|
| 457 |
+
return image.view(dtype_out)
|
| 458 |
+
else:
|
| 459 |
+
# unsigned int -> unsigned int
|
| 460 |
+
return _scale(image, 8 * itemsize_in, 8 * itemsize_out)
|
| 461 |
+
|
| 462 |
+
# signed int -> unsigned int
|
| 463 |
+
if kind_out == "u":
|
| 464 |
+
image = _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out)
|
| 465 |
+
result = np.empty(image.shape, dtype_out)
|
| 466 |
+
np.maximum(image, 0, out=result, dtype=image.dtype, casting="unsafe")
|
| 467 |
+
return result
|
| 468 |
+
|
| 469 |
+
# signed int -> signed int
|
| 470 |
+
if itemsize_in > itemsize_out:
|
| 471 |
+
return _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out - 1)
|
| 472 |
+
|
| 473 |
+
image = image.astype(_dtype_bits("i", itemsize_out * 8))
|
| 474 |
+
image -= imin_in # type: ignore
|
| 475 |
+
image = _scale(image, 8 * itemsize_in, 8 * itemsize_out, copy=False)
|
| 476 |
+
image += imin_out # type: ignore
|
| 477 |
+
return image.astype(dtype_out)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def ffmpeg_installed() -> bool:
|
| 481 |
+
return shutil.which("ffmpeg") is not None
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def video_is_playable(video_filepath: str) -> bool:
|
| 485 |
+
"""Determines if a video is playable in the browser.
|
| 486 |
+
|
| 487 |
+
A video is playable if it has a playable container and codec.
|
| 488 |
+
.mp4 -> h264
|
| 489 |
+
.webm -> vp9
|
| 490 |
+
.ogg -> theora
|
| 491 |
+
"""
|
| 492 |
+
try:
|
| 493 |
+
container = Path(video_filepath).suffix.lower()
|
| 494 |
+
probe = FFprobe(
|
| 495 |
+
global_options="-show_format -show_streams -select_streams v -print_format json",
|
| 496 |
+
inputs={video_filepath: None},
|
| 497 |
+
)
|
| 498 |
+
output = probe.run(stderr=subprocess.PIPE, stdout=subprocess.PIPE)
|
| 499 |
+
output = json.loads(output[0])
|
| 500 |
+
video_codec = output["streams"][0]["codec_name"]
|
| 501 |
+
return (container, video_codec) in [
|
| 502 |
+
(".mp4", "h264"),
|
| 503 |
+
(".ogg", "theora"),
|
| 504 |
+
(".webm", "vp9"),
|
| 505 |
+
]
|
| 506 |
+
# If anything goes wrong, assume the video can be played to not convert downstream
|
| 507 |
+
except (FFRuntimeError, IndexError, KeyError):
|
| 508 |
+
return True
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def convert_video_to_playable_mp4(video_path: str) -> str:
|
| 512 |
+
"""Convert the video to mp4. If something goes wrong return the original video."""
|
| 513 |
+
try:
|
| 514 |
+
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
|
| 515 |
+
output_path = Path(video_path).with_suffix(".mp4")
|
| 516 |
+
shutil.copy2(video_path, tmp_file.name)
|
| 517 |
+
# ffmpeg will automatically use h264 codec (playable in browser) when converting to mp4
|
| 518 |
+
ff = FFmpeg(
|
| 519 |
+
inputs={str(tmp_file.name): None},
|
| 520 |
+
outputs={str(output_path): None},
|
| 521 |
+
global_options="-y -loglevel quiet",
|
| 522 |
+
)
|
| 523 |
+
ff.run()
|
| 524 |
+
except FFRuntimeError as e:
|
| 525 |
+
print(f"Error converting video to browser-playable format {str(e)}")
|
| 526 |
+
output_path = video_path
|
| 527 |
+
finally:
|
| 528 |
+
# Remove temp file
|
| 529 |
+
os.remove(tmp_file.name) # type: ignore
|
| 530 |
+
return str(output_path)
|
falcon/lib/python3.10/site-packages/gradio/queueing.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import copy
|
| 5 |
+
import time
|
| 6 |
+
from asyncio import TimeoutError as AsyncTimeOutError
|
| 7 |
+
from collections import deque
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import fastapi
|
| 11 |
+
import httpx
|
| 12 |
+
|
| 13 |
+
from gradio.data_classes import Estimation, PredictBody, Progress, ProgressUnit
|
| 14 |
+
from gradio.helpers import TrackedIterable
|
| 15 |
+
from gradio.utils import AsyncRequest, run_coro_in_background, set_task_name
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Event:
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
websocket: fastapi.WebSocket,
|
| 22 |
+
session_hash: str,
|
| 23 |
+
fn_index: int,
|
| 24 |
+
):
|
| 25 |
+
self.websocket = websocket
|
| 26 |
+
self.session_hash: str = session_hash
|
| 27 |
+
self.fn_index: int = fn_index
|
| 28 |
+
self._id = f"{self.session_hash}_{self.fn_index}"
|
| 29 |
+
self.data: PredictBody | None = None
|
| 30 |
+
self.lost_connection_time: float | None = None
|
| 31 |
+
self.token: str | None = None
|
| 32 |
+
self.progress: Progress | None = None
|
| 33 |
+
self.progress_pending: bool = False
|
| 34 |
+
|
| 35 |
+
async def disconnect(self, code: int = 1000):
|
| 36 |
+
await self.websocket.close(code=code)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Queue:
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
live_updates: bool,
|
| 43 |
+
concurrency_count: int,
|
| 44 |
+
update_intervals: float,
|
| 45 |
+
max_size: int | None,
|
| 46 |
+
blocks_dependencies: list,
|
| 47 |
+
):
|
| 48 |
+
self.event_queue: deque[Event] = deque()
|
| 49 |
+
self.events_pending_reconnection = []
|
| 50 |
+
self.stopped = False
|
| 51 |
+
self.max_thread_count = concurrency_count
|
| 52 |
+
self.update_intervals = update_intervals
|
| 53 |
+
self.active_jobs: list[None | list[Event]] = [None] * concurrency_count
|
| 54 |
+
self.delete_lock = asyncio.Lock()
|
| 55 |
+
self.server_path = None
|
| 56 |
+
self.duration_history_total = 0
|
| 57 |
+
self.duration_history_count = 0
|
| 58 |
+
self.avg_process_time = 0
|
| 59 |
+
self.avg_concurrent_process_time = None
|
| 60 |
+
self.queue_duration = 1
|
| 61 |
+
self.live_updates = live_updates
|
| 62 |
+
self.sleep_when_free = 0.05
|
| 63 |
+
self.progress_update_sleep_when_free = 0.1
|
| 64 |
+
self.max_size = max_size
|
| 65 |
+
self.blocks_dependencies = blocks_dependencies
|
| 66 |
+
self.access_token = ""
|
| 67 |
+
self.queue_client = None
|
| 68 |
+
|
| 69 |
+
async def start(self, progress_tracking=False, ssl_verify=True):
|
| 70 |
+
# So that the client is attached to the running event loop
|
| 71 |
+
self.queue_client = httpx.AsyncClient(verify=ssl_verify)
|
| 72 |
+
|
| 73 |
+
run_coro_in_background(self.start_processing)
|
| 74 |
+
if progress_tracking:
|
| 75 |
+
run_coro_in_background(self.start_progress_tracking)
|
| 76 |
+
if not self.live_updates:
|
| 77 |
+
run_coro_in_background(self.notify_clients)
|
| 78 |
+
|
| 79 |
+
def close(self):
|
| 80 |
+
self.stopped = True
|
| 81 |
+
|
| 82 |
+
def resume(self):
|
| 83 |
+
self.stopped = False
|
| 84 |
+
|
| 85 |
+
def set_url(self, url: str):
|
| 86 |
+
self.server_path = url
|
| 87 |
+
|
| 88 |
+
def set_access_token(self, token: str):
|
| 89 |
+
self.access_token = token
|
| 90 |
+
|
| 91 |
+
def get_active_worker_count(self) -> int:
|
| 92 |
+
count = 0
|
| 93 |
+
for worker in self.active_jobs:
|
| 94 |
+
if worker is not None:
|
| 95 |
+
count += 1
|
| 96 |
+
return count
|
| 97 |
+
|
| 98 |
+
def get_events_in_batch(self) -> tuple[list[Event] | None, bool]:
|
| 99 |
+
if not (self.event_queue):
|
| 100 |
+
return None, False
|
| 101 |
+
|
| 102 |
+
first_event = self.event_queue.popleft()
|
| 103 |
+
events = [first_event]
|
| 104 |
+
|
| 105 |
+
event_fn_index = first_event.fn_index
|
| 106 |
+
batch = self.blocks_dependencies[event_fn_index]["batch"]
|
| 107 |
+
|
| 108 |
+
if batch:
|
| 109 |
+
batch_size = self.blocks_dependencies[event_fn_index]["max_batch_size"]
|
| 110 |
+
rest_of_batch = [
|
| 111 |
+
event for event in self.event_queue if event.fn_index == event_fn_index
|
| 112 |
+
][: batch_size - 1]
|
| 113 |
+
events.extend(rest_of_batch)
|
| 114 |
+
[self.event_queue.remove(event) for event in rest_of_batch]
|
| 115 |
+
|
| 116 |
+
return events, batch
|
| 117 |
+
|
| 118 |
+
async def start_processing(self) -> None:
|
| 119 |
+
while not self.stopped:
|
| 120 |
+
if not self.event_queue:
|
| 121 |
+
await asyncio.sleep(self.sleep_when_free)
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
if None not in self.active_jobs:
|
| 125 |
+
await asyncio.sleep(self.sleep_when_free)
|
| 126 |
+
continue
|
| 127 |
+
# Using mutex to avoid editing a list in use
|
| 128 |
+
async with self.delete_lock:
|
| 129 |
+
events, batch = self.get_events_in_batch()
|
| 130 |
+
|
| 131 |
+
if events:
|
| 132 |
+
self.active_jobs[self.active_jobs.index(None)] = events
|
| 133 |
+
task = run_coro_in_background(self.process_events, events, batch)
|
| 134 |
+
run_coro_in_background(self.broadcast_live_estimations)
|
| 135 |
+
set_task_name(task, events[0].session_hash, events[0].fn_index, batch)
|
| 136 |
+
|
| 137 |
+
async def start_progress_tracking(self) -> None:
|
| 138 |
+
while not self.stopped:
|
| 139 |
+
if not any(self.active_jobs):
|
| 140 |
+
await asyncio.sleep(self.progress_update_sleep_when_free)
|
| 141 |
+
continue
|
| 142 |
+
|
| 143 |
+
for job in self.active_jobs:
|
| 144 |
+
if job is None:
|
| 145 |
+
continue
|
| 146 |
+
for event in job:
|
| 147 |
+
if event.progress_pending and event.progress:
|
| 148 |
+
event.progress_pending = False
|
| 149 |
+
client_awake = await self.send_message(
|
| 150 |
+
event, event.progress.dict()
|
| 151 |
+
)
|
| 152 |
+
if not client_awake:
|
| 153 |
+
await self.clean_event(event)
|
| 154 |
+
|
| 155 |
+
await asyncio.sleep(self.progress_update_sleep_when_free)
|
| 156 |
+
|
| 157 |
+
def set_progress(
|
| 158 |
+
self,
|
| 159 |
+
event_id: str,
|
| 160 |
+
iterables: list[TrackedIterable] | None,
|
| 161 |
+
):
|
| 162 |
+
if iterables is None:
|
| 163 |
+
return
|
| 164 |
+
for job in self.active_jobs:
|
| 165 |
+
if job is None:
|
| 166 |
+
continue
|
| 167 |
+
for evt in job:
|
| 168 |
+
if evt._id == event_id:
|
| 169 |
+
progress_data: list[ProgressUnit] = []
|
| 170 |
+
for iterable in iterables:
|
| 171 |
+
progress_unit = ProgressUnit(
|
| 172 |
+
index=iterable.index,
|
| 173 |
+
length=iterable.length,
|
| 174 |
+
unit=iterable.unit,
|
| 175 |
+
progress=iterable.progress,
|
| 176 |
+
desc=iterable.desc,
|
| 177 |
+
)
|
| 178 |
+
progress_data.append(progress_unit)
|
| 179 |
+
evt.progress = Progress(progress_data=progress_data)
|
| 180 |
+
evt.progress_pending = True
|
| 181 |
+
|
| 182 |
+
def push(self, event: Event) -> int | None:
|
| 183 |
+
"""
|
| 184 |
+
Add event to queue, or return None if Queue is full
|
| 185 |
+
Parameters:
|
| 186 |
+
event: Event to add to Queue
|
| 187 |
+
Returns:
|
| 188 |
+
rank of submitted Event
|
| 189 |
+
"""
|
| 190 |
+
queue_len = len(self.event_queue)
|
| 191 |
+
if self.max_size is not None and queue_len >= self.max_size:
|
| 192 |
+
return None
|
| 193 |
+
self.event_queue.append(event)
|
| 194 |
+
return queue_len
|
| 195 |
+
|
| 196 |
+
async def clean_event(self, event: Event) -> None:
|
| 197 |
+
if event in self.event_queue:
|
| 198 |
+
async with self.delete_lock:
|
| 199 |
+
self.event_queue.remove(event)
|
| 200 |
+
|
| 201 |
+
async def broadcast_live_estimations(self) -> None:
|
| 202 |
+
"""
|
| 203 |
+
Runs 2 functions sequentially instead of concurrently. Otherwise dced clients are tried to get deleted twice.
|
| 204 |
+
"""
|
| 205 |
+
if self.live_updates:
|
| 206 |
+
await self.broadcast_estimations()
|
| 207 |
+
|
| 208 |
+
async def gather_event_data(self, event: Event, receive_timeout=60) -> bool:
|
| 209 |
+
"""
|
| 210 |
+
Gather data for the event
|
| 211 |
+
Parameters:
|
| 212 |
+
event: the Event to gather data for
|
| 213 |
+
receive_timeout: how long to wait for data to be received from frontend
|
| 214 |
+
"""
|
| 215 |
+
if not event.data:
|
| 216 |
+
client_awake = await self.send_message(event, {"msg": "send_data"})
|
| 217 |
+
if not client_awake:
|
| 218 |
+
return False
|
| 219 |
+
data, client_awake = await self.get_message(event, timeout=receive_timeout)
|
| 220 |
+
if not client_awake:
|
| 221 |
+
# In the event, we timeout due to large data size
|
| 222 |
+
# Let the client know, otherwise will hang
|
| 223 |
+
await self.send_message(
|
| 224 |
+
event,
|
| 225 |
+
{
|
| 226 |
+
"msg": "process_completed",
|
| 227 |
+
"output": {"error": "Time out uploading data to server"},
|
| 228 |
+
"success": False,
|
| 229 |
+
},
|
| 230 |
+
)
|
| 231 |
+
return False
|
| 232 |
+
event.data = data
|
| 233 |
+
return True
|
| 234 |
+
|
| 235 |
+
async def notify_clients(self) -> None:
|
| 236 |
+
"""
|
| 237 |
+
Notify clients about events statuses in the queue periodically.
|
| 238 |
+
"""
|
| 239 |
+
while not self.stopped:
|
| 240 |
+
await asyncio.sleep(self.update_intervals)
|
| 241 |
+
if self.event_queue:
|
| 242 |
+
await self.broadcast_estimations()
|
| 243 |
+
|
| 244 |
+
async def broadcast_estimations(self) -> None:
|
| 245 |
+
estimation = self.get_estimation()
|
| 246 |
+
# Send all messages concurrently
|
| 247 |
+
await asyncio.gather(
|
| 248 |
+
*[
|
| 249 |
+
self.send_estimation(event, estimation, rank)
|
| 250 |
+
for rank, event in enumerate(self.event_queue)
|
| 251 |
+
]
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
async def send_estimation(
|
| 255 |
+
self, event: Event, estimation: Estimation, rank: int
|
| 256 |
+
) -> Estimation:
|
| 257 |
+
"""
|
| 258 |
+
Send estimation about ETA to the client.
|
| 259 |
+
|
| 260 |
+
Parameters:
|
| 261 |
+
event:
|
| 262 |
+
estimation:
|
| 263 |
+
rank:
|
| 264 |
+
"""
|
| 265 |
+
estimation.rank = rank
|
| 266 |
+
|
| 267 |
+
if self.avg_concurrent_process_time is not None:
|
| 268 |
+
estimation.rank_eta = (
|
| 269 |
+
estimation.rank * self.avg_concurrent_process_time
|
| 270 |
+
+ self.avg_process_time
|
| 271 |
+
)
|
| 272 |
+
if None not in self.active_jobs:
|
| 273 |
+
# Add estimated amount of time for a thread to get empty
|
| 274 |
+
estimation.rank_eta += self.avg_concurrent_process_time
|
| 275 |
+
client_awake = await self.send_message(event, estimation.dict())
|
| 276 |
+
if not client_awake:
|
| 277 |
+
await self.clean_event(event)
|
| 278 |
+
return estimation
|
| 279 |
+
|
| 280 |
+
def update_estimation(self, duration: float) -> None:
|
| 281 |
+
"""
|
| 282 |
+
Update estimation by last x element's average duration.
|
| 283 |
+
|
| 284 |
+
Parameters:
|
| 285 |
+
duration:
|
| 286 |
+
"""
|
| 287 |
+
self.duration_history_total += duration
|
| 288 |
+
self.duration_history_count += 1
|
| 289 |
+
self.avg_process_time = (
|
| 290 |
+
self.duration_history_total / self.duration_history_count
|
| 291 |
+
)
|
| 292 |
+
self.avg_concurrent_process_time = self.avg_process_time / min(
|
| 293 |
+
self.max_thread_count, self.duration_history_count
|
| 294 |
+
)
|
| 295 |
+
self.queue_duration = self.avg_concurrent_process_time * len(self.event_queue)
|
| 296 |
+
|
| 297 |
+
def get_estimation(self) -> Estimation:
|
| 298 |
+
return Estimation(
|
| 299 |
+
queue_size=len(self.event_queue),
|
| 300 |
+
avg_event_process_time=self.avg_process_time,
|
| 301 |
+
avg_event_concurrent_process_time=self.avg_concurrent_process_time,
|
| 302 |
+
queue_eta=self.queue_duration,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
def get_request_params(self, websocket: fastapi.WebSocket) -> dict[str, Any]:
|
| 306 |
+
return {
|
| 307 |
+
"url": str(websocket.url),
|
| 308 |
+
"headers": dict(websocket.headers),
|
| 309 |
+
"query_params": dict(websocket.query_params),
|
| 310 |
+
"path_params": dict(websocket.path_params),
|
| 311 |
+
"client": {"host": websocket.client.host, "port": websocket.client.port}, # type: ignore
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
async def call_prediction(self, events: list[Event], batch: bool):
|
| 315 |
+
data = events[0].data
|
| 316 |
+
assert data is not None, "No event data"
|
| 317 |
+
token = events[0].token
|
| 318 |
+
data.event_id = events[0]._id if not batch else None
|
| 319 |
+
try:
|
| 320 |
+
data.request = self.get_request_params(events[0].websocket)
|
| 321 |
+
except ValueError:
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
if batch:
|
| 325 |
+
data.data = list(zip(*[event.data.data for event in events if event.data]))
|
| 326 |
+
data.request = [
|
| 327 |
+
self.get_request_params(event.websocket)
|
| 328 |
+
for event in events
|
| 329 |
+
if event.data
|
| 330 |
+
]
|
| 331 |
+
data.batched = True
|
| 332 |
+
response = await AsyncRequest(
|
| 333 |
+
method=AsyncRequest.Method.POST,
|
| 334 |
+
url=f"{self.server_path}api/predict",
|
| 335 |
+
json=dict(data),
|
| 336 |
+
headers={"Authorization": f"Bearer {self.access_token}"},
|
| 337 |
+
cookies={"access-token": token} if token is not None else None,
|
| 338 |
+
client=self.queue_client,
|
| 339 |
+
)
|
| 340 |
+
return response
|
| 341 |
+
|
| 342 |
+
async def process_events(self, events: list[Event], batch: bool) -> None:
|
| 343 |
+
awake_events: list[Event] = []
|
| 344 |
+
try:
|
| 345 |
+
for event in events:
|
| 346 |
+
client_awake = await self.gather_event_data(event)
|
| 347 |
+
if client_awake:
|
| 348 |
+
client_awake = await self.send_message(
|
| 349 |
+
event, {"msg": "process_starts"}
|
| 350 |
+
)
|
| 351 |
+
if client_awake:
|
| 352 |
+
awake_events.append(event)
|
| 353 |
+
if not awake_events:
|
| 354 |
+
return
|
| 355 |
+
begin_time = time.time()
|
| 356 |
+
response = await self.call_prediction(awake_events, batch)
|
| 357 |
+
if response.has_exception:
|
| 358 |
+
for event in awake_events:
|
| 359 |
+
await self.send_message(
|
| 360 |
+
event,
|
| 361 |
+
{
|
| 362 |
+
"msg": "process_completed",
|
| 363 |
+
"output": {"error": str(response.exception)},
|
| 364 |
+
"success": False,
|
| 365 |
+
},
|
| 366 |
+
)
|
| 367 |
+
elif response.json.get("is_generating", False):
|
| 368 |
+
old_response = response
|
| 369 |
+
while response.json.get("is_generating", False):
|
| 370 |
+
old_response = response
|
| 371 |
+
open_ws = []
|
| 372 |
+
for event in awake_events:
|
| 373 |
+
open = await self.send_message(
|
| 374 |
+
event,
|
| 375 |
+
{
|
| 376 |
+
"msg": "process_generating",
|
| 377 |
+
"output": old_response.json,
|
| 378 |
+
"success": old_response.status == 200,
|
| 379 |
+
},
|
| 380 |
+
)
|
| 381 |
+
open_ws.append(open)
|
| 382 |
+
awake_events = [
|
| 383 |
+
e for e, is_open in zip(awake_events, open_ws) if is_open
|
| 384 |
+
]
|
| 385 |
+
if not awake_events:
|
| 386 |
+
return
|
| 387 |
+
response = await self.call_prediction(awake_events, batch)
|
| 388 |
+
for event in awake_events:
|
| 389 |
+
if response.status != 200:
|
| 390 |
+
relevant_response = response
|
| 391 |
+
else:
|
| 392 |
+
relevant_response = old_response
|
| 393 |
+
|
| 394 |
+
await self.send_message(
|
| 395 |
+
event,
|
| 396 |
+
{
|
| 397 |
+
"msg": "process_completed",
|
| 398 |
+
"output": relevant_response.json,
|
| 399 |
+
"success": relevant_response.status == 200,
|
| 400 |
+
},
|
| 401 |
+
)
|
| 402 |
+
else:
|
| 403 |
+
output = copy.deepcopy(response.json)
|
| 404 |
+
for e, event in enumerate(awake_events):
|
| 405 |
+
if batch and "data" in output:
|
| 406 |
+
output["data"] = list(zip(*response.json.get("data")))[e]
|
| 407 |
+
await self.send_message(
|
| 408 |
+
event,
|
| 409 |
+
{
|
| 410 |
+
"msg": "process_completed",
|
| 411 |
+
"output": output,
|
| 412 |
+
"success": response.status == 200,
|
| 413 |
+
},
|
| 414 |
+
)
|
| 415 |
+
end_time = time.time()
|
| 416 |
+
if response.status == 200:
|
| 417 |
+
self.update_estimation(end_time - begin_time)
|
| 418 |
+
finally:
|
| 419 |
+
for event in awake_events:
|
| 420 |
+
try:
|
| 421 |
+
await event.disconnect()
|
| 422 |
+
except Exception:
|
| 423 |
+
pass
|
| 424 |
+
self.active_jobs[self.active_jobs.index(events)] = None
|
| 425 |
+
for event in events:
|
| 426 |
+
await self.clean_event(event)
|
| 427 |
+
# Always reset the state of the iterator
|
| 428 |
+
# If the job finished successfully, this has no effect
|
| 429 |
+
# If the job is cancelled, this will enable future runs
|
| 430 |
+
# to start "from scratch"
|
| 431 |
+
await self.reset_iterators(event.session_hash, event.fn_index)
|
| 432 |
+
|
| 433 |
+
async def send_message(self, event, data: dict, timeout: float | int = 1) -> bool:
|
| 434 |
+
try:
|
| 435 |
+
await asyncio.wait_for(
|
| 436 |
+
event.websocket.send_json(data=data), timeout=timeout
|
| 437 |
+
)
|
| 438 |
+
return True
|
| 439 |
+
except Exception:
|
| 440 |
+
await self.clean_event(event)
|
| 441 |
+
return False
|
| 442 |
+
|
| 443 |
+
async def get_message(self, event, timeout=5) -> tuple[PredictBody | None, bool]:
|
| 444 |
+
try:
|
| 445 |
+
data = await asyncio.wait_for(
|
| 446 |
+
event.websocket.receive_json(), timeout=timeout
|
| 447 |
+
)
|
| 448 |
+
return PredictBody(**data), True
|
| 449 |
+
except AsyncTimeOutError:
|
| 450 |
+
await self.clean_event(event)
|
| 451 |
+
return None, False
|
| 452 |
+
|
| 453 |
+
async def reset_iterators(self, session_hash: str, fn_index: int):
|
| 454 |
+
await AsyncRequest(
|
| 455 |
+
method=AsyncRequest.Method.POST,
|
| 456 |
+
url=f"{self.server_path}reset",
|
| 457 |
+
json={
|
| 458 |
+
"session_hash": session_hash,
|
| 459 |
+
"fn_index": fn_index,
|
| 460 |
+
},
|
| 461 |
+
client=self.queue_client,
|
| 462 |
+
)
|
falcon/lib/python3.10/site-packages/gradio/ranged_response.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Taken from https://gist.github.com/kevinastone/a6a62db57577b3f24e8a6865ed311463
|
| 2 |
+
# Context: https://github.com/encode/starlette/pull/1090
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import stat
|
| 8 |
+
from typing import NamedTuple
|
| 9 |
+
from urllib.parse import quote
|
| 10 |
+
|
| 11 |
+
import aiofiles
|
| 12 |
+
from aiofiles.os import stat as aio_stat
|
| 13 |
+
from starlette.datastructures import Headers
|
| 14 |
+
from starlette.exceptions import HTTPException
|
| 15 |
+
from starlette.responses import Response, guess_type
|
| 16 |
+
from starlette.staticfiles import StaticFiles
|
| 17 |
+
from starlette.types import Receive, Scope, Send
|
| 18 |
+
|
| 19 |
+
RANGE_REGEX = re.compile(r"^bytes=(?P<start>\d+)-(?P<end>\d*)$")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ClosedRange(NamedTuple):
|
| 23 |
+
start: int
|
| 24 |
+
end: int
|
| 25 |
+
|
| 26 |
+
def __len__(self) -> int:
|
| 27 |
+
return self.end - self.start + 1
|
| 28 |
+
|
| 29 |
+
def __bool__(self) -> bool:
|
| 30 |
+
return len(self) > 0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class OpenRange(NamedTuple):
|
| 34 |
+
start: int
|
| 35 |
+
end: int | None = None
|
| 36 |
+
|
| 37 |
+
def clamp(self, start: int, end: int) -> ClosedRange:
|
| 38 |
+
begin = max(self.start, start)
|
| 39 |
+
end = min(x for x in (self.end, end) if x)
|
| 40 |
+
|
| 41 |
+
begin = min(begin, end)
|
| 42 |
+
end = max(begin, end)
|
| 43 |
+
|
| 44 |
+
return ClosedRange(begin, end)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class RangedFileResponse(Response):
|
| 48 |
+
chunk_size = 4096
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
path: str | os.PathLike,
|
| 53 |
+
range: OpenRange,
|
| 54 |
+
headers: dict[str, str] | None = None,
|
| 55 |
+
media_type: str | None = None,
|
| 56 |
+
filename: str | None = None,
|
| 57 |
+
stat_result: os.stat_result | None = None,
|
| 58 |
+
method: str | None = None,
|
| 59 |
+
) -> None:
|
| 60 |
+
assert aiofiles is not None, "'aiofiles' must be installed to use FileResponse"
|
| 61 |
+
self.path = path
|
| 62 |
+
self.range = range
|
| 63 |
+
self.filename = filename
|
| 64 |
+
self.background = None
|
| 65 |
+
self.send_header_only = method is not None and method.upper() == "HEAD"
|
| 66 |
+
if media_type is None:
|
| 67 |
+
media_type = guess_type(filename or path)[0] or "text/plain"
|
| 68 |
+
self.media_type = media_type
|
| 69 |
+
self.init_headers(headers or {})
|
| 70 |
+
if self.filename is not None:
|
| 71 |
+
content_disposition_filename = quote(self.filename)
|
| 72 |
+
if content_disposition_filename != self.filename:
|
| 73 |
+
content_disposition = (
|
| 74 |
+
f"attachment; filename*=utf-8''{content_disposition_filename}"
|
| 75 |
+
)
|
| 76 |
+
else:
|
| 77 |
+
content_disposition = f'attachment; filename="{self.filename}"'
|
| 78 |
+
self.headers.setdefault("content-disposition", content_disposition)
|
| 79 |
+
self.stat_result = stat_result
|
| 80 |
+
|
| 81 |
+
def set_range_headers(self, range: ClosedRange) -> None:
|
| 82 |
+
assert self.stat_result
|
| 83 |
+
total_length = self.stat_result.st_size
|
| 84 |
+
content_length = len(range)
|
| 85 |
+
self.headers[
|
| 86 |
+
"content-range"
|
| 87 |
+
] = f"bytes {range.start}-{range.end}/{total_length}"
|
| 88 |
+
self.headers["content-length"] = str(content_length)
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
| 92 |
+
if self.stat_result is None:
|
| 93 |
+
try:
|
| 94 |
+
stat_result = await aio_stat(self.path)
|
| 95 |
+
self.stat_result = stat_result
|
| 96 |
+
except FileNotFoundError as fnfe:
|
| 97 |
+
raise RuntimeError(
|
| 98 |
+
f"File at path {self.path} does not exist."
|
| 99 |
+
) from fnfe
|
| 100 |
+
else:
|
| 101 |
+
mode = stat_result.st_mode
|
| 102 |
+
if not stat.S_ISREG(mode):
|
| 103 |
+
raise RuntimeError(f"File at path {self.path} is not a file.")
|
| 104 |
+
|
| 105 |
+
byte_range = self.range.clamp(0, self.stat_result.st_size)
|
| 106 |
+
self.set_range_headers(byte_range)
|
| 107 |
+
|
| 108 |
+
async with aiofiles.open(self.path, mode="rb") as file:
|
| 109 |
+
await file.seek(byte_range.start)
|
| 110 |
+
await send(
|
| 111 |
+
{
|
| 112 |
+
"type": "http.response.start",
|
| 113 |
+
"status": 206,
|
| 114 |
+
"headers": self.raw_headers,
|
| 115 |
+
}
|
| 116 |
+
)
|
| 117 |
+
if self.send_header_only:
|
| 118 |
+
await send(
|
| 119 |
+
{"type": "http.response.body", "body": b"", "more_body": False}
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
remaining_bytes = len(byte_range)
|
| 123 |
+
|
| 124 |
+
if not byte_range:
|
| 125 |
+
await send(
|
| 126 |
+
{"type": "http.response.body", "body": b"", "more_body": False}
|
| 127 |
+
)
|
| 128 |
+
return
|
| 129 |
+
|
| 130 |
+
while remaining_bytes > 0:
|
| 131 |
+
chunk_size = min(self.chunk_size, remaining_bytes)
|
| 132 |
+
chunk = await file.read(chunk_size)
|
| 133 |
+
remaining_bytes -= len(chunk)
|
| 134 |
+
await send(
|
| 135 |
+
{
|
| 136 |
+
"type": "http.response.body",
|
| 137 |
+
"body": chunk,
|
| 138 |
+
"more_body": remaining_bytes > 0,
|
| 139 |
+
}
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class RangedStaticFiles(StaticFiles):
|
| 144 |
+
def file_response(
|
| 145 |
+
self,
|
| 146 |
+
full_path: str | os.PathLike,
|
| 147 |
+
stat_result: os.stat_result,
|
| 148 |
+
scope: Scope,
|
| 149 |
+
status_code: int = 200,
|
| 150 |
+
) -> Response:
|
| 151 |
+
request_headers = Headers(scope=scope)
|
| 152 |
+
|
| 153 |
+
if request_headers.get("range"):
|
| 154 |
+
response = self.ranged_file_response(
|
| 155 |
+
full_path, stat_result=stat_result, scope=scope
|
| 156 |
+
)
|
| 157 |
+
else:
|
| 158 |
+
response = super().file_response(
|
| 159 |
+
full_path, stat_result=stat_result, scope=scope, status_code=status_code
|
| 160 |
+
)
|
| 161 |
+
response.headers["accept-ranges"] = "bytes"
|
| 162 |
+
return response
|
| 163 |
+
|
| 164 |
+
def ranged_file_response(
|
| 165 |
+
self,
|
| 166 |
+
full_path: str | os.PathLike,
|
| 167 |
+
stat_result: os.stat_result,
|
| 168 |
+
scope: Scope,
|
| 169 |
+
) -> Response:
|
| 170 |
+
method = scope["method"]
|
| 171 |
+
request_headers = Headers(scope=scope)
|
| 172 |
+
|
| 173 |
+
range_header = request_headers["range"]
|
| 174 |
+
|
| 175 |
+
match = RANGE_REGEX.search(range_header)
|
| 176 |
+
if not match:
|
| 177 |
+
raise HTTPException(400)
|
| 178 |
+
|
| 179 |
+
start, end = match.group("start"), match.group("end")
|
| 180 |
+
|
| 181 |
+
range = OpenRange(int(start), int(end) if end else None)
|
| 182 |
+
|
| 183 |
+
return RangedFileResponse(
|
| 184 |
+
full_path, range, stat_result=stat_result, method=method
|
| 185 |
+
)
|
falcon/lib/python3.10/site-packages/gradio/reload.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
|
| 3 |
+
Contains the functions that run when `gradio` is called from the command line. Specifically, allows
|
| 4 |
+
|
| 5 |
+
$ gradio app.py, to run app.py in reload mode where any changes in the app.py file or Gradio library reloads the demo.
|
| 6 |
+
$ gradio app.py my_demo.app, to use variable names other than "demo"
|
| 7 |
+
"""
|
| 8 |
+
import inspect
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from uvicorn import Config
|
| 14 |
+
from uvicorn.supervisors import ChangeReload
|
| 15 |
+
|
| 16 |
+
import gradio
|
| 17 |
+
from gradio import networking, utils
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _setup_config():
|
| 21 |
+
args = sys.argv[1:]
|
| 22 |
+
if len(args) == 0:
|
| 23 |
+
raise ValueError("No file specified.")
|
| 24 |
+
if len(args) == 1 or args[1].startswith("--"):
|
| 25 |
+
demo_name = "demo.app"
|
| 26 |
+
else:
|
| 27 |
+
demo_name = args[1]
|
| 28 |
+
if "." not in demo_name:
|
| 29 |
+
print(
|
| 30 |
+
"\nWARNING: As of Gradio 3.31, the parameter after the file path must be the name of the FastAPI app, not the Gradio demo. In most cases, this just means you should add '.app' after the name of your demo, e.g. 'demo' -> 'demo.app'."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
original_path = args[0]
|
| 34 |
+
abs_original_path = utils.abspath(original_path)
|
| 35 |
+
path = os.path.normpath(original_path)
|
| 36 |
+
path = path.replace("/", ".")
|
| 37 |
+
path = path.replace("\\", ".")
|
| 38 |
+
filename = os.path.splitext(path)[0]
|
| 39 |
+
|
| 40 |
+
gradio_folder = Path(inspect.getfile(gradio)).parent
|
| 41 |
+
|
| 42 |
+
port = networking.get_first_available_port(
|
| 43 |
+
networking.INITIAL_PORT_VALUE,
|
| 44 |
+
networking.INITIAL_PORT_VALUE + networking.TRY_NUM_PORTS,
|
| 45 |
+
)
|
| 46 |
+
print(
|
| 47 |
+
f"\nLaunching in *reload mode* on: http://{networking.LOCALHOST_NAME}:{port} (Press CTRL+C to quit)\n"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
gradio_app = f"{filename}:{demo_name}"
|
| 51 |
+
message = "Watching:"
|
| 52 |
+
message_change_count = 0
|
| 53 |
+
|
| 54 |
+
watching_dirs = []
|
| 55 |
+
if str(gradio_folder).strip():
|
| 56 |
+
watching_dirs.append(gradio_folder)
|
| 57 |
+
message += f" '{gradio_folder}'"
|
| 58 |
+
message_change_count += 1
|
| 59 |
+
|
| 60 |
+
abs_parent = abs_original_path.parent
|
| 61 |
+
if str(abs_parent).strip():
|
| 62 |
+
watching_dirs.append(abs_parent)
|
| 63 |
+
if message_change_count == 1:
|
| 64 |
+
message += ","
|
| 65 |
+
message += f" '{abs_parent}'"
|
| 66 |
+
|
| 67 |
+
print(message + "\n")
|
| 68 |
+
|
| 69 |
+
# guaranty access to the module of an app
|
| 70 |
+
sys.path.insert(0, os.getcwd())
|
| 71 |
+
|
| 72 |
+
# uvicorn.run blocks the execution (looping) which makes it hard to test
|
| 73 |
+
return Config(
|
| 74 |
+
gradio_app,
|
| 75 |
+
reload=True,
|
| 76 |
+
port=port,
|
| 77 |
+
log_level="warning",
|
| 78 |
+
reload_dirs=watching_dirs,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main():
|
| 83 |
+
# default execution pattern to start the server and watch changes
|
| 84 |
+
config = _setup_config()
|
| 85 |
+
server = networking.Server(config)
|
| 86 |
+
sock = config.bind_socket()
|
| 87 |
+
ChangeReload(config, target=server.run, sockets=[sock]).run()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
main()
|
falcon/lib/python3.10/site-packages/gradio/routes.py
ADDED
|
@@ -0,0 +1,824 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implements a FastAPI server to run the gradio interface. Note that some types in this
|
| 2 |
+
module use the Optional/Union notation so that they work correctly with pydantic."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import inspect
|
| 8 |
+
import json
|
| 9 |
+
import mimetypes
|
| 10 |
+
import os
|
| 11 |
+
import posixpath
|
| 12 |
+
import secrets
|
| 13 |
+
import tempfile
|
| 14 |
+
import traceback
|
| 15 |
+
from asyncio import TimeoutError as AsyncTimeOutError
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from copy import deepcopy
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Dict, List, Optional, Type
|
| 20 |
+
from urllib.parse import urlparse
|
| 21 |
+
|
| 22 |
+
import fastapi
|
| 23 |
+
import httpx
|
| 24 |
+
import markupsafe
|
| 25 |
+
import orjson
|
| 26 |
+
import pkg_resources
|
| 27 |
+
from fastapi import Depends, FastAPI, File, HTTPException, UploadFile, WebSocket, status
|
| 28 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 29 |
+
from fastapi.responses import (
|
| 30 |
+
FileResponse,
|
| 31 |
+
HTMLResponse,
|
| 32 |
+
JSONResponse,
|
| 33 |
+
PlainTextResponse,
|
| 34 |
+
)
|
| 35 |
+
from fastapi.security import OAuth2PasswordRequestForm
|
| 36 |
+
from fastapi.templating import Jinja2Templates
|
| 37 |
+
from gradio_client.documentation import document, set_documentation_group
|
| 38 |
+
from jinja2.exceptions import TemplateNotFound
|
| 39 |
+
from starlette.background import BackgroundTask
|
| 40 |
+
from starlette.responses import RedirectResponse, StreamingResponse
|
| 41 |
+
from starlette.websockets import WebSocketState
|
| 42 |
+
|
| 43 |
+
import gradio
|
| 44 |
+
import gradio.ranged_response as ranged_response
|
| 45 |
+
from gradio import utils
|
| 46 |
+
from gradio.context import Context
|
| 47 |
+
from gradio.data_classes import PredictBody, ResetBody
|
| 48 |
+
from gradio.exceptions import Error
|
| 49 |
+
from gradio.helpers import EventData
|
| 50 |
+
from gradio.queueing import Estimation, Event
|
| 51 |
+
from gradio.utils import cancel_tasks, run_coro_in_background, set_task_name
|
| 52 |
+
|
| 53 |
+
mimetypes.init()
|
| 54 |
+
|
| 55 |
+
STATIC_TEMPLATE_LIB = pkg_resources.resource_filename("gradio", "templates/")
|
| 56 |
+
STATIC_PATH_LIB = pkg_resources.resource_filename("gradio", "templates/frontend/static")
|
| 57 |
+
BUILD_PATH_LIB = pkg_resources.resource_filename("gradio", "templates/frontend/assets")
|
| 58 |
+
VERSION_FILE = pkg_resources.resource_filename("gradio", "version.txt")
|
| 59 |
+
with open(VERSION_FILE) as version_file:
|
| 60 |
+
VERSION = version_file.read()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ORJSONResponse(JSONResponse):
|
| 64 |
+
media_type = "application/json"
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def _render(content: Any) -> bytes:
|
| 68 |
+
return orjson.dumps(
|
| 69 |
+
content,
|
| 70 |
+
option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_PASSTHROUGH_DATETIME,
|
| 71 |
+
default=str,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def render(self, content: Any) -> bytes:
|
| 75 |
+
return ORJSONResponse._render(content)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def _render_str(content: Any) -> str:
|
| 79 |
+
return ORJSONResponse._render(content).decode("utf-8")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def toorjson(value):
|
| 83 |
+
return markupsafe.Markup(
|
| 84 |
+
ORJSONResponse._render_str(value)
|
| 85 |
+
.replace("<", "\\u003c")
|
| 86 |
+
.replace(">", "\\u003e")
|
| 87 |
+
.replace("&", "\\u0026")
|
| 88 |
+
.replace("'", "\\u0027")
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
templates = Jinja2Templates(directory=STATIC_TEMPLATE_LIB)
|
| 93 |
+
templates.env.filters["toorjson"] = toorjson
|
| 94 |
+
|
| 95 |
+
client = httpx.AsyncClient()
|
| 96 |
+
|
| 97 |
+
###########
|
| 98 |
+
# Auth
|
| 99 |
+
###########
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class App(FastAPI):
|
| 103 |
+
"""
|
| 104 |
+
FastAPI App Wrapper
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __init__(self, **kwargs):
|
| 108 |
+
self.tokens = {}
|
| 109 |
+
self.auth = None
|
| 110 |
+
self.blocks: gradio.Blocks | None = None
|
| 111 |
+
self.state_holder = {}
|
| 112 |
+
self.iterators = defaultdict(dict)
|
| 113 |
+
self.lock = asyncio.Lock()
|
| 114 |
+
self.queue_token = secrets.token_urlsafe(32)
|
| 115 |
+
self.startup_events_triggered = False
|
| 116 |
+
self.uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
| 117 |
+
Path(tempfile.gettempdir()) / "gradio"
|
| 118 |
+
)
|
| 119 |
+
# Allow user to manually set `docs_url` and `redoc_url`
|
| 120 |
+
# when instantiating an App; when they're not set, disable docs and redoc.
|
| 121 |
+
kwargs.setdefault("docs_url", None)
|
| 122 |
+
kwargs.setdefault("redoc_url", None)
|
| 123 |
+
super().__init__(**kwargs)
|
| 124 |
+
|
| 125 |
+
def configure_app(self, blocks: gradio.Blocks) -> None:
|
| 126 |
+
auth = blocks.auth
|
| 127 |
+
if auth is not None:
|
| 128 |
+
if not callable(auth):
|
| 129 |
+
self.auth = {account[0]: account[1] for account in auth}
|
| 130 |
+
else:
|
| 131 |
+
self.auth = auth
|
| 132 |
+
else:
|
| 133 |
+
self.auth = None
|
| 134 |
+
|
| 135 |
+
self.blocks = blocks
|
| 136 |
+
if hasattr(self.blocks, "_queue"):
|
| 137 |
+
self.blocks._queue.set_access_token(self.queue_token)
|
| 138 |
+
self.cwd = os.getcwd()
|
| 139 |
+
self.favicon_path = blocks.favicon_path
|
| 140 |
+
self.tokens = {}
|
| 141 |
+
self.root_path = blocks.root_path
|
| 142 |
+
|
| 143 |
+
def get_blocks(self) -> gradio.Blocks:
|
| 144 |
+
if self.blocks is None:
|
| 145 |
+
raise ValueError("No Blocks has been configured for this app.")
|
| 146 |
+
return self.blocks
|
| 147 |
+
|
| 148 |
+
def build_proxy_request(self, url_path):
|
| 149 |
+
url = httpx.URL(url_path)
|
| 150 |
+
assert self.blocks
|
| 151 |
+
# Don't proxy a URL unless it's a URL specifically loaded by the user using
|
| 152 |
+
# gr.load() to prevent SSRF or harvesting of HF tokens by malicious Spaces.
|
| 153 |
+
is_safe_url = any(
|
| 154 |
+
url.host == httpx.URL(root).host for root in self.blocks.root_urls
|
| 155 |
+
)
|
| 156 |
+
if not is_safe_url:
|
| 157 |
+
raise PermissionError("This URL cannot be proxied.")
|
| 158 |
+
is_hf_url = url.host.endswith(".hf.space")
|
| 159 |
+
headers = {}
|
| 160 |
+
if Context.hf_token is not None and is_hf_url:
|
| 161 |
+
headers["Authorization"] = f"Bearer {Context.hf_token}"
|
| 162 |
+
rp_req = client.build_request("GET", url, headers=headers)
|
| 163 |
+
return rp_req
|
| 164 |
+
|
| 165 |
+
@staticmethod
|
| 166 |
+
def create_app(
|
| 167 |
+
blocks: gradio.Blocks, app_kwargs: Dict[str, Any] | None = None
|
| 168 |
+
) -> App:
|
| 169 |
+
app_kwargs = app_kwargs or {}
|
| 170 |
+
app_kwargs.setdefault("default_response_class", ORJSONResponse)
|
| 171 |
+
app = App(**app_kwargs)
|
| 172 |
+
app.configure_app(blocks)
|
| 173 |
+
|
| 174 |
+
app.add_middleware(
|
| 175 |
+
CORSMiddleware,
|
| 176 |
+
allow_origins=["*"],
|
| 177 |
+
allow_methods=["*"],
|
| 178 |
+
allow_headers=["*"],
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
@app.get("/user")
|
| 182 |
+
@app.get("/user/")
|
| 183 |
+
def get_current_user(request: fastapi.Request) -> Optional[str]:
|
| 184 |
+
token = request.cookies.get("access-token") or request.cookies.get(
|
| 185 |
+
"access-token-unsecure"
|
| 186 |
+
)
|
| 187 |
+
return app.tokens.get(token)
|
| 188 |
+
|
| 189 |
+
@app.get("/login_check")
|
| 190 |
+
@app.get("/login_check/")
|
| 191 |
+
def login_check(user: str = Depends(get_current_user)):
|
| 192 |
+
if app.auth is None or user is not None:
|
| 193 |
+
return
|
| 194 |
+
raise HTTPException(
|
| 195 |
+
status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
async def ws_login_check(websocket: WebSocket) -> Optional[str]:
|
| 199 |
+
token = websocket.cookies.get("access-token") or websocket.cookies.get(
|
| 200 |
+
"access-token-unsecure"
|
| 201 |
+
)
|
| 202 |
+
return token # token is returned to allow request in queue
|
| 203 |
+
|
| 204 |
+
@app.get("/token")
|
| 205 |
+
@app.get("/token/")
|
| 206 |
+
def get_token(request: fastapi.Request) -> dict:
|
| 207 |
+
token = request.cookies.get("access-token")
|
| 208 |
+
return {"token": token, "user": app.tokens.get(token)}
|
| 209 |
+
|
| 210 |
+
@app.get("/app_id")
|
| 211 |
+
@app.get("/app_id/")
|
| 212 |
+
def app_id(request: fastapi.Request) -> dict:
|
| 213 |
+
return {"app_id": app.get_blocks().app_id}
|
| 214 |
+
|
| 215 |
+
@app.post("/login")
|
| 216 |
+
@app.post("/login/")
|
| 217 |
+
def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
| 218 |
+
username, password = form_data.username, form_data.password
|
| 219 |
+
if app.auth is None:
|
| 220 |
+
return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
|
| 221 |
+
if (
|
| 222 |
+
not callable(app.auth)
|
| 223 |
+
and username in app.auth
|
| 224 |
+
and app.auth[username] == password
|
| 225 |
+
) or (callable(app.auth) and app.auth.__call__(username, password)):
|
| 226 |
+
token = secrets.token_urlsafe(16)
|
| 227 |
+
app.tokens[token] = username
|
| 228 |
+
response = JSONResponse(content={"success": True})
|
| 229 |
+
response.set_cookie(
|
| 230 |
+
key="access-token",
|
| 231 |
+
value=token,
|
| 232 |
+
httponly=True,
|
| 233 |
+
samesite="none",
|
| 234 |
+
secure=True,
|
| 235 |
+
)
|
| 236 |
+
response.set_cookie(
|
| 237 |
+
key="access-token-unsecure", value=token, httponly=True
|
| 238 |
+
)
|
| 239 |
+
return response
|
| 240 |
+
else:
|
| 241 |
+
raise HTTPException(status_code=400, detail="Incorrect credentials.")
|
| 242 |
+
|
| 243 |
+
###############
|
| 244 |
+
# Main Routes
|
| 245 |
+
###############
|
| 246 |
+
|
| 247 |
+
@app.head("/", response_class=HTMLResponse)
|
| 248 |
+
@app.get("/", response_class=HTMLResponse)
|
| 249 |
+
def main(request: fastapi.Request, user: str = Depends(get_current_user)):
|
| 250 |
+
mimetypes.add_type("application/javascript", ".js")
|
| 251 |
+
blocks = app.get_blocks()
|
| 252 |
+
root_path = request.scope.get("root_path", "")
|
| 253 |
+
|
| 254 |
+
if app.auth is None or user is not None:
|
| 255 |
+
config = app.get_blocks().config
|
| 256 |
+
config["root"] = root_path
|
| 257 |
+
else:
|
| 258 |
+
config = {
|
| 259 |
+
"auth_required": True,
|
| 260 |
+
"auth_message": blocks.auth_message,
|
| 261 |
+
"is_space": app.get_blocks().is_space,
|
| 262 |
+
"root": root_path,
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
try:
|
| 266 |
+
template = (
|
| 267 |
+
"frontend/share.html" if blocks.share else "frontend/index.html"
|
| 268 |
+
)
|
| 269 |
+
return templates.TemplateResponse(
|
| 270 |
+
template,
|
| 271 |
+
{"request": request, "config": config},
|
| 272 |
+
)
|
| 273 |
+
except TemplateNotFound as err:
|
| 274 |
+
if blocks.share:
|
| 275 |
+
raise ValueError(
|
| 276 |
+
"Did you install Gradio from source files? Share mode only "
|
| 277 |
+
"works when Gradio is installed through the pip package."
|
| 278 |
+
) from err
|
| 279 |
+
else:
|
| 280 |
+
raise ValueError(
|
| 281 |
+
"Did you install Gradio from source files? You need to build "
|
| 282 |
+
"the frontend by running /scripts/build_frontend.sh"
|
| 283 |
+
) from err
|
| 284 |
+
|
| 285 |
+
@app.get("/info/", dependencies=[Depends(login_check)])
|
| 286 |
+
@app.get("/info", dependencies=[Depends(login_check)])
|
| 287 |
+
def api_info(serialize: bool = True):
|
| 288 |
+
config = app.get_blocks().config
|
| 289 |
+
return gradio.blocks.get_api_info(config, serialize) # type: ignore
|
| 290 |
+
|
| 291 |
+
@app.get("/config/", dependencies=[Depends(login_check)])
|
| 292 |
+
@app.get("/config", dependencies=[Depends(login_check)])
|
| 293 |
+
def get_config(request: fastapi.Request):
|
| 294 |
+
root_path = request.scope.get("root_path", "")
|
| 295 |
+
config = app.get_blocks().config
|
| 296 |
+
config["root"] = root_path
|
| 297 |
+
return config
|
| 298 |
+
|
| 299 |
+
@app.get("/static/{path:path}")
|
| 300 |
+
def static_resource(path: str):
|
| 301 |
+
static_file = safe_join(STATIC_PATH_LIB, path)
|
| 302 |
+
return FileResponse(static_file)
|
| 303 |
+
|
| 304 |
+
@app.get("/assets/{path:path}")
|
| 305 |
+
def build_resource(path: str):
|
| 306 |
+
build_file = safe_join(BUILD_PATH_LIB, path)
|
| 307 |
+
return FileResponse(build_file)
|
| 308 |
+
|
| 309 |
+
@app.get("/favicon.ico")
|
| 310 |
+
async def favicon():
|
| 311 |
+
blocks = app.get_blocks()
|
| 312 |
+
if blocks.favicon_path is None:
|
| 313 |
+
return static_resource("img/logo.svg")
|
| 314 |
+
else:
|
| 315 |
+
return FileResponse(blocks.favicon_path)
|
| 316 |
+
|
| 317 |
+
@app.head("/proxy={url_path:path}", dependencies=[Depends(login_check)])
|
| 318 |
+
@app.get("/proxy={url_path:path}", dependencies=[Depends(login_check)])
|
| 319 |
+
async def reverse_proxy(url_path: str):
|
| 320 |
+
# Adapted from: https://github.com/tiangolo/fastapi/issues/1788
|
| 321 |
+
try:
|
| 322 |
+
rp_req = app.build_proxy_request(url_path)
|
| 323 |
+
except PermissionError as err:
|
| 324 |
+
raise HTTPException(status_code=400, detail=str(err)) from err
|
| 325 |
+
rp_resp = await client.send(rp_req, stream=True)
|
| 326 |
+
return StreamingResponse(
|
| 327 |
+
rp_resp.aiter_raw(),
|
| 328 |
+
status_code=rp_resp.status_code,
|
| 329 |
+
headers=rp_resp.headers, # type: ignore
|
| 330 |
+
background=BackgroundTask(rp_resp.aclose),
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
@app.head("/file={path_or_url:path}", dependencies=[Depends(login_check)])
|
| 334 |
+
@app.get("/file={path_or_url:path}", dependencies=[Depends(login_check)])
|
| 335 |
+
async def file(path_or_url: str, request: fastapi.Request):
|
| 336 |
+
blocks = app.get_blocks()
|
| 337 |
+
if utils.validate_url(path_or_url):
|
| 338 |
+
return RedirectResponse(
|
| 339 |
+
url=path_or_url, status_code=status.HTTP_302_FOUND
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
abs_path = utils.abspath(path_or_url)
|
| 343 |
+
|
| 344 |
+
in_blocklist = any(
|
| 345 |
+
utils.is_in_or_equal(abs_path, blocked_path)
|
| 346 |
+
for blocked_path in blocks.blocked_paths
|
| 347 |
+
)
|
| 348 |
+
is_dotfile = any(part.startswith(".") for part in abs_path.parts)
|
| 349 |
+
is_dir = abs_path.is_dir()
|
| 350 |
+
|
| 351 |
+
if in_blocklist or is_dotfile or is_dir:
|
| 352 |
+
raise HTTPException(403, f"File not allowed: {path_or_url}.")
|
| 353 |
+
if not abs_path.exists():
|
| 354 |
+
raise HTTPException(404, f"File not found: {path_or_url}.")
|
| 355 |
+
|
| 356 |
+
in_app_dir = utils.is_in_or_equal(abs_path, app.cwd)
|
| 357 |
+
created_by_app = str(abs_path) in set().union(*blocks.temp_file_sets)
|
| 358 |
+
in_allowlist = any(
|
| 359 |
+
utils.is_in_or_equal(abs_path, allowed_path)
|
| 360 |
+
for allowed_path in blocks.allowed_paths
|
| 361 |
+
)
|
| 362 |
+
was_uploaded = utils.is_in_or_equal(abs_path, app.uploaded_file_dir)
|
| 363 |
+
|
| 364 |
+
if not (in_app_dir or created_by_app or in_allowlist or was_uploaded):
|
| 365 |
+
raise HTTPException(403, f"File not allowed: {path_or_url}.")
|
| 366 |
+
|
| 367 |
+
range_val = request.headers.get("Range", "").strip()
|
| 368 |
+
if range_val.startswith("bytes=") and "-" in range_val:
|
| 369 |
+
range_val = range_val[6:]
|
| 370 |
+
start, end = range_val.split("-")
|
| 371 |
+
if start.isnumeric() and end.isnumeric():
|
| 372 |
+
start = int(start)
|
| 373 |
+
end = int(end)
|
| 374 |
+
response = ranged_response.RangedFileResponse(
|
| 375 |
+
abs_path,
|
| 376 |
+
ranged_response.OpenRange(start, end),
|
| 377 |
+
dict(request.headers),
|
| 378 |
+
stat_result=os.stat(abs_path),
|
| 379 |
+
)
|
| 380 |
+
return response
|
| 381 |
+
return FileResponse(abs_path, headers={"Accept-Ranges": "bytes"})
|
| 382 |
+
|
| 383 |
+
@app.get("/file/{path:path}", dependencies=[Depends(login_check)])
|
| 384 |
+
async def file_deprecated(path: str, request: fastapi.Request):
|
| 385 |
+
return await file(path, request)
|
| 386 |
+
|
| 387 |
+
@app.post("/reset/")
|
| 388 |
+
@app.post("/reset")
|
| 389 |
+
async def reset_iterator(body: ResetBody):
|
| 390 |
+
if body.session_hash not in app.iterators:
|
| 391 |
+
return {"success": False}
|
| 392 |
+
async with app.lock:
|
| 393 |
+
app.iterators[body.session_hash][body.fn_index] = None
|
| 394 |
+
app.iterators[body.session_hash]["should_reset"].add(body.fn_index)
|
| 395 |
+
return {"success": True}
|
| 396 |
+
|
| 397 |
+
async def run_predict(
|
| 398 |
+
body: PredictBody,
|
| 399 |
+
request: Request | List[Request],
|
| 400 |
+
fn_index_inferred: int,
|
| 401 |
+
):
|
| 402 |
+
if hasattr(body, "session_hash"):
|
| 403 |
+
if body.session_hash not in app.state_holder:
|
| 404 |
+
app.state_holder[body.session_hash] = {
|
| 405 |
+
_id: deepcopy(getattr(block, "value", None))
|
| 406 |
+
for _id, block in app.get_blocks().blocks.items()
|
| 407 |
+
if getattr(block, "stateful", False)
|
| 408 |
+
}
|
| 409 |
+
session_state = app.state_holder[body.session_hash]
|
| 410 |
+
iterators = app.iterators[body.session_hash]
|
| 411 |
+
# The should_reset set keeps track of the fn_indices
|
| 412 |
+
# that have been cancelled. When a job is cancelled,
|
| 413 |
+
# the /reset route will mark the jobs as having been reset.
|
| 414 |
+
# That way if the cancel job finishes BEFORE the job being cancelled
|
| 415 |
+
# the job being cancelled will not overwrite the state of the iterator.
|
| 416 |
+
# In all cases, should_reset will be the empty set the next time
|
| 417 |
+
# the fn_index is run.
|
| 418 |
+
app.iterators[body.session_hash]["should_reset"] = set()
|
| 419 |
+
else:
|
| 420 |
+
session_state = {}
|
| 421 |
+
iterators = {}
|
| 422 |
+
event_id = getattr(body, "event_id", None)
|
| 423 |
+
raw_input = body.data
|
| 424 |
+
fn_index = body.fn_index
|
| 425 |
+
|
| 426 |
+
dependency = app.get_blocks().dependencies[fn_index_inferred]
|
| 427 |
+
target = dependency["targets"][0] if len(dependency["targets"]) else None
|
| 428 |
+
event_data = EventData(
|
| 429 |
+
app.get_blocks().blocks.get(target) if target else None,
|
| 430 |
+
body.event_data,
|
| 431 |
+
)
|
| 432 |
+
batch = dependency["batch"]
|
| 433 |
+
if not (body.batched) and batch:
|
| 434 |
+
raw_input = [raw_input]
|
| 435 |
+
try:
|
| 436 |
+
with utils.MatplotlibBackendMananger():
|
| 437 |
+
output = await app.get_blocks().process_api(
|
| 438 |
+
fn_index=fn_index_inferred,
|
| 439 |
+
inputs=raw_input,
|
| 440 |
+
request=request,
|
| 441 |
+
state=session_state,
|
| 442 |
+
iterators=iterators,
|
| 443 |
+
event_id=event_id,
|
| 444 |
+
event_data=event_data,
|
| 445 |
+
)
|
| 446 |
+
iterator = output.pop("iterator", None)
|
| 447 |
+
if hasattr(body, "session_hash"):
|
| 448 |
+
if fn_index in app.iterators[body.session_hash]["should_reset"]:
|
| 449 |
+
app.iterators[body.session_hash][fn_index] = None
|
| 450 |
+
else:
|
| 451 |
+
app.iterators[body.session_hash][fn_index] = iterator
|
| 452 |
+
if isinstance(output, Error):
|
| 453 |
+
raise output
|
| 454 |
+
except BaseException as error:
|
| 455 |
+
show_error = app.get_blocks().show_error or isinstance(error, Error)
|
| 456 |
+
traceback.print_exc()
|
| 457 |
+
return JSONResponse(
|
| 458 |
+
content={"error": str(error) if show_error else None},
|
| 459 |
+
status_code=500,
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
if not (body.batched) and batch:
|
| 463 |
+
output["data"] = output["data"][0]
|
| 464 |
+
return output
|
| 465 |
+
|
| 466 |
+
# had to use '/run' endpoint for Colab compatibility, '/api' supported for backwards compatibility
|
| 467 |
+
@app.post("/run/{api_name}", dependencies=[Depends(login_check)])
|
| 468 |
+
@app.post("/run/{api_name}/", dependencies=[Depends(login_check)])
|
| 469 |
+
@app.post("/api/{api_name}", dependencies=[Depends(login_check)])
|
| 470 |
+
@app.post("/api/{api_name}/", dependencies=[Depends(login_check)])
|
| 471 |
+
async def predict(
|
| 472 |
+
api_name: str,
|
| 473 |
+
body: PredictBody,
|
| 474 |
+
request: fastapi.Request,
|
| 475 |
+
username: str = Depends(get_current_user),
|
| 476 |
+
):
|
| 477 |
+
fn_index_inferred = None
|
| 478 |
+
if body.fn_index is None:
|
| 479 |
+
for i, fn in enumerate(app.get_blocks().dependencies):
|
| 480 |
+
if fn["api_name"] == api_name:
|
| 481 |
+
fn_index_inferred = i
|
| 482 |
+
break
|
| 483 |
+
if fn_index_inferred is None:
|
| 484 |
+
return JSONResponse(
|
| 485 |
+
content={
|
| 486 |
+
"error": f"This app has no endpoint /api/{api_name}/."
|
| 487 |
+
},
|
| 488 |
+
status_code=500,
|
| 489 |
+
)
|
| 490 |
+
else:
|
| 491 |
+
fn_index_inferred = body.fn_index
|
| 492 |
+
if (
|
| 493 |
+
not app.get_blocks().api_open
|
| 494 |
+
and app.get_blocks().queue_enabled_for_fn(fn_index_inferred)
|
| 495 |
+
and f"Bearer {app.queue_token}" != request.headers.get("Authorization")
|
| 496 |
+
):
|
| 497 |
+
raise HTTPException(
|
| 498 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 499 |
+
detail="Not authorized to skip the queue",
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# If this fn_index cancels jobs, then the only input we need is the
|
| 503 |
+
# current session hash
|
| 504 |
+
if app.get_blocks().dependencies[fn_index_inferred]["cancels"]:
|
| 505 |
+
body.data = [body.session_hash]
|
| 506 |
+
if body.request:
|
| 507 |
+
if body.batched:
|
| 508 |
+
gr_request = [
|
| 509 |
+
Request(username=username, **req) for req in body.request
|
| 510 |
+
]
|
| 511 |
+
else:
|
| 512 |
+
assert isinstance(body.request, dict)
|
| 513 |
+
gr_request = Request(username=username, **body.request)
|
| 514 |
+
else:
|
| 515 |
+
gr_request = Request(username=username, request=request)
|
| 516 |
+
result = await run_predict(
|
| 517 |
+
body=body,
|
| 518 |
+
fn_index_inferred=fn_index_inferred,
|
| 519 |
+
request=gr_request,
|
| 520 |
+
)
|
| 521 |
+
return result
|
| 522 |
+
|
| 523 |
+
@app.websocket("/queue/join")
|
| 524 |
+
async def join_queue(
|
| 525 |
+
websocket: WebSocket,
|
| 526 |
+
token: Optional[str] = Depends(ws_login_check),
|
| 527 |
+
):
|
| 528 |
+
blocks = app.get_blocks()
|
| 529 |
+
if app.auth is not None and token is None:
|
| 530 |
+
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
| 531 |
+
return
|
| 532 |
+
if blocks._queue.server_path is None:
|
| 533 |
+
app_url = get_server_url_from_ws_url(str(websocket.url))
|
| 534 |
+
blocks._queue.set_url(app_url)
|
| 535 |
+
await websocket.accept()
|
| 536 |
+
# In order to cancel jobs, we need the session_hash and fn_index
|
| 537 |
+
# to create a unique id for each job
|
| 538 |
+
try:
|
| 539 |
+
await asyncio.wait_for(
|
| 540 |
+
websocket.send_json({"msg": "send_hash"}), timeout=5
|
| 541 |
+
)
|
| 542 |
+
except AsyncTimeOutError:
|
| 543 |
+
return
|
| 544 |
+
|
| 545 |
+
try:
|
| 546 |
+
session_info = await asyncio.wait_for(
|
| 547 |
+
websocket.receive_json(), timeout=5
|
| 548 |
+
)
|
| 549 |
+
except AsyncTimeOutError:
|
| 550 |
+
return
|
| 551 |
+
|
| 552 |
+
event = Event(
|
| 553 |
+
websocket, session_info["session_hash"], session_info["fn_index"]
|
| 554 |
+
)
|
| 555 |
+
# set the token into Event to allow using the same token for call_prediction
|
| 556 |
+
event.token = token
|
| 557 |
+
event.session_hash = session_info["session_hash"]
|
| 558 |
+
|
| 559 |
+
# Continuous events are not put in the queue so that they do not
|
| 560 |
+
# occupy the queue's resource as they are expected to run forever
|
| 561 |
+
if blocks.dependencies[event.fn_index].get("every", 0):
|
| 562 |
+
await cancel_tasks({f"{event.session_hash}_{event.fn_index}"})
|
| 563 |
+
await blocks._queue.reset_iterators(event.session_hash, event.fn_index)
|
| 564 |
+
task = run_coro_in_background(
|
| 565 |
+
blocks._queue.process_events, [event], False
|
| 566 |
+
)
|
| 567 |
+
set_task_name(task, event.session_hash, event.fn_index, batch=False)
|
| 568 |
+
else:
|
| 569 |
+
rank = blocks._queue.push(event)
|
| 570 |
+
|
| 571 |
+
if rank is None:
|
| 572 |
+
await blocks._queue.send_message(event, {"msg": "queue_full"})
|
| 573 |
+
await event.disconnect()
|
| 574 |
+
return
|
| 575 |
+
estimation = blocks._queue.get_estimation()
|
| 576 |
+
await blocks._queue.send_estimation(event, estimation, rank)
|
| 577 |
+
while True:
|
| 578 |
+
await asyncio.sleep(1)
|
| 579 |
+
if websocket.application_state == WebSocketState.DISCONNECTED:
|
| 580 |
+
return
|
| 581 |
+
|
| 582 |
+
@app.get(
|
| 583 |
+
"/queue/status",
|
| 584 |
+
dependencies=[Depends(login_check)],
|
| 585 |
+
response_model=Estimation,
|
| 586 |
+
)
|
| 587 |
+
async def get_queue_status():
|
| 588 |
+
return app.get_blocks()._queue.get_estimation()
|
| 589 |
+
|
| 590 |
+
@app.post("/upload", dependencies=[Depends(login_check)])
|
| 591 |
+
async def upload_file(
|
| 592 |
+
files: List[UploadFile] = File(...),
|
| 593 |
+
):
|
| 594 |
+
output_files = []
|
| 595 |
+
file_manager = gradio.File()
|
| 596 |
+
for input_file in files:
|
| 597 |
+
output_files.append(
|
| 598 |
+
await file_manager.save_uploaded_file(
|
| 599 |
+
input_file, app.uploaded_file_dir
|
| 600 |
+
)
|
| 601 |
+
)
|
| 602 |
+
return output_files
|
| 603 |
+
|
| 604 |
+
@app.on_event("startup")
|
| 605 |
+
@app.get("/startup-events")
|
| 606 |
+
async def startup_events():
|
| 607 |
+
if not app.startup_events_triggered:
|
| 608 |
+
app.get_blocks().startup_events()
|
| 609 |
+
app.startup_events_triggered = True
|
| 610 |
+
return True
|
| 611 |
+
return False
|
| 612 |
+
|
| 613 |
+
@app.get("/theme.css", response_class=PlainTextResponse)
|
| 614 |
+
def theme_css():
|
| 615 |
+
return PlainTextResponse(app.get_blocks().theme_css, media_type="text/css")
|
| 616 |
+
|
| 617 |
+
@app.get("/robots.txt", response_class=PlainTextResponse)
|
| 618 |
+
def robots_txt():
|
| 619 |
+
if app.get_blocks().share:
|
| 620 |
+
return "User-agent: *\nDisallow: /"
|
| 621 |
+
else:
|
| 622 |
+
return "User-agent: *\nDisallow: "
|
| 623 |
+
|
| 624 |
+
return app
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
########
|
| 628 |
+
# Helper functions
|
| 629 |
+
########
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def safe_join(directory: str, path: str) -> str:
|
| 633 |
+
"""Safely path to a base directory to avoid escaping the base directory.
|
| 634 |
+
Borrowed from: werkzeug.security.safe_join"""
|
| 635 |
+
_os_alt_seps: List[str] = [
|
| 636 |
+
sep for sep in [os.path.sep, os.path.altsep] if sep is not None and sep != "/"
|
| 637 |
+
]
|
| 638 |
+
|
| 639 |
+
if path == "":
|
| 640 |
+
raise HTTPException(400)
|
| 641 |
+
|
| 642 |
+
filename = posixpath.normpath(path)
|
| 643 |
+
fullpath = os.path.join(directory, filename)
|
| 644 |
+
if (
|
| 645 |
+
any(sep in filename for sep in _os_alt_seps)
|
| 646 |
+
or os.path.isabs(filename)
|
| 647 |
+
or filename == ".."
|
| 648 |
+
or filename.startswith("../")
|
| 649 |
+
or os.path.isdir(fullpath)
|
| 650 |
+
):
|
| 651 |
+
raise HTTPException(403)
|
| 652 |
+
|
| 653 |
+
if not os.path.exists(fullpath):
|
| 654 |
+
raise HTTPException(404, "File not found")
|
| 655 |
+
|
| 656 |
+
return fullpath
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def get_types(cls_set: List[Type]):
|
| 660 |
+
docset = []
|
| 661 |
+
types = []
|
| 662 |
+
for cls in cls_set:
|
| 663 |
+
doc = inspect.getdoc(cls) or ""
|
| 664 |
+
doc_lines = doc.split("\n")
|
| 665 |
+
for line in doc_lines:
|
| 666 |
+
if "value (" in line:
|
| 667 |
+
types.append(line.split("value (")[1].split(")")[0])
|
| 668 |
+
docset.append(doc_lines[1].split(":")[-1])
|
| 669 |
+
return docset, types
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def get_server_url_from_ws_url(ws_url: str):
|
| 673 |
+
ws_url_parsed = urlparse(ws_url)
|
| 674 |
+
scheme = "http" if ws_url_parsed.scheme == "ws" else "https"
|
| 675 |
+
port = f":{ws_url_parsed.port}" if ws_url_parsed.port else ""
|
| 676 |
+
return f"{scheme}://{ws_url_parsed.hostname}{port}{ws_url_parsed.path.replace('queue/join', '')}"
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
set_documentation_group("routes")
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
class Obj:
|
| 683 |
+
"""
|
| 684 |
+
Using a class to convert dictionaries into objects. Used by the `Request` class.
|
| 685 |
+
Credit: https://www.geeksforgeeks.org/convert-nested-python-dictionary-to-object/
|
| 686 |
+
"""
|
| 687 |
+
|
| 688 |
+
def __init__(self, dict_):
|
| 689 |
+
self.__dict__.update(dict_)
|
| 690 |
+
for key, value in dict_.items():
|
| 691 |
+
if isinstance(value, (dict, list)):
|
| 692 |
+
value = Obj(value)
|
| 693 |
+
setattr(self, key, value)
|
| 694 |
+
|
| 695 |
+
def __getitem__(self, item):
|
| 696 |
+
return self.__dict__[item]
|
| 697 |
+
|
| 698 |
+
def __setitem__(self, item, value):
|
| 699 |
+
self.__dict__[item] = value
|
| 700 |
+
|
| 701 |
+
def __iter__(self):
|
| 702 |
+
for key, value in self.__dict__.items():
|
| 703 |
+
if isinstance(value, Obj):
|
| 704 |
+
yield (key, dict(value))
|
| 705 |
+
else:
|
| 706 |
+
yield (key, value)
|
| 707 |
+
|
| 708 |
+
def __contains__(self, item) -> bool:
|
| 709 |
+
if item in self.__dict__:
|
| 710 |
+
return True
|
| 711 |
+
for value in self.__dict__.values():
|
| 712 |
+
if isinstance(value, Obj) and item in value:
|
| 713 |
+
return True
|
| 714 |
+
return False
|
| 715 |
+
|
| 716 |
+
def keys(self):
|
| 717 |
+
return self.__dict__.keys()
|
| 718 |
+
|
| 719 |
+
def values(self):
|
| 720 |
+
return self.__dict__.values()
|
| 721 |
+
|
| 722 |
+
def items(self):
|
| 723 |
+
return self.__dict__.items()
|
| 724 |
+
|
| 725 |
+
def __str__(self) -> str:
|
| 726 |
+
return str(self.__dict__)
|
| 727 |
+
|
| 728 |
+
def __repr__(self) -> str:
|
| 729 |
+
return str(self.__dict__)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
@document()
|
| 733 |
+
class Request:
|
| 734 |
+
"""
|
| 735 |
+
A Gradio request object that can be used to access the request headers, cookies,
|
| 736 |
+
query parameters and other information about the request from within the prediction
|
| 737 |
+
function. The class is a thin wrapper around the fastapi.Request class. Attributes
|
| 738 |
+
of this class include: `headers`, `client`, `query_params`, and `path_params`. If
|
| 739 |
+
auth is enabled, the `username` attribute can be used to get the logged in user.
|
| 740 |
+
Example:
|
| 741 |
+
import gradio as gr
|
| 742 |
+
def echo(name, request: gr.Request):
|
| 743 |
+
print("Request headers dictionary:", request.headers)
|
| 744 |
+
print("IP address:", request.client.host)
|
| 745 |
+
return name
|
| 746 |
+
io = gr.Interface(echo, "textbox", "textbox").launch()
|
| 747 |
+
"""
|
| 748 |
+
|
| 749 |
+
def __init__(
|
| 750 |
+
self,
|
| 751 |
+
request: fastapi.Request | None = None,
|
| 752 |
+
username: str | None = None,
|
| 753 |
+
**kwargs,
|
| 754 |
+
):
|
| 755 |
+
"""
|
| 756 |
+
Can be instantiated with either a fastapi.Request or by manually passing in
|
| 757 |
+
attributes (needed for websocket-based queueing).
|
| 758 |
+
Parameters:
|
| 759 |
+
request: A fastapi.Request
|
| 760 |
+
"""
|
| 761 |
+
self.request = request
|
| 762 |
+
self.username = username
|
| 763 |
+
self.kwargs: Dict = kwargs
|
| 764 |
+
|
| 765 |
+
def dict_to_obj(self, d):
|
| 766 |
+
if isinstance(d, dict):
|
| 767 |
+
return json.loads(json.dumps(d), object_hook=Obj)
|
| 768 |
+
else:
|
| 769 |
+
return d
|
| 770 |
+
|
| 771 |
+
def __getattr__(self, name):
|
| 772 |
+
if self.request:
|
| 773 |
+
return self.dict_to_obj(getattr(self.request, name))
|
| 774 |
+
else:
|
| 775 |
+
try:
|
| 776 |
+
obj = self.kwargs[name]
|
| 777 |
+
except KeyError as ke:
|
| 778 |
+
raise AttributeError(
|
| 779 |
+
f"'Request' object has no attribute '{name}'"
|
| 780 |
+
) from ke
|
| 781 |
+
return self.dict_to_obj(obj)
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
@document()
|
| 785 |
+
def mount_gradio_app(
|
| 786 |
+
app: fastapi.FastAPI,
|
| 787 |
+
blocks: gradio.Blocks,
|
| 788 |
+
path: str,
|
| 789 |
+
gradio_api_url: str | None = None,
|
| 790 |
+
app_kwargs: dict[str, Any] | None = None,
|
| 791 |
+
) -> fastapi.FastAPI:
|
| 792 |
+
"""Mount a gradio.Blocks to an existing FastAPI application.
|
| 793 |
+
|
| 794 |
+
Parameters:
|
| 795 |
+
app: The parent FastAPI application.
|
| 796 |
+
blocks: The blocks object we want to mount to the parent app.
|
| 797 |
+
path: The path at which the gradio application will be mounted.
|
| 798 |
+
gradio_api_url: The full url at which the gradio app will run. This is only needed if deploying to Huggingface spaces of if the websocket endpoints of your deployed app are on a different network location than the gradio app. If deploying to spaces, set gradio_api_url to 'http://localhost:7860/'
|
| 799 |
+
app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
|
| 800 |
+
Example:
|
| 801 |
+
from fastapi import FastAPI
|
| 802 |
+
import gradio as gr
|
| 803 |
+
app = FastAPI()
|
| 804 |
+
@app.get("/")
|
| 805 |
+
def read_main():
|
| 806 |
+
return {"message": "This is your main app"}
|
| 807 |
+
io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
|
| 808 |
+
app = gr.mount_gradio_app(app, io, path="/gradio")
|
| 809 |
+
# Then run `uvicorn run:app` from the terminal and navigate to http://localhost:8000/gradio.
|
| 810 |
+
"""
|
| 811 |
+
blocks.dev_mode = False
|
| 812 |
+
blocks.config = blocks.get_config_file()
|
| 813 |
+
blocks.validate_queue_settings()
|
| 814 |
+
gradio_app = App.create_app(blocks, app_kwargs=app_kwargs)
|
| 815 |
+
|
| 816 |
+
@app.on_event("startup")
|
| 817 |
+
async def start_queue():
|
| 818 |
+
if gradio_app.get_blocks().enable_queue:
|
| 819 |
+
if gradio_api_url:
|
| 820 |
+
gradio_app.get_blocks()._queue.set_url(gradio_api_url)
|
| 821 |
+
gradio_app.get_blocks().startup_events()
|
| 822 |
+
|
| 823 |
+
app.mount(path, gradio_app)
|
| 824 |
+
return app
|
falcon/lib/python3.10/site-packages/gradio/strings.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import threading
|
| 3 |
+
from typing import Dict
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
MESSAGING_API_ENDPOINT = "https://api.gradio.app/gradio-messaging/en"
|
| 8 |
+
|
| 9 |
+
en = {
|
| 10 |
+
"RUNNING_LOCALLY": "Running on local URL: {}",
|
| 11 |
+
"RUNNING_LOCALLY_SEPARATED": "Running on local URL: {}://{}:{}",
|
| 12 |
+
"SHARE_LINK_DISPLAY": "Running on public URL: {}",
|
| 13 |
+
"COULD_NOT_GET_SHARE_LINK": "\nCould not create share link. Please check your internet connection or our status page: https://status.gradio.app. \n\nAlso please ensure that your antivirus or firewall is not blocking the binary file located at: {}",
|
| 14 |
+
"COLAB_NO_LOCAL": "Cannot display local interface on google colab, public link created.",
|
| 15 |
+
"PUBLIC_SHARE_TRUE": "\nTo create a public link, set `share=True` in `launch()`.",
|
| 16 |
+
"MODEL_PUBLICLY_AVAILABLE_URL": "Model available publicly at: {} (may take up to a minute for link to be usable)",
|
| 17 |
+
"GENERATING_PUBLIC_LINK": "Generating public link (may take a few seconds...):",
|
| 18 |
+
"BETA_INVITE": "\nThanks for being a Gradio user! If you have questions or feedback, please join our Discord server and chat with us: https://discord.gg/feTf9x3ZSB",
|
| 19 |
+
"COLAB_DEBUG_TRUE": "Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. "
|
| 20 |
+
"To turn off, set debug=False in launch().",
|
| 21 |
+
"COLAB_DEBUG_FALSE": "Colab notebook detected. To show errors in colab notebook, set debug=True in launch()",
|
| 22 |
+
"COLAB_WARNING": "Note: opening Chrome Inspector may crash demo inside Colab notebooks.",
|
| 23 |
+
"SHARE_LINK_MESSAGE": "\nThis share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)",
|
| 24 |
+
"INLINE_DISPLAY_BELOW": "Interface loading below...",
|
| 25 |
+
"TIPS": [
|
| 26 |
+
"You can add authentication to your app with the `auth=` kwarg in the `launch()` command; for example: `gr.Interface(...).launch(auth=('username', 'password'))`",
|
| 27 |
+
"Let users specify why they flagged input with the `flagging_options=` kwarg; for example: `gr.Interface(..., flagging_options=['too slow', 'incorrect output', 'other'])`",
|
| 28 |
+
"You can show or hide the button for flagging with the `allow_flagging=` kwarg; for example: gr.Interface(..., allow_flagging=False)",
|
| 29 |
+
"The inputs and outputs flagged by the users are stored in the flagging directory, specified by the flagging_dir= kwarg. You can view this data through the interface by setting the examples= kwarg to the flagging directory; for example gr.Interface(..., examples='flagged')",
|
| 30 |
+
"You can add a title and description to your interface using the `title=` and `description=` kwargs. The `article=` kwarg can be used to add a description under the interface; for example gr.Interface(..., title='My app', description='Lorem ipsum'). Try using Markdown!",
|
| 31 |
+
"For a classification or regression model, set `interpretation='default'` to see why the model made a prediction.",
|
| 32 |
+
],
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_updated_messaging(en: Dict):
|
| 37 |
+
try:
|
| 38 |
+
updated_messaging = requests.get(MESSAGING_API_ENDPOINT, timeout=3).json()
|
| 39 |
+
en.update(updated_messaging)
|
| 40 |
+
except Exception: # Use default messaging
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True":
|
| 45 |
+
threading.Thread(target=get_updated_messaging, args=(en,)).start()
|
falcon/lib/python3.10/site-packages/gradio/templates.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Callable
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL.Image import Image
|
| 7 |
+
|
| 8 |
+
from gradio import components
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TextArea(components.Textbox):
|
| 12 |
+
"""
|
| 13 |
+
Sets: lines=7
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
is_template = True
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
value: str | Callable | None = "",
|
| 21 |
+
*,
|
| 22 |
+
lines: int = 7,
|
| 23 |
+
max_lines: int = 20,
|
| 24 |
+
placeholder: str | None = None,
|
| 25 |
+
label: str | None = None,
|
| 26 |
+
show_label: bool = True,
|
| 27 |
+
interactive: bool | None = None,
|
| 28 |
+
visible: bool = True,
|
| 29 |
+
elem_id: str | None = None,
|
| 30 |
+
**kwargs,
|
| 31 |
+
):
|
| 32 |
+
super().__init__(
|
| 33 |
+
value=value,
|
| 34 |
+
lines=lines,
|
| 35 |
+
max_lines=max_lines,
|
| 36 |
+
placeholder=placeholder,
|
| 37 |
+
label=label,
|
| 38 |
+
show_label=show_label,
|
| 39 |
+
interactive=interactive,
|
| 40 |
+
visible=visible,
|
| 41 |
+
elem_id=elem_id,
|
| 42 |
+
**kwargs,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Webcam(components.Image):
|
| 47 |
+
"""
|
| 48 |
+
Sets: source="webcam", interactive=True
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
is_template = True
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
value: str | Image | np.ndarray | None = None,
|
| 56 |
+
*,
|
| 57 |
+
shape: tuple[int, int] | None = None,
|
| 58 |
+
image_mode: str = "RGB",
|
| 59 |
+
invert_colors: bool = False,
|
| 60 |
+
source: str = "webcam",
|
| 61 |
+
tool: str | None = None,
|
| 62 |
+
type: str = "numpy",
|
| 63 |
+
label: str | None = None,
|
| 64 |
+
show_label: bool = True,
|
| 65 |
+
interactive: bool | None = True,
|
| 66 |
+
visible: bool = True,
|
| 67 |
+
streaming: bool = False,
|
| 68 |
+
elem_id: str | None = None,
|
| 69 |
+
mirror_webcam: bool = True,
|
| 70 |
+
brush_radius: float | None = None,
|
| 71 |
+
**kwargs,
|
| 72 |
+
):
|
| 73 |
+
super().__init__(
|
| 74 |
+
value=value,
|
| 75 |
+
shape=shape,
|
| 76 |
+
image_mode=image_mode,
|
| 77 |
+
invert_colors=invert_colors,
|
| 78 |
+
source=source,
|
| 79 |
+
tool=tool,
|
| 80 |
+
type=type,
|
| 81 |
+
label=label,
|
| 82 |
+
show_label=show_label,
|
| 83 |
+
interactive=interactive,
|
| 84 |
+
visible=visible,
|
| 85 |
+
streaming=streaming,
|
| 86 |
+
elem_id=elem_id,
|
| 87 |
+
mirror_webcam=mirror_webcam,
|
| 88 |
+
brush_radius=brush_radius,
|
| 89 |
+
**kwargs,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class Sketchpad(components.Image):
|
| 94 |
+
"""
|
| 95 |
+
Sets: image_mode="L", source="canvas", shape=(28, 28), invert_colors=True, interactive=True
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
is_template = True
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
value: str | Image | np.ndarray | None = None,
|
| 103 |
+
*,
|
| 104 |
+
shape: tuple[int, int] = (28, 28),
|
| 105 |
+
image_mode: str = "L",
|
| 106 |
+
invert_colors: bool = True,
|
| 107 |
+
source: str = "canvas",
|
| 108 |
+
tool: str | None = None,
|
| 109 |
+
type: str = "numpy",
|
| 110 |
+
label: str | None = None,
|
| 111 |
+
show_label: bool = True,
|
| 112 |
+
interactive: bool | None = True,
|
| 113 |
+
visible: bool = True,
|
| 114 |
+
streaming: bool = False,
|
| 115 |
+
elem_id: str | None = None,
|
| 116 |
+
mirror_webcam: bool = True,
|
| 117 |
+
brush_radius: float | None = None,
|
| 118 |
+
**kwargs,
|
| 119 |
+
):
|
| 120 |
+
super().__init__(
|
| 121 |
+
value=value,
|
| 122 |
+
shape=shape,
|
| 123 |
+
image_mode=image_mode,
|
| 124 |
+
invert_colors=invert_colors,
|
| 125 |
+
source=source,
|
| 126 |
+
tool=tool,
|
| 127 |
+
type=type,
|
| 128 |
+
label=label,
|
| 129 |
+
show_label=show_label,
|
| 130 |
+
interactive=interactive,
|
| 131 |
+
visible=visible,
|
| 132 |
+
streaming=streaming,
|
| 133 |
+
elem_id=elem_id,
|
| 134 |
+
mirror_webcam=mirror_webcam,
|
| 135 |
+
brush_radius=brush_radius,
|
| 136 |
+
**kwargs,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class Paint(components.Image):
|
| 141 |
+
"""
|
| 142 |
+
Sets: source="canvas", tool="color-sketch", interactive=True
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
is_template = True
|
| 146 |
+
|
| 147 |
+
def __init__(
|
| 148 |
+
self,
|
| 149 |
+
value: str | Image | np.ndarray | None = None,
|
| 150 |
+
*,
|
| 151 |
+
shape: tuple[int, int] | None = None,
|
| 152 |
+
image_mode: str = "RGB",
|
| 153 |
+
invert_colors: bool = False,
|
| 154 |
+
source: str = "canvas",
|
| 155 |
+
tool: str = "color-sketch",
|
| 156 |
+
type: str = "numpy",
|
| 157 |
+
label: str | None = None,
|
| 158 |
+
show_label: bool = True,
|
| 159 |
+
interactive: bool | None = True,
|
| 160 |
+
visible: bool = True,
|
| 161 |
+
streaming: bool = False,
|
| 162 |
+
elem_id: str | None = None,
|
| 163 |
+
mirror_webcam: bool = True,
|
| 164 |
+
brush_radius: float | None = None,
|
| 165 |
+
**kwargs,
|
| 166 |
+
):
|
| 167 |
+
super().__init__(
|
| 168 |
+
value=value,
|
| 169 |
+
shape=shape,
|
| 170 |
+
image_mode=image_mode,
|
| 171 |
+
invert_colors=invert_colors,
|
| 172 |
+
source=source,
|
| 173 |
+
tool=tool,
|
| 174 |
+
type=type,
|
| 175 |
+
label=label,
|
| 176 |
+
show_label=show_label,
|
| 177 |
+
interactive=interactive,
|
| 178 |
+
visible=visible,
|
| 179 |
+
streaming=streaming,
|
| 180 |
+
elem_id=elem_id,
|
| 181 |
+
mirror_webcam=mirror_webcam,
|
| 182 |
+
brush_radius=brush_radius,
|
| 183 |
+
**kwargs,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class ImageMask(components.Image):
|
| 188 |
+
"""
|
| 189 |
+
Sets: source="upload", tool="sketch", interactive=True
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
is_template = True
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
value: str | Image | np.ndarray | None = None,
|
| 197 |
+
*,
|
| 198 |
+
shape: tuple[int, int] | None = None,
|
| 199 |
+
image_mode: str = "RGB",
|
| 200 |
+
invert_colors: bool = False,
|
| 201 |
+
source: str = "upload",
|
| 202 |
+
tool: str = "sketch",
|
| 203 |
+
type: str = "numpy",
|
| 204 |
+
label: str | None = None,
|
| 205 |
+
show_label: bool = True,
|
| 206 |
+
interactive: bool | None = True,
|
| 207 |
+
visible: bool = True,
|
| 208 |
+
streaming: bool = False,
|
| 209 |
+
elem_id: str | None = None,
|
| 210 |
+
mirror_webcam: bool = True,
|
| 211 |
+
brush_radius: float | None = None,
|
| 212 |
+
**kwargs,
|
| 213 |
+
):
|
| 214 |
+
super().__init__(
|
| 215 |
+
value=value,
|
| 216 |
+
shape=shape,
|
| 217 |
+
image_mode=image_mode,
|
| 218 |
+
invert_colors=invert_colors,
|
| 219 |
+
source=source,
|
| 220 |
+
tool=tool,
|
| 221 |
+
type=type,
|
| 222 |
+
label=label,
|
| 223 |
+
show_label=show_label,
|
| 224 |
+
interactive=interactive,
|
| 225 |
+
visible=visible,
|
| 226 |
+
streaming=streaming,
|
| 227 |
+
elem_id=elem_id,
|
| 228 |
+
mirror_webcam=mirror_webcam,
|
| 229 |
+
brush_radius=brush_radius,
|
| 230 |
+
**kwargs,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class ImagePaint(components.Image):
|
| 235 |
+
"""
|
| 236 |
+
Sets: source="upload", tool="color-sketch", interactive=True
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
is_template = True
|
| 240 |
+
|
| 241 |
+
def __init__(
|
| 242 |
+
self,
|
| 243 |
+
value: str | Image | np.ndarray | None = None,
|
| 244 |
+
*,
|
| 245 |
+
shape: tuple[int, int] | None = None,
|
| 246 |
+
image_mode: str = "RGB",
|
| 247 |
+
invert_colors: bool = False,
|
| 248 |
+
source: str = "upload",
|
| 249 |
+
tool: str = "color-sketch",
|
| 250 |
+
type: str = "numpy",
|
| 251 |
+
label: str | None = None,
|
| 252 |
+
show_label: bool = True,
|
| 253 |
+
interactive: bool | None = True,
|
| 254 |
+
visible: bool = True,
|
| 255 |
+
streaming: bool = False,
|
| 256 |
+
elem_id: str | None = None,
|
| 257 |
+
mirror_webcam: bool = True,
|
| 258 |
+
brush_radius: float | None = None,
|
| 259 |
+
**kwargs,
|
| 260 |
+
):
|
| 261 |
+
super().__init__(
|
| 262 |
+
value=value,
|
| 263 |
+
shape=shape,
|
| 264 |
+
image_mode=image_mode,
|
| 265 |
+
invert_colors=invert_colors,
|
| 266 |
+
source=source,
|
| 267 |
+
tool=tool,
|
| 268 |
+
type=type,
|
| 269 |
+
label=label,
|
| 270 |
+
show_label=show_label,
|
| 271 |
+
interactive=interactive,
|
| 272 |
+
visible=visible,
|
| 273 |
+
streaming=streaming,
|
| 274 |
+
elem_id=elem_id,
|
| 275 |
+
mirror_webcam=mirror_webcam,
|
| 276 |
+
brush_radius=brush_radius,
|
| 277 |
+
**kwargs,
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class Pil(components.Image):
|
| 282 |
+
"""
|
| 283 |
+
Sets: type="pil"
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
is_template = True
|
| 287 |
+
|
| 288 |
+
def __init__(
|
| 289 |
+
self,
|
| 290 |
+
value: str | Image | np.ndarray | None = None,
|
| 291 |
+
*,
|
| 292 |
+
shape: tuple[int, int] | None = None,
|
| 293 |
+
image_mode: str = "RGB",
|
| 294 |
+
invert_colors: bool = False,
|
| 295 |
+
source: str = "upload",
|
| 296 |
+
tool: str | None = None,
|
| 297 |
+
type: str = "pil",
|
| 298 |
+
label: str | None = None,
|
| 299 |
+
show_label: bool = True,
|
| 300 |
+
interactive: bool | None = None,
|
| 301 |
+
visible: bool = True,
|
| 302 |
+
streaming: bool = False,
|
| 303 |
+
elem_id: str | None = None,
|
| 304 |
+
mirror_webcam: bool = True,
|
| 305 |
+
brush_radius: float | None = None,
|
| 306 |
+
**kwargs,
|
| 307 |
+
):
|
| 308 |
+
super().__init__(
|
| 309 |
+
value=value,
|
| 310 |
+
shape=shape,
|
| 311 |
+
image_mode=image_mode,
|
| 312 |
+
invert_colors=invert_colors,
|
| 313 |
+
source=source,
|
| 314 |
+
tool=tool,
|
| 315 |
+
type=type,
|
| 316 |
+
label=label,
|
| 317 |
+
show_label=show_label,
|
| 318 |
+
interactive=interactive,
|
| 319 |
+
visible=visible,
|
| 320 |
+
streaming=streaming,
|
| 321 |
+
elem_id=elem_id,
|
| 322 |
+
mirror_webcam=mirror_webcam,
|
| 323 |
+
brush_radius=brush_radius,
|
| 324 |
+
**kwargs,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class PlayableVideo(components.Video):
|
| 329 |
+
"""
|
| 330 |
+
Sets: format="mp4"
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
is_template = True
|
| 334 |
+
|
| 335 |
+
def __init__(
|
| 336 |
+
self,
|
| 337 |
+
value: str | Callable | None = None,
|
| 338 |
+
*,
|
| 339 |
+
format: str | None = "mp4",
|
| 340 |
+
source: str = "upload",
|
| 341 |
+
label: str | None = None,
|
| 342 |
+
show_label: bool = True,
|
| 343 |
+
interactive: bool | None = None,
|
| 344 |
+
visible: bool = True,
|
| 345 |
+
elem_id: str | None = None,
|
| 346 |
+
mirror_webcam: bool = True,
|
| 347 |
+
include_audio: bool | None = None,
|
| 348 |
+
**kwargs,
|
| 349 |
+
):
|
| 350 |
+
super().__init__(
|
| 351 |
+
value=value,
|
| 352 |
+
format=format,
|
| 353 |
+
source=source,
|
| 354 |
+
label=label,
|
| 355 |
+
show_label=show_label,
|
| 356 |
+
interactive=interactive,
|
| 357 |
+
visible=visible,
|
| 358 |
+
elem_id=elem_id,
|
| 359 |
+
mirror_webcam=mirror_webcam,
|
| 360 |
+
include_audio=include_audio,
|
| 361 |
+
**kwargs,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class Microphone(components.Audio):
|
| 366 |
+
"""
|
| 367 |
+
Sets: source="microphone"
|
| 368 |
+
"""
|
| 369 |
+
|
| 370 |
+
is_template = True
|
| 371 |
+
|
| 372 |
+
def __init__(
|
| 373 |
+
self,
|
| 374 |
+
value: str | tuple[int, np.ndarray] | Callable | None = None,
|
| 375 |
+
*,
|
| 376 |
+
source: str = "microphone",
|
| 377 |
+
type: str = "numpy",
|
| 378 |
+
label: str | None = None,
|
| 379 |
+
show_label: bool = True,
|
| 380 |
+
interactive: bool | None = None,
|
| 381 |
+
visible: bool = True,
|
| 382 |
+
streaming: bool = False,
|
| 383 |
+
elem_id: str | None = None,
|
| 384 |
+
**kwargs,
|
| 385 |
+
):
|
| 386 |
+
super().__init__(
|
| 387 |
+
value=value,
|
| 388 |
+
source=source,
|
| 389 |
+
type=type,
|
| 390 |
+
label=label,
|
| 391 |
+
show_label=show_label,
|
| 392 |
+
interactive=interactive,
|
| 393 |
+
visible=visible,
|
| 394 |
+
streaming=streaming,
|
| 395 |
+
elem_id=elem_id,
|
| 396 |
+
**kwargs,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class Files(components.File):
|
| 401 |
+
"""
|
| 402 |
+
Sets: file_count="multiple"
|
| 403 |
+
"""
|
| 404 |
+
|
| 405 |
+
is_template = True
|
| 406 |
+
|
| 407 |
+
def __init__(
|
| 408 |
+
self,
|
| 409 |
+
value: str | list[str] | Callable | None = None,
|
| 410 |
+
*,
|
| 411 |
+
file_count: str = "multiple",
|
| 412 |
+
type: str = "file",
|
| 413 |
+
label: str | None = None,
|
| 414 |
+
show_label: bool = True,
|
| 415 |
+
interactive: bool | None = None,
|
| 416 |
+
visible: bool = True,
|
| 417 |
+
elem_id: str | None = None,
|
| 418 |
+
**kwargs,
|
| 419 |
+
):
|
| 420 |
+
super().__init__(
|
| 421 |
+
value=value,
|
| 422 |
+
file_count=file_count,
|
| 423 |
+
type=type,
|
| 424 |
+
label=label,
|
| 425 |
+
show_label=show_label,
|
| 426 |
+
interactive=interactive,
|
| 427 |
+
visible=visible,
|
| 428 |
+
elem_id=elem_id,
|
| 429 |
+
**kwargs,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class Numpy(components.Dataframe):
|
| 434 |
+
"""
|
| 435 |
+
Sets: type="numpy"
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
is_template = True
|
| 439 |
+
|
| 440 |
+
def __init__(
|
| 441 |
+
self,
|
| 442 |
+
value: list[list[Any]] | Callable | None = None,
|
| 443 |
+
*,
|
| 444 |
+
headers: list[str] | None = None,
|
| 445 |
+
row_count: int | tuple[int, str] = (1, "dynamic"),
|
| 446 |
+
col_count: int | tuple[int, str] | None = None,
|
| 447 |
+
datatype: str | list[str] = "str",
|
| 448 |
+
type: str = "numpy",
|
| 449 |
+
max_rows: int | None = 20,
|
| 450 |
+
max_cols: int | None = None,
|
| 451 |
+
overflow_row_behaviour: str = "paginate",
|
| 452 |
+
label: str | None = None,
|
| 453 |
+
show_label: bool = True,
|
| 454 |
+
interactive: bool | None = None,
|
| 455 |
+
visible: bool = True,
|
| 456 |
+
elem_id: str | None = None,
|
| 457 |
+
wrap: bool = False,
|
| 458 |
+
**kwargs,
|
| 459 |
+
):
|
| 460 |
+
super().__init__(
|
| 461 |
+
value=value,
|
| 462 |
+
headers=headers,
|
| 463 |
+
row_count=row_count,
|
| 464 |
+
col_count=col_count,
|
| 465 |
+
datatype=datatype,
|
| 466 |
+
type=type,
|
| 467 |
+
max_rows=max_rows,
|
| 468 |
+
max_cols=max_cols,
|
| 469 |
+
overflow_row_behaviour=overflow_row_behaviour,
|
| 470 |
+
label=label,
|
| 471 |
+
show_label=show_label,
|
| 472 |
+
interactive=interactive,
|
| 473 |
+
visible=visible,
|
| 474 |
+
elem_id=elem_id,
|
| 475 |
+
wrap=wrap,
|
| 476 |
+
**kwargs,
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class Matrix(components.Dataframe):
|
| 481 |
+
"""
|
| 482 |
+
Sets: type="array"
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
is_template = True
|
| 486 |
+
|
| 487 |
+
def __init__(
|
| 488 |
+
self,
|
| 489 |
+
value: list[list[Any]] | Callable | None = None,
|
| 490 |
+
*,
|
| 491 |
+
headers: list[str] | None = None,
|
| 492 |
+
row_count: int | tuple[int, str] = (1, "dynamic"),
|
| 493 |
+
col_count: int | tuple[int, str] | None = None,
|
| 494 |
+
datatype: str | list[str] = "str",
|
| 495 |
+
type: str = "array",
|
| 496 |
+
max_rows: int | None = 20,
|
| 497 |
+
max_cols: int | None = None,
|
| 498 |
+
overflow_row_behaviour: str = "paginate",
|
| 499 |
+
label: str | None = None,
|
| 500 |
+
show_label: bool = True,
|
| 501 |
+
interactive: bool | None = None,
|
| 502 |
+
visible: bool = True,
|
| 503 |
+
elem_id: str | None = None,
|
| 504 |
+
wrap: bool = False,
|
| 505 |
+
**kwargs,
|
| 506 |
+
):
|
| 507 |
+
super().__init__(
|
| 508 |
+
value=value,
|
| 509 |
+
headers=headers,
|
| 510 |
+
row_count=row_count,
|
| 511 |
+
col_count=col_count,
|
| 512 |
+
datatype=datatype,
|
| 513 |
+
type=type,
|
| 514 |
+
max_rows=max_rows,
|
| 515 |
+
max_cols=max_cols,
|
| 516 |
+
overflow_row_behaviour=overflow_row_behaviour,
|
| 517 |
+
label=label,
|
| 518 |
+
show_label=show_label,
|
| 519 |
+
interactive=interactive,
|
| 520 |
+
visible=visible,
|
| 521 |
+
elem_id=elem_id,
|
| 522 |
+
wrap=wrap,
|
| 523 |
+
**kwargs,
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class List(components.Dataframe):
|
| 528 |
+
"""
|
| 529 |
+
Sets: type="array", col_count=1
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
is_template = True
|
| 533 |
+
|
| 534 |
+
def __init__(
|
| 535 |
+
self,
|
| 536 |
+
value: list[list[Any]] | Callable | None = None,
|
| 537 |
+
*,
|
| 538 |
+
headers: list[str] | None = None,
|
| 539 |
+
row_count: int | tuple[int, str] = (1, "dynamic"),
|
| 540 |
+
col_count: int | tuple[int, str] = 1,
|
| 541 |
+
datatype: str | list[str] = "str",
|
| 542 |
+
type: str = "array",
|
| 543 |
+
max_rows: int | None = 20,
|
| 544 |
+
max_cols: int | None = None,
|
| 545 |
+
overflow_row_behaviour: str = "paginate",
|
| 546 |
+
label: str | None = None,
|
| 547 |
+
show_label: bool = True,
|
| 548 |
+
interactive: bool | None = None,
|
| 549 |
+
visible: bool = True,
|
| 550 |
+
elem_id: str | None = None,
|
| 551 |
+
wrap: bool = False,
|
| 552 |
+
**kwargs,
|
| 553 |
+
):
|
| 554 |
+
super().__init__(
|
| 555 |
+
value=value,
|
| 556 |
+
headers=headers,
|
| 557 |
+
row_count=row_count,
|
| 558 |
+
col_count=col_count,
|
| 559 |
+
datatype=datatype,
|
| 560 |
+
type=type,
|
| 561 |
+
max_rows=max_rows,
|
| 562 |
+
max_cols=max_cols,
|
| 563 |
+
overflow_row_behaviour=overflow_row_behaviour,
|
| 564 |
+
label=label,
|
| 565 |
+
show_label=show_label,
|
| 566 |
+
interactive=interactive,
|
| 567 |
+
visible=visible,
|
| 568 |
+
elem_id=elem_id,
|
| 569 |
+
wrap=wrap,
|
| 570 |
+
**kwargs,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
Mic = Microphone
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Column-2853eb31.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
div.svelte-vt1mxs{display:flex;position:relative;flex-direction:column}div.svelte-vt1mxs>*,div.svelte-vt1mxs>.form>*{width:var(--size-full)}.gap.svelte-vt1mxs{gap:var(--layout-gap)}.hide.svelte-vt1mxs{display:none}.compact.svelte-vt1mxs>*,.compact.svelte-vt1mxs .box{border-radius:0}.compact.svelte-vt1mxs,.panel.svelte-vt1mxs{border:solid var(--panel-border-width) var(--panel-border-color);border-radius:var(--container-radius);background:var(--panel-background-fill);padding:var(--spacing-lg)}
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Copy-143d56db.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import{S as p,i as c,s as h,B as a,C as e,g as u,E as i,F as n,q as g}from"./index-188ef5e8.js";function v(l){let t,s;return{c(){t=a("svg"),s=a("polyline"),e(s,"points","20 6 9 17 4 12"),e(t,"xmlns","http://www.w3.org/2000/svg"),e(t,"width","100%"),e(t,"height","100%"),e(t,"viewBox","0 0 24 24"),e(t,"fill","none"),e(t,"stroke","currentColor"),e(t,"stroke-width","3"),e(t,"stroke-linecap","round"),e(t,"stroke-linejoin","round")},m(o,r){u(o,t,r),i(t,s)},p:n,i:n,o:n,d(o){o&&g(t)}}}class m extends p{constructor(t){super(),c(this,t,null,v,h,{})}}function w(l){let t,s,o;return{c(){t=a("svg"),s=a("path"),o=a("path"),e(s,"fill","currentColor"),e(s,"d","M28 10v18H10V10h18m0-2H10a2 2 0 0 0-2 2v18a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2Z"),e(o,"fill","currentColor"),e(o,"d","M4 18H2V4a2 2 0 0 1 2-2h14v2H4Z"),e(t,"xmlns","http://www.w3.org/2000/svg"),e(t,"width","100%"),e(t,"height","100%"),e(t,"viewBox","0 0 32 32")},m(r,d){u(r,t,d),i(t,s),i(t,o)},p:n,i:n,o:n,d(r){r&&g(t)}}}class x extends p{constructor(t){super(),c(this,t,null,w,h,{})}}export{x as C,m as a};
|
| 2 |
+
//# sourceMappingURL=Copy-143d56db.js.map
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Form-68b374ed.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import{S as m,i as c,s as r,a4 as d,G as g,C as h,M as u,D as f,g as w,a6 as b,a7 as v,a8 as F,p as q,t as C,q as S}from"./index-188ef5e8.js";function y(n){let s,l;const _=n[4].default,t=d(_,n,n[3],null);return{c(){s=g("div"),t&&t.c(),h(s,"class","form svelte-b6y5bg"),u(s,"hidden",!n[0]),f(s,"flex-grow",n[1]),f(s,"min-width",`calc(min(${n[2]}px, 100%))`)},m(e,i){w(e,s,i),t&&t.m(s,null),l=!0},p(e,[i]){t&&t.p&&(!l||i&8)&&b(t,_,e,e[3],l?F(_,e[3],i,null):v(e[3]),null),(!l||i&1)&&u(s,"hidden",!e[0]),i&2&&f(s,"flex-grow",e[1]),i&4&&f(s,"min-width",`calc(min(${e[2]}px, 100%))`)},i(e){l||(q(t,e),l=!0)},o(e){C(t,e),l=!1},d(e){e&&S(s),t&&t.d(e)}}}function D(n,s,l){let{$$slots:_={},$$scope:t}=s,{visible:e=!0}=s,{scale:i=1}=s,{min_width:o=0}=s;return n.$$set=a=>{"visible"in a&&l(0,e=a.visible),"scale"in a&&l(1,i=a.scale),"min_width"in a&&l(2,o=a.min_width),"$$scope"in a&&l(3,t=a.$$scope)},[e,i,o,t,_]}class M extends m{constructor(s){super(),c(this,s,D,y,r,{visible:0,scale:1,min_width:2})}}export{M as F};
|
| 2 |
+
//# sourceMappingURL=Form-68b374ed.js.map
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Info-b7dfbb56.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"Info-b7dfbb56.js","sources":["../../../../js/atoms/src/Info.svelte"],"sourcesContent":["<div>\n\t<slot />\n</div>\n\n<style>\n\tdiv {\n\t\tmargin-bottom: var(--spacing-lg);\n\t\tcolor: var(--block-info-text-color);\n\t\tfont-weight: var(--block-info-text-weight);\n\t\tfont-size: var(--block-info-text-size);\n\t\tline-height: var(--line-sm);\n\t}\n</style>\n"],"names":["insert","target","div","anchor"],"mappings":"+RAAAA,EAEKC,EAAAC,EAAAC,CAAA"}
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Caligraphic-Regular-3398dd02.woff
ADDED
|
Binary file (7.66 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Fraktur-Regular-5e28753b.woff
ADDED
|
Binary file (13.2 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Main-Bold-c76c5d69.woff
ADDED
|
Binary file (29.9 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Main-Italic-0d85ae7c.ttf
ADDED
|
Binary file (33.6 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Main-Italic-97479ca6.woff2
ADDED
|
Binary file (17 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Math-BoldItalic-850c0af5.woff
ADDED
|
Binary file (18.7 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Math-Italic-8a8d2445.woff
ADDED
|
Binary file (18.7 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Size3-Regular-500e04d5.ttf
ADDED
|
Binary file (7.59 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/KaTeX_Size4-Regular-99f9c675.woff
ADDED
|
Binary file (5.98 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/Model3D-98fc2b2c.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.gallery.svelte-1ayixqk{padding:var(--size-1) var(--size-2)}
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/TabItem.svelte_svelte_type_style_lang-f9698472.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"TabItem.svelte_svelte_type_style_lang-f9698472.js","sources":["../../../../js/tabs/src/Tabs.svelte"],"sourcesContent":["<script context=\"module\">\n\texport const TABS = {};\n</script>\n\n<script lang=\"ts\">\n\timport { setContext, createEventDispatcher, tick } from \"svelte\";\n\timport { writable } from \"svelte/store\";\n\timport type { SelectData } from \"@gradio/utils\";\n\n\tinterface Tab {\n\t\tname: string;\n\t\tid: object;\n\t}\n\n\texport let visible: boolean = true;\n\texport let elem_id: string = \"id\";\n\texport let elem_classes: Array<string> = [];\n\texport let selected: number | string | object;\n\n\tlet tabs: Array<Tab> = [];\n\n\tconst selected_tab = writable<false | object | number | string>(false);\n\tconst selected_tab_index = writable<number>(0);\n\tconst dispatch = createEventDispatcher<{\n\t\tchange: undefined;\n\t\tselect: SelectData;\n\t}>();\n\n\tsetContext(TABS, {\n\t\tregister_tab: (tab: Tab) => {\n\t\t\ttabs.push({ name: tab.name, id: tab.id });\n\t\t\tselected_tab.update((current) => current ?? tab.id);\n\t\t\ttabs = tabs;\n\t\t\treturn tabs.length - 1;\n\t\t},\n\t\tunregister_tab: (tab: Tab) => {\n\t\t\tconst i = tabs.findIndex((t) => t.id === tab.id);\n\t\t\ttabs.splice(i, 1);\n\t\t\tselected_tab.update((current) =>\n\t\t\t\tcurrent === tab.id ? tabs[i]?.id || tabs[tabs.length - 1]?.id : current\n\t\t\t);\n\t\t},\n\t\tselected_tab,\n\t\tselected_tab_index\n\t});\n\n\tfunction change_tab(id: object | string | number) {\n\t\tselected = id;\n\t\t$selected_tab = id;\n\t\t$selected_tab_index = tabs.findIndex((t) => t.id === id);\n\t\tdispatch(\"change\");\n\t}\n\n\t$: selected !== null && change_tab(selected);\n</script>\n\n<div class=\"tabs {elem_classes.join(' ')}\" class:hide={!visible} id={elem_id}>\n\t<div class=\"tab-nav scroll-hide\">\n\t\t{#each tabs as t, i (t.id)}\n\t\t\t{#if t.id === $selected_tab}\n\t\t\t\t<button class=\"selected\">\n\t\t\t\t\t{t.name}\n\t\t\t\t</button>\n\t\t\t{:else}\n\t\t\t\t<button\n\t\t\t\t\ton:click={() => {\n\t\t\t\t\t\tchange_tab(t.id);\n\t\t\t\t\t\tdispatch(\"select\", { value: t.name, index: i });\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t{t.name}\n\t\t\t\t</button>\n\t\t\t{/if}\n\t\t{/each}\n\t</div>\n\t<slot />\n</div>\n\n<style>\n\t.tabs {\n\t\tposition: relative;\n\t}\n\n\t.hide {\n\t\tdisplay: none;\n\t}\n\n\t.tab-nav {\n\t\tdisplay: flex;\n\t\tposition: relative;\n\t\tflex-wrap: wrap;\n\t\tborder-bottom: 1px solid var(--border-color-primary);\n\t}\n\n\tbutton {\n\t\tmargin-bottom: -1px;\n\t\tborder: 1px solid transparent;\n\t\tborder-color: transparent;\n\t\tborder-bottom: none;\n\t\tborder-top-right-radius: var(--container-radius);\n\t\tborder-top-left-radius: var(--container-radius);\n\t\tpadding: var(--size-1) var(--size-4);\n\t\tcolor: var(--body-text-color-subdued);\n\t\tfont-weight: var(--section-header-text-weight);\n\t\tfont-size: var(--section-header-text-size);\n\t}\n\n\tbutton:hover {\n\t\tcolor: var(--body-text-color);\n\t}\n\t.selected {\n\t\tborder-color: var(--border-color-primary);\n\t\tbackground: var(--background-fill-primary);\n\t\tcolor: var(--body-text-color);\n\t}\n\n\t.bar {\n\t\tdisplay: block;\n\t\tposition: absolute;\n\t\tbottom: -2px;\n\t\tleft: 0;\n\t\tz-index: 999;\n\t\tbackground: var(--background-fill-primary);\n\t\twidth: 100%;\n\t\theight: 2px;\n\t\tcontent: \"\";\n\t}\n</style>\n"],"names":["t0_value","ctx","insert","target","button","anchor","dirty","set_data","t0","create_if_block","get_key","i","div1","append","div0","TABS","visible","$$props","elem_id","elem_classes","selected","tabs","selected_tab","writable","selected_tab_index","dispatch","createEventDispatcher","setContext","tab","current","t","change_tab","id","$$invalidate","set_store_value","$selected_tab","$selected_tab_index"],"mappings":"mTAsEMA,EAAAC,MAAE,KAAI,6HANRC,EAOQC,EAAAC,EAAAC,CAAA,uDADNC,EAAA,GAAAN,KAAAA,EAAAC,MAAE,KAAI,KAAAM,EAAAC,EAAAR,CAAA,+CATNA,EAAAC,MAAE,KAAI,2FADRC,EAEQC,EAAAC,EAAAC,CAAA,wBADNC,EAAA,GAAAN,KAAAA,EAAAC,MAAE,KAAI,KAAAM,EAAAC,EAAAR,CAAA,iEAFJC,EAAC,EAAA,EAAC,KAAOA,EAAa,CAAA,EAAAQ,oRADrBR,EAAI,CAAA,EAAU,MAAAS,EAAAT,GAAAA,MAAE,mBAArB,OAAIU,GAAA,EAAA,kPAFUV,EAAY,CAAA,EAAC,KAAK,GAAG,EAAA,gBAAA,WAA8BA,EAAO,CAAA,CAAA,cAApBA,EAAO,CAAA,CAAA,UAA/DC,EAoBKC,EAAAS,EAAAP,CAAA,EAnBJQ,EAiBKD,EAAAE,CAAA,kGAhBGb,EAAI,CAAA,mIAFKA,EAAY,CAAA,EAAC,KAAK,GAAG,EAAA,uDAA8BA,EAAO,CAAA,CAAA,yBAApBA,EAAO,CAAA,CAAA,gHAvDjDc,EAAI,CAAA,uDAaN,CAAA,QAAAC,EAAmB,EAAI,EAAAC,EACvB,CAAA,QAAAC,EAAkB,IAAI,EAAAD,GACtB,aAAAE,EAAY,EAAA,EAAAF,GACZ,SAAAG,CAAkC,EAAAH,EAEzCI,EAAI,CAAA,QAEFC,EAAeC,EAA2C,EAAK,2BAC/DC,EAAqBD,EAAiB,CAAC,sBACvC,MAAAE,EAAWC,IAKjBC,EAAWZ,EAAI,CACd,aAAea,IACdP,EAAK,KAAO,CAAA,KAAMO,EAAI,KAAM,GAAIA,EAAI,EAAE,CAAA,EACtCN,EAAa,OAAQO,GAAYA,GAAWD,EAAI,EAAE,SAE3CP,EAAK,OAAS,GAEtB,eAAiBO,GAAQ,CAClB,MAAAjB,EAAIU,EAAK,UAAWS,GAAMA,EAAE,KAAOF,EAAI,EAAE,EAC/CP,EAAK,OAAOV,EAAG,CAAC,EAChBW,EAAa,OAAQO,GACpBA,IAAYD,EAAI,GAAKP,EAAKV,CAAC,GAAG,IAAMU,EAAKA,EAAK,OAAS,CAAC,GAAG,GAAKQ,CAAO,GAGzE,aAAAP,EACA,mBAAAE,IAGQ,SAAAO,EAAWC,EAA4B,CAC/CC,EAAA,EAAAb,EAAWY,CAAE,EACbE,EAAAZ,EAAAa,EAAgBH,EAAEG,CAAA,MAClBC,EAAsBf,EAAK,UAAWS,GAAMA,EAAE,KAAOE,CAAE,EAAAI,CAAA,EACvDX,EAAS,QAAQ,kBAgBbM,EAAWD,EAAE,EAAE,EACfL,EAAS,SAAQ,CAAI,MAAOK,EAAE,KAAM,MAAOnB,CAAC,CAAA,qOAd9CS,IAAa,MAAQW,EAAWX,CAAQ"}
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/UploadText-2a4d151d.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"UploadText-2a4d151d.js","sources":["../../../../js/app/src/components/UploadText.svelte"],"sourcesContent":["<script lang=\"ts\">\n\timport { _ } from \"svelte-i18n\";\n\n\texport let type: \"video\" | \"image\" | \"audio\" | \"file\" | \"csv\" = \"file\";\n\n\tconst defs = {\n\t\timage: \"interface.drop_image\",\n\t\tvideo: \"interface.drop_video\",\n\t\taudio: \"interface.drop_audio\",\n\t\tfile: \"interface.drop_file\",\n\t\tcsv: \"interface.drop_csv\"\n\t};\n</script>\n\n<div class=\"wrap\">\n\t{$_(defs[type])}\n\t<span class=\"or\">- {$_(\"or\")} -</span>\n\t{$_(\"interface.click_to_upload\")}\n</div>\n\n<style>\n\t.wrap {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tjustify-content: center;\n\t\tmin-height: var(--size-60);\n\t\tcolor: var(--block-label-text-color);\n\t\tline-height: var(--line-md);\n\t}\n\n\t.or {\n\t\tcolor: var(--body-text-color-subdued);\n\t}\n\n\t@media (--screen-md) {\n\t\t.wrap {\n\t\t\tfont-size: var(--text-lg);\n\t\t}\n\t}\n</style>\n"],"names":["ctx","t3_value","t6_value","insert","target","div","anchor","append","span","set_data","t0","t0_value","dirty","t3","t6","type","$$props","defs"],"mappings":"2LAeEA,EAAE,CAAA,EAACA,EAAI,CAAA,EAACA,EAAI,CAAA,CAAA,CAAA,EAAA,WACOC,EAAAD,KAAG,IAAI,EAAA,SAC1BE,EAAAF,KAAG,2BAA2B,EAAA,wDADd,IAAE,aAAU,IAAE,yFAFhCG,EAIKC,EAAAC,EAAAC,CAAA,gBAFJC,EAAqCF,EAAAG,CAAA,2DADpCR,EAAE,CAAA,EAACA,EAAI,CAAA,EAACA,EAAI,CAAA,CAAA,CAAA,EAAA,KAAAS,EAAAC,EAAAC,CAAA,EACOC,EAAA,GAAAX,KAAAA,EAAAD,KAAG,IAAI,EAAA,KAAAS,EAAAI,EAAAZ,CAAA,EAC1BW,EAAA,GAAAV,KAAAA,EAAAF,KAAG,2BAA2B,EAAA,KAAAS,EAAAK,EAAAZ,CAAA,qEAdpB,GAAA,CAAA,KAAAa,EAAqD,MAAM,EAAAC,QAEhEC,EAAI,CACT,MAAO,uBACP,MAAO,uBACP,MAAO,uBACP,KAAM,sBACN,IAAK"}
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/dsv-576afacd.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var D={},A={},E=34,m=10,R=13;function I(r){return new Function("d","return {"+r.map(function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'}).join(",")+"}")}function B(r,t){var e=I(r);return function(a,c){return t(e(a),c,r)}}function F(r){var t=Object.create(null),e=[];return r.forEach(function(a){for(var c in a)c in t||e.push(t[c]=c)}),e}function f(r,t){var e=r+"",a=e.length;return a<t?new Array(t-a+1).join(0)+e:e}function L(r){return r<0?"-"+f(-r,6):r>9999?"+"+f(r,6):f(r,4)}function S(r){var t=r.getUTCHours(),e=r.getUTCMinutes(),a=r.getUTCSeconds(),c=r.getUTCMilliseconds();return isNaN(r)?"Invalid Date":L(r.getUTCFullYear())+"-"+f(r.getUTCMonth()+1,2)+"-"+f(r.getUTCDate(),2)+(c?"T"+f(t,2)+":"+f(e,2)+":"+f(a,2)+"."+f(c,3)+"Z":a?"T"+f(t,2)+":"+f(e,2)+":"+f(a,2)+"Z":e||t?"T"+f(t,2)+":"+f(e,2)+"Z":"")}function Z(r){var t=new RegExp('["'+r+`
|
| 2 |
+
\r]`),e=r.charCodeAt(0);function a(n,o){var s,i,u=c(n,function(h,l){if(s)return s(h,l-1);i=h,s=o?B(h,o):I(h)});return u.columns=i||[],u}function c(n,o){var s=[],i=n.length,u=0,h=0,l,v=i<=0,C=!1;n.charCodeAt(i-1)===m&&--i,n.charCodeAt(i-1)===R&&--i;function w(){if(v)return A;if(C)return C=!1,D;var j,d=u,p;if(n.charCodeAt(d)===E){for(;u++<i&&n.charCodeAt(u)!==E||n.charCodeAt(++u)===E;);return(j=u)>=i?v=!0:(p=n.charCodeAt(u++))===m?C=!0:p===R&&(C=!0,n.charCodeAt(u)===m&&++u),n.slice(d+1,j-1).replace(/""/g,'"')}for(;u<i;){if((p=n.charCodeAt(j=u++))===m)C=!0;else if(p===R)C=!0,n.charCodeAt(u)===m&&++u;else if(p!==e)continue;return n.slice(d,j)}return v=!0,n.slice(d,i)}for(;(l=w())!==A;){for(var T=[];l!==D&&l!==A;)T.push(l),l=w();o&&(T=o(T,h++))==null||s.push(T)}return s}function U(n,o){return n.map(function(s){return o.map(function(i){return g(s[i])}).join(r)})}function O(n,o){return o==null&&(o=F(n)),[o.map(g).join(r)].concat(U(n,o)).join(`
|
| 3 |
+
`)}function M(n,o){return o==null&&(o=F(n)),U(n,o).join(`
|
| 4 |
+
`)}function b(n){return n.map(N).join(`
|
| 5 |
+
`)}function N(n){return n.map(g).join(r)}function g(n){return n==null?"":n instanceof Date?S(n):t.test(n+="")?'"'+n.replace(/"/g,'""')+'"':n}return{parse:a,parseRows:c,format:O,formatBody:M,formatRows:b,formatRow:N,formatValue:g}}export{Z as d};
|
| 6 |
+
//# sourceMappingURL=dsv-576afacd.js.map
|
falcon/lib/python3.10/site-packages/gradio/templates/frontend/assets/index-0008c077.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"index-0008c077.js","sources":["../../../../js/icons/src/Music.svelte","../../../../node_modules/.pnpm/svelte-range-slider-pips@2.0.2/node_modules/svelte-range-slider-pips/src/RangePips.svelte","../../../../node_modules/.pnpm/svelte-range-slider-pips@2.0.2/node_modules/svelte-range-slider-pips/src/RangeSlider.svelte","../../../../js/audio/src/Audio.svelte","../../../../js/audio/src/StaticAudio.svelte","../../../../js/app/src/components/Audio/Audio.svelte","../../../../js/app/src/components/Audio/index.ts"],"sourcesContent":["<svg\n\txmlns=\"http://www.w3.org/2000/svg\"\n\twidth=\"100%\"\n\theight=\"100%\"\n\tviewBox=\"0 0 24 24\"\n\tfill=\"none\"\n\tstroke=\"currentColor\"\n\tstroke-width=\"1.5\"\n\tstroke-linecap=\"round\"\n\tstroke-linejoin=\"round\"\n\tclass=\"feather feather-music\"\n>\n\t<path d=\"M9 18V5l12-2v13\" />\n\t<circle cx=\"6\" cy=\"18\" r=\"3\" />\n\t<circle cx=\"18\" cy=\"16\" r=\"3\" />\n</svg>\n","<script>\n\n // range slider props\n export let range = false;\n export let min = 0;\n export let max = 100;\n export let step = 1;\n export let values = [(max + min) / 2];\n export let vertical = false;\n export let reversed = false;\n export let hoverable = true;\n export let disabled = false;\n\n // range pips / values props\n export let pipstep = undefined;\n export let all = true;\n export let first = undefined;\n export let last = undefined;\n export let rest = undefined;\n\n // formatting props\n export let prefix = \"\";\n export let suffix = \"\";\n export let formatter = (v,i) => v;\n\n // stylistic props\n export let focus = undefined;\n export let orientationStart = undefined;\n\n // methods\n export let percentOf = undefined;\n export let moveHandle = undefined;\n\n $: pipStep = pipstep || ((max - min) / step >= ( vertical ? 50 : 100 ) ? (max - min) / ( vertical ? 10 : 20 ) : 1);\n\n $: pipCount = parseInt((max - min) / (step * pipStep), 10);\n\n $: pipVal = function(val) {\n return min + val * step * pipStep;\n };\n\n $: isSelected = function(val) {\n return values.some(v => v === val);\n };\n\n $: inRange = function(val) {\n if (range === \"min\") {\n return values[0] > val;\n } else if (range === \"max\") {\n return values[0] < val;\n } else if (range) {\n return values[0] < val && values[1] > val;\n }\n };\n\n function labelClick(val) {\n moveHandle( undefined, val );\n }\n</script>\n\n<style>\n :global(.rangeSlider) {\n --pip: var(--range-pip, lightslategray);\n --pip-text: var(--range-pip-text, var(--pip));\n --pip-active: var(--range-pip-active, darkslategrey);\n --pip-active-text: var(--range-pip-active-text, var(--pip-active));\n --pip-hover: var(--range-pip-hover, darkslategrey);\n --pip-hover-text: var(--range-pip-hover-text, var(--pip-hover));\n --pip-in-range: var(--range-pip-in-range, var(--pip-active));\n --pip-in-range-text: var(--range-pip-in-range-text, var(--pip-active-text));\n }\n :global(.rangePips) {\n position: absolute;\n height: 1em;\n left: 0;\n right: 0;\n bottom: -1em;\n }\n :global(.rangePips.vertical) {\n height: auto;\n width: 1em;\n left: 100%;\n right: auto;\n top: 0;\n bottom: 0;\n }\n :global(.rangePips .pip) {\n height: 0.4em;\n position: absolute;\n top: 0.25em;\n width: 1px;\n white-space: nowrap;\n }\n :global(.rangePips.vertical .pip) {\n height: 1px;\n width: 0.4em;\n left: 0.25em;\n top: auto;\n bottom: auto;\n }\n :global(.rangePips .pipVal) {\n position: absolute;\n top: 0.4em;\n transform: translate(-50%, 25%);\n }\n :global(.rangePips.vertical .pipVal) {\n position: absolute;\n top: 0;\n left: 0.4em;\n transform: translate(25%, -50%);\n }\n :global(.rangePips .pip) {\n transition: all 0.15s ease;\n }\n :global(.rangePips .pipVal) {\n transition: all 0.15s ease, font-weight 0s linear;\n }\n :global(.rangePips .pip) {\n color: lightslategray;\n color: var(--pip-text);\n background-color: lightslategray;\n background-color: var(--pip);\n }\n :global(.rangePips .pip.selected) {\n color: darkslategrey;\n color: var(--pip-active-text);\n background-color: darkslategrey;\n background-color: var(--pip-active);\n }\n :global(.rangePips.hoverable:not(.disabled) .pip:hover) {\n color: darkslategrey;\n color: var(--pip-hover-text);\n background-color: darkslategrey;\n background-color: var(--pip-hover);\n }\n :global(.rangePips .pip.in-range) {\n color: darkslategrey;\n color: var(--pip-in-range-text);\n background-color: darkslategrey;\n background-color: var(--pip-in-range);\n }\n :global(.rangePips .pip.selected) {\n height: 0.75em;\n }\n :global(.rangePips.vertical .pip.selected) {\n height: 1px;\n width: 0.75em;\n }\n :global(.rangePips .pip.selected .pipVal) {\n font-weight: bold;\n top: 0.75em;\n }\n :global(.rangePips.vertical .pip.selected .pipVal) {\n top: 0;\n left: 0.75em;\n }\n :global(.rangePips.hoverable:not(.disabled) .pip:not(.selected):hover) {\n transition: none;\n }\n :global(.rangePips.hoverable:not(.disabled) .pip:not(.selected):hover .pipVal) {\n transition: none;\n font-weight: bold;\n }\n</style>\n\n<div \n class=\"rangePips\" \n class:disabled\n class:hoverable \n class:vertical \n class:reversed \n class:focus \n>\n {#if ( all && first !== false ) || first }\n <span\n class=\"pip first\"\n class:selected={isSelected(min)}\n class:in-range={inRange(min)}\n style=\"{orientationStart}: 0%;\"\n on:click={labelClick(min)}\n on:touchend|preventDefault={labelClick(min)}\n >\n {#if all === 'label' || first === 'label'}\n <span class=\"pipVal\">\n {#if prefix}<span class=\"pipVal-prefix\">{prefix}</span>{/if}{formatter(min,0,0)}{#if suffix}<span class=\"pipVal-suffix\">{suffix}</span>{/if}\n </span>\n {/if}\n </span>\n {/if}\n\n {#if ( all && rest !== false ) || rest}\n {#each Array(pipCount + 1) as _, i}\n {#if pipVal(i) !== min && pipVal(i) !== max}\n <span\n class=\"pip\"\n class:selected={isSelected(pipVal(i))}\n class:in-range={inRange(pipVal(i))}\n style=\"{orientationStart}: {percentOf(pipVal(i))}%;\"\n on:click={labelClick(pipVal(i))}\n on:touchend|preventDefault={labelClick(pipVal(i))}\n >\n {#if all === 'label' || rest === 'label'}\n <span class=\"pipVal\">\n {#if prefix}<span class=\"pipVal-prefix\">{prefix}</span>{/if}{formatter(pipVal(i),i,percentOf(pipVal(i)))}{#if suffix}<span class=\"pipVal-suffix\">{suffix}</span>{/if}\n </span>\n {/if}\n </span>\n {/if}\n {/each}\n {/if}\n\n {#if ( all && last !== false ) || last}\n <span\n class=\"pip last\"\n class:selected={isSelected(max)}\n class:in-range={inRange(max)}\n style=\"{orientationStart}: 100%;\"\n on:click={labelClick(max)}\n on:touchend|preventDefault={labelClick(max)}\n >\n {#if all === 'label' || last === 'label'}\n <span class=\"pipVal\">\n {#if prefix}<span class=\"pipVal-prefix\">{prefix}</span>{/if}{formatter(max,pipCount,100)}{#if suffix}<span class=\"pipVal-suffix\">{suffix}</span>{/if}\n </span>\n {/if}\n </span>\n {/if}\n \n</div>\n","<script>\n import { spring } from \"svelte/motion\";\n import { createEventDispatcher } from \"svelte\";\n import RangePips from \"./RangePips.svelte\";\n\n // dom references\n export let slider;\n\n // range slider props\n export let range = false;\n export let pushy = false;\n export let min = 0;\n export let max = 100;\n export let step = 1;\n export let values = [(max + min) / 2];\n export let vertical = false;\n export let float = false;\n export let reversed = false;\n export let hoverable = true;\n export let disabled = false;\n\n // range pips / values props\n export let pips = false;\n export let pipstep = undefined;\n export let all = undefined;\n export let first = undefined;\n export let last = undefined;\n export let rest = undefined;\n\n // formatting props\n export let id = undefined;\n export let prefix = \"\";\n export let suffix = \"\";\n export let formatter = (v,i,p) => v;\n export let handleFormatter = formatter;\n\n // stylistic props\n export let precision = 2;\n export let springValues = { stiffness: 0.15, damping: 0.4 };\n\n // prepare dispatched events\n const dispatch = createEventDispatcher();\n\n // state management\n let valueLength = 0;\n let focus = false;\n let handleActivated = false;\n let handlePressed = false;\n let keyboardActive = false;\n let activeHandle = values.length - 1;\n let startValue;\n let previousValue;\n\n // copy the initial values in to a spring function which\n // will update every time the values array is modified\n\n let springPositions;\n\n $: {\n\n // check that \"values\" is an array, or set it as array\n // to prevent any errors in springs, or range trimming\n if ( !Array.isArray( values ) ) {\n values = [(max + min) / 2];\n console.error( \"'values' prop should be an Array (https://github.com/simeydotme/svelte-range-slider-pips#slider-props)\" );\n }\n // trim the range so it remains as a min/max (only 2 handles)\n // and also align the handles to the steps\n values = trimRange(values.map((v) => alignValueToStep(v)));\n\n // check if the valueLength (length of values[]) has changed,\n // because if so we need to re-seed the spring function with the\n // new values array.\n if ( valueLength !== values.length ) {\n // set the initial spring values when the slider initialises,\n // or when values array length has changed\n springPositions = spring(values.map((v) => percentOf(v)), springValues );\n } else {\n // update the value of the spring function for animated handles\n // whenever the values has updated\n springPositions.set(values.map((v) => percentOf(v)));\n }\n // set the valueLength for the next check\n valueLength = values.length;\n };\n\n /**\n * take in a value, and then calculate that value's percentage\n * of the overall range (min-max);\n * @param {number} val the value we're getting percent for\n * @return {number} the percentage value\n **/\n $: percentOf = function (val) {\n let perc = ((val - min) / (max - min)) * 100;\n if (isNaN(perc) || perc <= 0) {\n return 0;\n } else if (perc >= 100) {\n return 100;\n } else {\n return parseFloat(perc.toFixed(precision));\n }\n };\n\n /**\n * clamp a value from the range so that it always\n * falls within the min/max values\n * @param {number} val the value to clamp\n * @return {number} the value after it's been clamped\n **/\n $: clampValue = function (val) {\n // return the min/max if outside of that range\n return val <= min ? min : val >= max ? max : val;\n };\n\n /**\n * align the value with the steps so that it\n * always sits on the closest (above/below) step\n * @param {number} val the value to align\n * @return {number} the value after it's been aligned\n **/\n $: alignValueToStep = function (val) {\n // sanity check for performance\n if (val <= min) {\n return min;\n } else if (val >= max) {\n return max;\n }\n\n // find the middle-point between steps\n // and see if the value is closer to the\n // next step, or previous step\n let remainder = (val - min) % step;\n let aligned = val - remainder;\n if (Math.abs(remainder) * 2 >= step) {\n aligned += remainder > 0 ? step : -step;\n }\n // make sure the value is within acceptable limits\n aligned = clampValue(aligned);\n // make sure the returned value is set to the precision desired\n // this is also because javascript often returns weird floats\n // when dealing with odd numbers and percentages\n\n return parseFloat(aligned.toFixed(precision));\n };\n\n /**\n * the orientation of the handles/pips based on the\n * input values of vertical and reversed\n **/\n $: orientationStart = vertical ? reversed ? 'top' : 'bottom' : reversed ? 'right' : 'left';\n $: orientationEnd = vertical ? reversed ? 'bottom' : 'top' : reversed ? 'left' : 'right';\n\n /**\n * helper func to get the index of an element in it's DOM container\n * @param {object} el dom object reference we want the index of\n * @returns {number} the index of the input element\n **/\n function index(el) {\n if (!el) return -1;\n var i = 0;\n while ((el = el.previousElementSibling)) {\n i++;\n }\n return i;\n }\n\n /**\n * normalise a mouse or touch event to return the\n * client (x/y) object for that event\n * @param {event} e a mouse/touch event to normalise\n * @returns {object} normalised event client object (x,y)\n **/\n function normalisedClient(e) {\n if (e.type.includes(\"touch\")) {\n return e.touches[0];\n } else {\n return e;\n }\n }\n\n /**\n * check if an element is a handle on the slider\n * @param {object} el dom object reference we want to check\n * @returns {boolean}\n **/\n function targetIsHandle(el) {\n const handles = slider.querySelectorAll(\".handle\");\n const isHandle = Array.prototype.includes.call(handles, el);\n const isChild = Array.prototype.some.call(handles, (e) => e.contains(el));\n return isHandle || isChild;\n }\n\n /**\n * trim the values array based on whether the property\n * for 'range' is 'min', 'max', or truthy. This is because we\n * do not want more than one handle for a min/max range, and we do\n * not want more than two handles for a true range.\n * @param {array} values the input values for the rangeSlider\n * @return {array} the range array for creating a rangeSlider\n **/\n function trimRange(values) {\n if (range === \"min\" || range === \"max\") {\n return values.slice(0, 1);\n } else if (range) {\n return values.slice(0, 2);\n } else {\n return values;\n }\n }\n\n /**\n * helper to return the slider dimensions for finding\n * the closest handle to user interaction\n * @return {object} the range slider DOM client rect\n **/\n function getSliderDimensions() {\n return slider.getBoundingClientRect();\n }\n\n /**\n * helper to return closest handle to user interaction\n * @param {object} clientPos the client{x,y} positions to check against\n * @return {number} the index of the closest handle to clientPos\n **/\n function getClosestHandle(clientPos) {\n // first make sure we have the latest dimensions\n // of the slider, as it may have changed size\n const dims = getSliderDimensions();\n // calculate the interaction position, percent and value\n let handlePos = 0;\n let handlePercent = 0;\n let handleVal = 0;\n if (vertical) {\n handlePos = clientPos.clientY - dims.top;\n handlePercent = (handlePos / dims.height) * 100;\n handlePercent = reversed ? handlePercent : 100 - handlePercent;\n } else {\n handlePos = clientPos.clientX - dims.left;\n handlePercent = (handlePos / dims.width) * 100;\n handlePercent = reversed ? 100 - handlePercent : handlePercent;\n }\n handleVal = ((max - min) / 100) * handlePercent + min;\n\n let closest;\n\n // if we have a range, and the handles are at the same\n // position, we want a simple check if the interaction\n // value is greater than return the second handle\n if (range === true && values[0] === values[1]) {\n if (handleVal > values[1]) {\n return 1;\n } else {\n return 0;\n }\n // if there are multiple handles, and not a range, then\n // we sort the handles values, and return the first one closest\n // to the interaction value\n } else {\n closest = values.indexOf(\n [...values].sort((a, b) => Math.abs(handleVal - a) - Math.abs(handleVal - b))[0]\n );\n }\n return closest;\n }\n\n /**\n * take the interaction position on the slider, convert\n * it to a value on the range, and then send that value\n * through to the moveHandle() method to set the active\n * handle's position\n * @param {object} clientPos the client{x,y} of the interaction\n **/\n function handleInteract(clientPos) {\n // first make sure we have the latest dimensions\n // of the slider, as it may have changed size\n const dims = getSliderDimensions();\n // calculate the interaction position, percent and value\n let handlePos = 0;\n let handlePercent = 0;\n let handleVal = 0;\n if (vertical) {\n handlePos = clientPos.clientY - dims.top;\n handlePercent = (handlePos / dims.height) * 100;\n handlePercent = reversed ? handlePercent : 100 - handlePercent;\n } else {\n handlePos = clientPos.clientX - dims.left;\n handlePercent = (handlePos / dims.width) * 100;\n handlePercent = reversed ? 100 - handlePercent : handlePercent;\n }\n handleVal = ((max - min) / 100) * handlePercent + min;\n // move handle to the value\n moveHandle(activeHandle, handleVal);\n }\n\n /**\n * move a handle to a specific value, respecting the clamp/align rules\n * @param {number} index the index of the handle we want to move\n * @param {number} value the value to move the handle to\n * @return {number} the value that was moved to (after alignment/clamping)\n **/\n function moveHandle(index, value) {\n // align & clamp the value so we're not doing extra\n // calculation on an out-of-range value down below\n value = alignValueToStep(value);\n // use the active handle if handle index is not provided\n if ( typeof index === 'undefined' ) {\n index = activeHandle;\n }\n // if this is a range slider perform special checks\n if (range) {\n // restrict the handles of a range-slider from\n // going past one-another unless \"pushy\" is true\n if (index === 0 && value > values[1]) {\n if (pushy) {\n values[1] = value;\n } else {\n value = values[1];\n }\n } else if (index === 1 && value < values[0]) {\n if (pushy) {\n values[0] = value;\n } else {\n value = values[0];\n }\n }\n }\n\n // if the value has changed, update it\n if (values[index] !== value) {\n values[index] = value;\n }\n\n // fire the change event when the handle moves,\n // and store the previous value for the next time\n if (previousValue !== value) {\n eChange();\n previousValue = value;\n }\n return value;\n }\n\n /**\n * helper to find the beginning range value for use with css style\n * @param {array} values the input values for the rangeSlider\n * @return {number} the beginning of the range\n **/\n function rangeStart(values) {\n if (range === \"min\") {\n return 0;\n } else {\n return values[0];\n }\n }\n\n /**\n * helper to find the ending range value for use with css style\n * @param {array} values the input values for the rangeSlider\n * @return {number} the end of the range\n **/\n function rangeEnd(values) {\n if (range === \"max\") {\n return 0;\n } else if (range === \"min\") {\n return 100 - values[0];\n } else {\n return 100 - values[1];\n }\n }\n\n /**\n * when the user has unfocussed (blurred) from the\n * slider, deactivate all handles\n * @param {event} e the event from browser\n **/\n function sliderBlurHandle(e) {\n if (keyboardActive) {\n focus = false;\n handleActivated = false;\n handlePressed = false;\n }\n }\n\n /**\n * when the user focusses the handle of a slider\n * set it to be active\n * @param {event} e the event from browser\n **/\n function sliderFocusHandle(e) {\n if ( !disabled ) {\n activeHandle = index(e.target);\n focus = true;\n }\n }\n\n /**\n * handle the keyboard accessible features by checking the\n * input type, and modfier key then moving handle by appropriate amount\n * @param {event} e the event from browser\n **/\n function sliderKeydown(e) {\n if ( !disabled ) {\n const handle = index(e.target);\n let jump = e.ctrlKey || e.metaKey || e.shiftKey ? step * 10 : step;\n let prevent = false;\n\n switch (e.key) {\n case \"PageDown\":\n jump *= 10;\n case \"ArrowRight\":\n case \"ArrowUp\":\n moveHandle(handle, values[handle] + jump);\n prevent = true;\n break;\n case \"PageUp\":\n jump *= 10;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n moveHandle(handle, values[handle] - jump);\n prevent = true;\n break;\n case \"Home\":\n moveHandle(handle, min);\n prevent = true;\n break;\n case \"End\":\n moveHandle(handle, max);\n prevent = true;\n break;\n }\n if (prevent) {\n e.preventDefault();\n e.stopPropagation();\n }\n }\n }\n\n /**\n * function to run when the user touches\n * down on the slider element anywhere\n * @param {event} e the event from browser\n **/\n function sliderInteractStart(e) {\n if ( !disabled ) {\n const el = e.target;\n const clientPos = normalisedClient(e);\n // set the closest handle as active\n focus = true;\n handleActivated = true;\n handlePressed = true;\n activeHandle = getClosestHandle(clientPos);\n\n // fire the start event\n startValue = previousValue = alignValueToStep(values[activeHandle]);\n eStart();\n\n // for touch devices we want the handle to instantly\n // move to the position touched for more responsive feeling\n if (e.type === \"touchstart\" && !el.matches(\".pipVal\")) {\n handleInteract(clientPos);\n }\n }\n }\n\n /**\n * function to run when the user stops touching\n * down on the slider element anywhere\n * @param {event} e the event from browser\n **/\n function sliderInteractEnd(e) {\n // fire the stop event for touch devices\n if (e.type === \"touchend\") {\n eStop();\n }\n handlePressed = false;\n }\n\n /**\n * unfocus the slider if the user clicked off of\n * it, somewhere else on the screen\n * @param {event} e the event from browser\n **/\n function bodyInteractStart(e) {\n keyboardActive = false;\n if (focus && e.target !== slider && !slider.contains(e.target)) {\n focus = false;\n }\n }\n\n /**\n * send the clientX through to handle the interaction\n * whenever the user moves acros screen while active\n * @param {event} e the event from browser\n **/\n function bodyInteract(e) {\n if ( !disabled ) {\n if (handleActivated) {\n handleInteract(normalisedClient(e));\n }\n }\n }\n\n /**\n * if user triggers mouseup on the body while\n * a handle is active (without moving) then we\n * trigger an interact event there\n * @param {event} e the event from browser\n **/\n function bodyMouseUp(e) {\n if ( !disabled ) {\n const el = e.target;\n // this only works if a handle is active, which can\n // only happen if there was sliderInteractStart triggered\n // on the slider, already\n if (handleActivated) {\n if (el === slider || slider.contains(el)) {\n focus = true;\n // don't trigger interact if the target is a handle (no need) or\n // if the target is a label (we want to move to that value from rangePips)\n if (!targetIsHandle(el) && !el.matches(\".pipVal\")) {\n handleInteract(normalisedClient(e));\n }\n }\n // fire the stop event for mouse device\n // when the body is triggered with an active handle\n eStop();\n }\n }\n handleActivated = false;\n handlePressed = false;\n }\n\n /**\n * if user triggers touchend on the body then we\n * defocus the slider completely\n * @param {event} e the event from browser\n **/\n function bodyTouchEnd(e) {\n handleActivated = false;\n handlePressed = false;\n }\n\n function bodyKeyDown(e) {\n if ( !disabled ) {\n if (e.target === slider || slider.contains(e.target)) {\n keyboardActive = true;\n }\n }\n }\n\n function eStart() {\n !disabled && dispatch(\"start\", {\n activeHandle,\n value: startValue,\n values: values.map((v) => alignValueToStep(v)),\n });\n }\n\n function eStop() {\n !disabled && dispatch(\"stop\", {\n activeHandle,\n startValue: startValue,\n value: values[activeHandle],\n values: values.map((v) => alignValueToStep(v)),\n });\n }\n\n function eChange() {\n !disabled && dispatch(\"change\", {\n activeHandle,\n startValue: startValue,\n previousValue:\n typeof previousValue === \"undefined\" ? startValue : previousValue,\n value: values[activeHandle],\n values: values.map((v) => alignValueToStep(v)),\n });\n }\n</script>\n\n<style>\n :global(.rangeSlider) {\n --slider: var(--range-slider, #d7dada);\n --handle-inactive: var(--range-handle-inactive, #99a2a2);\n --handle: var(--range-handle, #838de7);\n --handle-focus: var(--range-handle-focus, #4a40d4);\n --handle-border: var(--range-handle-border, var(--handle));\n --range-inactive: var(--range-range-inactive, var(--handle-inactive));\n --range: var(--range-range, var(--handle-focus));\n --float-inactive: var(--range-float-inactive, var(--handle-inactive));\n --float: var(--range-float, var(--handle-focus));\n --float-text: var(--range-float-text, white);\n }\n :global(.rangeSlider) {\n position: relative;\n border-radius: 100px;\n height: 0.5em;\n margin: 1em;\n transition: opacity 0.2s ease;\n user-select: none;\n }\n :global(.rangeSlider *) {\n user-select: none;\n }\n :global(.rangeSlider.pips) {\n margin-bottom: 1.8em;\n }\n :global(.rangeSlider.pip-labels) {\n margin-bottom: 2.8em;\n }\n :global(.rangeSlider.vertical) {\n display: inline-block;\n border-radius: 100px;\n width: 0.5em;\n min-height: 200px;\n }\n :global(.rangeSlider.vertical.pips) {\n margin-right: 1.8em;\n margin-bottom: 1em;\n }\n :global(.rangeSlider.vertical.pip-labels) {\n margin-right: 2.8em;\n margin-bottom: 1em;\n }\n :global(.rangeSlider .rangeHandle) {\n position: absolute;\n display: block;\n height: 1.4em;\n width: 1.4em;\n top: 0.25em;\n bottom: auto;\n transform: translateY(-50%) translateX(-50%);\n z-index: 2;\n }\n :global(.rangeSlider.reversed .rangeHandle) {\n transform: translateY(-50%) translateX(50%);\n }\n :global(.rangeSlider.vertical .rangeHandle) {\n left: 0.25em;\n top: auto;\n transform: translateY(50%) translateX(-50%);\n }\n :global(.rangeSlider.vertical.reversed .rangeHandle) {\n transform: translateY(-50%) translateX(-50%);\n }\n :global(.rangeSlider .rangeNub),\n :global(.rangeSlider .rangeHandle:before) {\n position: absolute;\n left: 0;\n top: 0;\n display: block;\n border-radius: 10em;\n height: 100%;\n width: 100%;\n transition: box-shadow 0.2s ease;\n }\n :global(.rangeSlider .rangeHandle:before) {\n content: \"\";\n left: 1px;\n top: 1px;\n bottom: 1px;\n right: 1px;\n height: auto;\n width: auto;\n box-shadow: 0 0 0 0px var(--handle-border);\n opacity: 0;\n }\n :global(.rangeSlider.hoverable:not(.disabled) .rangeHandle:hover:before) {\n box-shadow: 0 0 0 8px var(--handle-border);\n opacity: 0.2;\n }\n :global(.rangeSlider.hoverable:not(.disabled) .rangeHandle.press:before),\n :global(.rangeSlider.hoverable:not(.disabled) .rangeHandle.press:hover:before) {\n box-shadow: 0 0 0 12px var(--handle-border);\n opacity: 0.4;\n }\n :global(.rangeSlider.range:not(.min):not(.max) .rangeNub) {\n border-radius: 10em 10em 10em 1.6em;\n }\n :global(.rangeSlider.range .rangeHandle:nth-of-type(1) .rangeNub) {\n transform: rotate(-135deg);\n }\n :global(.rangeSlider.range .rangeHandle:nth-of-type(2) .rangeNub) {\n transform: rotate(45deg);\n }\n :global(.rangeSlider.range.reversed .rangeHandle:nth-of-type(1) .rangeNub) {\n transform: rotate(45deg);\n }\n :global(.rangeSlider.range.reversed .rangeHandle:nth-of-type(2) .rangeNub) {\n transform: rotate(-135deg);\n }\n :global(.rangeSlider.range.vertical .rangeHandle:nth-of-type(1) .rangeNub) {\n transform: rotate(135deg);\n }\n :global(.rangeSlider.range.vertical .rangeHandle:nth-of-type(2) .rangeNub) {\n transform: rotate(-45deg);\n }\n :global(.rangeSlider.range.vertical.reversed .rangeHandle:nth-of-type(1) .rangeNub) {\n transform: rotate(-45deg);\n }\n :global(.rangeSlider.range.vertical.reversed .rangeHandle:nth-of-type(2) .rangeNub) {\n transform: rotate(135deg);\n }\n :global(.rangeSlider .rangeFloat) {\n display: block;\n position: absolute;\n left: 50%;\n top: -0.5em;\n transform: translate(-50%, -100%);\n font-size: 1em;\n text-align: center;\n opacity: 0;\n pointer-events: none;\n white-space: nowrap;\n transition: all 0.2s ease;\n font-size: 0.9em;\n padding: 0.2em 0.4em;\n border-radius: 0.2em;\n }\n :global(.rangeSlider .rangeHandle.active .rangeFloat),\n :global(.rangeSlider.hoverable .rangeHandle:hover .rangeFloat) {\n opacity: 1;\n top: -0.2em;\n transform: translate(-50%, -100%);\n }\n :global(.rangeSlider .rangeBar) {\n position: absolute;\n display: block;\n transition: background 0.2s ease;\n border-radius: 1em;\n height: 0.5em;\n top: 0;\n user-select: none;\n z-index: 1;\n }\n :global(.rangeSlider.vertical .rangeBar) {\n width: 0.5em;\n height: auto;\n }\n :global(.rangeSlider) {\n background-color: #d7dada;\n background-color: var(--slider);\n }\n :global(.rangeSlider .rangeBar) {\n background-color: #99a2a2;\n background-color: var(--range-inactive);\n }\n :global(.rangeSlider.focus .rangeBar) {\n background-color: #838de7;\n background-color: var(--range);\n }\n :global(.rangeSlider .rangeNub) {\n background-color: #99a2a2;\n background-color: var(--handle-inactive);\n }\n :global(.rangeSlider.focus .rangeNub) {\n background-color: #838de7;\n background-color: var(--handle);\n }\n :global(.rangeSlider .rangeHandle.active .rangeNub) {\n background-color: #4a40d4;\n background-color: var(--handle-focus);\n }\n :global(.rangeSlider .rangeFloat) {\n color: white;\n color: var(--float-text);\n background-color: #99a2a2;\n background-color: var(--float-inactive);\n }\n :global(.rangeSlider.focus .rangeFloat) {\n background-color: #4a40d4;\n background-color: var(--float);\n }\n :global(.rangeSlider.disabled) {\n opacity: 0.5;\n }\n :global(.rangeSlider.disabled .rangeNub) {\n background-color: #d7dada;\n background-color: var(--slider);\n }\n</style>\n\n<div\n {id}\n bind:this={slider}\n class=\"rangeSlider\"\n class:range\n class:disabled\n class:hoverable\n class:vertical\n class:reversed\n class:focus\n class:min={range === 'min'}\n class:max={range === 'max'}\n class:pips\n class:pip-labels={all === 'label' || first === 'label' || last === 'label' || rest === 'label'}\n on:mousedown={sliderInteractStart}\n on:mouseup={sliderInteractEnd}\n on:touchstart|preventDefault={sliderInteractStart}\n on:touchend|preventDefault={sliderInteractEnd}\n>\n {#each values as value, index}\n <span\n role=\"slider\"\n class=\"rangeHandle\"\n class:active={focus && activeHandle === index}\n class:press={handlePressed && activeHandle === index}\n data-handle={index}\n on:blur={sliderBlurHandle}\n on:focus={sliderFocusHandle}\n on:keydown={sliderKeydown}\n style=\"{orientationStart}: {$springPositions[index]}%; z-index: {activeHandle === index ? 3 : 2};\"\n aria-valuemin={range === true && index === 1 ? values[0] : min}\n aria-valuemax={range === true && index === 0 ? values[1] : max}\n aria-valuenow={value}\n aria-valuetext=\"{prefix}{handleFormatter(value,index,percentOf(value))}{suffix}\"\n aria-orientation={vertical ? 'vertical' : 'horizontal'}\n aria-disabled={disabled}\n {disabled}\n tabindex=\"{ disabled ? -1 : 0 }\"\n >\n <span class=\"rangeNub\" />\n {#if float}\n <span class=\"rangeFloat\">\n {#if prefix}<span class=\"rangeFloat-prefix\">{prefix}</span>{/if}{handleFormatter(value,index,percentOf(value))}{#if suffix}<span class=\"rangeFloat-suffix\">{suffix}</span>{/if}\n </span>\n {/if}\n </span>\n {/each}\n {#if range}\n <span\n class=\"rangeBar\"\n style=\"{orientationStart}: {rangeStart($springPositions)}%; \n {orientationEnd}: {rangeEnd($springPositions)}%;\" />\n {/if}\n {#if pips}\n <RangePips\n {values}\n {min}\n {max}\n {step}\n {range}\n {vertical}\n {reversed}\n {orientationStart}\n {hoverable}\n {disabled}\n {all}\n {first}\n {last}\n {rest}\n {pipstep}\n {prefix}\n {suffix}\n {formatter}\n {focus}\n {percentOf}\n {moveHandle}\n />\n {/if}\n</div>\n\n<svelte:window\n on:mousedown={bodyInteractStart}\n on:touchstart={bodyInteractStart}\n on:mousemove={bodyInteract}\n on:touchmove={bodyInteract}\n on:mouseup={bodyMouseUp}\n on:touchend={bodyTouchEnd}\n on:keydown={bodyKeyDown} />\n","<script context=\"module\" lang=\"ts\">\n\timport type { FileData } from \"@gradio/upload\";\n\timport { Button } from \"@gradio/button\";\n\texport interface AudioData extends FileData {\n\t\tcrop_min?: number;\n\t\tcrop_max?: number;\n\t}\n</script>\n\n<script lang=\"ts\">\n\timport { onDestroy, createEventDispatcher, tick } from \"svelte\";\n\timport { Upload, ModifyUpload } from \"@gradio/upload\";\n\timport { BlockLabel } from \"@gradio/atoms\";\n\timport { Music } from \"@gradio/icons\";\n\t// @ts-ignore\n\timport Range from \"svelte-range-slider-pips\";\n\n\timport type { IBlobEvent, IMediaRecorder } from \"extendable-media-recorder\";\n\n\texport let value: null | { name: string; data: string } = null;\n\texport let label: string;\n\texport let show_label: boolean = true;\n\texport let name: string = \"\";\n\texport let source: \"microphone\" | \"upload\" | \"none\";\n\texport let pending: boolean = false;\n\texport let streaming: boolean = false;\n\texport let autoplay: boolean;\n\n\t// TODO: make use of this\n\t// export let type: \"normal\" | \"numpy\" = \"normal\";\n\n\tlet recording = false;\n\tlet recorder: IMediaRecorder;\n\tlet mode = \"\";\n\tlet header: Uint8Array | undefined = undefined;\n\tlet pending_stream: Array<Uint8Array> = [];\n\tlet submit_pending_stream_on_pending_end: boolean = false;\n\tlet player: HTMLAudioElement;\n\tlet inited = false;\n\tlet crop_values = [0, 100];\n\tconst STREAM_TIMESLICE = 500;\n\tconst NUM_HEADER_BYTES = 44;\n\tlet audio_chunks: Array<Blob> = [];\n\tlet audio_blob;\n\tlet module_promises:\n\t\t| [\n\t\t\t\tPromise<typeof import(\"extendable-media-recorder\")>,\n\t\t\t\tPromise<typeof import(\"extendable-media-recorder-wav-encoder\")>\n\t\t ];\n\n\tfunction get_modules() {\n\t\tmodule_promises = [\n\t\t\timport(\"extendable-media-recorder\"),\n\t\t\timport(\"extendable-media-recorder-wav-encoder\")\n\t\t];\n\t}\n\n\tif (streaming) {\n\t\tget_modules();\n\t}\n\n\tconst dispatch = createEventDispatcher<{\n\t\tchange: AudioData;\n\t\tstream: AudioData;\n\t\tedit: AudioData;\n\t\tplay: undefined;\n\t\tpause: undefined;\n\t\tstop: undefined;\n\t\tend: undefined;\n\t\tdrag: boolean;\n\t\terror: string;\n\t\tupload: FileData;\n\t\tclear: undefined;\n\t\tstart_recording: undefined;\n\t\tstop_recording: undefined;\n\t}>();\n\n\tfunction blob_to_data_url(blob: Blob): Promise<string> {\n\t\treturn new Promise((fulfill, reject) => {\n\t\t\tlet reader = new FileReader();\n\t\t\treader.onerror = reject;\n\t\t\treader.onload = () => fulfill(reader.result as string);\n\t\t\treader.readAsDataURL(blob);\n\t\t});\n\t}\n\n\tconst dispatch_blob = async (\n\t\tblobs: Array<Uint8Array> | Blob[],\n\t\tevent: \"stream\" | \"change\"\n\t) => {\n\t\tlet audio_blob = new Blob(blobs, { type: \"audio/wav\" });\n\t\tvalue = {\n\t\t\tdata: await blob_to_data_url(audio_blob),\n\t\t\tname: \"audio.wav\"\n\t\t};\n\t\tdispatch(event, value);\n\t};\n\n\tasync function prepare_audio() {\n\t\tlet stream: MediaStream | null;\n\n\t\ttry {\n\t\t\tstream = await navigator.mediaDevices.getUserMedia({ audio: true });\n\t\t} catch (err) {\n\t\t\tif (err instanceof DOMException && err.name == \"NotAllowedError\") {\n\t\t\t\tdispatch(\n\t\t\t\t\t\"error\",\n\t\t\t\t\t\"Please allow access to the microphone for recording.\"\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\tif (stream == null) return;\n\n\t\tif (streaming) {\n\t\t\tconst [{ MediaRecorder, register }, { connect }] = await Promise.all(\n\t\t\t\tmodule_promises\n\t\t\t);\n\n\t\t\tawait register(await connect());\n\n\t\t\trecorder = new MediaRecorder(stream, { mimeType: \"audio/wav\" });\n\n\t\t\tasync function handle_chunk(event: IBlobEvent) {\n\t\t\t\tlet buffer = await event.data.arrayBuffer();\n\t\t\t\tlet payload = new Uint8Array(buffer);\n\t\t\t\tif (!header) {\n\t\t\t\t\theader = new Uint8Array(buffer.slice(0, NUM_HEADER_BYTES));\n\t\t\t\t\tpayload = new Uint8Array(buffer.slice(NUM_HEADER_BYTES));\n\t\t\t\t}\n\t\t\t\tif (pending) {\n\t\t\t\t\tpending_stream.push(payload);\n\t\t\t\t} else {\n\t\t\t\t\tlet blobParts = [header].concat(pending_stream, [payload]);\n\t\t\t\t\tdispatch_blob(blobParts, \"stream\");\n\t\t\t\t\tpending_stream = [];\n\t\t\t\t}\n\t\t\t}\n\t\t\trecorder.addEventListener(\"dataavailable\", handle_chunk);\n\t\t} else {\n\t\t\trecorder = new MediaRecorder(stream);\n\n\t\t\trecorder.addEventListener(\"dataavailable\", (event) => {\n\t\t\t\taudio_chunks.push(event.data);\n\t\t\t});\n\n\t\t\trecorder.addEventListener(\"stop\", async () => {\n\t\t\t\trecording = false;\n\t\t\t\tawait dispatch_blob(audio_chunks, \"change\");\n\t\t\t\taudio_chunks = [];\n\t\t\t});\n\t\t}\n\n\t\tinited = true;\n\t}\n\n\t$: if (submit_pending_stream_on_pending_end && pending === false) {\n\t\tsubmit_pending_stream_on_pending_end = false;\n\t\tif (header && pending_stream) {\n\t\t\tlet blobParts: Array<Uint8Array> = [header].concat(pending_stream);\n\t\t\tpending_stream = [];\n\t\t\tdispatch_blob(blobParts, \"stream\");\n\t\t}\n\t}\n\n\tasync function record() {\n\t\trecording = true;\n\t\tdispatch(\"start_recording\");\n\t\tif (!inited) await prepare_audio();\n\t\theader = undefined;\n\t\tif (streaming) {\n\t\t\trecorder.start(STREAM_TIMESLICE);\n\t\t} else {\n\t\t\trecorder.start();\n\t\t}\n\t}\n\n\tonDestroy(() => {\n\t\tif (recorder && recorder.state !== \"inactive\") {\n\t\t\trecorder.stop();\n\t\t}\n\t});\n\n\tconst stop = async () => {\n\t\tdispatch(\"stop_recording\");\n\t\trecorder.stop();\n\t\tif (streaming) {\n\t\t\trecording = false;\n\t\t\tif (pending) {\n\t\t\t\tsubmit_pending_stream_on_pending_end = true;\n\t\t\t}\n\t\t}\n\t};\n\n\tfunction clear() {\n\t\tdispatch(\"change\");\n\t\tdispatch(\"clear\");\n\t\tmode = \"\";\n\t\tvalue = null;\n\t}\n\n\tfunction loaded(node: HTMLAudioElement) {\n\t\tfunction clamp_playback() {\n\t\t\tconst start_time = (crop_values[0] / 100) * node.duration;\n\t\t\tconst end_time = (crop_values[1] / 100) * node.duration;\n\t\t\tif (node.currentTime < start_time) {\n\t\t\t\tnode.currentTime = start_time;\n\t\t\t}\n\n\t\t\tif (node.currentTime > end_time) {\n\t\t\t\tnode.currentTime = start_time;\n\t\t\t\tnode.pause();\n\t\t\t}\n\t\t}\n\n\t\tnode.addEventListener(\"timeupdate\", clamp_playback);\n\n\t\treturn {\n\t\t\tdestroy: () => node.removeEventListener(\"timeupdate\", clamp_playback)\n\t\t};\n\t}\n\n\tfunction handle_change({\n\t\tdetail: { values }\n\t}: {\n\t\tdetail: { values: [number, number] };\n\t}) {\n\t\tif (!value) return;\n\n\t\tdispatch(\"change\", {\n\t\t\tdata: value.data,\n\t\t\tname,\n\t\t\tcrop_min: values[0],\n\t\t\tcrop_max: values[1]\n\t\t});\n\n\t\tdispatch(\"edit\");\n\t}\n\n\tfunction handle_load({\n\t\tdetail\n\t}: {\n\t\tdetail: {\n\t\t\tdata: string;\n\t\t\tname: string;\n\t\t\tsize: number;\n\t\t\tis_example: boolean;\n\t\t};\n\t}) {\n\t\tvalue = detail;\n\t\tdispatch(\"change\", { data: detail.data, name: detail.name });\n\t\tdispatch(\"upload\", detail);\n\t}\n\n\tfunction handle_ended() {\n\t\tdispatch(\"stop\");\n\t\tdispatch(\"end\");\n\t}\n\n\tlet old_val: any;\n\tfunction value_has_changed(val: any) {\n\t\tif (val === old_val) return false;\n\t\telse {\n\t\t\told_val = val;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\texport let dragging = false;\n\t$: dispatch(\"drag\", dragging);\n\t$: autoplay && player && value_has_changed(value?.data) && player.play();\n</script>\n\n<BlockLabel\n\t{show_label}\n\tIcon={Music}\n\tfloat={source === \"upload\" && value === null}\n\tlabel={label || \"Audio\"}\n/>\n{#if value === null || streaming}\n\t{#if source === \"microphone\"}\n\t\t<div class=\"mic-wrap\">\n\t\t\t{#if recording}\n\t\t\t\t<Button size=\"sm\" on:click={stop}>\n\t\t\t\t\t<span class=\"record-icon\">\n\t\t\t\t\t\t<span class=\"pinger\" />\n\t\t\t\t\t\t<span class=\"dot\" />\n\t\t\t\t\t</span>\n\t\t\t\t\tStop recording\n\t\t\t\t</Button>\n\t\t\t{:else}\n\t\t\t\t<Button size=\"sm\" on:click={record}>\n\t\t\t\t\t<span class=\"record-icon\">\n\t\t\t\t\t\t<span class=\"dot\" />\n\t\t\t\t\t</span>\n\t\t\t\t\tRecord from microphone\n\t\t\t\t</Button>\n\t\t\t{/if}\n\t\t</div>\n\t{:else if source === \"upload\"}\n\t\t<!-- explicitly listed out audio mimetypes due to iOS bug not recognizing audio/* -->\n\t\t<Upload\n\t\t\tfiletype=\"audio/aac,audio/midi,audio/mpeg,audio/ogg,audio/wav,audio/x-wav,audio/opus,audio/webm,audio/flac,audio/vnd.rn-realaudio,audio/x-ms-wma,audio/x-aiff,audio/amr,audio/*\"\n\t\t\ton:load={handle_load}\n\t\t\tbind:dragging\n\t\t>\n\t\t\t<slot />\n\t\t</Upload>\n\t{/if}\n{:else}\n\t<ModifyUpload\n\t\ton:clear={clear}\n\t\ton:edit={() => (mode = \"edit\")}\n\t\teditable\n\t\tabsolute={true}\n\t/>\n\n\t<audio\n\t\tuse:loaded\n\t\tcontrols\n\t\tbind:this={player}\n\t\tpreload=\"metadata\"\n\t\tsrc={value.data}\n\t\ton:play\n\t\ton:pause\n\t\ton:ended={handle_ended}\n\t/>\n\n\t{#if mode === \"edit\" && player?.duration}\n\t\t<Range\n\t\t\tbind:values={crop_values}\n\t\t\trange\n\t\t\tmin={0}\n\t\t\tmax={100}\n\t\t\tstep={1}\n\t\t\ton:change={handle_change}\n\t\t/>\n\t{/if}\n{/if}\n\n<style>\n\t.mic-wrap {\n\t\tpadding: var(--size-2);\n\t}\n\n\t.record-icon {\n\t\tdisplay: flex;\n\t\tposition: relative;\n\t\tmargin-right: var(--size-2);\n\t\twidth: 6px;\n\t\theight: 6px;\n\t}\n\n\t.dot {\n\t\tdisplay: inline-flex;\n\t\tposition: relative;\n\t\tborder-radius: var(--radius-full);\n\t\tbackground: var(--color-red-500);\n\t\twidth: 6px;\n\t\theight: 6px;\n\t}\n\n\t.pinger {\n\t\tdisplay: inline-flex;\n\t\tposition: absolute;\n\t\topacity: 0.9;\n\t\tanimation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;\n\t\tborder-radius: var(--radius-full);\n\t\tbackground: var(--color-red-500);\n\t\twidth: var(--size-full);\n\t\theight: var(--size-full);\n\t}\n\n\t@keyframes ping {\n\t\t75%,\n\t\t100% {\n\t\t\ttransform: scale(2);\n\t\t\topacity: 0;\n\t\t}\n\t}\n\n\taudio {\n\t\tpadding: var(--size-2);\n\t\twidth: var(--size-full);\n\t\theight: var(--size-14);\n\t}\n</style>\n","<script context=\"module\" lang=\"ts\">\n\timport type { FileData } from \"@gradio/upload\";\n\timport { Empty } from \"@gradio/atoms\";\n\texport interface AudioData extends FileData {\n\t\tcrop_min?: number;\n\t\tcrop_max?: number;\n\t}\n</script>\n\n<script lang=\"ts\">\n\timport { createEventDispatcher } from \"svelte\";\n\timport { BlockLabel } from \"@gradio/atoms\";\n\n\timport { Music } from \"@gradio/icons\";\n\n\texport let value: null | { name: string; data: string } = null;\n\texport let label: string;\n\texport let name: string;\n\texport let show_label: boolean = true;\n\texport let autoplay: boolean;\n\n\tconst dispatch = createEventDispatcher<{\n\t\tchange: AudioData;\n\t\tplay: undefined;\n\t\tpause: undefined;\n\t\tend: undefined;\n\t\tstop: undefined;\n\t}>();\n\n\t$: value &&\n\t\tdispatch(\"change\", {\n\t\t\tname: name,\n\t\t\tdata: value?.data\n\t\t});\n\n\tlet el: HTMLAudioElement;\n\n\tlet old_val: any;\n\tfunction value_has_changed(val: any) {\n\t\tif (val === old_val) return false;\n\t\telse {\n\t\t\told_val = val;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t$: autoplay && el && value_has_changed(value) && el.play();\n\n\tfunction handle_ended() {\n\t\tdispatch(\"stop\");\n\t\tdispatch(\"end\");\n\t}\n</script>\n\n<BlockLabel {show_label} Icon={Music} float={false} label={label || \"Audio\"} />\n{#if value === null}\n\t<Empty size=\"small\">\n\t\t<Music />\n\t</Empty>\n{:else}\n\t<audio\n\t\tbind:this={el}\n\t\tcontrols\n\t\tpreload=\"metadata\"\n\t\tsrc={value.data}\n\t\ton:play\n\t\ton:pause\n\t\ton:ended={handle_ended}\n\t/>\n{/if}\n\n<style>\n\taudio {\n\t\tpadding: var(--size-2);\n\t\twidth: var(--size-full);\n\t\theight: var(--size-14);\n\t}\n</style>\n","<script lang=\"ts\">\n\timport { createEventDispatcher } from \"svelte\";\n\timport { _ } from \"svelte-i18n\";\n\timport UploadText from \"../UploadText.svelte\";\n\n\timport type { FileData } from \"@gradio/upload\";\n\timport type { LoadingStatus } from \"../StatusTracker/types\";\n\n\timport { Audio, StaticAudio } from \"@gradio/audio\";\n\timport StatusTracker from \"../StatusTracker/StatusTracker.svelte\";\n\timport { Block } from \"@gradio/atoms\";\n\n\timport { normalise_file } from \"@gradio/upload\";\n\n\tconst dispatch = createEventDispatcher<{\n\t\tchange: typeof value;\n\t\tstream: typeof value;\n\t\terror: string;\n\t}>();\n\n\texport let elem_id: string = \"\";\n\texport let elem_classes: Array<string> = [];\n\texport let visible: boolean = true;\n\texport let mode: \"static\" | \"dynamic\";\n\texport let value: null | FileData | string = null;\n\texport let name: string;\n\texport let source: \"microphone\" | \"upload\";\n\texport let label: string;\n\texport let root: string;\n\texport let show_label: boolean;\n\texport let pending: boolean;\n\texport let streaming: boolean;\n\texport let root_url: null | string;\n\texport let container: boolean = false;\n\texport let scale: number = 1;\n\texport let min_width: number | undefined = undefined;\n\texport let loading_status: LoadingStatus;\n\texport let autoplay: boolean = false;\n\n\tlet _value: null | FileData;\n\t$: _value = normalise_file(value, root, root_url);\n\n\tlet dragging: boolean;\n</script>\n\n<Block\n\tvariant={mode === \"dynamic\" && value === null && source === \"upload\"\n\t\t? \"dashed\"\n\t\t: \"solid\"}\n\tborder_mode={dragging ? \"focus\" : \"base\"}\n\tpadding={false}\n\t{elem_id}\n\t{elem_classes}\n\t{visible}\n\t{container}\n\t{scale}\n\t{min_width}\n>\n\t<StatusTracker {...loading_status} />\n\n\t{#if mode === \"dynamic\"}\n\t\t<Audio\n\t\t\t{label}\n\t\t\t{show_label}\n\t\t\tvalue={_value}\n\t\t\ton:change={({ detail }) => {\n\t\t\t\tvalue = detail;\n\t\t\t\tdispatch(\"change\", value);\n\t\t\t}}\n\t\t\ton:stream={({ detail }) => {\n\t\t\t\tvalue = detail;\n\t\t\t\tdispatch(\"stream\", value);\n\t\t\t}}\n\t\t\ton:drag={({ detail }) => (dragging = detail)}\n\t\t\t{name}\n\t\t\t{source}\n\t\t\t{pending}\n\t\t\t{streaming}\n\t\t\t{autoplay}\n\t\t\ton:edit\n\t\t\ton:play\n\t\t\ton:pause\n\t\t\ton:stop\n\t\t\ton:end\n\t\t\ton:start_recording\n\t\t\ton:stop_recording\n\t\t\ton:upload\n\t\t\ton:error={({ detail }) => {\n\t\t\t\tloading_status = loading_status || {};\n\t\t\t\tloading_status.status = \"error\";\n\t\t\t\tloading_status.message = detail;\n\t\t\t}}\n\t\t>\n\t\t\t<UploadText type=\"audio\" />\n\t\t</Audio>\n\t{:else}\n\t\t<StaticAudio\n\t\t\t{autoplay}\n\t\t\t{show_label}\n\t\t\tvalue={_value}\n\t\t\tname={_value?.name || \"audio_file\"}\n\t\t\t{label}\n\t\t/>\n\t{/if}\n</Block>\n","export { default as Component } from \"./Audio.svelte\";\nexport const modes = [\"static\", \"dynamic\"];\n\nexport const document = () => ({\n\ttype: {\n\t\tinput_payload: \"{ name: string; data: string }\",\n\t\tresponse_object: \"{ name: string; data: string, is_file: boolean }\"\n\t},\n\tdescription: {\n\t\tinput_payload: \"audio data as object with filename and base64 string\",\n\t\tresponse_object:\n\t\t\t\"object that includes path to audio file. The URL: {ROOT}file={name} contains the data\"\n\t},\n\texample_data: {\n\t\tname: \"audio.wav\",\n\t\tdata: \"data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=\"\n\t}\n});\n"],"names":["insert","target","svg","anchor","append","path","circle0","circle1","if_block","ctx","create_if_block_10","toggle_class","span","is_function","t_value","create_if_block_12","create_if_block_11","dirty","set_data","t","i","create_if_block_6","attr","span_style_value","create_if_block_8","create_if_block_7","create_if_block_1","create_if_block_3","create_if_block_2","if_block0","create_if_block_9","if_block1","create_if_block_4","if_block2","create_if_block","div","range","$$props","min","max","step","values","vertical","reversed","hoverable","disabled","pipstep","all","first","last","rest","prefix","suffix","formatter","v","focus","orientationStart","percentOf","moveHandle","labelClick","val","$$invalidate","pipStep","pipCount","pipVal","isSelected","inRange","span1","span1_aria_valuemin_value","span1_aria_valuemax_value","span0","index","el","normalisedClient","e","slider","pushy","float","pips","id","p","handleFormatter","precision","springValues","dispatch","createEventDispatcher","valueLength","handleActivated","handlePressed","keyboardActive","activeHandle","startValue","previousValue","springPositions","targetIsHandle","handles","isHandle","isChild","trimRange","getSliderDimensions","getClosestHandle","clientPos","dims","handlePos","handlePercent","handleVal","closest","a","b","handleInteract","value","alignValueToStep","eChange","rangeStart","rangeEnd","sliderBlurHandle","sliderFocusHandle","sliderKeydown","handle","jump","prevent","sliderInteractStart","eStart","sliderInteractEnd","eStop","bodyInteractStart","bodyInteract","bodyMouseUp","bodyTouchEnd","bodyKeyDown","$$value","clampValue","remainder","aligned","perc","$$subscribe_springPositions","spring","orientationEnd","src_url_equal","audio","audio_src_value","current","span2","Music","blocklabel_changes","STREAM_TIMESLICE","NUM_HEADER_BYTES","blob_to_data_url","blob","fulfill","reject","reader","label","show_label","name","source","pending","streaming","autoplay","recording","recorder","mode","header","pending_stream","submit_pending_stream_on_pending_end","player","inited","crop_values","audio_chunks","module_promises","get_modules","dispatch_blob","blobs","event","audio_blob","prepare_audio","stream","err","MediaRecorder","register","connect","handle_chunk","buffer","payload","blobParts","record","onDestroy","stop","clear","loaded","node","clamp_playback","start_time","end_time","handle_change","handle_load","detail","handle_ended","old_val","value_has_changed","dragging","edit_handler","elem_id","elem_classes","visible","root","root_url","container","scale","min_width","loading_status","_value","normalise_file","modes","document"],"mappings":"uzCAAAA,EAeKC,EAAAC,EAAAC,CAAA,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