← Gradio

Intro to Gradio

Turn a Python function into a web app you can click, in five short PRIMM steps.

By the end of this lesson you will have run a small web app built from one Python function, worked out which lines of code create which parts of the screen, and changed the app to do something new.

The lesson follows PRIMM: you Predict before you run, then Run, Investigate, Modify, and finally Make something of your own.

PredictRead the code and say what it will do before you run anything.

What will greet return?

app.py
def greet(name, excited):
    message = f"Hello, {name}"
    return message + "!!!" if excited else message + "."

Read the function below. Do not run anything yet.

Write down what greet returns for each call:

  1. greet("Ada", False)
  2. greet("Ada", True)
  3. greet("", True)

Which of these did you find hardest to predict, and why?

Reveal what happens
Predict first, then reveal the result
RunRun it and compare the result with your prediction.

Start the app

Install Gradio and run the file:

pip install gradio
python app.py

Open the address that appears in your terminal (usually http://127.0.0.1:7860).

app.py
if __name__ == "__main__":
    demo.launch(
        server_name="127.0.0.1",
        server_port=7860,
    )
Run the file, then open the local address
InvestigateTrace how each line of code connects to what you see.

Link the code to the screen

Look at the gr.Interface(...) call and answer, in your own words:

  1. Which line creates the Name box? Which creates the checkbox?
  2. inputs has two items and greet has two parameters. How does Gradio know which input goes to which parameter?
  3. What does fn=greet (with no brackets) tell Gradio to do?

Test your answer to question 2: swap the two items in inputs, run the app, and see what changes.

app.py
demo = gr.Interface(
    fn=greet,
    inputs=[
        gr.Textbox(label="Name"),
        gr.Checkbox(label="Excited?"),
    ],
    outputs=gr.Textbox(label="Greeting"),
    title="My first Gradio app",
    flagging_mode="never",
)
Every part of the screen comes from a line of code
ModifyChange the code on purpose and check the result.

Change the behaviour

Make one change at a time, run it, and check it did what you expected.

  1. Change the greeting so excited names end in "!!! 🎉".
  2. Change the box label from "Name" to "Your name". What else do you need to keep in sync?
  3. Add a third input, such as a number box gr.Number(label="Times"), and make greet repeat the greeting that many times.
MakeBuild something new using what you have learned.

Build your own

Build a new app from scratch, using greet as your model. Pick one:

Write the function first and test it by calling it directly. Only then wrap it in gr.Interface.