gradio/CHANGELOG.md
Abubakar Abid e360f159a9
Add support for loading Private Spaces using HF Token (#2568)
* pass token & add typing

* updated docstring

* reorg

* improve docs

* test for private space

* changelog

* addressing review

* fix tests

* fix websocket headers
2022-10-31 20:29:13 -07:00

79 KiB

Upcoming Release

New Features:

No changes to highlight.

Bug Fixes:

No changes to highlight.

Documentation Changes:

No changes to highlight.

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

No changes to highlight.

Contributors Shoutout:

No changes to highlight.

Version 3.8.1de# Version 1

Bug Fixes:

  • Ensure gradio apps embedded via spaces use the correct endpoint for predictions. @pngwn in PR 2567
  • Ensure gradio apps embedded via spaces use the correct websocket protocol. @pngwn in PR 2571

New Features:

Running Events Continuously

Gradio 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:

  • Create live visualizations that show the most up to date data
  • Refresh the state of the frontend automatically in response to changes in the backend

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()

live_demo

Bug Fixes:

No changes to highlight.

Documentation Changes:

No changes to highlight.

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

  • Allows loading private Spaces by passing an an api_key to gr.Interface.load() by @abidlabs in PR 2568

Contributors Shoutout:

No changes to highlight.

Version 3.8

New Features:

  • Allows event listeners to accept a single dictionary as its argument, where the keys are the components and the values are the component values. This is set by passing the input components in the event listener as a set instead of a list. @aliabid94 in PR 2550

Bug Fixes:

Documentation Changes:

No changes to highlight.

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

Contributors Shoutout:

No changes to highlight.

Version 3.7

New Features:

Batched Functions

Gradio 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).

Upload Event

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)  

Bug Fixes:

  • Fixes issue where plotly animations, interactivity, titles, legends, were not working properly. @dawoodkhan82 in PR 2486
  • Prevent requests to the /api endpoint from skipping the queue if the queue is enabled for that event by @freddyaboulton in PR 2493
  • Fixes a bug with cancels in event triggers so that it works properly if multiple Blocks are rendered by @abidlabs in PR 2530
  • Prevent invalid targets of events from crashing the whole application. @pngwn in PR 2534
  • Properly dequeue cancelled events when multiple apps are rendered by @freddyaboulton in PR 2540

Documentation Changes:

  • Added an example interactive dashboard to the "Tabular & Plots" section of the Demos page by @freddyaboulton in PR 2508

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

  • Fixes the error message if a user builds Gradio locally and tries to use share=True by @abidlabs in PR 2502
  • Allows the render() function to return self by @Raul9595 in PR 2514
  • Fixes issue where plotly animations, interactivity, titles, legends, were not working properly. @dawoodkhan82 in PR 2486
  • Gradio now supports batched functions by @abidlabs in PR 2218
  • Add upload event for Video, Audio, Image, and File components @dawoodkhan82 in PR 2448
  • Changes websocket path for Spaces as it is no longer necessary to have a different URL for websocket connections on Spaces by @abidlabs in PR 2528
  • Clearer error message when events are defined outside of a Blocks scope, and a warning if you try to use Series or Parallel with Blocks by @abidlabs in PR 2543
  • Adds support for audio samples that are in float64, float16, or uint16 formats by @abidlabs in PR 2545

Contributors Shoutout:

No changes to highlight.

Version 3.6

New Features:

Cancelling Running Events

Running 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.

cancel_on_change_rl

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()

stop_interface_rl

Bug Fixes:

  • Add loading status tracker UI to HTML and Markdown components. @pngwn in PR 2474
  • Fixed videos being mirrored in the front-end if source is not webcam by @freddyaboulton in PR 2475
  • Add clear button for timeseries component @dawoodkhan82 in PR 2487
  • Removes special characters from temporary filenames so that the files can be served by components @abidlabs in PR 2480
  • Fixed infinite reload loop when mounting gradio as a sub application by @freddyaboulton in PR 2477

Documentation Changes:

  • Adds a demo to show how a sound alert can be played upon completion of a prediction by @abidlabs in PR 2478

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

Contributors Shoutout:

No changes to highlight.

Version 3.5

Bug Fixes:

  • 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:

    • no default value is provided,
    • they are not set as the input or output of an event,
    • interactive kwarg is not set.

    @pngwn in PR 2459

New Features:

  • When an 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 1711
  • The gr.Dataset component now accepts HTML and Markdown components by @abidlabs in PR 2437

Documentation Changes:

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

  • The Carousel 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.

Full Changelog:

Contributors Shoutout:

No changes to highlight.

Version 3.4.1

New Features:

1. See Past and Upcoming Changes in the Release History 👀

You can now see gradio's release history directly on the website, and also keep track of upcoming changes. Just go here.

release-history

Bug Fixes:

  1. Fix typo in guide image path by @freddyaboulton in PR 2357
  2. Raise error if Blocks has duplicate component with same IDs by @abidlabs in PR 2359
  3. Catch the permission exception on the audio component by @Ian-GL in PR 2330
  4. Fix image_classifier_interface_load demo by @freddyaboulton in PR 2365
  5. Fix combining adjacent components without gaps by introducing gr.Row(variant="compact") by @aliabid94 in PR 2291 This comes with deprecation of the following arguments for Component.style: round, margin, border.
  6. Fix audio streaming, which was previously choppy in PR 2351. Big thanks to @yannickfunk for the proposed solution.
  7. Fix bug where new typeable slider doesn't respect the minimum and maximum values @dawoodkhan82 in PR 2380

Documentation Changes:

  1. 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.

  2. 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.

  3. Small fixes to docs for Image component by @abidlabs in PR 2372

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

Contributors Shoutout:

No changes to highlight.

Version 3.4

New Features:

You 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()
gallery_captions

2. Type Values into the Slider 🔢

You can now type values directly on the Slider component! Here's what it looks like:

type-slider

3. Better Sketching and Inpainting 🎨

We've made a lot of changes to our Image component so that it can support better sketching and inpainting.

Now supports:

  • A standalone black-and-white sketch
import gradio as gr
demo = gr.Interface(lambda x: x, gr.Sketchpad(), gr.Image())
demo.launch()

bw

  • A standalone color sketch
import gradio as gr
demo = gr.Interface(lambda x: x, gr.Paint(), gr.Image())
demo.launch()

color-sketch

  • An uploadable image with black-and-white or color sketching
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()

sketch-new

  • Webcam with black-and-white or color sketching
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()

webcam-sketch

As well as other fixes

Bug Fixes:

  1. Fix bug where max concurrency count is not respected in queue by @freddyaboulton in PR 2286
  2. fix : queue could be blocked by @SkyTNT in PR 2288
  3. Supports gr.update() in example caching by @abidlabs in PR 2309
  4. Clipboard fix for iframes by @abidlabs in PR 2321
  5. Fix: Dataframe column headers are reset when you add a new column by @dawoodkhan82 in PR 2318
  6. Added support for URLs for Video, Audio, and Image by @abidlabs in PR 2256
  7. Add documentation about how to create and use the Gradio FastAPI app by @abidlabs in PR 2263

Documentation Changes:

  1. Adding a Playground Tab to the Website by @aliabd in PR 1860
  2. Gradio for Tabular Data Science Workflows Guide by @merveenoyan in PR 2199
  3. Promotes postprocess and preprocess to documented parameters by @abidlabs in PR 2293
  4. Update 2)key_features.md by @voidxd in PR 2326
  5. Add docs to blocks context postprocessing function by @Ian-GL in PR 2332

Testing and Infrastructure Changes

  1. Website fixes and refactoring by @aliabd in PR 2280
  2. Don't deploy to spaces on release by @freddyaboulton in PR 2313

Full Changelog:

Contributors Shoutout:

Version 3.3

New Features:

1. Iterative Outputs

You 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]

example

2. Accordion Layout 🆕

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 

accordion

3. Skops Integration 📈

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()

187936493-5c90c01d-a6dd-400f-aa42-833a096156a1

Bug Fixes:

No changes to highlight.

Documentation Changes:

No changes to highlight.

Testing and Infrastructure Changes:

No changes to highlight.

Breaking Changes:

No changes to highlight.

Full Changelog:

Contributors Shoutout:

Version 3.2

New Features:

1. Improvements to Queuing 🥇

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:

  • Now supports concurrent workers (parallelization)
demo = gr.Interface(...)
demo.queue(concurrency_count=3)
demo.launch()
  • Configure a maximum queue size
demo = gr.Interface(...)
demo.queue(max_size=100)
demo.launch()
  • If a user closes their tab / browser, they leave the queue, which means the demo will run faster for everyone else

2. Fixes to Examples

  • Dataframe examples will render properly, and look much clearer in the UI: (thanks to PR #2125)

Screen Shot 2022-08-30 at 8 29 58 PM

  • Image and Video thumbnails are cropped to look neater and more uniform: (thanks to PR #2109)

Screen Shot 2022-08-30 at 8 32 15 PM

  • Other fixes in PR #2131 and #2064 make it easier to design and use Examples

3. Component Fixes 🧱

  • Specify the width and height of an image in its style tag (thanks to PR #2133)
components.Image().style(height=260, width=300)
  • Automatic conversion of videos so they are playable in the browser (thanks to PR #2003). Gradio will check if a video's format is playable in the browser and, if it isn't, will automatically convert it to a format that is (mp4).
  • Pass in a json filepath to the Label component (thanks to PR #2083)
  • Randomize the default value of a Slider (thanks to PR #1935)

slider-random

  • Improvements to State in PR #2100

4. Ability to Randomize Input Sliders and Reload Data whenever the Page Loads

  • In some cases, you want to be able to show a different set of input data to every user as they load the page app. For example, you might want to randomize the value of a "seed" 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()

5. New Guide 🖊️

Full Changelog:

Contributors Shoutout:

Version 3.1

New Features:

1. Embedding Demos on Any Website 💻

With 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:

Screen Shot 2022-07-14 at 2 41 44 PM

Read more in the Embedding Gradio Demos guide.

2. Reload Mode 👨‍💻

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:

Blocks

3. Inpainting Support on 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:

FXApVlFVsAALSD-

4. Markdown and HTML support in Dataframes 🔢

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:

image (8)

5. 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.

Screen Shot 2022-07-14 at 2 23 50 PM

gr.Examples takes two required parameters:

  • examples which takes in a nested list
  • inputs which takes in a component or list of components

You can read more in the Examples docs or the Adding Examples to your Demos guide.

6. Fixes to Audio Streaming

With PR [#1828](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.

Screen Shot 2022-07-19 at 6 02 35 PM

Full Changelog:

Contributors Shoutout:

Version 3.0

🔥 Gradio 3.0 is the biggest update to the library, ever.

New Features:

1. Blocks 🧱

Blocks 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:

  • Group together related demos as multiple tabs in one web app
  • Change the layout of your demo instead of just having all of the inputs on the left and outputs on the right
  • Have multi-step interfaces, in which the output of one model becomes the input to the next model, or have more flexible data flows in general
  • Change a component's properties (for example, the choices in a Dropdown) or its visibility based on user input

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()

hello-blocks

Read our Introduction to Blocks guide for more, and join the 🎈 Gradio Blocks Party!

2. Our Revamped Design 🎨

We've upgraded our design across the entire library: from components, and layouts all the way to dark mode.

kitchen_sink

3. A New Website 💻

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.

website

4. New Components: Model3D, Dataset, and More..

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.

Model3d

Full Changelog:

Contributors Shoutout: