Skip to content

Commit 398f556

Browse files
authored
Merge pull request #848 from gradio-app/update-demos
Started updating demos to use the new `gradio.components` syntax
2 parents a8ab1c8 + 40efaac commit 398f556

12 files changed

Lines changed: 157 additions & 62 deletions

File tree

demo/calculator/run.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import gradio as gr
22

3-
43
def calculator(num1, operation, num2):
54
if operation == "add":
65
return num1 + num2
@@ -12,9 +11,9 @@ def calculator(num1, operation, num2):
1211
return num1 / num2
1312

1413

15-
iface = gr.Interface(
14+
demo = gr.Interface(
1615
calculator,
17-
["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"],
16+
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
1817
"number",
1918
examples=[
2019
[5, "add", 3],
@@ -28,4 +27,4 @@ def calculator(num1, operation, num2):
2827
)
2928

3029
if __name__ == "__main__":
31-
iface.launch()
30+
demo.launch()

demo/calculator_live/run.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ def calculator(num1, operation, num2):
1212
return num1 / num2
1313

1414

15-
iface = gr.Interface(
15+
demo = gr.Interface(
1616
calculator,
17-
["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"],
17+
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
1818
"number",
1919
live=True,
2020
)
2121

2222
if __name__ == "__main__":
23-
iface.launch()
23+
demo.launch()

demo/kinematics_blocks/run.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import gradio as gr
2+
import matplotlib.pyplot as plt
3+
import numpy as np
4+
5+
6+
def plot(v, a):
7+
g = 9.81
8+
theta = a/180*3.14
9+
tmax = ((2 * v) * np.sin(theta)) / g
10+
timemat = tmax*np.linspace(0,1,40)[:,None]
11+
12+
x = ((v * timemat) * np.cos(theta))
13+
y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat ** 2))
14+
15+
fig = plt.figure()
16+
plt.scatter(x=x, y=y, marker='.')
17+
plt.xlim(0, 100)
18+
plt.ylim(0, 60)
19+
return fig
20+
21+
demo = gr.Blocks()
22+
23+
with demo:
24+
gr.Markdown("Let's do some kinematics! Choose the speed and angle to see the trajectory.")
25+
26+
with gr.Row():
27+
speed = gr.Slider(25, min=1, max=30,label="Speed")
28+
angle = gr.Slider(45, min=0, max=90, label="Angle")
29+
output = gr.Image(type="plot")
30+
btn = gr.Button("Run")
31+
btn.click(plot, [speed, angle], output)
32+
33+
if __name__ == "__main__":
34+
demo.launch()

demo/static_textbox_blocks/run.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import gradio as gr
2+
3+
demo = gr.Blocks()
4+
5+
with demo:
6+
gr.Textbox("Hello")
7+
gr.Number(5)
8+
9+
if __name__ == "__main__":
10+
demo.launch()

demo/write_config.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""Writes the config file for any of the demos to an output file
2+
3+
Usage: python write_config.py <demo_name> <output_file>
4+
Example: python write_config.py calculator output.json
5+
6+
Assumes:
7+
- The demo_name is a folder in this directory
8+
- The demo_name folder contains a run.py file
9+
- The run.py which defines a Gradio Interface/Blocks instance called demo
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import argparse
15+
import importlib
16+
import json
17+
18+
import gradio as gr
19+
20+
parser = argparse.ArgumentParser()
21+
parser.add_argument("demo_name", help="the name of the demo whose config to write")
22+
parser.add_argument("file_path", help="the path at which to write the config file")
23+
args = parser.parse_args()
24+
25+
# import the run.py file from inside the directory specified by args.demo_name
26+
run = importlib.import_module(f"{args.demo_name}.run")
27+
28+
demo: gr.Blocks = run.iface
29+
config = demo.get_config_file()
30+
31+
json.dump(config, open(args.file_path, "w"), indent=2)

demo/xray_blocks/run.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,11 @@
2323
with gr.Row():
2424
xray_scan = gr.components.Image()
2525
xray_results = gr.components.JSON()
26-
output_textbox = gr.components.Textbox()
27-
input_textbox = gr.components.Textbox(default_value="Hello This Is a Input Textbox")
2826
xray_run = gr.Button("Run", css={
2927
"background-color": "red",
3028
"--hover-color": "orange"
3129
})
3230
xray_run.click(xray_model, inputs=[disease, xray_scan], outputs=xray_results)
33-
xray_run.click(xray_model, inputs=[disease, xray_scan], outputs=output_textbox)
3431

3532
with gr.TabItem("CT Scan"):
3633
with gr.Row():
@@ -41,8 +38,4 @@
4138

4239
overall_probability = gr.components.Textbox()
4340

44-
# TODO: remove later
45-
import json
46-
print(json.dumps(xray_blocks.get_config_file(), indent=2))
47-
4841
xray_blocks.launch()

gradio/__init__.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,31 @@
44
import gradio.inputs as inputs
55
import gradio.outputs as outputs
66
from gradio.blocks import Blocks, Column, Row, TabItem, Tabs
7+
from gradio.components import (
8+
HTML,
9+
JSON,
10+
Audio,
11+
Button,
12+
Carousel,
13+
Chatbot,
14+
Checkbox,
15+
CheckboxGroup,
16+
Dataframe,
17+
Dropdown,
18+
File,
19+
HighlightedText,
20+
Image,
21+
KeyValues,
22+
Label,
23+
Markdown,
24+
Number,
25+
Radio,
26+
Slider,
27+
State,
28+
Textbox,
29+
Timeseries,
30+
Video,
31+
)
732
from gradio.flagging import (
833
CSVLogger,
934
FlaggingCallback,
@@ -13,7 +38,6 @@
1338
from gradio.interface import Interface, close_all, reset_all
1439
from gradio.mix import Parallel, Series
1540
from gradio.routes import get_state, set_state
16-
from gradio.static import Button, Markdown
1741

1842
current_pkg_version = pkg_resources.require("gradio")[0].version
1943
__version__ = current_pkg_version

gradio/blocks.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import os
24
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
35

gradio/components.py

Lines changed: 42 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,12 @@
1616
import PIL
1717
from ffmpy import FFmpeg
1818
from markdown_it import MarkdownIt
19+
import matplotlib.figure
1920

2021
from gradio import processing_utils, test_data
2122
from gradio.blocks import Block
2223

24+
2325
class Component(Block):
2426
"""
2527
A base class for defining the methods that all gradio components should have.
@@ -752,27 +754,27 @@ class CheckboxGroup(Component):
752754

753755
def __init__(
754756
self,
755-
default_value: List[str] = None,
756-
*,
757757
choices: List[str],
758+
*,
759+
default_selected: List[str] = None,
758760
type: str = "value",
759761
label: Optional[str] = None,
760762
css: Optional[Dict] = None,
761763
**kwargs,
762764
):
763765
"""
764766
Parameters:
765-
default_value (List[str]): default selected list of options.
766767
choices (List[str]): list of options to select from.
768+
default_selected (List[str]): default selected list of options.
767769
type (str): Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected.
768770
label (str): component name in interface.
769771
"""
770772
if (
771-
default_value is None
773+
default_selected is None
772774
): # Mutable parameters shall not be given as default parameters in the function.
773-
default_value = []
775+
default_selected = []
774776
self.choices = choices
775-
self.default = default_value
777+
self.default = default_selected
776778
self.type = type
777779
self.test_input = self.choices
778780
self.interpret_by_tokens = False
@@ -880,25 +882,27 @@ class Radio(Component):
880882

881883
def __init__(
882884
self,
883-
default_value: Optional[str] = None,
884-
*,
885885
choices: List[str],
886+
*,
887+
default_selected: Optional[str] = None,
886888
type: str = "value",
887889
label: Optional[str] = None,
888890
css: Optional[Dict] = None,
889891
**kwargs,
890892
):
891893
"""
892894
Parameters:
893-
default_value (str): the button selected by default. If None, no button is selected by default.
894895
choices (List[str]): list of options to select from.
896+
default_selected (str): the button selected by default. If None, no button is selected by default.
895897
type (str): Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
896898
label (str): component name in interface.
897899
"""
898900
self.choices = choices
899901
self.type = type
900902
self.test_input = self.choices[0]
901-
self.default = default_value if default_value is not None else self.choices[0]
903+
self.default = (
904+
default_selected if default_selected is not None else self.choices[0]
905+
)
902906
self.interpret_by_tokens = False
903907
super().__init__(label=label, css=css, **kwargs)
904908

@@ -983,24 +987,24 @@ class Dropdown(Radio):
983987

984988
def __init__(
985989
self,
986-
default_value: Optional[str] = None,
987-
*,
988990
choices: List[str],
991+
*,
992+
default_selected: Optional[str] = None,
989993
type: str = "value",
990994
label: Optional[str] = None,
991995
css: Optional[Dict] = None,
992996
**kwargs,
993997
):
994998
"""
995999
Parameters:
996-
default_value (str): default value selected in dropdown. If None, no value is selected by default.
9971000
choices (List[str]): list of options to select from.
1001+
default_selected (str): default value selected in dropdown. If None, no value is selected by default.
9981002
type (str): Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
9991003
label (str): component name in interface.
10001004
"""
10011005
# Everything is same with Dropdown and Radio, so let's make use of it :)
10021006
super().__init__(
1003-
default_value=default_value,
1007+
default_selected=default_selected,
10041008
choices=choices,
10051009
type=type,
10061010
label=label,
@@ -1281,7 +1285,7 @@ def postprocess(self, y):
12811285
dtype = "pil"
12821286
elif isinstance(y, str):
12831287
dtype = "file"
1284-
elif isinstance(y, ModuleType):
1288+
elif isinstance(y, (ModuleType, matplotlib.figure.Figure)):
12851289
dtype = "plot"
12861290
else:
12871291
raise ValueError(
@@ -2670,7 +2674,12 @@ class Chatbot(Component):
26702674
"""
26712675

26722676
def __init__(
2673-
self, default_value="", *, label: Optional[str] = None, css: Optional[Dict] = None, **kwargs
2677+
self,
2678+
default_value="",
2679+
*,
2680+
label: Optional[str] = None,
2681+
css: Optional[Dict] = None,
2682+
**kwargs,
26742683
):
26752684
"""
26762685
Parameters:
@@ -2722,12 +2731,9 @@ def __init__(
27222731
super().__init__(label=label, css=css, **kwargs)
27232732
self.md = MarkdownIt()
27242733
self.value = self.md.render(default_value)
2725-
2734+
27262735
def get_template_context(self):
2727-
return {
2728-
"value": self.value,
2729-
**super().get_template_context()
2730-
}
2736+
return {"value": self.value, **super().get_template_context()}
27312737

27322738

27332739
class Button(Component):
@@ -2741,12 +2747,20 @@ def __init__(
27412747
):
27422748
super().__init__(label=label, css=css, **kwargs)
27432749
self.value = default_value
2744-
2750+
27452751
def get_template_context(self):
2746-
return {
2747-
"value": self.value,
2748-
**super().get_template_context()
2749-
}
2752+
return {"value": self.value, **super().get_template_context()}
2753+
2754+
def click(self, fn: Callable, inputs: List[Component], outputs: List[Component]):
2755+
"""
2756+
Parameters:
2757+
fn: Callable function
2758+
inputs: List of inputs
2759+
outputs: List of outputs
2760+
Returns: None
2761+
"""
2762+
self.set_event_trigger("click", fn, inputs, outputs)
2763+
27502764

27512765
class DatasetViewer(Component):
27522766
def __init__(
@@ -2761,12 +2775,12 @@ def __init__(
27612775
super().__init__(label=label, css=css, **kwargs)
27622776
self.types = types
27632777
self.value = default_value
2764-
2778+
27652779
def get_template_context(self):
27662780
return {
27672781
"types": [_type.__class__.__name__.lower() for _type in types],
27682782
"value": self.value,
2769-
**super().get_template_context()
2783+
**super().get_template_context(),
27702784
}
27712785

27722786
def click(self, fn: Callable, inputs: List[Component], outputs: List[Component]):

0 commit comments

Comments
 (0)