gr.Video
, gr.Audio
, gr.Image
, gr.Chatbot
, and gr.Gallery
components now include a share icon when deployed on Spaces. This behavior can be modified by setting the show_share_button
parameter in the component classes. by @aliabid94 in PR 4651space
, src
, and host
attributes to be updated dynamically by @pngwn in PR 4461api_name
parameter now accepts False
as a value, which means it does not show up in named or unnamed endpoints. By @abidlabs in PR 4683pathlib.Path
in gr.Video
, gr.Gallery
, and gr.Chatbot
by sunilkumardash9 in PR 4581.info
attribute to update when update()
is called on them. by @jebarpg in PR 4715.Image
components undo button works mode is mask
or color-sketch
by @amyorz in PR 4692gr.components
by @abidlabs in PR 4566select
event was not triggered in gr.Gallery
if height
was set to be large with allow_preview=False
by @freddyaboulton in PR 4551visible=False
in gr.Group
event did not work by @abidlabs in PR 4567make_waveform
to work with paths that contain spaces @akx in PR 4570 & PR 4578stop_recording
event for gr.Audio
and gr.Video
components by @freddyaboulton in PR 4554gr.Gallery
where height
and object_fit
parameters where being ignored by @freddyaboulton in PR 4576AnnotatedImage
css styling was causing the annotation masks to not be displayed correctly by @freddyaboulton in PR 4628Progress
component now appears even when no iterable
is specified in tqdm
constructor by @itrushkin in PR 4475plot
parameter deprecation warnings should now only be emitted for Image
components by @freddyaboulton in PR 4709type
deprecation warning by @freddyaboulton in PR 4709autoplay=True
and the video source is dynamically updated @pngwn in PR 4705gr.Dropdown
being cutoff at the bottom by @abidlabs in PR 4691.show_label
was hiding the entire component for gr.Label
by @freddyaboulton in PR 4713.git-blame-ignore-revs
by @akx in PR 4586typing.Literal
where possible in gradio library and client by @freddyaboulton in PR 4608cleared_value
from some components as its no longer used internally by @freddyaboulton in PR 4685PR 4683 removes the explict named endpoint “load_examples” from gr.Interface that was introduced in PR 4456.
gr.ClearButton
which allows users to easily clear the values of components by @abidlabs in PR 4456Example usage:
import gradio as gr
with gr.Blocks() as demo:
chatbot = gr.Chatbot([("Hello", "How are you?")])
with gr.Row():
textbox = gr.Textbox(scale=3, interactive=True)
gr.ClearButton([textbox, chatbot], scale=1)
demo.launch()
start_recording
and stop_recording
events to Video
and Audio
components by @pngwn in PR 4422autoplay
kwarg to Video
and Audio
components by @pngwn in PR 4453allow_preview
parameter to Gallery
to control whether a detailed preview is displayed on click by
@freddyaboulton in PR 4470latex_delimiters
parameter to Chatbot
to control the delimiters used for LaTeX and to disable LaTeX in the Chatbot
by @dawoodkhan82 in PR 4516gr.Warning
and gr.Info
modals. Simply put the code gr.Warning("Your warning message")
or gr.Info("Your info message")
as a standalone line in your function. By @aliabid94 in PR 4518. Example:
def start_process(name):
gr.Info("Starting process")
if name is None:
gr.Warning("Name is empty")
...
if success == False:
raise gr.Error("Process failed")
<a>
element, by @akx in PR 4449.format='mp4'
on a video component would cause the function to error out if the uploaded video was not playable by @freddyaboulton in PR 4467_js
parameter to work even without backend function, by @aliabid94 in PR 4486.gr.Chatbot()
by @dawoodkhan82 in PR 4491Label
component by @abidlabs in PR 4456show_label
will not automatically be set to True
in gr.BarPlot.update
by @freddyaboulton in PR 4531gr.BarPlot
group text now respects darkmode by @freddyaboulton in PR 4531new Promise()
s by @akx in PR 4442.mount_gradio_app
, by @charlesfrye in PR4519.Clear
button has been changed for Slider
, CheckboxGroup
, Radio
, Dropdown
components by @abidlabs in PR 4456. The Clear button now sets the value of these components to be empty as opposed to the original default set by the developer. This is to make them in line with the rest of the Gradio components.$
as a default LaTeX delimiter for the Chatbot
by @dawoodkhan82 in PR 4516. The specific LaTeX delimeters can be set using the new latex_delimiters
parameter in Chatbot
.gr.UploadButton
component now supports the variant
and interactive
parameters by @abidlabs in PR 4436.gr.File(file_count='multiple')
could not be cached as output by @freddyaboulton in PR 4421/proxy
route by @abidlabs in PR 4406.gr.UploadButton
could not be used to upload the same file twice by @dawoodkhan82 in PR 4437/proxy
route was being incorrectly constructed by the frontend by @abidlabs in PR 4430.import spaces; spaces.disable_gradio_auto_wrap()
by @cbensimon in PR 4389..style
parameter and moved arguments to constructor. Added support for .update()
to all arguments initially in style. Added scale
and min_width
support to every Component. By @aliabid94 in PR 4374every
to work with generators by @dkjshk in PR 4434validate_url
to check for 403 errors and use a GET request in place of a HEAD by @alvindaiyan in PR 4388.gradio deploy
to launch a Gradio app to Spaces directly from your terminal. By @aliabid94 in PR 4033.show_progress='corner'
argument to event listeners, which will not cover the output components with the progress animation, but instead show it in the corner of the components. By @aliabid94 in PR 4396.Blocks.load
behave like other event listeners (allows chaining then
off of it) @anentropic in PR 4304interactive=True
in output components of a gr.Interface
by @abidlabs in PR 4356./file
routes by @abidlabs in PR 4370./proxy
route by @abidlabs in PR 4368.markedjs
sanitize function with DOMPurify sanitizer for gr.Chatbot()
by @dawoodkhan82 in PR 4360/file=
route no longer allows accessing dotfiles or files in “dot directories” by @akx in PR 4303Interface.launch()
and Blocks.launch()
now accept an app_kwargs
argument to allow customizing the configuration of the underlying FastAPI app, by @akx in PR 4282run_on_click
parameter in gr.Examples
by @abidlabs in PR 4258.initial_height
attribute by @whitphx in PR 4223mount_css
fn to remove circular dependency @whitphx in PR 4222gr.Chatbot()
using KaTeX
by @dawoodkhan82 in PR 4285.gradio app.py
) can now accept command line arguments by @micky2be in PR 4119format
argument to Audio
component by @freddyaboulton in PR 4178chatbot_dialogpt
demo by @dawoodkhan82 in PR 4238.gr.Chatbot()
markdown parsing to frontend using marked
library and prism
by @dawoodkhan82 in PR 4150Image
component by @der3318 in PR 4204.root_path
parameter to launch()
that allows running Gradio applications on subpaths (e.g. www.example.com/app) behind a proxy, by @abidlabs in PR 4133.input
event listener, which is only triggered when a user changes the component value (as compared to .change
, which is also triggered when a component updates as the result of a function trigger), by @aliabid94 in PR 4157.gr.File(file_count='multiple')
output components by @freddyaboulton in PR 4153/info
route by @freddyaboulton in PR 4039gr.Slider
release
event not triggering on mobile by @space-nuko in PR 4098State
component info from the /info
route by @abidlabs in PR 4107zh-cn.json
to zh-CN.json
by @abidlabs in PR 4086gr.Code()
component with streaming by @dawoodkhan82 in PR 4043visual-question-answering
, document-question-answering
, and image-to-text
using gr.Interface.load("models/...")
and gr.Interface.from_pipeline
by @osanseviero in PR 3887gr.Chatbot()
, by @dawoodkhan82 in PR 4048matplotlib
not rendering correctly if the backend was not set to Agg
by @abidlabs in PR 4029gr.State
across different Interfaces/Blocks within larger Blocks would not work by @abidlabs in PR 4030gr.HuggingFaceDatasetSaver
behavior changed internally. The flagging/
folder is not a .git/
folder anymore when using it. organization
parameter is now ignored in favor of passing a full dataset id as dataset_name
(e.g. "username/my-dataset"
).\n
) are not automatically converted to <br>
in gr.Markdown()
or gr.Chatbot()
. For multiple new lines, a developer must add multiple <br>
tags.gr.HuggingFaceDatasetSaver
using HTTP methods instead of git pull/push by @Wauplin in PR 3973gr.Image
sketch modes, by @space-nuko in PR 3615gr.Video()
would not work inside a gr.Tab()
by @dawoodkhan82 in PR 3891gr.Gallery()
where setting height causes aspect ratio of images to collapse by @dawoodkhan82 in PR 3830[PR 3895](https://github.com/gradio-app/gradio/pull/3895)
.[PR 3895](https://github.com/gradio-app/gradio/pull/3895)
.Status
enum by @10zinten in PR 3931gr.ChatBot
to handle image url tye-singwa in PR 3953gr
consistent across the docs by @duerrsimon in PR 3901gradio.themes
utilities (introduced in 3.24.0) have been eradicated.
By @akx in PR 3958gr.themes.builder()
by @deepkyu in PR 3869_js
and setting outputs
to None
in gradio.Blocks()
by @DavG25 in PR 3883New AnnotatedImage component allows users to highlight regions of an image, either by providing bounding boxes, or 0-1 pixel masks. This component is useful for tasks such as image segmentation, object detection, and image captioning.
Example usage:
with gr.Blocks() as demo:
img = gr.Image()
img_section = gr.AnnotatedImage()
def mask(img):
top_left_corner = [0, 0, 20, 20]
random_mask = np.random.randint(0, 2, img.shape[:2])
return (img, [(top_left_corner, "left corner"), (random_mask, "random")])
img.change(mask, img, img_section)
See the image_segmentation demo for a full example. By @aliabid94 in PR 3836
Video
component supports subtitles(path_to_video, path_to_subtitles)
from your function. Both .srt
and .vtt
formats are supported:with gr.Blocks() as demo:
gr.Video(("video.mp4", "captions.srt"))
gr.Chatbot()
component by @dawoodkhan82 in PR 3816Updates the “view API” page in Gradio apps to use the gradio_client
library by @aliabd in PR 3765
Read more about how to use the gradio_client
library here: https://gradio.app/getting-started-with-the-python-client/
Improve error messages when number of inputs/outputs to event handlers mismatch, by @space-nuko in PR 3519
Add select
listener to Images, allowing users to click on any part of an image and get the coordinates of the click by @aliabid94 in PR 3786.
with gr.Blocks() as demo:
img = gr.Image()
textbox = gr.Textbox()
def select_handler(img, evt: gr.SelectData):
selected_pixel = img[evt.index[1], evt.index[0]]
return f"Selected pixel: {selected_pixel}"
img.select(select_handler, img, textbox)
rows
, columns
and object-fit
in style()
for gr.Gallery()
component by @dawoodkhan82 in PR 3586file_count='multiple'
case by @freddyaboulton in PR 3782select
event once the dataframe has been selected. By @yiyuezhuo in PR 3861Trigger the release event when Slider number input is released or unfocused by @freddyaboulton in PR 3589
Created Theme Builder, which allows users to create themes without writing any code, by @aliabid94 in PR 3664. Launch by:
import gradio as gr
gr.themes.builder()
The Dropdown
component now has a allow_custom_value
parameter that lets users type in custom values not in the original list of choices.
The Colorpicker
component now has a .blur()
event
By @freddyaboulton in PR 3581.
Chatbot
and Image
components so that files passed during processing are added to a directory where they can be served from, by @abidlabs in PR 3523huggingface_hub
@dawoodkhan82 in PR 3488gr.load()
loads and applies the upstream theme, by @abidlabs in PR 3641lines
set to larger than 20 by @dawoodkhan82 in PR 3637gr.Dataframe
value, by @space-nuko in PR 3646gr.Image
not filling the entire element size, by @space-nuko in PR 3649gr.Code
support the lines
property, by @space-nuko in PR 3651_js
return values being double wrapped in an array, by @space-nuko in PR 3594gr.File
component to state that its preprocessing method converts the uploaded file to a temporary file, by @RussellLuo in PR 3660gr.Progress
used in same function, by @space-nuko in PR 3671Remove All
button in gr.Dropdown
single-select mode by @space-nuko in PR 3678gr.Dropdown
besides the selected item receiving a checkmark, by @space-nuko in PR 3644gr.Dropdown
issues and improve usability, by @space-nuko in PR 3705HuggingFaceDatasetJSONSaver
by @osanseviero in PR 3604Audio
and State
components, and fixes the pictionary
demo by @abidlabs in PR 3611ruff
, by @akx in PR 3710orig_name
to Video output in the backend so that the front end can set the right name for downloaded video files by @freddyaboulton in PR 3700Once you have created a theme, you can upload it to the HuggingFace Hub to let others view it, use it, and build off of it! You can also download, reuse, and remix other peoples’ themes. See https://gradio.app/theming-guide/ for more details.
By @freddyaboulton in PR 3428
gr.Code()
component. By @abidlabs in PR 3556Gradio now supports a new theme system, which allows you to customize the look and feel of your app. You can now use the theme=
kwarg to pass in a prebuilt theme, or customize your own! See https://gradio.app/theming-guide/ for more details. By @aliabid94 in PR 3470 and PR 3497
elem_classes
Add keyword argument elem_classes
to Components to control class names of components, in the same manner as existing elem_id
.
By @aliabid94 in PR 3466
gr.Request
object failing to handle dictionaries when nested keys couldn’t be converted to variable names #3454 by @radames in PR 3459pyright==1.1.298
for stability by @abidlabs in PR 3475IOComponent.add_interactive_to_config()
by @space-nuko in PR 3476IOComponent.generate_sample()
by @space-nuko in PR 3475You can now share your gradio themes with the world!
After creating a theme, you can upload it to the HuggingFace Hub to let others view it, use it, and build off of it!
There are two ways to upload a theme, via the theme class instance or the command line.
my_theme.push_to_hub(repo_name="my_theme",
version="0.2.0",
hf_token="...")
First save the theme to disk
my_theme.dump(filename="my_theme.json")
Then use the upload_theme
command:
upload_theme\
"my_theme.json"\
"my_theme"\
"0.2.0"\
"<hf-token>"
The version
must be a valid semantic version string.
This creates a space on the huggingface hub to host the theme files and show potential users a preview of your theme.
An example theme space is here: https://huggingface.co/spaces/freddyaboulton/dracula_revamped
To use a theme from the hub, use the from_hub
method on the ThemeClass
and pass it to your app:
my_theme = gr.Theme.from_hub("freddyaboulton/my_theme")
with gr.Blocks(theme=my_theme) as demo:
....
You can also pass the theme string directly to Blocks
or Interface
(gr.Blocks(theme="freddyaboulton/my_theme")
)
You can pin your app to an upstream theme version by using semantic versioning expressions.
For example, the following would ensure the theme we load from the my_theme
repo was between versions 0.1.0
and 0.2.0
:
with gr.Blocks(theme="freddyaboulton/my_theme@>=0.1.0,<0.2.0") as demo:
....
by @freddyaboulton in PR 3428
New code component allows you to enter, edit and display code with full syntax highlighting by @pngwn in PR 3421
Chatbot
component now supports audio, video, and imagesThe Chatbot
component now supports audio, video, and images with a simple syntax: simply
pass in a tuple with the URL or filepath (the second optional element of the tuple is alt text), and the image/audio/video will be displayed:
gr.Chatbot([
(("driving.mp4",), "cool video"),
(("cantina.wav",), "cool audio"),
(("lion.jpg", "A lion"), "cool pic"),
]).style(height=800)
Note: images were previously supported via Markdown syntax and that is still supported for backwards compatibility. By @dawoodkhan82 in PR 3413
Allow consecutive function triggers with .then
and .success
by @aliabid94 in PR 3430
New code component allows you to enter, edit and display code with full syntax highlighting by @pngwn in PR 3421
.select()
event listener, which also includes event data that can be passed as an argument to a function with type hint gr.SelectData
. The following components support the .select()
event listener: Chatbot, CheckboxGroup, Dataframe, Dropdown, File, Gallery, HighlightedText, Label, Radio, TabItem, Tab, Textbox. Example usage:import gradio as gr
with gr.Blocks() as demo:
gallery = gr.Gallery(["images/1.jpg", "images/2.jpg", "images/3.jpg"])
selected_index = gr.Textbox()
def on_select(evt: gr.SelectData):
return evt.index
gallery.select(on_select, None, selected_index)
By @aliabid94 in PR 3399
huggingface_hub
to send telemetry on interface
and blocks
; eventually to replace segment by @dawoodkhan82 in PR 3342generic_update
by shallow copying by @gitgithan in PR 3405 to fix #3282BlockContext
in utils.py
by @freddyaboulton in PR 3424generic_update
by shallow copying by @gitgithan in PR 3405 to fix #3282JSON
component (show_label parameter, icons) in @abidlabs in PR 3451height
kwarg to style in gr.Chatbot()
component by @dawoodkhan82 in PR 3369chatbot = gr.Chatbot().style(height=500)
Now you can trigger your python function to run when the slider is released as opposed to every slider change value!
Simply use the release
method on the slider
slider.release(function, inputs=[...], outputs=[...], api_name="predict")
By @freddyaboulton in PR 3353
The standard dropdown component now supports searching for choices. Also when multiselect
is True
, you can specify max_choices
to set the maximum number of choices you want the user to be able to select from the dropdown component.
gr.Dropdown(label="Choose your favorite colors", choices=["red", "blue", "green", "yellow", "orange"], multiselect=True, max_choices=2)
by @dawoodkhan82 in PR 3211
Output images will now automatically have a download button displayed to make it easier to save and share the results of Machine Learning art models.
By @freddyaboulton in PR 3297
gr.Button
component by setting interactive=False
by @abidlabs in PR 3266 and PR 3288flagging_options
display text and saved flag separately by @abidlabs in PR 3289brush_radius
for the Image
component both as a default and via Image.update()
by @pngwn in PR 3277info=
argument to form components to enable extra context provided to users, by @aliabid94 in PR 3291gr.Request()
object using the .username
attribute by @abidlabs in PR 3296preview
option to Gallery.style
that launches the gallery in preview mode when first loaded by @freddyaboulton in PR 3345mirror_webcam
is always respected by @pngwn in PR 3245initial_height
when loading is complete so the embed finds its natural height once it is loaded @pngwn in PR 3292shape
argument on the front end when creating Image Sketches by @pngwn in PR 3277Dropdown's
value to be []
and adding a change event on the dropdown by @freddyaboulton in PR 3295height
set in Gallery.style
was not respected by the front-end by @freddyaboulton in PR 3343gr.Dropdown(Multiselect=True)
is an empty list and the initial value for gr.Dropdown(Multiselect=False)
is an empty string by @pngwn in PR 3338analytics_enabled=True
by @abidlabs in PR 3349types
field to the dependency field in the config by @freddyaboulton in PR 3315gr.BarPlot
component by @abidlabs in PR 3275chatbot.style(color_map=)
by [@aliabid94] in PR 3370When embedding a spaces-hosted gradio app as a web component, you now get an improved UI linking back to the original space, better error handling and more intelligent load performance. No changes are required to your code to benefit from this enhanced experience; simply upgrade your gradio SDK to the latest version.
This behaviour is configurable. You can disable the info panel at the bottom by passing info="false"
. You can disable the container entirely by passing container="false"
.
Error statuses are reported in the UI with an easy way for end-users to report problems to the original space author via the community tab of that Hugginface space:
By default, gradio apps are lazy loaded, vastly improving performance when there are several demos on the page. Metadata is loaded ahead of time, but the space will only be loaded and rendered when it is in view.
This behaviour is configurable. You can pass eager="true"
to load and render the space regardless of whether or not it is currently on the screen.
gr.BarPlot
component! 📊Create interactive bar plots from a high-level interface with gr.BarPlot
.
No need to remember matplotlib syntax anymore!
Example usage:
import gradio as gr
import pandas as pd
simple = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
with gr.Blocks() as demo:
gr.BarPlot(
simple,
x="a",
y="b",
title="Simple Bar Plot with made up data",
tooltip=['a', 'b'],
)
demo.launch()
By @freddyaboulton in PR 3157
Fixed a bug that prevented bokeh plots from being displayed on the front end and extended support for both 2.x and 3.x versions of bokeh!
By @freddyaboulton in PR 3212
None
as the second value in the tuple, to add a single message in the chatbot from the “bot” side.gr.Chatbot([("Hi, I'm DialoGPT. Try asking me a question.", None)])
By @dawoodkhan82 in PR 3165
gr.utils.delete_none
to only remove props whose values are None
from the config by @abidlabs in PR 3188change
event is now triggered when users click the ‘Clear All’ button of the multiselect DropDown component by @freddyaboulton in PR 3195clear
event is now triggered when images are cleared by @freddyaboulton in PR 3218File
component or UploadButton
component includes a file_types
parameter along with file_count=="dir"
) by @abidlabs in PR 3194gr.Error
instead of a regular Python error when you use gr.Interface.load()
to load a model and there’s an error querying the HF API by @abidlabs in PR 3194If your Interface function is a generator, there used to be a separate Stop
button displayed next
to the Submit
button.
We’ve revamed the Submit
button so that it turns into a Stop
button during the generation process.
Clicking on the Stop
button will cancel the generation and turn it back to a Submit
button.
The Stop
button will automatically turn back to a Submit
button at the end of the generation if you don’t use it!
By @freddyaboulton in PR 3124
You can now call queue
on your demo
outside of the if __name__ == "__main__"
block and
run the script in reload mode with the gradio
command.
Any changes to the app.py
file will be reflected in the webpage automatically and the queue will work
properly!
By @freddyaboulton in PR 3089
demo = gr.Interface(...)
demo.launch(
file_directories=["/var/lib/demo/path/to/resources"]
)
By @maxaudron in PR 3075
Column
) by @abidlabs in PR 3123Interface
via the %%blocks
jupyter notebook magic command by @freddyaboulton in PR 3126launch
will not be respected when using reload mode, e.g. gradio
command by @freddyaboulton in PR 3089equal_height
parameter should be passed to the .style()
method of gr.Row()
by @freddyaboulton in PR 3125fake_diffusion
demos by @freddyaboulton in PR 3120Previously photos uploaded via iOS would be rotated after processing. This has been fixed by @freddyaboulton in PR 3089
A share link will automatically be created when running on Kaggle kernels (notebooks) so that the front-end is properly displayed.
By @freddyaboulton in PR 3101
Gallery.style(grid=...)
by by @aliabd in PR 3107markdown-it-py
version to 2.0.0
so that the dollar math plugin is compatible by @freddyaboulton in PR 3102You can now load image-to-text
and conversational
pipelines from the hub!
io = gr.Interface.load("models/nlpconnect/vit-gpt2-image-captioning",
api_key="<optional-api-key>")
io.launch()
chatbot = gr.Interface.load("models/microsoft/DialoGPT-medium",
api_key="<optional-api-key>")
chatbot.launch()
By @freddyaboulton in PR 3011
No need for an additional file output component to enable model3d file downloads anymore. We now added a download button to the model3d component itself.
By @dawoodkhan82 in PR 3014
Authentication on spaces works now! Third party cookies must be enabled on your browser to be able to log in. Some browsers disable third party cookies by default (Safari, Chrome Incognito).
/file/
route that was broken in a recent change in PR 3010huggingface_hub
for the HuggingFaceDatasetSaver in PR 3025closed
app by @freddyaboulton in PR 3022file_types
parameter of gr.File
or gr.UploadButton
was not a list by @freddyaboulton in PR 3048UploadButton
by @freddyaboulton in PR 3053gr.LinePlot
for the blocks_kinematics
demo by @freddyaboulton in PR 2998interface_series_load
to include some inline markdown code by @abidlabs in PR 3051mount_gradio_app
would not launch if the queue was enabled in a gradio app by @freddyaboulton in PR 2939blocks_plug
demo that prevented switching tabs programmatically with python @TashaSkyUp in PR 2971.gr.Progress
argument after the input arguments to any function. Example:def reverse(word, progress=gr.Progress()):
progress(0, desc="Starting")
time.sleep(1)
new_string = ""
for letter in progress.tqdm(word, desc="Reversing"):
time.sleep(0.25)
new_string = letter + new_string
return new_string
demo = gr.Interface(reverse, gr.Text(), gr.Text())
Progress indicator bar by @aliabid94 in PR 2750.
title
argument to TabbedInterface
by @MohamedAliRashad in #2888gr.File
and gr.UploadButton
, using file_types
parameter (e.g gr.File(file_count="multiple", file_types=["text", ".json", ".csv"])
) by @dawoodkhan82 in #2901multiselect
option to Dropdown
by @dawoodkhan82 in #2871multiselect
set to true
a user can now select multiple options from the gr.Dropdown
component.gr.Dropdown(["angola", "pakistan", "canada"], multiselect=True, value=["angola"])
default_enabled=False
made it so that the entire queue did not start by @freddyaboulton in PR 2876blocks_style
demo that was preventing it from launching by @freddyaboulton in PR 2890DataFrame
and LinePlot
component, by @abidlabs in PR 2816default_enabled
parameter of the Blocks.queue
method has no effect by @freddyaboulton in PR 2876Gradio’s newest plotting component gr.LinePlot
! 📈
With this component you can easily create time series visualizations with customizable appearance for your demos and dashboards … all without having to know an external plotting library.
For an example of the api see below:
gr.LinePlot(stocks,
x="date",
y="price",
color="symbol",
color_legend_position="bottom",
width=600, height=400, title="Stock Prices")
By @freddyaboulton in PR 2807
examples_per_page
parameter of the Examples
component was not passed to the internal Dataset
component by @freddyaboulton in PR 2861allow_flagging="auto"
in gr.Interface()
by @abidlabs in PR 2695gr.CheckboxGroup
would crash the entire app by @freddyaboulton in PR 2866DataFrame
and ScatterPlot
component,
by @abidlabs in PR 2794[@aliencaocao](https://github.com/aliencaocao)
in [PR 2846](https://github.com/gradio-app/gradio/pull/2846)
x_lim
, y_lim
and legend positions for gr.ScatterPlot
by @freddyaboulton in PR 2807Adds a gr.make_waveform()
function that creates a waveform video by combining an audio and an optional background image by @dawoodkhan82 and @aliabid94 in [PR 2706](https://github.com/gradio-app/gradio/pull/2706. Helpful for making audio outputs much more shareable.
every
ParameterWhen a component’s initial value is a function, the every
parameter re-runs the function every every
seconds. By @abidlabs in PR 2806. Here’s a code example:
import gradio as gr
with gr.Blocks() as demo:
df = gr.DataFrame(run_query, every=60*60)
demo.queue().launch()
*No changes to highlight.
Replaces tunneling logic based on ssh port-forwarding to that based on frp
by XciD and Wauplin in PR 2509
You don’t need to do anything differently, but when you set share=True
in launch()
,
you’ll get this message and a public link that look a little bit different:
Setting up a public link... we have recently upgraded the way public links are generated. If you encounter any problems, please downgrade to gradio version 3.13.0
.
Running on public URL: https://bec81a83-5b5c-471e.gradio.live
These links are a more secure and scalable way to create shareable demos!
gr.Dataframe()
to take a pandas.DataFrame
that includes numpy array and other types as its initial value, by @abidlabs in PR 2804altair
to requirements.txt by @freddyaboulton in PR 2811visible
in classes in templates.py
by @abidlabs in PR 2805https://api.ipify.org
to https://checkip.amazonaws.com/
by @abidlabs in PR 2810visible
in classes in templates.py
by @abidlabs in PR 2805https://api.ipify.org
to https://checkip.amazonaws.com/
by @abidlabs in PR 2810It is now possible to create a scatter plot natively in Gradio!
The gr.ScatterPlot
component accepts a pandas dataframe and some optional configuration parameters
and will automatically create a plot for you!
This is the first of many native plotting components in Gradio!
For an example of how to use gr.ScatterPlot
see below:
import gradio as gr
from vega_datasets import data
cars = data.cars()
with gr.Blocks() as demo:
gr.ScatterPlot(show_label=False,
value=cars,
x="Horsepower",
y="Miles_per_Gallon",
color="Origin",
tooltip="Name",
title="Car Data",
y_title="Miles per Gallon",
color_legend_title="Origin of Car").style(container=False)
demo.launch()
By @freddyaboulton in PR 2764
The Plot
component can now accept altair plots as values!
Simply return an altair plot from your event listener and gradio will display it in the front-end.
See the example below:
import gradio as gr
import altair as alt
from vega_datasets import data
cars = data.cars()
chart = (
alt.Chart(cars)
.mark_point()
.encode(
x="Horsepower",
y="Miles_per_Gallon",
color="Origin",
)
)
with gr.Blocks() as demo:
gr.Plot(value=chart)
demo.launch()
By @freddyaboulton in PR 2741
The Label
component now accepts a color
argument by @freddyaboulton in PR 2736.
The color
argument should either be a valid css color name or hexadecimal string.
You can update the color with gr.Label.update
!
This lets you create Alert and Warning boxes with the Label
component. See below:
import gradio as gr
import random
def update_color(value):
if value < 0:
# This is bad so use red
return "#FF0000"
elif 0 <= value <= 20:
# Ok but pay attention (use orange)
return "#ff9966"
else:
# Nothing to worry about
return None
def update_value():
choice = random.choice(['good', 'bad', 'so-so'])
color = update_color(choice)
return gr.Label.update(value=choice, color=color)
with gr.Blocks() as demo:
label = gr.Label(value=-10)
demo.load(lambda: update_value(), inputs=None, outputs=[label], every=1)
demo.queue().launch()
Add Brazilian Portuguese translation (pt-BR.json) by @pstwh in PR 2753:
gr.Blocks().load()
by @abidlabs in PR 2755Chatbot
component now supports a subset of Markdown (including bold, italics, code, images)You can now pass in some Markdown to the Chatbot component and it will show up, meaning that you can pass in images as well! by @abidlabs in PR 2731
Here’s a simple example that references a local image lion.jpg
that is in the same
folder as the Python script:
import gradio as gr
with gr.Blocks() as demo:
gr.Chatbot([("hi", "hello **abubakar**"), ("![](/file=lion.jpg)", "cool pic")])
demo.launch()
To see a more realistic example, see the new demo /demo/chatbot_multimodal/run.py
.
Added mathtext (a subset of latex) support to gr.Markdown. Added by @kashif and @aliabid94 in PR 2696.
Example of how it can be used:
gr.Markdown(
r"""
# Hello World! $\frac{\sqrt{x + y}}{4}$ is today's lesson.
""")
You can now update the Accordion label
and open
status with gr.Accordion.update
by @freddyaboulton in PR 2690
import gradio as gr
with gr.Blocks() as demo:
with gr.Accordion(label="Open for greeting", open=False) as accordion:
gr.Textbox("Hello!")
open_btn = gr.Button(value="Open Accordion")
close_btn = gr.Button(value="Close Accordion")
open_btn.click(
lambda: gr.Accordion.update(open=True, label="Open Accordion"),
inputs=None,
outputs=[accordion],
)
close_btn.click(
lambda: gr.Accordion.update(open=False, label="Closed Accordion"),
inputs=None,
outputs=[accordion],
)
demo.launch()
File
component can properly preprocess files to “binary” byte-string format by CoffeeVampir3 in PR 2727include_audio
in Video component. When True
, for source="webcam"
this will record audio and video, for source="upload"
this will retain the audio in an uploaded video by @mandargogate in PR 2721There is now a new component called the UploadButton
which is a file upload component but in button form! You can also specify what file types it should accept in the form of a list (ex: image
, video
, audio
, text
, or generic file
). Added by @dawoodkhan82 in PR 2591.
Example of how it can be used:
import gradio as gr
def upload_file(files):
file_paths = [file.name for file in files]
return file_paths
with gr.Blocks() as demo:
file_output = gr.File()
upload_button = gr.UploadButton("Click to Upload a File", file_types=["image", "video"], file_count="multiple")
upload_button.upload(upload_file, upload_button, file_output)
demo.launch()
New API Docs page with in-browser playground and updated aesthetics. @gary149 in PR 2652
Previously our login page had its own CSS, had no dark mode, and had an ugly json message on the wrong credentials. Made the page more aesthetically consistent, added dark mode support, and a nicer error message. @aliabid94 in PR 2684
You can now access the Request object directly in your Python function by @abidlabs in PR 2641. This means that you can access request headers, the client IP address, and so on. In order to use it, add a parameter to your function and set its type hint to be gr.Request
. Here’s a simple example:
import gradio as gr
def echo(name, request: gr.Request):
if request:
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
return name
io = gr.Interface(echo, "textbox", "textbox").launch()
https://user-images.githubusercontent.com/9021060/202878400-cb16ed47-f4dd-4cb0-b2f0-102a9ff64135.mov
gr.Interface.load()
by @abidlabs in PR 2694'password'
and 'email'
types to Textbox
. @pngwn in PR 2653gr.Textbox
component will now raise an exception if type
is not “text”, “email”, or “password” @pngwn in PR 2653. This will cause demos using the deprecated gr.Textbox(type="number")
to raise an exception.gr.Interface.load
by @freddyaboulton PR 2640interactive
property of a component could not be updated by @freddyaboulton in PR 2639pd.read_sql
as opposed to low-level postgres connector by @freddyaboulton in PR 2604gr.Templates
to accept parameters to override the defaults by @abidlabs in PR 2600ValueError()
if constructed with invalid parameters for type
or source
(for components that take those parameters) in PR 2610When you load an upstream app with gr.Blocks.load
, you can now specify which fn
to call with the api_name
parameter.
import gradio as gr
english_translator = gr.Blocks.load(name="spaces/gradio/english-translator")
german = english_translator("My name is Freddy", api_name='translate-to-german')
The api_name
parameter will take precedence over the fn_index
parameter.
gr.Blocks.load()
now correctly loads example files from Spaces @abidlabs in PR 2594api_name
to Blocks.__call__
by @freddyaboulton in PR 2593Gradio now supports the ability to run an event continuously on a fixed schedule. To use this feature,
pass every=# of seconds
to the event definition. This will run the event every given number of seconds!
This can be used to:
Here is an example of a live plot that refreshes every half second:
import math
import gradio as gr
import plotly.express as px
import numpy as np
plot_end = 2 * math.pi
def get_plot(period=1):
global plot_end
x = np.arange(plot_end - 2 * math.pi, plot_end, 0.02)
y = np.sin(2*math.pi*period * x)
fig = px.line(x=x, y=y)
plot_end += 2 * math.pi
return fig
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
gr.Markdown("Change the value of the slider to automatically update the plot")
period = gr.Slider(label="Period of plot", value=1, minimum=0, maximum=10, step=1)
plot = gr.Plot(label="Plot (updates every half second)")
dep = demo.load(get_plot, None, plot, every=0.5)
period.change(get_plot, period, plot, every=0.5, cancels=[dep])
demo.queue().launch()
queue
and auth
when working with reload mode by by @freddyaboulton in PR 3089api_key
to gr.Interface.load()
by @abidlabs in PR 2568every
keyword to event listeners that runs events on a fixed schedule by @freddyaboulton in PR 2512Gradio now supports the ability to pass batched functions. Batched 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 words and a list of ints), and returns a list of trimmed words as output:
import time
def trim_words(words, lens):
trimmed_words = []
time.sleep(5)
for w, l in zip(words, lens):
trimmed_words.append(w[:l])
return [trimmed_words]
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,
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)
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
word = gr.Textbox(label="word", value="abc")
leng = gr.Number(label="leng", precision=0, value=1)
output = gr.Textbox(label="Output")
with gr.Row():
run = gr.Button()
event = run.click(trim_words, [word, leng], output, batch=True, max_batch_size=16)
demo.queue()
demo.launch()
In the example above, 16 requests could be processed in parallel (for a total inference time of 5 seconds), instead of each request being processed separately (for a total inference time of 80 seconds).
Video
, Audio
, Image
, and File
components now support a upload()
event that is triggered when a user uploads a file into any of these components.
Example usage:
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
input_video = gr.Video()
output_video = gr.Video()
# Clears the output video when an input video is uploaded
input_video.upload(lambda : None, None, output_video)
/api
endpoint from skipping the queue if the queue is enabled for that event by @freddyaboulton in PR 2493cancels
in event triggers so that it works properly if multiple
Blocks are rendered by @abidlabs in PR 2530share=True
by @abidlabs in PR 2502upload
event for Video
, Audio
, Image
, and File
components @dawoodkhan82 in PR 2448Series
or Parallel
with Blocks
by @abidlabs in PR 2543float64
, float16
, or uint16
formats by @abidlabs in PR 2545Running events can be cancelled when other events are triggered! To test this feature, pass the cancels
parameter to the event listener.
For this feature to work, the queue must be enabled.
Code:
import time
import gradio as gr
def fake_diffusion(steps):
for i in range(steps):
time.sleep(1)
yield str(i)
def long_prediction(*args, **kwargs):
time.sleep(10)
return 42
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
n = gr.Slider(1, 10, value=9, step=1, label="Number Steps")
run = gr.Button()
output = gr.Textbox(label="Iterative Output")
stop = gr.Button(value="Stop Iterating")
with gr.Column():
prediction = gr.Number(label="Expensive Calculation")
run_pred = gr.Button(value="Run Expensive Calculation")
with gr.Column():
cancel_on_change = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Change")
click_event = run.click(fake_diffusion, n, output)
stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])
pred_event = run_pred.click(fn=long_prediction, inputs=None, outputs=prediction)
cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])
demo.queue(concurrency_count=1, max_size=20).launch()
For interfaces, a stop button will be added automatically if the function uses a yield
statement.
import gradio as gr
import time
def iteration(steps):
for i in range(steps):
time.sleep(0.5)
yield i
gr.Interface(iteration,
inputs=gr.Slider(minimum=1, maximum=10, step=1, value=5),
outputs=gr.Number()).queue().launch()
Ensure that Gradio does not take control of the HTML page title when embedding a gradio app as a web component, this behaviour flipped by adding control_page_title="true"
to the webcomponent. @pngwn in PR 2400
Decreased latency in iterative-output demos by making the iteration asynchronous @freddyaboulton in PR 2409
Fixed queue getting stuck under very high load by @freddyaboulton in PR 2374
Ensure that components always behave as if interactive=True
were set when the following conditions are true:
interactive
kwarg is not set.Image
component is set to source="upload"
, it is now possible to drag and drop and image to replace a previously uploaded image by @pngwn in PR 1711gr.Dataset
component now accepts HTML
and Markdown
components by @abidlabs in PR 2437Carousel
component is officially deprecated. Since gradio 3.0, code containing the Carousel
component would throw warnings. As of the next release, the Carousel
component will raise an exception.Image
component is set to source="upload"
, it is now possible to drag and drop and image to replace a previously uploaded image by @pngwn in PR 2400Blocks.load()
event by @abidlabs in PR 2413gr.Plot()
component @dawoodkhan82 in PR 2402Textbox
and Number
components @dawoodkhan82 in PR 2448You can now see gradio’s release history directly on the website, and also keep track of upcoming changes. Just go here.
gr.Row(variant="compact")
by @aliabid94 in PR 2291 This comes with deprecation of the following arguments for Component.style
: round
, margin
, border
.New Guide: Connecting to a Database 🗄️
A new guide by @freddyaboulton that explains how you can use Gradio to connect your app to a database. Read more here.
New Guide: Running Background Tasks 🥷
A new guide by @freddyaboulton that explains how you can run background tasks from your gradio app. Read more here.
Small fixes to docs for Image
component by @abidlabs in PR 2372
analytics
dependency by @abidlabs in PR 2347Image
component by @abidlabs in PR 2372gr.update()
dictionary even if post-processing is disabled @abidlabs in PR 2385You can now pass captions to images in the Gallery component. To do so you need to pass a {List} of (image, {str} caption) tuples. This is optional and the component also accepts just a list of the images.
Here’s an example:
import gradio as gr
images_with_captions = [
("https://images.unsplash.com/photo-1551969014-7d2c4cddf0b6", "Cheetah by David Groves"),
("https://images.unsplash.com/photo-1546182990-dffeafbe841d", "Lion by Francesco"),
("https://images.unsplash.com/photo-1561731216-c3a4d99437d5", "Tiger by Mike Marrah")
]
with gr.Blocks() as demo:
gr.Gallery(value=images_with_captions)
demo.launch()
You can now type values directly on the Slider component! Here’s what it looks like:
We’ve made a lot of changes to our Image component so that it can support better sketching and inpainting.
Now supports:
import gradio as gr
demo = gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())
demo.launch()
import gradio as gr
demo = gr.Interface(lambda x: x, gr.Paint(), gr.Image())
demo.launch()
import gradio as gr
demo = gr.Interface(lambda x: x, gr.Image(source='upload', tool='color-sketch'), gr.Image()) # for black and white, tool = 'sketch'
demo.launch()
import gradio as gr
demo = gr.Interface(lambda x: x, gr.Image(source='webcam', tool='color-sketch'), gr.Image()) # for black and white, tool = 'sketch'
demo.launch()
As well as other fixes
gr.update()
in example caching by @abidlabs in PR 2309postprocess
and preprocess
to documented parameters by @abidlabs in PR 2293postprocess
and preprocess
to documented parameters by @abidlabs in PR 2293gr.update()
in example caching by @abidlabs in PR 2309You can now create an iterative output simply by having your function return a generator!
Here’s (part of) an example that was used to generate the interface below it. See full code.
def predict(steps, seed):
generator = torch.manual_seed(seed)
for i in range(1,steps):
yield pipeline(generator=generator, num_inference_steps=i)["sample"][0]
This version of Gradio introduces a new layout component to Blocks: the Accordion. Wrap your elements in a neat, expandable layout that allows users to toggle them as needed.
Usage: (Read the docs)
with gr.Accordion("open up"):
# components here
Our new integration with skops allows you to load tabular classification and regression models directly from the hub.
Here’s a classification example showing how quick it is to set up an interface for a model.
import gradio as gr
gr.Interface.load("models/scikit-learn/tabular-playground").launch()
We’ve implemented a brand new queuing system based on web sockets instead of HTTP long polling. Among other things, this allows us to manage queue sizes better on Hugging Face Spaces. There are also additional queue-related parameters you can add:
demo = gr.Interface(...)
demo.queue(concurrency_count=3)
demo.launch()
demo = gr.Interface(...)
demo.queue(max_size=100)
demo.launch()
components.Image().style(height=260, width=300)
Slider
input. Or you might want to show a Textbox
with the current date. We now supporting passing functions as the default value in input components. When you pass in a function, it gets re-evaluated every time someone loads the demo, allowing you to reload / change data for different users.Here’s an example loading the current date time into an input Textbox:
import gradio as gr
import datetime
with gr.Blocks() as demo:
gr.Textbox(datetime.datetime.now)
demo.launch()
Note that we don’t evaluate the function — datetime.datetime.now()
— we pass in the function itself to get this behavior — datetime.datetime.now
Because randomizing the initial value of Slider
is a common use case, we’ve added a randomize
keyword argument you can use to randomize its initial value:
import gradio as gr
demo = gr.Interface(lambda x:x, gr.Slider(0, 10, randomize=True), "number")
demo.launch()
Label
component now accepts file paths to .json
files by @abidlabs in PR 2083file
route as well by @abidlabs in PR 2099State
by @abidlabs in PR 2100gr.Examples
by @abidlabs in PR 2131With PR #1444, Gradio is now distributed as a web component. This means demos can be natively embedded on websites. You’ll just need to add two lines: one to load the gradio javascript, and one to link to the demos backend.
Here’s a simple example that embeds the demo from a Hugging Face space:
<script
type="module"
src="https://gradio.s3-us-west-2.amazonaws.com/3.0.18/gradio.js"
></script>
<gradio-app space="abidlabs/pytorch-image-classifier"></gradio-app>
But you can also embed demos that are running anywhere, you just need to link the demo to src
instead of space
. In fact, all the demos on the gradio website are embedded this way:
Read more in the Embedding Gradio Demos guide.
Reload mode helps developers create gradio demos faster by automatically reloading the demo whenever the code changes. It can support development on Python IDEs (VS Code, PyCharm, etc), the terminal, as well as Jupyter notebooks.
If your demo code is in a script named app.py
, instead of running python app.py
you can now run gradio app.py
and that will launch the demo in reload mode:
Launching in reload mode on: http://127.0.0.1:7860 (Press CTRL+C to quit)
Watching...
WARNING: The --reload flag should not be used in production on Windows.
If you’re working from a Jupyter or Colab Notebook, use these magic commands instead: %load_ext gradio
when you import gradio, and %%blocks
in the top of the cell with the demo code. Here’s an example that shows how much faster the development becomes:
gr.Image()
🎨We updated the Image component to add support for inpainting demos. It works by adding tool="sketch"
as a parameter, that passes both an image and a sketchable mask to your prediction function.
Here’s an example from the LAMA space:
We upgraded the Dataframe component in PR #1684 to support rendering Markdown and HTML inside the cells.
This means you can build Dataframes that look like the following:
gr.Examples()
for Blocks 🧱We’ve added the gr.Examples
component helper to allow you to add examples to any Blocks demo. This class is a wrapper over the gr.Dataset
component.
gr.Examples takes two required parameters:
examples
which takes in a nested listinputs
which takes in a component or list of componentsYou can read more in the Examples docs or the Adding Examples to your Demos guide.
With PR 1828 we now hide the status loading animation, as well as remove the echo in streaming. Check out the stream_audio demo for more or read through our Real Time Speech Recognition guide.
integrate()
method moved to Blocks
by @abidlabs in PR 1776Blocks is a new, low-level API that allows you to have full control over the data flows and layout of your application. It allows you to build very complex, multi-step applications. For example, you might want to:
Here’s a simple example that creates the demo below it:
import gradio as gr
def update(name):
return f"Welcome to Gradio, {name}!"
demo = gr.Blocks()
with demo:
gr.Markdown(
"""
# Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(fn=update,
inputs=inp,
outputs=out)
demo.launch()
Read our Introduction to Blocks guide for more, and join the 🎈 Gradio Blocks Party!
We’ve upgraded our design across the entire library: from components, and layouts all the way to dark mode.
We’ve upgraded gradio.app to make it cleaner, faster and easier to use. Our docs now come with components and demos embedded directly on the page. So you can quickly get up to speed with what you’re looking for.
We’ve introduced a lot of new components in 3.0
, including Model3D
, Dataset
, Markdown
, Button
and Gallery
. You can find all the components and play around with them here.
gradio.components
syntax by @abidlabs in PR 848blocks-dev
by @abidlabs in PR 861Blocks
instances to be used like a Block
in other Blocks
by @abidlabs in PR 919Launchable()
by @abidlabs in PR 968