Gradio Client
Gradio Client is a Python library designed for programmatically interacting with deployed Gradio applications. It allows developers to make API calls to Gradio-hosted machine learning models or other Gradio apps without needing the UI. The current stable version is 2.4.0. It's actively developed as part of the broader Gradio ecosystem, with frequent updates corresponding to Gradio's release cycle.
Warnings
- breaking The `gradio.client` module was deprecated and removed in Gradio v3.14. Functionality was moved to the separate `gradio-client` package. If you were using `gradio.client.Client` directly, you must now install `gradio-client` and import `Client` from there.
- gotcha Distinction between `client.predict()` and `client.submit()`: `predict()` is a synchronous, blocking call that returns the result directly. `submit()` returns a `Job` object, allowing for asynchronous execution, polling for results, and handling streaming outputs. Using `predict()` for long-running tasks or when streaming is expected will block your program.
- gotcha File inputs/outputs are handled automatically but can be unintuitive. When providing a local file path as input, `gradio-client` uploads it. When receiving a file output, `predict()` returns a temporary file path on the local machine.
- gotcha Authentication for private Hugging Face Spaces requires an `hf_token`. Forgetting to provide this token will result in authentication errors when trying to access private models.
Install
-
pip install gradio-client
Imports
- Client
from gradio_client import Client
Quickstart
import os
from gradio_client import Client
# Replace with your Gradio app URL or Hugging Face Space ID
# For private Spaces, set the HF_TOKEN environment variable or pass hf_token directly.
SPACE_URL = os.environ.get('GRADIO_SPACE_URL', 'https://hf.space/gradio/calculator')
HF_TOKEN = os.environ.get('HF_TOKEN', '') # Optional: for private Hugging Face Spaces
client = Client(SPACE_URL, hf_token=HF_TOKEN)
# Example for a simple calculator app with 'add' function taking two numbers
try:
# Use client.predict for synchronous calls
result = client.predict(2, 3, api_name='/add')
print(f"Result of 2 + 3: {result}")
# Use client.submit for asynchronous calls or streaming output (not shown here)
job = client.submit(10, 5, api_name='/subtract')
print(f"Result of 10 - 5 (via job): {job.result()}")
except Exception as e:
print(f"Error interacting with Gradio app: {e}")
print("Please ensure the Gradio app is running and the API name is correct.")