Merge in Examples and cache_examples fixes

* soft reset and remove a commit,
then commit the further commits  again

* fix flagging for tests

* format fix

* fixes

Co-authored-by: Ali <aliabid94@gmail.com>
This commit is contained in:
Ömer Faruk Özdemir 2022-04-11 23:18:42 +03:00 committed by GitHub
parent 7576f06aa8
commit a1509850dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 201 additions and 813 deletions

View File

@ -8,13 +8,12 @@ Hello friends
"""
with gr.Blocks() as demo:
txt = gr.Textbox(label="Input", lines=5)
txt_2 = gr.Textbox(label="Output")
txt_3 = gr.Textbox(str, label="Output")
btn = gr.Button('Submit')
btn.click(lambda a : a, inputs=[txt], outputs=[txt_2])
btn = gr.Button("Submit")
btn.click(lambda a: a, inputs=[txt], outputs=[txt_2])
if __name__ == "__main__":
demo.launch()

View File

@ -1,12 +1,14 @@
import gradio as gr
def print_message(n):
return "Welcome! This page has loaded for " + n
with gr.Blocks() as demo:
t = gr.Textbox("Frank", label="Name")
t2 = gr.Textbox(label="Output")
demo.load(print_message, t, t2)
t = gr.Textbox("Frank", label="Name")
t2 = gr.Textbox(label="Output")
demo.load(print_message, t, t2)
if __name__ == "__main__":

View File

@ -8,13 +8,15 @@ import gradio as gr
def fake_gan(*args):
time.sleep(1)
image = random.choice([
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
])
image = random.choice(
[
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
]
)
return image

View File

@ -20,12 +20,10 @@ def classify_image(inp):
image = gr.Image(shape=(224, 224))
label = gr.Label(num_top_classes=3)
demo = gr.Interface(
gr.Interface(
fn=classify_image,
inputs=image,
outputs=label,
outputs="image",
examples=[["images/cheetah1.jpg"], ["images/lion.jpg"]],
)
if __name__ == "__main__":
demo.launch()
cache_examples=True,
).launch()

View File

@ -1,7 +1,8 @@
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
import gradio as gr
def plot(v, a):
g = 9.81

View File

@ -11,14 +11,14 @@ tts_demo = gr.Interface.load(
"huggingface/facebook/fastspeech2-en-ljspeech",
title=None,
examples=tts_examples,
description="Give me something to say!"
description="Give me something to say!",
)
stt_demo = gr.Interface.load(
"huggingface/facebook/wav2vec2-base-960h",
title=None,
inputs="mic",
description="Let me try to guess what you're saying!"
description="Let me try to guess what you're saying!",
)
demo = gr.TabbedInterface([tts_demo, stt_demo], ["Text-to-speech", "Speech-to-text"])

View File

@ -1,7 +1,7 @@
import gradio as gr
import random
import gradio as gr
xray_model = lambda diseases, img: {disease: random.random() for disease in diseases}
ct_model = lambda diseases, img: {disease: 0.1 for disease in diseases}

Binary file not shown.

View File

@ -1,4 +1,4 @@
Metadata-Version: 2.1
Metadata-Version: 1.0
Name: gradio
Version: 2.7.0b70
Summary: Python library for easily interacting with trained machine learning models
@ -6,9 +6,6 @@ Home-page: https://github.com/gradio-app/gradio-UI
Author: Abubakar Abid, Ali Abid, Ali Abdalla, Dawood Khan, Ahsen Khaliq, Pete Allen, Ömer Faruk Özdemir
Author-email: team@gradio.app
License: Apache License 2.0
Description: UNKNOWN
Keywords: machine learning,visualization,reproducibility
Platform: UNKNOWN
License-File: LICENSE
UNKNOWN

View File

@ -1,5 +1,5 @@
analytics-python
aiohttp
analytics-python
fastapi
ffmpy
markdown-it-py[linkify,plugins]
@ -10,7 +10,7 @@ pandas
paramiko
pillow
pycryptodome
python-multipart
pydub
python-multipart
requests
uvicorn

View File

@ -42,7 +42,8 @@ class Block:
fn: Callable,
inputs: List[Component],
outputs: List[Component],
preprocess=True,
preprocess: bool = True,
postprocess: bool = True,
queue=False,
no_target: bool = False,
) -> None:
@ -53,6 +54,8 @@ class Block:
fn: Callable function
inputs: input list
outputs: output list
preprocess: whether to run the preprocess methods of components
postprocess: whether to run the postprocess methods of components
no_target: if True, sets "targets" to [], used for Blocks "load" event
Returns: None
"""
@ -62,7 +65,7 @@ class Block:
if not isinstance(outputs, list):
outputs = [outputs]
Context.root_block.fns.append((fn, preprocess))
Context.root_block.fns.append((fn, preprocess, postprocess))
Context.root_block.dependencies.append(
{
"targets": [self._id] if not no_target else [],
@ -208,7 +211,7 @@ class Blocks(BlockContext):
def process_api(self, data: Dict[str, Any], username: str = None) -> Dict[str, Any]:
raw_input = data["data"]
fn_index = data["fn_index"]
fn, preprocess = self.fns[fn_index]
fn, preprocess, postprocess = self.fns[fn_index]
dependency = self.dependencies[fn_index]
if preprocess:
@ -221,13 +224,14 @@ class Blocks(BlockContext):
predictions = fn(*raw_input)
if len(dependency["outputs"]) == 1:
predictions = (predictions,)
processed_output = [
self.blocks[output_id].postprocess(predictions[i])
if predictions[i] is not None
else None
for i, output_id in enumerate(dependency["outputs"])
]
return {"data": processed_output}
if postprocess:
predictions = [
self.blocks[output_id].postprocess(predictions[i])
if predictions[i] is not None
else None
for i, output_id in enumerate(dependency["outputs"])
]
return {"data": predictions}
def get_template_context(self):
return {"type": "column"}

View File

@ -89,7 +89,7 @@ class Component(Block):
return data
def save_flagged_file(
self, dir: str, label: Optional[str], data: Any, encryption_key: bool
self, dir: str, label: str, data: Any, encryption_key: bool
) -> Optional[str]:
"""
Saved flagged data (e.g. image or audio) as a file and returns filepath
@ -1279,6 +1279,9 @@ class Image(Component):
"""
return self.save_flagged_file(dir, label, data, encryption_key)
def restore_flagged(self, dir, data, encryption_key):
return os.path.join(dir, data)
def generate_sample(self):
return deepcopy(media_data.BASE64_IMAGE)
@ -2868,13 +2871,14 @@ class Dataset(Component):
*,
components: List[Component],
samples: List[List[Any]],
value: Optional[Number] = None,
type: str = "values",
label: Optional[str] = None,
css: Optional[Dict] = None,
**kwargs,
):
super().__init__(label=label, css=css, **kwargs)
self.components = components
self.type = type
self.headers = [c.label for c in components]
self.samples = samples
@ -2885,9 +2889,19 @@ class Dataset(Component):
],
"headers": self.headers,
"samples": self.samples,
"type": self.type,
**super().get_template_context(),
}
def preprocess(self, x: Any) -> Any:
"""
Any preprocessing needed to be performed on function input.
"""
if self.type == "index":
return x
elif self.type == "values":
return self.samples[x]
def click(self, fn: Callable, inputs: List[Component], outputs: List[Component]):
"""
Parameters:
@ -2898,6 +2912,18 @@ class Dataset(Component):
"""
self.set_event_trigger("click", fn, inputs, outputs)
def _click_no_postprocess(
self, fn: Callable, inputs: List[Component], outputs: List[Component]
):
"""
Parameters:
fn: Callable function
inputs: List of inputs
outputs: List of outputs
Returns: None
"""
self.set_event_trigger("click", fn, inputs, outputs, postprocess=False)
class Interpretation(Component):
"""

View File

@ -6,6 +6,7 @@ including various methods for constructing an interface and then launching it.
from __future__ import annotations
import copy
import csv
import inspect
import os
import random
@ -32,6 +33,7 @@ from gradio.external import load_from_pipeline, load_interface # type: ignore
from gradio.flagging import CSVLogger, FlaggingCallback # type: ignore
from gradio.inputs import State as i_State # type: ignore
from gradio.outputs import State as o_State # type: ignore
from gradio.process_examples import cache_interface_examples, load_from_cache
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
import transformers
@ -106,6 +108,7 @@ class Interface(Blocks):
outputs: str | Component | List[str | Component] = None,
verbose: bool = False,
examples: Optional[List[Any] | List[List[Any]] | str] = None,
cache_examples: bool = False,
examples_per_page: int = 10,
live: bool = False,
layout: str = "unaligned",
@ -326,19 +329,48 @@ class Interface(Blocks):
self.css = css_file.read()
else:
self.css = css
if (
examples is None
or isinstance(examples, str)
or (
isinstance(examples, list)
and (len(examples) == 0 or isinstance(examples[0], list))
)
if examples is None or (
isinstance(examples, list)
and (len(examples) == 0 or isinstance(examples[0], list))
):
self.examples = examples
elif (
isinstance(examples, list) and len(self.input_components) == 1
): # If there is only one input component, examples can be provided as a regular list instead of a list of lists
self.examples = [[e] for e in examples]
elif isinstance(examples, str):
if not os.path.exists(examples):
raise FileNotFoundError(
"Could not find examples directory: " + examples
)
log_file = os.path.join(examples, "log.csv")
if not os.path.exists(log_file):
if len(self.input_components) == 1:
exampleset = [
[os.path.join(examples, item)] for item in os.listdir(examples)
]
else:
raise FileNotFoundError(
"Could not find log file (required for multiple inputs): "
+ log_file
)
else:
with open(log_file) as logs:
exampleset = list(csv.reader(logs))
exampleset = exampleset[1:] # remove header
for i, example in enumerate(exampleset):
for j, (component, cell) in enumerate(
zip(
self.input_components + self.output_components,
example,
)
):
exampleset[i][j] = component.restore_flagged(
examples,
cell,
None,
)
self.examples = exampleset
else:
raise ValueError(
"Examples argument must either be a directory or a nested "
@ -404,13 +436,6 @@ class Interface(Blocks):
)
self.enable_queue = enable_queue
if self.enable_queue is not None:
warnings.warn(
"The `enable_queue` parameter in the `Interface`"
"will be deprecated and may not work properly. "
"Please use the `enable_queue` parameter in "
"`launch()` instead"
)
self.favicon_path = None
self.height = height
@ -462,6 +487,10 @@ class Interface(Blocks):
if component.label is None:
component.label = "output_" + str(i)
self.cache_examples = cache_examples
if cache_examples:
cache_interface_examples(self)
if self.allow_flagging != "never":
self.flagging_callback.setup(
self.input_components + self.output_components, self.flagging_dir
@ -545,12 +574,33 @@ class Interface(Blocks):
)
if self.examples:
examples = Dataset(
components=self.input_components, samples=self.examples
components=self.input_components,
samples=self.examples,
type="index",
)
examples.click(
lambda x: x, inputs=[examples], outputs=self.input_components
def load_example(example_id):
processed_examples = [
component.preprocess_example(sample)
for component, sample in zip(
self.input_components, self.examples[example_id]
)
]
if self.cache_examples:
processed_examples += load_from_cache(self, example_id)
if len(processed_examples) == 1:
return processed_examples[0]
else:
return processed_examples
examples._click_no_postprocess(
load_example,
inputs=[examples],
outputs=self.input_components
+ (self.output_components if self.cache_examples else []),
)
flag_btn.click(
flag_btn._click_no_preprocess(
lambda *flag_data: self.flagging_callback.flag(flag_data),
inputs=self.input_components + self.output_components,
outputs=[],

View File

@ -41,9 +41,7 @@ def cache_interface_examples(interface: Interface) -> None:
f"Cache at {os.path.abspath(CACHE_FILE)} not found. Caching now in '{CACHED_FOLDER}/' directory."
)
cache_logger = CSVLogger()
cache_logger.setup(
interface.input_components + interface.output_components, CACHED_FOLDER
)
cache_logger.setup(interface.output_components, CACHED_FOLDER)
for example_id, _ in enumerate(interface.examples):
try:
prediction = process_example(interface, example_id)[0]
@ -56,7 +54,7 @@ def cache_interface_examples(interface: Interface) -> None:
def load_from_cache(interface: Interface, example_id: int) -> List[Any]:
"""Loads a particular cached example for the interface."""
with open(CACHE_FILE) as cache:
examples = list(csv.reader(cache, quotechar="'"))
examples = list(csv.reader(cache))
example = examples[example_id + 1] # +1 to adjust for header
output = []
for component, cell in zip(interface.output_components, example):

View File

@ -45,8 +45,8 @@
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.1/iframeResizer.contentWindow.min.js"></script>
<title>Gradio</title>
<script type="module" crossorigin src="./assets/index.72491765.js"></script>
<link rel="stylesheet" href="./assets/index.4f55c05a.css">
<script type="module" crossorigin src="./assets/index.3738fcaf.js"></script>
<link rel="stylesheet" href="./assets/index.38c11487.css">
</head>
<body style="height: 100%; margin: 0; padding: 0">

View File

@ -438,7 +438,7 @@ class TestImage(unittest.TestCase):
to_save = image_input.save_flagged(tmpdirname, "image_input", img, None)
self.assertEqual("image_input/1.png", to_save)
restored = image_input.restore_flagged(tmpdirname, to_save, None)
self.assertEqual(restored, "image_input/1.png")
self.assertEqual(restored, os.path.join(tmpdirname, "image_input/1.png"))
self.assertIsInstance(image_input.generate_sample(), str)
image_input = gr.Image(

View File

@ -380,7 +380,7 @@ class TestImage(unittest.TestCase):
to_save = image_input.save_flagged(tmpdirname, "image_input", img, None)
self.assertEqual("image_input/1.png", to_save)
restored = image_input.restore_flagged(tmpdirname, to_save, None)
self.assertEqual(restored, "image_input/1.png")
self.assertEqual(restored, os.path.join(tmpdirname, "image_input/1.png"))
self.assertIsInstance(image_input.generate_sample(), str)
image_input = gr.inputs.Image(

View File

@ -1,143 +0,0 @@
<script context="module" lang="ts">
interface CustomWindow extends Window {
gradio_mode: "app" | "website";
}
declare let window: CustomWindow;
</script>
<script lang="ts">
import Interface from "./Interface.svelte";
import { _ } from "svelte-i18n";
import { setupi18n } from "./i18n";
setupi18n();
interface Component {
name: string;
[key: string]: unknown;
}
export let title: string;
export let description: string;
export let article: string;
export let theme: string;
export let style: string | null;
export let dark: boolean;
export let input_components: Array<Component>;
export let output_components: Array<Component>;
export let examples: Array<Array<unknown>>;
export let fn: (...args: any) => Promise<unknown>;
export let root: string;
export let space: string | undefined = undefined;
export let allow_flagging: string;
export let flagging_options: Array<string> | undefined = undefined;
export let allow_interpretation: boolean;
export let live: boolean;
export let queue: boolean;
export let static_src: string;
$: embedded = space !== undefined;
</script>
<div
class="gradio-bg flex flex-col dark:bg-gray-600 {window.gradio_mode === 'app'
? 'h-full'
: 'h-auto'}"
{theme}
class:dark
class:min-h-full={!embedded}
>
<div
class="gradio-page container mx-auto flex flex-col box-border flex-grow text-gray-700 dark:text-gray-50"
class:embedded
>
<div class="content pt-4 px-4 mb-4">
{#if title}
<h1 class="title text-center p-4 text-4xl">{title}</h1>
{/if}
{#if description}
<p class="description pb-4">{@html description}</p>
{/if}
<Interface
{input_components}
{output_components}
{examples}
{theme}
{fn}
{root}
{allow_flagging}
{flagging_options}
{allow_interpretation}
{live}
{queue}
{static_src}
/>
{#if article}
<p class="article prose pt-8 pb-4 max-w-none">
{@html article}
</p>
{/if}
</div>
{#if embedded}
<div class="footer bg-gray-100 p-4 rounded-b">
<a
href={"https://huggingface.co/spaces/" + space}
class="font-semibold"
>
{space && space.includes("/")
? space[space.indexOf("/") + 1].toUpperCase() +
space.substring(space.indexOf("/") + 2)
: space}
</a>
built with
<a href="https://gradio.app" target="_blank" class="font-semibold"
>Gradio</a
>, hosted on
<a
href="https://huggingface.co/spaces"
target="_blank"
class="font-semibold">Hugging Face Spaces</a
>.
</div>
{:else}
<div
class="footer flex-shrink-0 inline-flex gap-2.5 items-center text-gray-400 justify-center py-2"
>
<a href="api" target="_blank" rel="noreferrer">
{$_("interface.view_api")}
<img
class="h-4 inline-block"
src="{static_src}/static/img/api-logo.svg"
alt="api"
/>
</a>
&bull;
<a href="https://gradio.app" target="_blank" rel="noreferrer">
{$_("interface.built_with_Gradio")}
<img
class="h-5 inline-block"
src="{static_src}/static/img/logo.svg"
alt="logo"
/>
</a>
</div>
{/if}
</div>
</div>
<style global lang="postcss">
@tailwind base;
@tailwind components;
@tailwind utilities;
.gradio-page.embedded {
@apply rounded border-2 border-gray-100 shadow-lg;
}
.gradio-page:not(.embedded) {
@apply h-full;
.content {
@apply flex-grow flex-shrink-0 pt-4 px-4;
}
}
</style>

View File

@ -1,108 +0,0 @@
<script lang="ts">
// import { input_component_map } from "./components/directory";
import { _ } from "svelte-i18n";
interface Component {
name: string;
[key: string]: unknown;
}
export let examples: Array<Array<unknown>>;
export let examples_dir: string;
export let example_id: number | undefined;
export let setExampleId: Function;
export let examples_per_page: number;
export let input_components: Array<Component>;
export let theme: string;
export let style: string | null;
let selected_examples = examples;
let gallery = input_components.length === 1;
</script>
<!--
<div class="examples" {theme}>
<h4 class="text-lg font-semibold my-2">{$_("interface.examples")}</h4>
<div
class="examples-holder mt-4 inline-block max-w-full"
class:gallery
class:overflow-x-auto={!gallery}
>
{#if gallery}
<div class="examples-gallery flex gap-2 flex-wrap">
{#each selected_examples as example_row, i}
<button
class="example cursor-pointer p-2 rounded bg-gray-50 dark:bg-gray-700 transition"
on:click={() => setExampleId(i)}
>
<svelte:component
this={input_component_map[input_components[0].name].example}
{theme}
value={example_row[0]}
{examples_dir}
/>
</button>
{/each}
</div>
{:else}
<table
class="examples-table table-auto p-2 bg-gray-50 dark:bg-gray-600 rounded max-w-full border-collapse"
>
<thead class="border-b-2 dark:border-gray-600">
<tr>
{#each input_components as input_component}
<th class="py-2 px-4">
{input_component.label}
</th>
{/each}
</tr>
</thead>
<tbody>
{#each selected_examples as example_row, i}
<tr
class="cursor-pointer transition"
class:selected={i === example_id}
on:click={() => setExampleId(i)}
>
{#each example_row as example_cell, j}
<td class="py-2 px-4">
<svelte:component
this={input_component_map[input_components[j].name].example}
{theme}
value={example_cell}
{examples_dir}
/>
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
{/if}
</div>
</div>
<style lang="postcss" global>
.examples[theme="default"] {
.examples-holder:not(.gallery) {
@apply shadow;
.examples-table {
@apply rounded dark:bg-gray-700;
thead {
@apply border-gray-300 dark:border-gray-600;
}
tbody tr:hover {
@apply bg-amber-500 dark:bg-red-700 text-white;
}
}
}
.examples-holder .examples-gallery {
.example {
@apply shadow;
}
.example:hover {
@apply bg-amber-500 text-white;
}
}
}
</style> -->

View File

@ -1,435 +0,0 @@
<script lang="ts">
import { deepCopy } from "./components/utils/helpers";
import ExampleSet from "./ExampleSet.svelte";
import { _ } from "svelte-i18n";
import { component_map } from "./components/directory";
interface Component {
name: string;
[key: string]: unknown;
}
export let input_components: Array<Component>;
export let output_components: Array<Component>;
export let theme: string;
export let style: string | null;
export let fn: (...args: any) => Promise<unknown>;
export let examples: Array<Array<unknown>>;
export let root: string;
export let allow_flagging: string;
export let flagging_options: Array<string> | undefined = undefined;
export let allow_interpretation: boolean;
export let avg_durations: undefined | Array<number> = undefined;
export let live: boolean;
export let queue: boolean;
export let static_src: string;
let examples_dir = root + "file/";
let interpret_mode = false;
let submission_count = 0;
let state = "START";
let last_duration: number | null = null;
let has_changed = false;
let queue_index: number | null = null;
let initial_queue_index: number | null = null;
let just_flagged: boolean = false;
const default_inputs: Array<unknown> = input_components.map((component) =>
"default" in component ? component.default : null
);
const default_outputs = new Array(output_components.length).fill(null);
let input_values: Array<unknown> = deepCopy(default_inputs);
let output_values = deepCopy(default_outputs);
let interpretation_values: Array<unknown> = [];
let timer: NodeJS.Timeout = null;
let timer_start = 0;
let timer_diff = 0;
let avg_duration = Array.isArray(avg_durations) ? avg_durations[0] : null;
let expected_duration: number | null = null;
const setValues = (index: number, value: unknown) => {
has_changed = true;
input_values[index] = value;
if (live && state !== "PENDING") {
submit();
}
};
const setExampleId = async (example_id: number) => {
input_components.forEach(async (input_component, i) => {
const process_example =
component_map[input_component.name].process_example;
if (process_example !== undefined) {
input_values[i] = await process_example(
examples[example_id][i],
examples_dir
);
} else {
input_values[i] = examples[example_id][i];
}
});
};
const startTimer = () => {
timer_start = Date.now();
timer_diff = 0;
timer = setInterval(() => {
timer_diff = (Date.now() - timer_start) / 1000;
}, 100);
};
const stopTimer = () => {
clearInterval(timer);
};
const submit = () => {
if (state === "PENDING") {
return;
}
for (let [i, input_component] of input_components.entries()) {
if (
input_values[i] === null &&
input_component.name !== "state" &&
input_component.optional !== true
) {
return;
}
}
state = "PENDING";
submission_count += 1;
has_changed = false;
let submission_count_at_click = submission_count;
startTimer();
fn("predict", { data: input_values }, queue, queueCallback)
.then((output) => {
if (
state !== "PENDING" ||
submission_count_at_click !== submission_count
) {
return;
}
stopTimer();
output_values = output["data"];
for (let [i, value] of output_values.entries()) {
if (output_components[i].name === "state") {
for (let [j, input_component] of input_components.entries()) {
if (input_component.name === "state") {
input_values[j] = value;
}
}
}
}
if ("durations" in output) {
last_duration = output["durations"][0];
}
if ("avg_durations" in output) {
avg_duration = output["avg_durations"][0];
if (queue && initial_queue_index) {
expected_duration = avg_duration * (initial_queue_index + 1);
} else {
expected_duration = avg_duration;
}
}
state = "COMPLETE";
if (live && has_changed) {
submit();
}
})
.catch((e) => {
if (
state !== "PENDING" ||
submission_count_at_click !== submission_count
) {
return;
}
stopTimer();
console.error(e);
state = "ERROR";
output_values = deepCopy(default_outputs);
});
};
const clear = () => {
input_values = deepCopy(default_inputs);
output_values = deepCopy(default_outputs);
interpret_mode = false;
state = "START";
stopTimer();
};
const flag = (flag_option: string | null) => {
let flag_data: Record<string, any> = {
input_data: input_values,
output_data: output_values
};
if (flag_option !== null) {
flag_data["flag_option"] = flag_option;
}
just_flagged = true;
setTimeout(() => {
just_flagged = false;
}, 500);
fn("flag", {
data: flag_data
});
};
const interpret = () => {
if (interpret_mode) {
interpret_mode = false;
} else {
fn(
"interpret",
{
data: input_values
},
queue,
queueCallback
).then((output) => {
interpret_mode = true;
interpretation_values = output.interpretation_scores;
});
}
};
const queueCallback = (index: number, is_initial: boolean) => {
if (is_initial) {
initial_queue_index = index;
}
queue_index = index;
};
</script>
<div class="gradio-interface" {theme}>
<div class="panels flex flex-wrap justify-center gap-4 flex-col sm:flex-row">
<div class="panel flex-1">
<div
class="component-set p-2 rounded flex flex-col flex-1 gap-2"
style="min-height: 36px"
>
{#each input_components as input_component, i}
{#if input_component.name !== "state"}
<div class="component" key={i}>
<div class="panel-header mb-1.5">
{input_component.label}{#if input_component.optional}
&nbsp;<em>(optional)</em>{/if}
</div>
<svelte:component
this={component_map[input_component.name][
interpret_mode ? "interpretation" : "component"
]}
{...input_component}
{theme}
{static_src}
value={input_values[i]}
interpretation={interpret_mode
? interpretation_values[i]
: null}
setValue={(value) => setValues(i, value)}
/>
</div>
{/if}
{/each}
</div>
<div class="panel-buttons flex gap-4 my-4">
<button
class="panel-button bg-gray-50 dark:bg-gray-700 flex-1 p-3 rounded transition font-semibold focus:outline-none"
on:click={clear}
>
{$_("interface.clear")}
</button>
<button
class="panel-button submit bg-gray-50 dark:bg-gray-700 flex-1 p-3 rounded transition font-semibold focus:outline-none"
on:click={submit}
>
{$_("interface.submit")}
</button>
</div>
</div>
<div class="panel flex-1">
<div
class="component-set p-2 rounded flex flex-col flex-1 gap-2 relative"
style="min-height: 36px"
class:opacity-50={state === "PENDING"}
>
{#if state !== "START"}
<div class="state absolute right-2 flex items-center gap-0.5 text-xs">
{#if state === "PENDING"}
<div class="timer font-mono text-right" style="max">
{timer_diff.toFixed(1)}s
{#if expected_duration !== null}
<span>
(ETA: {expected_duration.toFixed(
1
)}s<!--
-->{#if queue_index}
, {queue_index} ahead<!--
-->{/if})<!--
--></span
>
{/if}
</div>
<img
src="{static_src}/static/img/logo.svg"
alt="Pending"
class="pending h-5 ml-1 inline-block"
/>
{:else if state === "ERROR"}
<img
src="{static_src}/static/img/logo_error.svg"
alt="Error"
class="error h-5 ml-2 inline-block"
/>
{:else if state === "COMPLETE" && last_duration !== null}
<div class="duration font-mono">{last_duration.toFixed(1)}s</div>
{/if}
</div>
{/if}
{#each output_components as output_component, i}
{#if output_values[i] !== null && output_component.name !== "state"}
<div class="component">
<div class="panel-header mb-1.5">{output_component.label}</div>
<svelte:component
this={component_map[output_component.name].component}
{...output_component}
{theme}
{static_src}
value={output_values[i]}
/>
</div>
{/if}
{/each}
</div>
<div class="panel-buttons flex gap-4 my-4">
{#if allow_interpretation !== false}
<button
class="panel-button flag bg-gray-50 dark:bg-gray-700 flex-1 p-3 rounded transition font-semibold focus:outline-none"
on:click={interpret}
>
{#if interpret_mode}
Hide
{:else}
{$_("interface.interpret")}
{/if}
</button>
{/if}
{#if allow_flagging !== "never"}
{#if flagging_options}
<button
class="panel-button group flag relative bg-gray-50 dark:bg-gray-700 flex-1 p-3 rounded transition font-semibold focus:outline-none"
class:just_flagged
>
{$_("interface.flag")}
<div
class="flag-options hidden group-hover:block absolute top-8 left-0 bg-white border-gray-200 border-2 w-full dark:bg-gray-500 dark:border-none"
>
{#each flagging_options as option}
<div
class="flag-option p-2 transition"
on:click={() => {
flag(option);
}}
>
{option}
</div>
{/each}
</div>
</button>
{:else}
<button
class="panel-button flag bg-gray-50 dark:bg-gray-700 flex-1 p-3 rounded transition font-semibold focus:outline-none"
class:just_flagged
on:click={() => flag(null)}
>
{$_("interface.flag")}
</button>
{/if}
{/if}
</div>
</div>
</div>
{#if examples}
<ExampleSet
{examples}
{input_components}
{theme}
{examples_dir}
{setExampleId}
/>
{/if}
</div>
<style lang="postcss" global>
.pending {
@keyframes ld-breath {
0% {
animation-timing-function: cubic-bezier(
0.9647,
0.2413,
-0.0705,
0.7911
);
transform: scale(0.9);
}
51% {
animation-timing-function: cubic-bezier(
0.9226,
0.2631,
-0.0308,
0.7628
);
transform: scale(1.2);
}
100% {
transform: scale(0.9);
}
}
animation: ld-breath 0.75s infinite linear;
}
.flag-option {
@apply hover:bg-gray-100;
}
.gradio-interface[theme="default"] {
.component-set {
@apply bg-gray-50 dark:bg-gray-700 dark:drop-shadow-xl shadow;
}
.component {
@apply mb-2;
}
.panel-header {
@apply uppercase text-xs;
}
.panel-button {
@apply hover:bg-gray-100 dark:hover:bg-gray-600 shadow;
}
.panel-button.disabled {
@apply text-gray-400 cursor-not-allowed;
}
.panel-button.submit {
@apply bg-amber-500 hover:bg-amber-400 dark:bg-red-700 dark:hover:bg-red-600 text-white;
}
.panel-button.just_flagged {
@apply bg-red-300 hover:bg-red-300;
}
.examples {
.examples-table-holder:not(.gallery) {
@apply shadow;
.examples-table {
@apply rounded dark:bg-gray-700;
thead {
@apply border-gray-300 dark:border-gray-600;
}
tbody tr:hover {
@apply bg-amber-500 dark:bg-red-700 text-white;
}
}
}
.examples-table-holder.gallery .examples-table {
tbody td {
@apply shadow;
}
tbody td:hover {
@apply bg-amber-500 text-white;
}
}
}
}
</style>

View File

@ -12,11 +12,12 @@
export let source: "microphone" | "upload";
export let type: "normal" | "numpy" = "normal";
export let label: string;
export let root: string;
if (default_value) value = default_value;
let _value: null | FileData;
$: _value = normalise_file(value);
$: _value = normalise_file(value, root);
</script>
{#if mode === "dynamic"}

View File

@ -1,3 +1,2 @@
export { default as Component } from "./Audio.svelte";
export { loadAsFile } from "../utils/example_processors";
export const modes = ["static", "dynamic"];

View File

@ -62,7 +62,7 @@
class="sample cursor-pointer p-2 rounded bg-gray-50 dark:bg-gray-700 transition"
class:selected={i + page * samples_per_page === sample_id}
on:click={() => {
value = samples[i];
value = i;
dispatch("click", i + page * samples_per_page);
}}
>
@ -94,7 +94,7 @@
class="cursor-pointer transition"
class:selected={i + page * samples_per_page === sample_id}
on:click={() => {
value = samples[i];
value = i;
dispatch("click", i + page * samples_per_page);
}}
>

View File

@ -0,0 +1,23 @@
<script lang="ts">
export let value: Array<Array<string | number>>;
</script>
<table class="input-dataframe-example">
{#each value.slice(0, 3) as row}
<tr>
{#each row.slice(0, 3) as cell}
<td class="p-2">{cell}</td>
{/each}
{#if row.length > 3}
<td class="p-2">...</td>
{/if}
</tr>
{/each}
{#if value.length > 3}
<tr>
{#each Array(Math.min(4, value[0].length)) as _}
<td class="p-2">...</td>
{/each}
</tr>
{/if}
</table>

View File

@ -5,6 +5,11 @@ import ExampleCheckboxGroup from "./ExampleComponents/CheckboxGroup.svelte";
import ExampleSlider from "./ExampleComponents/Slider.svelte";
import ExampleRadio from "./ExampleComponents/Radio.svelte";
import ExampleImage from "./ExampleComponents/Image.svelte";
import ExampleTextbox from "./ExampleComponents/Textbox.svelte";
import ExampleAudio from "./ExampleComponents/Audio.svelte";
import ExampleVideo from "./ExampleComponents/Video.svelte";
import ExampleFile from "./ExampleComponents/File.svelte";
import ExampleDataframe from "./ExampleComponents/Dataframe.svelte";
export const component_map = {
dropdown: ExampleDropdown,
@ -13,5 +18,10 @@ export const component_map = {
number: ExampleNumber,
slider: ExampleSlider,
radio: ExampleRadio,
image: ExampleImage
image: ExampleImage,
textbox: ExampleTextbox,
audio: ExampleAudio,
video: ExampleVideo,
file: ExampleFile,
dataframe: ExampleDataframe
};

View File

@ -8,11 +8,12 @@
export let default_value: null | FileData = null;
export let style: string = "";
export let mode: "static" | "dynamic";
export let root: string;
if (default_value) value = default_value;
let _value: null | FileData;
$: _value = normalise_file(value);
$: _value = normalise_file(value, root);
</script>
{#if mode === "dynamic"}

View File

@ -1,3 +1,2 @@
export { default as Component } from "./File.svelte";
export { loadAsFile } from "../utils/example_processors";
export const modes = ["static", "dynamic"];

View File

@ -1,4 +1,3 @@
export { default as Component } from "./Image.svelte";
export { default as ExampleComponent } from "../Dataset/ExampleComponents/Image.svelte";
export { loadAsData } from "../utils/example_processors";
export const modes = ["static", "dynamic"];

View File

@ -11,13 +11,14 @@
export let default_value: FileData | null;
export let style: string = "";
export let source: string;
export let root: string;
export let mode: "static" | "dynamic";
if (default_value) value = default_value;
let _value: null | FileData;
$: _value = normalise_file(value);
$: _value = normalise_file(value, root);
</script>
{#if mode === "static" && _value}

View File

@ -1,3 +1,2 @@
export { default as Component } from "./Video.svelte";
export { loadAsFile } from "../utils/example_processors";
export const modes = ["static", "dynamic"];

View File

@ -1,34 +0,0 @@
export const loadAsFile = async (x: string, examples_dir: String) => {
return {
name: x,
data: examples_dir + x,
is_example: true
};
};
export const loadAsData = async (
x: string,
examples_dir: string
): Promise<string> => {
let file_url = examples_dir + x;
let response = await fetch(file_url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let blob = await response.blob();
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener(
"load",
function () {
resolve(reader.result as string);
},
false
);
reader.onerror = () => {
return reject();
};
reader.readAsDataURL(blob);
});
};

View File

@ -1,3 +1,5 @@
import type { FileData } from "@gradio/upload";
interface XYValue {
x: number;
y: number;

View File

@ -1,4 +1,3 @@
import App from "./App.svelte";
import Blocks from "./Blocks.svelte";
import Login from "./Login.svelte";
import { fn } from "./api";
@ -101,17 +100,10 @@ window.launchGradio = (config: Config, element_query: string) => {
target.classList.add("dark");
}
config.fn = fn.bind(null, config.root + "api/");
if (config.mode === "blocks") {
new Blocks({
target: target,
props: config
});
} else {
new App({
target: target,
props: config
});
}
new Blocks({
target: target,
props: config
});
}
};

View File

@ -2,4 +2,5 @@ export interface FileData {
name: string;
size?: number;
data: string;
is_example?: boolean;
}

View File

@ -1,7 +1,8 @@
import type { FileData } from "./types";
export function normalise_file(
file: string | FileData | null
file: string | FileData | null,
root: string
): FileData | null {
if (file == null) return null;
if (typeof file === "string") {
@ -9,5 +10,8 @@ export function normalise_file(
name: "file_data",
data: file
};
} else return file;
} else if (file.is_example) {
file.data = root + "file/" + file.name;
}
return file;
}