make use of gr. consistent (#3901)

* make use of gr. consistent

* add changelog

* Update CHANGELOG.md

* fix digit_classifier notebook

* lint

---------

Co-authored-by: freddyaboulton <alfonsoboulton@gmail.com>
This commit is contained in:
Simon Duerr 2023-04-19 21:55:37 +02:00 committed by GitHub
parent e0eea96766
commit 6e7abf8645
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 66 additions and 60 deletions

View File

@ -13,7 +13,7 @@ No changes to highlight.
## Documentation Changes:
No changes to highlight.
- Make use of `gr` consistent across the docs by [@duerrsimon](https://github.com/duerrsimon) in [PR 3901](https://github.com/gradio-app/gradio/pull/3901)
## Testing and Infrastructure Changes:

View File

@ -1 +1 @@
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: digit_classifier"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tensorflow"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from urllib.request import urlretrieve\n", "\n", "import tensorflow as tf\n", "\n", "import gradio\n", "import gradio as gr\n", "\n", "urlretrieve(\n", " \"https://gr-models.s3-us-west-2.amazonaws.com/mnist-model.h5\", \"mnist-model.h5\"\n", ")\n", "model = tf.keras.models.load_model(\"mnist-model.h5\")\n", "\n", "\n", "def recognize_digit(image):\n", " image = image.reshape(1, -1)\n", " prediction = model.predict(image).tolist()[0]\n", " return {str(i): prediction[i] for i in range(10)}\n", "\n", "\n", "im = gradio.Image(shape=(28, 28), image_mode=\"L\", invert_colors=False, source=\"canvas\")\n", "\n", "demo = gr.Interface(\n", " recognize_digit,\n", " im,\n", " gradio.Label(num_top_classes=3),\n", " live=True,\n", " interpretation=\"default\",\n", " capture_session=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: digit_classifier"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio tensorflow"]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["from urllib.request import urlretrieve\n", "\n", "import tensorflow as tf\n", "\n", "import gradio as gr\n", "\n", "urlretrieve(\n", " \"https://gr-models.s3-us-west-2.amazonaws.com/mnist-model.h5\", \"mnist-model.h5\"\n", ")\n", "model = tf.keras.models.load_model(\"mnist-model.h5\")\n", "\n", "\n", "def recognize_digit(image):\n", " image = image.reshape(1, -1)\n", " prediction = model.predict(image).tolist()[0]\n", " return {str(i): prediction[i] for i in range(10)}\n", "\n", "\n", "im = gr.Image(shape=(28, 28), image_mode=\"L\", invert_colors=False, source=\"canvas\")\n", "\n", "demo = gr.Interface(\n", " recognize_digit,\n", " im,\n", " gr.Label(num_top_classes=3),\n", " live=True,\n", " interpretation=\"default\",\n", " capture_session=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}

View File

@ -2,7 +2,6 @@ from urllib.request import urlretrieve
import tensorflow as tf
import gradio
import gradio as gr
urlretrieve(
@ -17,12 +16,12 @@ def recognize_digit(image):
return {str(i): prediction[i] for i in range(10)}
im = gradio.Image(shape=(28, 28), image_mode="L", invert_colors=False, source="canvas")
im = gr.Image(shape=(28, 28), image_mode="L", invert_colors=False, source="canvas")
demo = gr.Interface(
recognize_digit,
im,
gradio.Label(num_top_classes=3),
gr.Label(num_top_classes=3),
live=True,
interpretation="default",
capture_session=True,

View File

@ -5,17 +5,19 @@ except ImportError:
import warnings
import gradio
import gradio as gr
def load_ipython_extension(ipython):
__demo = gradio.Blocks()
__demo = gr.Blocks()
@register_cell_magic
@needs_local_scope
def blocks(line, cell, local_ns=None):
if "gr.Interface" in cell:
warnings.warn("Usage of gr.Interface with %%blocks may result in errors.")
warnings.warn(
"Usage of gradio.Interface with %%blocks may result in errors."
)
with __demo.clear():
exec(cell, None, local_ns)
__demo.launch(quiet=True)

View File

@ -16,8 +16,8 @@ class Row(BlockContext):
"""
Row is a layout element within Blocks that renders all children horizontally.
Example:
with gradio.Blocks() as demo:
with gradio.Row():
with gr.Blocks() as demo:
with gr.Row():
gr.Image("lion.jpg")
gr.Image("tiger.jpg")
demo.launch()
@ -81,12 +81,12 @@ class Column(BlockContext):
Column is a layout element within Blocks that renders all children vertically. The widths of columns can be set through the `scale` and `min_width` parameters.
If a certain scale results in a column narrower than min_width, the min_width parameter will win.
Example:
with gradio.Blocks() as demo:
with gradio.Row():
with gradio.Column(scale=1):
with gr.Blocks() as demo:
with gr.Row():
with gr.Column(scale=1):
text1 = gr.Textbox()
text2 = gr.Textbox()
with gradio.Column(scale=4):
with gr.Column(scale=4):
btn1 = gr.Button("Button 1")
btn2 = gr.Button("Button 2")
Guides: controlling-layout
@ -180,11 +180,11 @@ class Tab(BlockContext, Selectable):
"""
Tab (or its alias TabItem) is a layout element. Components defined within the Tab will be visible when this tab is selected tab.
Example:
with gradio.Blocks() as demo:
with gradio.Tab("Lion"):
with gr.Blocks() as demo:
with gr.Tab("Lion"):
gr.Image("lion.jpg")
gr.Button("New Lion")
with gradio.Tab("Tiger"):
with gr.Tab("Tiger"):
gr.Image("tiger.jpg")
gr.Button("New Tiger")
Guides: controlling-layout
@ -231,7 +231,7 @@ class Group(BlockContext):
Group is a layout element within Blocks which groups together children so that
they do not have any padding or margin between them.
Example:
with gradio.Group():
with gr.Group():
gr.Textbox(label="First")
gr.Textbox(label="Last")
"""
@ -269,7 +269,7 @@ class Box(BlockContext):
Box is a a layout element which places children in a box with rounded corners and
some padding around them.
Example:
with gradio.Box():
with gr.Box():
gr.Textbox(label="First")
gr.Textbox(label="Last")
"""
@ -314,7 +314,7 @@ class Accordion(BlockContext):
"""
Accordion is a layout element which can be toggled to show/hide the contained content.
Example:
with gradio.Accordion("See Details"):
with gr.Accordion("See Details"):
gr.Markdown("lorem ipsum")
"""

View File

@ -22,6 +22,8 @@ pip install gradio
$code_hello_world
We shorten the imported name to `gr` for better readability of code using Gradio. This is a widely adopted convention that you should follow so that anyone working with your code can easily understand it.
3\. The demo below will appear automatically within the Jupyter Notebook, or pop in a browser on [http://localhost:7860](http://localhost:7860) if running from a script:
$demo_hello_world
@ -36,7 +38,7 @@ Note: you can also do `python app.py`, but it won't provide the automatic reload
## The `Interface` Class
You'll notice that in order to make the demo, we created a `gradio.Interface`. This `Interface` class can wrap any Python function with a user interface. In the example above, we saw a simple text-based function, but the function could be anything from music generator to a tax calculator to the prediction function of a pretrained machine learning model.
You'll notice that in order to make the demo, we created a `gr.Interface`. This `Interface` class can wrap any Python function with a user interface. In the example above, we saw a simple text-based function, but the function could be anything from music generator to a tax calculator to the prediction function of a pretrained machine learning model.
The core `Interface` class is initialized with three required parameters:

View File

@ -1,6 +1,6 @@
# Key Features
Let's go through some of the most popular features of Gradio! Here are Gradio's key features:
Let's go through some of the most popular features of Gradio! Here are Gradio's key features:
1. [Adding example inputs](#example-inputs)
2. [Passing custom error messages](#errors)
@ -20,7 +20,7 @@ You can provide example data that a user can easily load into `Interface`. This
$code_calculator
$demo_calculator
You can load a large dataset into the examples to browse and interact with the dataset through Gradio. The examples will be automatically paginated (you can configure this through the `examples_per_page` argument of `Interface`).
You can load a large dataset into the examples to browse and interact with the dataset through Gradio. The examples will be automatically paginated (you can configure this through the `examples_per_page` argument of `Interface`).
Continue learning about examples in the [More On Examples](https://gradio.app/more-on-examples) guide.
@ -61,6 +61,7 @@ For example, with the calculator interface shown above, we would have the flagge
```
*flagged/logs.csv*
```csv
num1,operation,num2,Output
5,add,7,12
@ -82,6 +83,7 @@ With the sepia interface shown earlier, we would have the flagged data stored in
```
*flagged/logs.csv*
```csv
im,Output
im/0.png,Output/0.png
@ -96,27 +98,26 @@ If you wish for the user to provide a reason for flagging, you can pass a list o
As you've seen, Gradio includes components that can handle a variety of different data types, such as images, audio, and video. Most components can be used both as inputs or outputs.
When a component is used as an input, Gradio automatically handles the *preprocessing* needed to convert the data from a type sent by the user's browser (such as a base64 representation of a webcam snapshot) to a form that can be accepted by your function (such as a `numpy` array).
When a component is used as an input, Gradio automatically handles the *preprocessing* needed to convert the data from a type sent by the user's browser (such as a base64 representation of a webcam snapshot) to a form that can be accepted by your function (such as a `numpy` array).
Similarly, when a component is used as an output, Gradio automatically handles the *postprocessing* needed to convert the data from what is returned by your function (such as a list of image paths) to a form that can be displayed in the user's browser (such as a `Gallery` of images in base64 format).
You can control the *preprocessing* using the parameters when constructing the image component. For example, here if you instantiate the `Image` component with the following parameters, it will convert the image to the `PIL` type and reshape it to be `(100, 100)` no matter the original size that it was submitted as:
```py
img = gradio.Image(shape=(100, 100), type="pil")
img = gr.Image(shape=(100, 100), type="pil")
```
In contrast, here we keep the original size of the image, but invert the colors before converting it to a numpy array:
```py
img = gradio.Image(invert_colors=True, type="numpy")
img = gr.Image(invert_colors=True, type="numpy")
```
Postprocessing is a lot easier! Gradio automatically recognizes the format of the returned data (e.g. is the `Image` a `numpy` array or a `str` filepath?) and postprocesses it into a format that can be displayed by the browser.
Take a look at the [Docs](https://gradio.app/docs) to see all the preprocessing-related parameters for each Component.
## Styling
Gradio themes are the easiest way to customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the `theme=` kwarg to the `Interface` constructor. For example:
@ -127,7 +128,6 @@ demo = gr.Interface(..., theme=gr.themes.Monochrome())
Gradio comes with a set of prebuilt themes which you can load from `gr.themes.*`. You can extend these themes or create your own themes from scratch - see the [Theming guide](https://gradio.app/theming-guide) for more details.
For additional styling ability, you can pass any CSS to your app using the `css=` kwarg.
The base class for the Gradio app is `gradio-container`, so here's an example that changes the background color of the Gradio app:
@ -144,18 +144,19 @@ 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
If your app expects heavy traffic, use the `queue()` method to control processing rate. This will queue up calls so only a certain number of requests are processed at a single time. Queueing uses websockets, which also prevent network timeouts, so you should use queueing if the inference time of your function is long (> 1min).
If your app expects heavy traffic, use the `queue()` method to control processing rate. This will queue up calls so only a certain number of requests are processed at a single time. Queueing uses websockets, which also prevent network timeouts, so you should use queueing if the inference time of your function is long (> 1min).
With `Interface`:
```python
demo = gr.Interface(...).queue()
demo.launch()
```
With `Blocks`:
```python
with gr.Blocks() as demo:
#...
@ -172,6 +173,7 @@ demo.queue(concurrency_count=3)
See the [Docs on queueing](/docs/#queue) on configuring other queuing parameters.
To specify only certain functions for queueing in Blocks:
```python
with gr.Blocks() as demo2:
num1 = gr.Number()
@ -207,7 +209,7 @@ Supplying a generator into Gradio **requires** you to enable queuing in the unde
## Progress Bars
Gradio supports the ability to create a custom Progress Bars so that you have customizability and control over the progress update that you show to the user. In order to enable this, simply add an argument to your method that has a default value of a `gradio.Progress` instance. Then you can update the progress levels by calling this instance directly with a float between 0 and 1, or using the `tqdm()` method of the `Progress` instance to track progress over an iterable, as shown below. Queueing must be enabled for progress updates.
Gradio supports the ability to create a custom Progress Bars so that you have customizability and control over the progress update that you show to the user. In order to enable this, simply add an argument to your method that has a default value of a `gr.Progress` instance. Then you can update the progress levels by calling this instance directly with a float between 0 and 1, or using the `tqdm()` method of the `Progress` instance to track progress over an iterable, as shown below. Queueing must be enabled for progress updates.
$code_progress_simple
$demo_progress_simple
@ -219,7 +221,7 @@ If you use the `tqdm` library, you can even report progress updates automaticall
Gradio supports the ability to pass *batch* functions. Batch functions are just
functions which take in a list of inputs and return a list of predictions.
For example, here is a batched function that takes in two lists of inputs (a list of
For example, here is a batched function that takes in two lists of inputs (a list of
words and a list of ints), and returns a list of trimmed words as output:
```py
@ -234,12 +236,13 @@ def trim_words(words, lens):
```
The advantage of using batched functions is that if you enable queuing, the Gradio
server can automatically *batch* incoming requests and process them in parallel,
server can automatically *batch* incoming requests and process them in parallel,
potentially speeding up your demo. Here's what the Gradio code looks like (notice
the `batch=True` and `max_batch_size=16` -- both of these parameters can be passed
into event triggers or into the `Interface` class)
into event triggers or into the `Interface` class)
With `Interface`:
```python
demo = gr.Interface(trim_words, ["textbox", "number"], ["output"],
batch=True, max_batch_size=16)
@ -247,8 +250,8 @@ demo.queue()
demo.launch()
```
With `Blocks`:
```py
import gradio as gr

View File

@ -22,7 +22,7 @@ with gr.Blocks() as demo:
btn2 = gr.Button("Button 2")
```
Learn more about Rows in the [docs](https://gradio.app/docs/#row).
Learn more about Rows in the [docs](https://gradio.app/docs/#row).
## Columns and Nesting
@ -31,22 +31,22 @@ Components within a Column will be placed vertically atop each other. Since the
$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. Notice how the relative widths of the two columns is set by the `scale` parameter. The column with twice the `scale` value takes up twice the width.
See how the first column has two Textboxes arranged vertically. The second column has an Image and Button arranged vertically. Notice how the relative widths of the two columns is set by the `scale` parameter. The column with twice the `scale` value takes up twice the width.
Columns have a `min_width` parameter as well (320 pixels by default). This prevents adjacent columns from becoming too narrow on mobile screens.
Learn more about Columns in the [docs](https://gradio.app/docs/#column).
Learn more about Columns in the [docs](https://gradio.app/docs/#column).
## Tabs and Accordions
You can also create Tabs using the `with gradio.Tab('tab_name'):` clause. Any component created inside of a `with gradio.Tab('tab_name'):` context appears in that tab. Consecutive Tab clauses are grouped together so that a single tab can be selected at one time, and only the components within that Tab's context are shown.
You can also create Tabs using the `with gr.Tab('tab_name'):` clause. Any component created inside of a `with gr.Tab('tab_name'):` context appears in that tab. Consecutive Tab clauses are grouped together so that a single tab can be selected at one time, and only the components within that Tab's context are shown.
For example:
$code_blocks_flipper
$demo_blocks_flipper
Also note the `gradio.Accordion('label')` in this example. The Accordion is a layout that can be toggled open or closed. Like `Tabs`, it is a layout element that can selectively hide or show content. Any components that are defined inside of a `with gradio.Accordion('label'):` will be hidden or shown when the accordion's toggle icon is clicked.
Also note the `gr.Accordion('label')` in this example. The Accordion is a layout that can be toggled open or closed. Like `Tabs`, it is a layout element that can selectively hide or show content. Any components that are defined inside of a `with gr.Accordion('label'):` will be hidden or shown when the accordion's toggle icon is clicked.
Learn more about [Tabs](https://gradio.app/docs/#tab) and [Accordions](https://gradio.app/docs/#accordion) in the docs.
@ -59,14 +59,13 @@ $demo_blocks_form
## Variable Number of Outputs
By adjusting the visibility of components in a dynamic way, it is possible to create
By adjusting the visibility of components in a dynamic way, it is possible to create
demos with Gradio that support a *variable numbers of outputs*. Here's a very simple example
where the number of output textboxes is controlled by an input slider:
$code_variable_outputs
$demo_variable_outputs
## Defining and Rendering Components Separately
In some cases, you might want to define components before you actually render them in your UI. For instance, you might want to show an examples section using `gr.Examples` above the corresponding `gr.Textbox` input. Since `gr.Examples` requires as a parameter the input component object, you will need to first define the input component, but then render it later, after you have defined the `gr.Examples` object.
@ -82,4 +81,3 @@ with gr.Blocks() as demo:
gr.Examples(["hello", "bonjour", "merhaba"], input_textbox)
input_textbox.render()
```

View File

@ -1,14 +1,14 @@
# How to Use the Plot Component for Maps
Related spaces:
Related spaces:
Tags: PLOTS, MAPS
## Introduction
This guide explains how you can use Gradio to plot geographical data on a map using the `gradio.Plot` component. The Gradio `Plot` component works with Matplotlib, Bokeh and Plotly. Plotly is what we will be working with in this guide. Plotly allows developers to easily create all sorts of maps with their geographical data. Take a look [here](https://plotly.com/python/maps/) for some examples.
## Overview
## Overview
We will be using the New York City Airbnb dataset, which is hosted on kaggle [here](https://www.kaggle.com/datasets/dgomonov/new-york-city-airbnb-open-data). I've uploaded it to the Hugging Face Hub as a dataset [here](https://huggingface.co/datasets/gradio/NYC-Airbnb-Open-Data) for easier use and download. Using this data we will plot Airbnb locations on a map output and allow filtering based on price and location. Below is the demo that we will be building. ⚡️
$demo_map_airbnb
@ -32,7 +32,7 @@ def filter_map(min_price, max_price, boroughs):
```
In the code above, we first load the csv data into a pandas dataframe. Let's begin by defining a function that we will use as the prediction function for the gradio app. This function will accept the minimum price and maximum price range as well as the list of boroughs to filter the resulting map. We can use the passed in values (`min_price`, `max_price`, and list of `boroughs`) to filter the dataframe and create `new_df`. Next we will create `text_list` of the names and prices of each Airbnb to use as labels on the map.
## Step 2 - Map Figure 🌐
Plotly makes it easy to work with maps. Let's take a look below how we can create a map figure.
@ -71,9 +71,9 @@ Above, we create a scatter plot on mapbox by passing it our list of latitudes an
More info [here](https://plotly.com/python/scattermapbox/) on scatter plots using Mapbox and Plotly.
## Step 3 - Gradio App ⚡️
We will use two `gradio.Number` components and a `gradio.CheckboxGroup` to allow users of our app to specify price ranges and borough locations. We will then use the `gr.Plot` component as an output for our Plotly + Mapbox map we created earlier.
We will use two `gr.Number` components and a `gr.CheckboxGroup` to allow users of our app to specify price ranges and borough locations. We will then use the `gr.Plot` component as an output for our Plotly + Mapbox map we created earlier.
```python
with gr.Blocks() as demo:
@ -95,6 +95,7 @@ This is what the full demo code looks like:
$code_map_airbnb
## Step 4 - Deployment 🤗
If you run the code above, your app will start running locally.
You can even get a temporary shareable link by passing the `share=True` parameter to `launch`.
@ -104,6 +105,7 @@ Let's deploy our Gradio app to the free HuggingFace Spaces platform.
If you haven't used Spaces before, follow the previous guide [here](/using_hugging_face_integrations).
## Conclusion 🎉
And you're all done! That's all the code you need to build a map demo.
Here's a link to the demo [Map demo](https://huggingface.co/spaces/gradio/map_airbnb) and [complete code](https://huggingface.co/spaces/gradio/map_airbnb/blob/main/run.py) (on Hugging Face Spaces)

View File

@ -4,7 +4,7 @@ Tags: NLP, TEXT, CHAT
## Introduction
Chatbots are widely used in natural language processing (NLP) research and industry. Because chatbots are designed to be used directly by customers and end users, it is important to validate that chatbots are behaving as expected when confronted with a wide variety of input prompts.
Chatbots are widely used in natural language processing (NLP) research and industry. Because chatbots are designed to be used directly by customers and end users, it is important to validate that chatbots are behaving as expected when confronted with a wide variety of input prompts.
Using `gradio`, you can easily build a demo of your chatbot model and share that with your users, or try it yourself using an intuitive chatbot GUI.
@ -23,7 +23,7 @@ $code_chatbot_simple
There are three Gradio components here:
* A `Chatbot`, whose value stores the entire history of the conversation, as a list of response pairs between the user and bot.
* A `Chatbot`, whose value stores the entire history of the conversation, as a list of response pairs between the user and bot.
* A `Textbox` where the user can type their message, and then hit enter/submit to trigger the chatbot response
* A `Clear` button to clear the entire Chatbot history
@ -53,9 +53,9 @@ Of course, in practice, you would replace `bot()` with your own more complex fun
Finally, we enable queuing by running `demo.queue()`, which is required for streaming intermediate outputs. You can try the improved chatbot by scrolling to the demo at the top of this page.
## Adding Markdown, Images, Audio, or Videos
## Adding Markdown, Images, Audio, or Videos
The `gradio.Chatbot` component supports a subset of markdown including bold, italics, and code. For example, we could write a function that responds to a user's message, with a bold **That's cool!**, like this:
The `gr.Chatbot` component supports a subset of markdown including bold, italics, and code. For example, we could write a function that responds to a user's message, with a bold **That's cool!**, like this:
```py
def bot(history):
@ -77,4 +77,4 @@ Putting this together, we can create a *multimodal* chatbot with a textbox for a
$code_chatbot_multimodal
$demo_chatbot_multimodal
And you're done! That's all the code you need to build an interface for your chatbot model.
And you're done! That's all the code you need to build an interface for your chatbot model.

View File

@ -124,12 +124,12 @@ def override_signature(name, signature):
cls["override_signature"] = signature
override_signature("Blocks", "with gradio.Blocks():")
override_signature("Row", "with gradio.Row():")
override_signature("Column", "with gradio.Column():")
override_signature("Tab", "with gradio.Tab():")
override_signature("Group", "with gradio.Group():")
override_signature("Box", "with gradio.Box():")
override_signature("Blocks", "with gr.Blocks():")
override_signature("Row", "with gr.Row():")
override_signature("Column", "with gr.Column():")
override_signature("Tab", "with gr.Tab():")
override_signature("Group", "with gr.Group():")
override_signature("Box", "with gr.Box():")
override_signature("Dataset", "gr.Dataset(components, samples)")