mirror of
https://github.com/gradio-app/gradio.git
synced 2025-03-25 12:10:31 +08:00
ClearButton browser test (#4749)
* Icon testids * Simpler test * Add test * Demo check * Add notebook * Revert demo * Fix code * Add non-None callable value * change --------- Co-authored-by: pngwn <hello@pngwn.io>
This commit is contained in:
parent
67ce44dee1
commit
3a6406e5d5
1
demo/clear_components/run.ipynb
Normal file
1
demo/clear_components/run.ipynb
Normal file
File diff suppressed because one or more lines are too long
184
demo/clear_components/run.py
Normal file
184
demo/clear_components/run.py
Normal file
@ -0,0 +1,184 @@
|
||||
import gradio as gr
|
||||
from datetime import datetime
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import pandas as pd
|
||||
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import random
|
||||
import os
|
||||
|
||||
|
||||
def random_plot():
|
||||
start_year = 2020
|
||||
x = np.arange(start_year, start_year + random.randint(0, 10))
|
||||
year_count = x.shape[0]
|
||||
plt_format = "-"
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
series = np.arange(0, year_count, dtype=float)
|
||||
series = series**2
|
||||
series += np.random.rand(year_count)
|
||||
ax.plot(x, series, plt_format)
|
||||
return fig
|
||||
|
||||
|
||||
images = [
|
||||
"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",
|
||||
]
|
||||
file_dir = os.path.join(os.path.dirname(__file__), "..", "kitchen_sink", "files")
|
||||
model3d_dir = os.path.join(os.path.dirname(__file__), "..", "model3D", "files")
|
||||
highlighted_text_output_1 = [
|
||||
{
|
||||
"entity": "I-LOC",
|
||||
"score": 0.9988978,
|
||||
"index": 2,
|
||||
"word": "Chicago",
|
||||
"start": 5,
|
||||
"end": 12,
|
||||
},
|
||||
{
|
||||
"entity": "I-MISC",
|
||||
"score": 0.9958592,
|
||||
"index": 5,
|
||||
"word": "Pakistani",
|
||||
"start": 22,
|
||||
"end": 31,
|
||||
},
|
||||
]
|
||||
highlighted_text_output_2 = [
|
||||
{
|
||||
"entity": "I-LOC",
|
||||
"score": 0.9988978,
|
||||
"index": 2,
|
||||
"word": "Chicago",
|
||||
"start": 5,
|
||||
"end": 12,
|
||||
},
|
||||
{
|
||||
"entity": "I-LOC",
|
||||
"score": 0.9958592,
|
||||
"index": 5,
|
||||
"word": "Pakistan",
|
||||
"start": 22,
|
||||
"end": 30,
|
||||
},
|
||||
]
|
||||
|
||||
highlighted_text = "Does Chicago have any Pakistani restaurants"
|
||||
|
||||
|
||||
def random_model3d():
|
||||
model_3d = random.choice(
|
||||
[os.path.join(model3d_dir, model) for model in os.listdir(model3d_dir) if model != "source.txt"]
|
||||
)
|
||||
return model_3d
|
||||
|
||||
|
||||
|
||||
components = [
|
||||
gr.Textbox(value=lambda: datetime.now(), label="Current Time"),
|
||||
gr.Number(value=lambda: random.random(), label="Random Percentage"),
|
||||
gr.Slider(minimum=0, maximum=100, randomize=True, label="Slider with randomize"),
|
||||
gr.Slider(
|
||||
minimum=0,
|
||||
maximum=1,
|
||||
value=lambda: random.random(),
|
||||
label="Slider with value func",
|
||||
),
|
||||
gr.Checkbox(value=lambda: random.random() > 0.5, label="Random Checkbox"),
|
||||
gr.CheckboxGroup(
|
||||
choices=["a", "b", "c", "d"],
|
||||
value=lambda: random.choice(["a", "b", "c", "d"]),
|
||||
label="Random CheckboxGroup",
|
||||
),
|
||||
gr.Radio(
|
||||
choices=list(string.ascii_lowercase),
|
||||
value=lambda: random.choice(string.ascii_lowercase),
|
||||
),
|
||||
gr.Dropdown(
|
||||
choices=["a", "b", "c", "d", "e"],
|
||||
value=lambda: random.choice(["a", "b", "c"]),
|
||||
),
|
||||
gr.Image(
|
||||
value=lambda: random.choice(images)
|
||||
),
|
||||
gr.Video(value=lambda: os.path.join(file_dir, "world.mp4")),
|
||||
gr.Audio(value=lambda: os.path.join(file_dir, "cantina.wav")),
|
||||
gr.File(
|
||||
value=lambda: random.choice(
|
||||
[os.path.join(file_dir, img) for img in os.listdir(file_dir)]
|
||||
)
|
||||
),
|
||||
gr.Dataframe(
|
||||
value=lambda: pd.DataFrame({"random_number_rows": range(random.randint(0, 10))})
|
||||
),
|
||||
gr.Timeseries(value=lambda: os.path.join(file_dir, "time.csv")),
|
||||
gr.ColorPicker(value=lambda: random.choice(["#000000", "#ff0000", "#0000FF"])),
|
||||
gr.Label(value=lambda: random.choice(["Pedestrian", "Car", "Cyclist"])),
|
||||
gr.HighlightedText(
|
||||
value=lambda: random.choice(
|
||||
[
|
||||
{"text": highlighted_text, "entities": highlighted_text_output_1},
|
||||
{"text": highlighted_text, "entities": highlighted_text_output_2},
|
||||
]
|
||||
),
|
||||
),
|
||||
gr.JSON(value=lambda: random.choice([{"a": 1}, {"b": 2}])),
|
||||
gr.HTML(
|
||||
value=lambda: random.choice(
|
||||
[
|
||||
'<p style="color:red;">I am red</p>',
|
||||
'<p style="color:blue;">I am blue</p>',
|
||||
]
|
||||
)
|
||||
),
|
||||
gr.Gallery(
|
||||
value=lambda: images
|
||||
),
|
||||
gr.Model3D(value=random_model3d),
|
||||
gr.Plot(value=random_plot),
|
||||
gr.Markdown(value=lambda: f"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}"),
|
||||
]
|
||||
|
||||
|
||||
def evaluate_values(*args):
|
||||
are_false = []
|
||||
for a in args:
|
||||
if isinstance(a, (pd.DataFrame, np.ndarray)):
|
||||
are_false.append(not a.any().any())
|
||||
elif isinstance(a, str) and a.startswith("#"):
|
||||
are_false.append(a == "#000000")
|
||||
else:
|
||||
are_false.append(not a)
|
||||
return all(are_false)
|
||||
|
||||
|
||||
with gr.Blocks() as demo:
|
||||
for i, component in enumerate(components):
|
||||
component.label = f"component_{str(i).zfill(2)}"
|
||||
component.render()
|
||||
clear = gr.ClearButton(value="Clear", components=components)
|
||||
result = gr.Textbox(label="Are all cleared?")
|
||||
hide = gr.Button(value="Hide")
|
||||
reveal = gr.Button(value="Reveal")
|
||||
hide.click(
|
||||
lambda: [c.update(visible=False) for c in components],
|
||||
inputs=[],
|
||||
outputs=components
|
||||
)
|
||||
reveal.click(
|
||||
lambda: [c.update(visible=True) for c in components],
|
||||
inputs=[],
|
||||
outputs=components
|
||||
)
|
||||
get_value = gr.Button(value="Get Values")
|
||||
get_value.click(evaluate_values, components, result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
demo.launch()
|
@ -1,111 +0,0 @@
|
||||
import gradio as gr
|
||||
from datetime import datetime
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import pandas as pd
|
||||
|
||||
from demos.kitchen_sink_random.constants import (
|
||||
file_dir,
|
||||
img_dir,
|
||||
highlighted_text,
|
||||
highlighted_text_output_2,
|
||||
highlighted_text_output_1,
|
||||
random_plot,
|
||||
random_model3d,
|
||||
)
|
||||
|
||||
|
||||
components = [
|
||||
gr.Textbox(value=lambda: datetime.now(), label="Current Time"),
|
||||
gr.Number(value=lambda: random.random(), label="Random Percentage"),
|
||||
gr.Slider(minimum=-1, maximum=1, randomize=True, label="Slider with randomize"),
|
||||
gr.Slider(
|
||||
minimum=0,
|
||||
maximum=1,
|
||||
value=lambda: random.random(),
|
||||
label="Slider with value func",
|
||||
),
|
||||
gr.Checkbox(value=lambda: random.random() > 0.5, label="Random Checkbox"),
|
||||
gr.CheckboxGroup(
|
||||
choices=["a", "b", "c", "d"],
|
||||
value=lambda: random.choice(["a", "b", "c", "d"]),
|
||||
label="Random CheckboxGroup",
|
||||
),
|
||||
gr.Radio(
|
||||
choices=list(string.ascii_lowercase),
|
||||
value=lambda: random.choice(string.ascii_lowercase),
|
||||
),
|
||||
gr.Dropdown(
|
||||
choices=["a", "b", "c", "d", "e"],
|
||||
value=lambda: random.choice(["a", "b", "c"]),
|
||||
),
|
||||
gr.Image(
|
||||
value=lambda: random.choice(
|
||||
[os.path.join(img_dir, img) for img in os.listdir(img_dir)]
|
||||
)
|
||||
),
|
||||
gr.Video(value=lambda: os.path.join(file_dir, "world.mp4")),
|
||||
gr.Audio(value=lambda: os.path.join(file_dir, "cantina.wav")),
|
||||
gr.File(
|
||||
value=lambda: random.choice(
|
||||
[os.path.join(file_dir, img) for img in os.listdir(file_dir)]
|
||||
)
|
||||
),
|
||||
gr.Dataframe(
|
||||
value=lambda: pd.DataFrame({"random_number_rows": range(random.randint(0, 10))})
|
||||
),
|
||||
gr.Timeseries(value=lambda: os.path.join(file_dir, "time.csv")),
|
||||
gr.ColorPicker(value=lambda: random.choice(["#000000", "#ff0000", "#0000FF"])),
|
||||
gr.Label(value=lambda: random.choice(["Pedestrian", "Car", "Cyclist"])),
|
||||
gr.HighlightedText(
|
||||
value=lambda: random.choice(
|
||||
[
|
||||
{"text": highlighted_text, "entities": highlighted_text_output_1},
|
||||
{"text": highlighted_text, "entities": highlighted_text_output_2},
|
||||
]
|
||||
),
|
||||
),
|
||||
gr.JSON(value=lambda: random.choice([{"a": 1}, {"b": 2}])),
|
||||
gr.HTML(
|
||||
value=lambda: random.choice(
|
||||
[
|
||||
'<p style="color:red;">I am red</p>',
|
||||
'<p style="color:blue;">I am blue</p>',
|
||||
]
|
||||
)
|
||||
),
|
||||
gr.Gallery(
|
||||
value=lambda: [os.path.join(img_dir, img) for img in os.listdir(img_dir)]
|
||||
),
|
||||
gr.Model3D(value=random_model3d),
|
||||
gr.Plot(value=random_plot),
|
||||
gr.Markdown(value=lambda: f"### {random.choice(['Hello', 'Hi', 'Goodbye!'])}"),
|
||||
]
|
||||
|
||||
|
||||
with gr.Blocks() as demo:
|
||||
for component in components:
|
||||
component.render()
|
||||
reset = gr.Button(value="Reset")
|
||||
hide = gr.Button(value="Hide")
|
||||
reveal = gr.Button(value="Reveal")
|
||||
reset.click(
|
||||
lambda: [c.update(value=None) for c in components],
|
||||
inputs=[],
|
||||
outputs=components,
|
||||
)
|
||||
hide.click(
|
||||
lambda: [c.update(visible=False) for c in components],
|
||||
inputs=[],
|
||||
outputs=components
|
||||
)
|
||||
reveal.click(
|
||||
lambda: [c.update(visible=True) for c in components],
|
||||
inputs=[],
|
||||
outputs=components
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
demo.launch()
|
28
js/app/test/clear_components.spec.ts
Normal file
28
js/app/test/clear_components.spec.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { test, expect } from "@gradio/tootils";
|
||||
|
||||
test("Components value can be set via callable to a non-None value", async ({
|
||||
page
|
||||
}) => {
|
||||
const textBoxValue = await page.getByLabel(`component_00`).inputValue();
|
||||
expect(textBoxValue.length).toBeGreaterThan(1);
|
||||
|
||||
const sliderValue = await page.getByLabel(`component_01`).inputValue();
|
||||
expect(parseFloat(sliderValue)).toBeGreaterThan(0);
|
||||
|
||||
const dropDownValue = await page.getByLabel(`component_07`).inputValue();
|
||||
expect(Array("a", "b", "c").includes(dropDownValue)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("gr.ClearButton clears every component's value", async ({ page }) => {
|
||||
await Promise.all([
|
||||
page.waitForResponse("**/run/predict"),
|
||||
page.click("text=Get Values")
|
||||
]);
|
||||
await expect(page.getByLabel("Are all cleared?")).toHaveValue("False");
|
||||
await page.click("text=Clear");
|
||||
await Promise.all([
|
||||
page.waitForResponse("**/run/predict"),
|
||||
page.click("text=Get Values")
|
||||
]);
|
||||
await expect(page.getByLabel("Are all cleared?")).toHaveValue("True");
|
||||
});
|
@ -18,6 +18,7 @@ def copy_all_demos(source_dir: str, dest_dir: str):
|
||||
"calculator",
|
||||
"cancel_events",
|
||||
"chatbot_multimodal",
|
||||
"clear_components",
|
||||
"code",
|
||||
"fake_gan",
|
||||
"fake_diffusion_with_gif",
|
||||
@ -32,7 +33,6 @@ def copy_all_demos(source_dir: str, dest_dir: str):
|
||||
"matrix_transpose",
|
||||
"model3D",
|
||||
"native_plots",
|
||||
"reset_components",
|
||||
"reverse_audio",
|
||||
"stt_or_tts",
|
||||
"stream_audio",
|
||||
|
@ -23,7 +23,7 @@ gradio_version = gradio_version.strip()
|
||||
# 2. reset_components includes media files that are only present in all_demos (only for PRs)
|
||||
# 3. custom_path doesn't have .launch since the point is to show how to launch with uvicorn
|
||||
# 4. The same reason as 2 for kitchen_sink_random and blocks_kitchen_sink
|
||||
DEMOS_TO_SKIP = {"all_demos", "reset_components", "custom_path", "kitchen_sink_random", "blocks_kitchen_sink"}
|
||||
DEMOS_TO_SKIP = {"all_demos", "clear_components", "custom_path", "kitchen_sink_random", "blocks_kitchen_sink"}
|
||||
|
||||
|
||||
def upload_demo_to_space(
|
||||
|
Loading…
x
Reference in New Issue
Block a user