2
0
mirror of https://github.com/gradio-app/gradio.git synced 2025-04-18 12:50:30 +08:00
This commit is contained in:
Ali Abid 2022-07-25 04:46:11 +01:00
parent 3a93202fd6
commit 7a486d77f6
9 changed files with 171 additions and 20 deletions

@ -8,8 +8,9 @@ with gr.Blocks() as demo:
symptoms_box = gr.CheckboxGroup(["Cough", "Fever", "Runny Nose"])
submit_btn = gr.Button("Submit")
diagnosis_box = gr.Textbox(label="Diagnosis")
patient_summary_box = gr.Textbox(label="Patient Summary", visible=False)
with gr.Column(visible=False) as output_col:
diagnosis_box = gr.Textbox(label="Diagnosis")
patient_summary_box = gr.Textbox(label="Patient Summary", visible=False)
def submit(name, age, symptoms):
if len(name) == 0:
@ -17,6 +18,7 @@ with gr.Blocks() as demo:
if age < 0 or age > 200:
return {error_box: gr.update(value="Enter valid age", visible=True)}
return {
output_col: gr.update(visible=True),
diagnosis_box: "covid" if "Cough" in symptoms else "flu",
patient_summary_box: gr.update(value=f"{name}, {age} y/o", visible=True)
}
@ -24,7 +26,7 @@ with gr.Blocks() as demo:
submit_btn.click(
submit,
[name_box, age_box, symptoms_box],
[error_box, diagnosis_box, patient_summary_box],
[error_box, diagnosis_box, patient_summary_box, output_col],
)
if __name__ == "__main__":

36
demo/hangman/run.py Normal file

@ -0,0 +1,36 @@
import gradio as gr
import random
secret_word = "gradio"
with gr.Blocks() as demo:
used_letters_var = gr.Variable([])
with gr.Row() as row:
with gr.Column():
input_letter = gr.Textbox(label="Enter letter")
btn = gr.Button("Guess Letter")
with gr.Column():
hangman = gr.Textbox(
label="Hangman",
value="_"*len(secret_word)
)
used_letters_box = gr.Textbox()
def guess_letter(letter, used_letters):
used_letters.append(letter)
answer = "".join([
(letter if letter in used_letters else "_")
for letter in secret_word
])
return {
used_letters_var: used_letters,
used_letters_box: ", ".join(used_letters),
hangman: answer
}
btn.click(
guess_letter,
[input_letter, used_letters_var],
[used_letters_var, used_letters_box, hangman]
)
if __name__ == "__main__":
demo.launch()

Binary file not shown.

After

(image error) Size: 20 KiB

@ -0,0 +1,12 @@
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
text1 = gr.Textbox(label="prompt 1")
text2 = gr.Textbox(label="prompt 2")
with gr.Column():
img1 = gr.Image("images/cheetah.jpg")
btn = gr.Button("Go").style(full_width=True)
if __name__ == "__main__":
demo.launch()

@ -4,7 +4,7 @@ Let's go through some of the most popular features of Gradio!
## Example Inputs
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argument of the Interface constructor. Each sublist within the outer list represents a data sample, and each element within the sublist represents an input for each input component. The format of example data for each component is specified in the [Docs](https://gradio.app/docs).
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argument of the Interface constructor. Each sublist within the outer list represents a data sample, and each element within the sublist represents an input for each input component. The format of example data for each component is specified in the [Docs](https://gradio.app/docs).
$code_calculator
$demo_calculator
@ -73,6 +73,15 @@ im/1.png,Output/1.png
If you wish for the user to provide a reason for flagging, you can pass a list of strings to the `flagging_options` argument of Interface. Users will have to select one of the strings when flagging, which will be saved as an additional column to the CSV.
## Styling
Many components can be styled through the `style()` method. For example:
```python
img = gr.Image("lion.jpg").style(height='24', rounded=False)
```
Take a look at the [Docs](https://gradio.app/docs) to see all the styling options for each Component.
## Queuing

@ -0,0 +1,48 @@
# Controlling Layout
By default, Components in Blocks are arranged vertically. Let's take a look at how we can rearrange Components. Under the hood, this layout structure uses the [flexbox model of web development](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox).
## Rows
Elements within a `with gr.Row` clause will all be displayed horizontally. For example, to display two Buttons side by side:
```python
with gr.Blocks() as demo:
with gr.Row():
btn1 = gr.Button("Button 1")
btn2 = gr.Button("Button 2")
```
To make every element in a Row have the same height, use the `equal_height` argument.
```python
with gr.Blocks() as demo:
with gr.Row(equal_height=True):
textbox = gr.Textbox()
btn2 = gr.Button("Button 2")
```
## Columns and Nesting
Components within a Column will be placed vertically atop each other. Since the vertical layout is the default layout for Blocks apps anyway, to be useful, Columns are usually nested within Rows. For example:
$code_rows_and_columns
$demo_rows_and_columns
See how the first column has two Textboxes arranged vertically. The second column has an Image and Button arranged vertically.
## Tabs
You can also create Tabs using the `with gradio.Tabs():` clause, and create multiple `with gradio.TabItem('tab_name'):` children. Any component created inside of a `with gradio.TabItem(name_of_tab):` context appears in that tab.
For example:
$code_blocks_flipper
$demo_blocks_flipper
## Visibility
Both Components and Layout elements have a `visible` argument that can set initially and also updated using `gr.update()`. Setting `gr.update(visible=...)` on a Column can be used to show or hide a set of Components.
$code_blocks_form
$demo_blocks_form

@ -0,0 +1,29 @@
# State in Blocks
## Global State
Global state in Blocks works the same as in Interface. Any variable created outside a function call is a reference shared between all users.
## Session State
Gradio supports session **state**, where data persists across multiple submits within a page session, in Blocks apps as well. To reiterate, session data is *not* shared between different users of your model. To store data in a session state, you need to do three things:
1. Create a `gr.Variable()` object. If there is a default value to this stateful object, pass that into the constructor.
2. In the event listener, put the `Variable` object as an input and output.
3. In the event listener function, add the variable to the input parameters and the return value.
Let's take a look at a game of hangman.
$code_hangman
$demo_hangman
Let's see how we do each of the 3 steps listed above in this game:
1. We store the used letters in `used_letters_var`. In the constructor of `Variable`, we set the initial value of this to `[]`, an empty list.
2. In `btn.click()`, we have a reference to `used_letters_var` in both the inputs and outputs.
3. In `guess_letter`, we pass the value of this `Variable` to `used_letters`, and then return an updated value of this `Variable` in the return statement.
With more complex apps, you will likely have many Variables storing session state in a single Blocks app.

@ -0,0 +1,31 @@
# Custom JS and CSS
## Custom CSS
For additional styling ability, you can pass any CSS to your app using the `css=` kwarg:
```python
with gr.Blocks(css="body {background-color: red}") as demo:
...
```
You can also pass the filepath to a CSS file to this argument.
## The `elem_id` Argument
You can `elem_id` to add an HTML element `id` to any component. This will allow you to select elements more easily with CSS.
```python
with gr.Blocks(css="#warning {color: red}") as demo:
box1 = gr.Textbox(value="Good Job")
box2 = gr.Textbox(value="Failure", elem_id="warning")
```
The CSS ruleset will only target the second Textbox here.
## Custom JS
Event listeners have a `_js` argument that can take a Javascript function as a string and treat it just like a Python event listener function. You can pass both a Javascript function and a Python function (in which case the Javascript function is run first) or only Javascript (and set the Python `fn` to `None`). Take a look at the code below:
$code_blocks_js_methods
$demo_blocks_js_methods

@ -1,16 +0,0 @@
## Adding examples to a Blocks app
In order to add examples to an app written with the Blocks API, you need to use the `gr.Examples` component helper.
This class is a wrapper over the `gr.Dataset` component.
During class creation, `gr.Examples` will instantiate a `gr.Dataset` and attach an event listener on the dataset click event
that will populate all the inputs with the values of that row of the dataset.
To show this in practice, we will build the same calculator but with Blocks instead of an Interface.
$code_calculator_blocks
$demo_calculator_blocks
By the way, Interface uses `gr.Examples` under the hood too!
So if you know how this example works you also know how the Interface examples work! 🥳