Merge pull request #848 from gradio-app/update-demos

Started updating demos to use the new `gradio.components` syntax
This commit is contained in:
Abubakar Abid 2022-03-22 18:53:31 -07:00 committed by GitHub
commit 398f5560d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 157 additions and 62 deletions

View File

@ -1,6 +1,5 @@
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
@ -12,9 +11,9 @@ def calculator(num1, operation, num2):
return num1 / num2
iface = gr.Interface(
demo = gr.Interface(
calculator,
["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"],
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
"number",
examples=[
[5, "add", 3],
@ -28,4 +27,4 @@ iface = gr.Interface(
)
if __name__ == "__main__":
iface.launch()
demo.launch()

View File

@ -12,12 +12,12 @@ def calculator(num1, operation, num2):
return num1 / num2
iface = gr.Interface(
demo = gr.Interface(
calculator,
["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"],
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
"number",
live=True,
)
if __name__ == "__main__":
iface.launch()
demo.launch()

View File

@ -0,0 +1,34 @@
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
def plot(v, a):
g = 9.81
theta = a/180*3.14
tmax = ((2 * v) * np.sin(theta)) / g
timemat = tmax*np.linspace(0,1,40)[:,None]
x = ((v * timemat) * np.cos(theta))
y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat ** 2))
fig = plt.figure()
plt.scatter(x=x, y=y, marker='.')
plt.xlim(0, 100)
plt.ylim(0, 60)
return fig
demo = gr.Blocks()
with demo:
gr.Markdown("Let's do some kinematics! Choose the speed and angle to see the trajectory.")
with gr.Row():
speed = gr.Slider(25, min=1, max=30,label="Speed")
angle = gr.Slider(45, min=0, max=90, label="Angle")
output = gr.Image(type="plot")
btn = gr.Button("Run")
btn.click(plot, [speed, angle], output)
if __name__ == "__main__":
demo.launch()

View File

@ -0,0 +1,10 @@
import gradio as gr
demo = gr.Blocks()
with demo:
gr.Textbox("Hello")
gr.Number(5)
if __name__ == "__main__":
demo.launch()

31
demo/write_config.py Normal file
View File

@ -0,0 +1,31 @@
"""Writes the config file for any of the demos to an output file
Usage: python write_config.py <demo_name> <output_file>
Example: python write_config.py calculator output.json
Assumes:
- The demo_name is a folder in this directory
- The demo_name folder contains a run.py file
- The run.py which defines a Gradio Interface/Blocks instance called demo
"""
from __future__ import annotations
import argparse
import importlib
import json
import gradio as gr
parser = argparse.ArgumentParser()
parser.add_argument("demo_name", help="the name of the demo whose config to write")
parser.add_argument("file_path", help="the path at which to write the config file")
args = parser.parse_args()
# import the run.py file from inside the directory specified by args.demo_name
run = importlib.import_module(f"{args.demo_name}.run")
demo: gr.Blocks = run.iface
config = demo.get_config_file()
json.dump(config, open(args.file_path, "w"), indent=2)

View File

@ -23,14 +23,11 @@ with xray_blocks:
with gr.Row():
xray_scan = gr.components.Image()
xray_results = gr.components.JSON()
output_textbox = gr.components.Textbox()
input_textbox = gr.components.Textbox(default_value="Hello This Is a Input Textbox")
xray_run = gr.Button("Run", css={
"background-color": "red",
"--hover-color": "orange"
})
xray_run.click(xray_model, inputs=[disease, xray_scan], outputs=xray_results)
xray_run.click(xray_model, inputs=[disease, xray_scan], outputs=output_textbox)
with gr.TabItem("CT Scan"):
with gr.Row():
@ -41,8 +38,4 @@ with xray_blocks:
overall_probability = gr.components.Textbox()
# TODO: remove later
import json
print(json.dumps(xray_blocks.get_config_file(), indent=2))
xray_blocks.launch()

View File

@ -4,6 +4,31 @@ import gradio.components as components
import gradio.inputs as inputs
import gradio.outputs as outputs
from gradio.blocks import Blocks, Column, Row, TabItem, Tabs
from gradio.components import (
HTML,
JSON,
Audio,
Button,
Carousel,
Chatbot,
Checkbox,
CheckboxGroup,
Dataframe,
Dropdown,
File,
HighlightedText,
Image,
KeyValues,
Label,
Markdown,
Number,
Radio,
Slider,
State,
Textbox,
Timeseries,
Video,
)
from gradio.flagging import (
CSVLogger,
FlaggingCallback,
@ -13,7 +38,6 @@ from gradio.flagging import (
from gradio.interface import Interface, close_all, reset_all
from gradio.mix import Parallel, Series
from gradio.routes import get_state, set_state
from gradio.static import Button, Markdown
current_pkg_version = pkg_resources.require("gradio")[0].version
__version__ = current_pkg_version

View File

@ -1,3 +1,5 @@
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple

View File

@ -16,10 +16,12 @@ import pandas as pd
import PIL
from ffmpy import FFmpeg
from markdown_it import MarkdownIt
import matplotlib.figure
from gradio import processing_utils, test_data
from gradio.blocks import Block
class Component(Block):
"""
A base class for defining the methods that all gradio components should have.
@ -752,9 +754,9 @@ class CheckboxGroup(Component):
def __init__(
self,
default_value: List[str] = None,
*,
choices: List[str],
*,
default_selected: List[str] = None,
type: str = "value",
label: Optional[str] = None,
css: Optional[Dict] = None,
@ -762,17 +764,17 @@ class CheckboxGroup(Component):
):
"""
Parameters:
default_value (List[str]): default selected list of options.
choices (List[str]): list of options to select from.
default_selected (List[str]): default selected list of options.
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.
label (str): component name in interface.
"""
if (
default_value is None
default_selected is None
): # Mutable parameters shall not be given as default parameters in the function.
default_value = []
default_selected = []
self.choices = choices
self.default = default_value
self.default = default_selected
self.type = type
self.test_input = self.choices
self.interpret_by_tokens = False
@ -880,9 +882,9 @@ class Radio(Component):
def __init__(
self,
default_value: Optional[str] = None,
*,
choices: List[str],
*,
default_selected: Optional[str] = None,
type: str = "value",
label: Optional[str] = None,
css: Optional[Dict] = None,
@ -890,15 +892,17 @@ class Radio(Component):
):
"""
Parameters:
default_value (str): the button selected by default. If None, no button is selected by default.
choices (List[str]): list of options to select from.
default_selected (str): the button selected by default. If None, no button is selected by default.
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.
label (str): component name in interface.
"""
self.choices = choices
self.type = type
self.test_input = self.choices[0]
self.default = default_value if default_value is not None else self.choices[0]
self.default = (
default_selected if default_selected is not None else self.choices[0]
)
self.interpret_by_tokens = False
super().__init__(label=label, css=css, **kwargs)
@ -983,9 +987,9 @@ class Dropdown(Radio):
def __init__(
self,
default_value: Optional[str] = None,
*,
choices: List[str],
*,
default_selected: Optional[str] = None,
type: str = "value",
label: Optional[str] = None,
css: Optional[Dict] = None,
@ -993,14 +997,14 @@ class Dropdown(Radio):
):
"""
Parameters:
default_value (str): default value selected in dropdown. If None, no value is selected by default.
choices (List[str]): list of options to select from.
default_selected (str): default value selected in dropdown. If None, no value is selected by default.
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.
label (str): component name in interface.
"""
# Everything is same with Dropdown and Radio, so let's make use of it :)
super().__init__(
default_value=default_value,
default_selected=default_selected,
choices=choices,
type=type,
label=label,
@ -1281,7 +1285,7 @@ class Image(Component):
dtype = "pil"
elif isinstance(y, str):
dtype = "file"
elif isinstance(y, ModuleType):
elif isinstance(y, (ModuleType, matplotlib.figure.Figure)):
dtype = "plot"
else:
raise ValueError(
@ -2670,7 +2674,12 @@ class Chatbot(Component):
"""
def __init__(
self, default_value="", *, label: Optional[str] = None, css: Optional[Dict] = None, **kwargs
self,
default_value="",
*,
label: Optional[str] = None,
css: Optional[Dict] = None,
**kwargs,
):
"""
Parameters:
@ -2722,12 +2731,9 @@ class Markdown(Component):
super().__init__(label=label, css=css, **kwargs)
self.md = MarkdownIt()
self.value = self.md.render(default_value)
def get_template_context(self):
return {
"value": self.value,
**super().get_template_context()
}
return {"value": self.value, **super().get_template_context()}
class Button(Component):
@ -2741,12 +2747,20 @@ class Button(Component):
):
super().__init__(label=label, css=css, **kwargs)
self.value = default_value
def get_template_context(self):
return {
"value": self.value,
**super().get_template_context()
}
return {"value": self.value, **super().get_template_context()}
def click(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)
class DatasetViewer(Component):
def __init__(
@ -2761,12 +2775,12 @@ class DatasetViewer(Component):
super().__init__(label=label, css=css, **kwargs)
self.types = types
self.value = default_value
def get_template_context(self):
return {
"types": [_type.__class__.__name__.lower() for _type in types],
"value": self.value,
**super().get_template_context()
**super().get_template_context(),
}
def click(self, fn: Callable, inputs: List[Component], outputs: List[Component]):

View File

@ -18,8 +18,8 @@ from markdown_it import MarkdownIt
from mdit_py_plugins.footnote import footnote_plugin
from gradio import interpretation, utils
from gradio.components import Component, get_component_instance, Markdown, Button
from gradio.blocks import BlockContext, Row, Column
from gradio.blocks import BlockContext, Column, Row
from gradio.components import Button, Component, Markdown, get_component_instance
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
@ -644,10 +644,11 @@ class Interface(Launchable):
}
def process_api(self, data: Dict[str, Any], username: str = None) -> Dict[str, Any]:
class RequestApi():
class RequestApi:
SUBMIT = 0
CLEAR = 1
FLAG = 2
raw_input = data["data"]
fn_index = data["fn_index"]
if fn_index == RequestApi.SUBMIT:
@ -658,7 +659,7 @@ class Interface(Launchable):
"data": [None]
* (len(self.input_components) + len(self.output_components))
}
elif fn_index == RequestApi.FLAG: # flag
elif fn_index == RequestApi.FLAG: # flag
pass
def process(self, raw_input: List[Any]) -> Tuple[List[Any], List[float]]:

View File

@ -1,13 +0,0 @@
from __future__ import annotations
from gradio.components import Button, Markdown
# TODO: (faruk) Remove this file in version 3.0
class Markdown(Markdown):
pass
class Button(Button):
pass

View File

@ -45,9 +45,9 @@
</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.a42f83b7.js"></script>
<script type="module" crossorigin src="./assets/index.b8adfcc9.js"></script>
<link rel="modulepreload" href="./assets/vendor.cb9b505c.js">
<link rel="stylesheet" href="./assets/index.5f57d3ce.css">
<link rel="stylesheet" href="./assets/index.7e32d9ef.css">
</head>
<body style="height: 100%; margin: 0; padding: 0">