Getting Started with the Gradio Python Client
The Gradio Python client allows you to effortlessly use any Gradio application as an API. This guide provides a comprehensive overview of how to utilize the gradio_client library to interact with Gradio applications, whether they're hosted on Hugging Face Spaces or your own server.
Prerequisites
- Basic Understanding: Familiarity with Gradio's input and output components is beneficial but not mandatory.
- Python Version: Ensure you're using Python 3.10 or higher.
Installation
If you have the latest version of Gradio installed, gradio_client is included as a dependency. To install or upgrade gradio_client, use:
pip install --upgrade gradio_client
Connecting to a Gradio Application
1. Connecting to a Public Space on Hugging Face
Create a Client instance by specifying the Hugging Face Space URL:
from gradio_client import Client
client = Client("abidlabs/en2fr") # Example Space: English to French translator
2. Connecting to a Private Space
If the Gradio Space is private, provide your Hugging Face token:
from gradio_client import Client
client = Client("abidlabs/my-private-space", hf_token="YOUR_HF_TOKEN")
Obtain your Hugging Face token here.
3. Using a Custom Hosted Gradio Application
For applications hosted outside Hugging Face Spaces, include the full URL:
from gradio_client import Client
client = Client("https://your-gradio-app-url.com")
4. Handling Authentication
If the Gradio app requires authentication, pass the username and password as a tuple:
from gradio_client import Client
client = Client(
"space_name",
auth=("username", "password")
)
Managing API Limits with Private Spaces
To avoid request limitations on public Spaces, duplicate the Space to your private account:
import os
from gradio_client import Client, handle_file
HF_TOKEN = os.environ.get("HF_TOKEN")
client = Client.duplicate("abidlabs/whisper", hf_token=HF_TOKEN)
response = client.predict(handle_file("audio_sample.wav"))
print(response) # "This is a test of the whisper speech recognition model."
Note: Duplicating a Space leveraging GPU resources will incur costs based on GPU usage.
Interacting with the API
1. Viewing Available API Endpoints
After connecting, view available APIs using:
client.view_api()
This displays information about the available endpoints, their parameters, and return types.
2. Making Predictions
Basic Prediction:
from gradio_client import Client
client = Client("abidlabs/en2fr", api_name='/predict')
result = client.predict("Hello")
print(result) # Output: "Bonjour"
Multiple Parameters:
client = Client("gradio/calculator")
result = client.predict(num1=4, operation="add", num2=5)
print(result) # Output: 9.0
Using Default Values:
If the API has default values, you can omit some parameters:
client = Client("abidlabs/image_generator")
result = client.predict(text="an astronaut riding a camel")
print(result)
Handling Files:
Use handle_file() to upload files or provide URLs:
from gradio_client import Client, handle_file
client = Client("abidlabs/whisper")
transcription = client.predict(
audio=handle_file("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3")
)
print(transcription)
Asynchronous Operations
1. Submitting Jobs
Instead of blocking the main thread, submit jobs asynchronously:
from gradio_client import Client
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict") # Non-blocking
# Perform other tasks here
result = job.result() # Blocking when needed
print(result) # Output: "Bonjour"
2. Adding Callbacks
Execute functions after job completion:
from gradio_client import Client
def print_result(result):
print(f"The translated result is: {result}")
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict", result_callbacks=[print_result])
3. Checking Job Status
Monitor the status of a job:
from gradio_client import Client
client = Client(src="gradio/calculator")
job = client.submit(5, "add", 4, api_name="/predict")
status = job.status()
print(status) # Example Output: <Status.STARTING: 'STARTING'>
4. Canceling Jobs
Cancel pending or ongoing jobs:
client = Client("abidlabs/whisper")
job1 = client.submit(handle_file("audio_sample1.wav"))
job2 = client.submit(handle_file("audio_sample2.wav"))
job1.cancel() # Returns False if already started
job2.cancel() # Returns True if successfully canceled
Handling Generator Endpoints
For APIs that yield multiple outputs over time:
from gradio_client import Client
import time
client = Client(src="gradio/count_generator")
job = client.submit(3, api_name="/count")
while not job.done():
time.sleep(0.1)
outputs = job.outputs()
print(outputs) # Output: ['0', '1', '2']
Alternatively, iterate over job outputs as they become available:
for output in job:
print(output)
Managing Session State
Some Gradio demos use session state to maintain user interactions. When using the Python client:
- The client handles session state automatically across multiple requests.
- To reset the session state, use:
client.reset_session()
Example: Transcribing Audio with Whisper
Here's a complete example using the Whisper model to transcribe an audio file:
from gradio_client import Client, handle_file
client = Client("abidlabs/whisper")
transcription = client.predict(
audio=handle_file("audio_sample.wav")
)
print(transcription)
# Output: "This is a test of the whisper speech recognition model."
Conclusion
The gradio_client library provides a versatile and straightforward way to integrate Gradio applications into your Python workflows. Whether you're leveraging public Spaces on Hugging Face or hosting your own Gradio server, this client simplifies API interactions, including synchronous and asynchronous operations, session management, and more.
For more detailed information and advanced usage, refer to the official Gradio documentation.