← Journal
Give Gradio a Python Function: Building an Interface

Give Gradio a Python Function: Building an Interface

I tested UI generation from functions and input/output components, tab layout and event wiring with Blocks, and a conversational screen with ChatInterface in Gradio 6.20.0. I ran three demos using basic components with no network access.

Repository covered in this article

gradio-app/gradio

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!

43.1k Python Apache License 2.0

You can spend more time building input fields, run buttons, result displays, and chat history than testing a machine-learning model when you start from the frontend to show your team how it behaves. If you share a notebook, you hand the other person responsibility for the runtime and cell operations, so showing the value of a short Python function takes extra setup. Declare input and output types, and Gradio can bring up an interface. Add layout and event wiring when you need them, and UI prototyping around the model stays light. I used Gradio to test three approaches in isolation: automatic UI generation, custom layout, and a conversational screen.

Gradio is a framework for adding web UIs to Python functions and machine-learning models. The Gradio project releases the framework under the Apache-2.0 License (*1). I pinned Gradio to 6.20.0 and checked three component groups with different roles: gr.Interface, gr.Blocks, and gr.ChatInterface.

1. Setting up the test environment

I pinned the environment to the combination used in the test. Readers do not need the browser tools I used to capture the screens, so I left them out. The setup needs one Python package: gradio==6.20.0.

FROM docker.io/library/python:3.12.13-slim

ENV GRADIO_ANALYTICS_ENABLED=False

RUN pip install --no-cache-dir --quiet 'gradio==6.20.0'

WORKDIR /work

Setting GRADIO_ANALYTICS_ENABLED=False disables telemetry calls to api.gradio.app and keeps the version-check thread from starting; I confirmed both behaviors in the 6.20.0 source (*2). At install time, pip makes network requests to fetch packages. That build traffic is separate from the application-startup setting.

Start with an empty directory for the experiment. Put the Dockerfile and the three Python files that appear below in it. Leave secret keys, credentials, customer data, and unreleased source code out of that directory. Install dependencies during a build step; do not mount the host directory during that step.

podman build -t gradio-sandbox .

Mount the source read-only and bind the port to the host's 127.0.0.1 interface. Replace app_interface with app_blocks or app_chat to start either of the other two files under the same conditions. The container listens on 0.0.0.0, while the host limits exposure to the loopback interface. With share=False, Gradio creates no public tunnel.

podman run --rm \
  --memory 2g --cpus 2 --pids-limit 512 \
  -e GRADIO_ANALYTICS_ENABLED=False \
  -p 127.0.0.1:7860:7860 \
  -v "$(pwd)":/work:ro,Z -w /work gradio-sandbox \
  python -c 'from app_interface import demo; demo.launch(server_name="0.0.0.0", server_port=7860, share=False)'

I used the host's standard container network so a browser on the host could open the interface. In our sandbox, I put the browser used for screen checks in the same isolated environment and ran the app with --network none. On a normal local setup, you can check the interface through the loopback port without a separate screen-capture environment.

This test covers the basic components used here, including Textbox, Slider, Number, and Chatbot. The browser sent all 60 requests to localhost. Gradio 6.20.0 has code that fetches assets from unpkg.com for Plotly-based geographic plots, splat/EXR texture loading in gr.Model3D, and audio/video trimming through browser-side ffmpeg. I did not use those features, so this test cannot support the claim that all Gradio features work offline. The --network none setting blocks external communication. Mounted paths remain writable, and resource use has no limit. I mounted the directory read-only and set limits on memory, CPU, and process count.

2. Building a UI from a function with gr.Interface

I started with a text-analysis function and passed it to gr.Interface. analyze_text() takes the body text and a target reading speed, then returns a character count, average sentence length, and estimated reading time. Match its two arguments with a Textbox and a Slider, and its three return values with Textbox components; Gradio gives you an interface with an input field, a slider, a run button, and output fields (*3).

import re
import gradio as gr


def analyze_text(text: str, target_cpm: int) -> tuple[str, str, str]:
    char_count = len(re.sub(r"\s", "", text))
    sentence_count = len([s for s in re.split(r"[。.!?]", text) if s.strip()]) or 1
    avg_sentence_len = char_count / sentence_count
    reading_minutes = char_count / target_cpm if target_cpm else 0
    return (
        f"{char_count} 文字",
        f"{avg_sentence_len:.1f} 文字/文",
        f"{reading_minutes:.1f} 分",
    )


demo = gr.Interface(
    fn=analyze_text,
    inputs=[
        gr.Textbox(label="本文", lines=6, value="ここに記事の下書きを貼り付けると、語数と想定読了時間が自動で計算されます。"),
        gr.Slider(200, 800, value=400, step=10, label="想定読速度(文字/分)"),
    ],
    outputs=[
        gr.Textbox(label="文字数"),
        gr.Textbox(label="平均文長"),
        gr.Textbox(label="想定読了時間"),
    ],
    title="テキスト分析デモ",
)

if __name__ == "__main__":
    demo.launch(server_name="127.0.0.1", server_port=7860, share=False)

After I entered a 79-character body, the interface showed an average sentence length of 39.5 characters and an estimated reading time of 0.2 minutes at 400 characters per minute. The interface placed the components that correspond to the function's arguments and return values side by side. I wrote no page-specific HTML or JavaScript.

The gr.Interface screen after entering text and reading speed, with 79 characters, an average sentence length of 39.5 characters, and an estimated reading time of 0.2 minutes
The gr.Interface screen after entering text and reading speed, with 79 characters, an average sentence length of 39.5 characters, and an estimated reading time of 0.2 minutes

The first aggregation logic made one wrong assumption: whitespace tokenization, common in English examples, counted an entire Japanese sentence as one word.

word_count = len(re.findall(r"\S+", text))

# returns 1 for Japanese text, which has no spaces

I had reused an English tokenization assumption for Japanese input. The error came from my preprocessing assumption, so Gradio was not at fault. I left morphological analysis out and changed the metrics to character count after removing whitespace and average sentence length by sentence-ending punctuation. Check the assumption that spaces mark word boundaries before reusing English tokenization for Japanese or CJK text.

3. Making layout and events explicit with gr.Blocks

I moved from Interface's automatic layout to gr.Blocks and built two tabs: temperature conversion and BMI calculation. Blocks lets you choose component positions and specify which function each operation calls (*4). On the BMI tab, I attached .change() to both sliders, so either change updates the output through the same bmi() function.

import gradio as gr


def to_celsius(fahrenheit: float) -> float:
    return round((fahrenheit - 32) * 5 / 9, 2)


def bmi(weight_kg: float, height_cm: float) -> str:
    if not height_cm:
        return "-"
    h_m = height_cm / 100
    value = weight_kg / (h_m * h_m)
    if value < 18.5:
        cat = "低体重"
    elif value < 25:
        cat = "普通体重"
    elif value < 30:
        cat = "肥満(1度)"
    else:
        cat = "肥満(2度以上)"
    return f"{value:.1f} ({cat})"


with gr.Blocks(title="Blocksレイアウトデモ") as demo:
    gr.Markdown("## 複数ウィジェットを組み合わせたBlocksレイアウト")
    with gr.Tab("温度換算"):
        f_in = gr.Number(label="華氏(F)", value=98.6)
        c_out = gr.Textbox(label="摂氏(C)")
        f_in.change(to_celsius, inputs=f_in, outputs=c_out)
    with gr.Tab("BMI計算"):
        with gr.Row():
            weight = gr.Slider(30, 150, value=65, step=1, label="体重(kg)")
            height = gr.Slider(120, 210, value=170, step=1, label="身長(cm)")
        bmi_out = gr.Textbox(label="BMI")
        weight.change(bmi, inputs=[weight, height], outputs=bmi_out)
        height.change(bmi, inputs=[weight, height], outputs=bmi_out)

if __name__ == "__main__":
    demo.launch(server_name="127.0.0.1", server_port=7860, share=False)

I moved the weight slider to its 150 kg maximum and set the height to 170 cm. The BMI field changed to 51.9 (肥満(2度以上)). Interface packages the function call flow into one screen. The Blocks code shows the wiring from two input events to one output. Choose this structure when inputs grow and you want to divide the screen by use case.

The gr.Blocks screen with temperature-conversion and BMI-calculation tabs, displaying a BMI of 51.9 after the weight changes to 150 kg and the height to 170 cm
The gr.Blocks screen with temperature-conversion and BMI-calculation tabs, displaying a BMI of 51.9 after the weight changes to 150 kg and the height to 170 cm

4. Testing a conversational UI with gr.ChatInterface

The last test connected a response function to gr.ChatInterface. Pass a function that accepts a message string and history, and Gradio builds a chat screen with an input field, a send action, and message bubbles on both sides (*5).

import gradio as gr


def respond(message: str, history):
    text = message.strip()
    if not text:
        reply = "何か入力してください。"
    elif text.endswith("?") or text.endswith("?"):
        reply = f"「{text}」への即答は難しいですが、まず前提を分解してみましょう。"
    elif any(k in text for k in ["ありがとう", "thanks"]):
        reply = "どういたしまして。"
    else:
        reply = f"「{text}」について、もう少し具体的に教えてください。"
    return reply


demo = gr.ChatInterface(
    fn=respond,
    title="ルールベース応答デモ(モデル呼び出しなし)",
    examples=["これは動きますか?", "ありがとう"],
    chatbot=gr.Chatbot(height=260),
)

if __name__ == "__main__":
    demo.launch(server_name="127.0.0.1", server_port=7860, share=False)

The respond() function checks the end of the message and a few keywords. The rule-based function makes no calls to an LLM, machine-learning model, or external API. I chose this function to test the ChatInterface UI component without a network dependency. The image documents message placement and conversation-history behavior. The sent message appears in the right bubble, the reply in the left, and both appear in the conversation history.

The gr.ChatInterface screen with the user's message on the right and the rule-based function's reply on the left
The gr.ChatInterface screen with the user's message on the right and the rule-based function's reply on the left

UI prototyping that starts with a function

Once you have a model inference function, start with Interface and test the interaction. Move to Blocks as inputs grow, and add processing suited to a conversational format to ChatInterface. This sequence lets you leave screen design open at first and update the UI as the logic changes. Bring a small demo into review, collect feedback, then add the layout and operational safeguards you need. These steps reduce the work at the boundary between model development and UI development. You can turn test results into a shareable form within a short cycle each day.

Sources

*1 Gradio (GitHub), https://github.com/gradio-app/gradio, Apache-2.0 License*2 Gradio 6.20.0 analytics.py, https://github.com/gradio-app/gradio/blob/gradio%406.20.0/gradio/analytics.py, Apache-2.0 License*3 Gradio Docs: Interface, https://www.gradio.app/docs/gradio/interface, Apache-2.0 License*4 Gradio Docs: Blocks, https://www.gradio.app/docs/gradio/blocks, Apache-2.0 License*5 Gradio Docs: ChatInterface, https://www.gradio.app/docs/gradio/chatinterface, Apache-2.0 License