Python library for easily interacting with trained machine learning models
npx @tessl/cli install tessl/pypi-gradio_client@1.12.0A lightweight Python client library for interacting with Gradio applications as APIs. The client enables developers to programmatically connect to and make predictions on any Gradio app, whether hosted on Hugging Face Spaces or running elsewhere, providing a seamless bridge between interactive Gradio interfaces and programmatic access for batch processing, automation, and integration into larger ML pipelines.
pip install gradio_clientfrom gradio_client import ClientCommon imports for file handling:
from gradio_client import Client, file, handle_file, FileDataAll public imports:
from gradio_client import Client, file, handle_file, FileData, __version__from gradio_client import Client
# Connect to a Hugging Face Space
client = Client("abidlabs/whisper-large-v2")
# Make a synchronous prediction
result = client.predict("test.mp4", api_name="/predict")
print(result) # >> "What a nice recording!"
# Submit an asynchronous job
job = client.submit("hello", api_name="/predict")
result = job.result() # Wait for completion
print(result) # >> 49
# Connect to a private Space with token
client = Client("username/private-space", hf_token="hf_...")
# Connect to any Gradio URL
client = Client("https://bec81a83-5b5c-471e.gradio.live")
# View available API endpoints
client.view_api()The gradio_client architecture is built around several key components:
The client automatically handles authentication, file transfers, session management, and protocol negotiation, providing a simple interface while supporting advanced features like Space duplication, Discord bot deployment, and streaming responses.
Core client functionality for connecting to Gradio applications, managing connections, and configuring client behavior including authentication, SSL verification, and custom headers.
class Client:
def __init__(
self,
src: str,
hf_token: str | None = None,
max_workers: int = 40,
verbose: bool = True,
auth: tuple[str, str] | None = None,
httpx_kwargs: dict[str, Any] | None = None,
*,
headers: dict[str, str] | None = None,
download_files: str | Path | Literal[False] = DEFAULT_TEMP_DIR,
ssl_verify: bool = True,
analytics_enabled: bool = True,
): ...
def close(self) -> None: ...
def reset_session(self) -> None: ...
def view_api(self, all_endpoints: bool | None = None, print_info: bool = True, return_format: Literal["dict", "str"] | None = None) -> dict | str | None: ...
def add_zero_gpu_headers(self, headers: dict[str, str]) -> dict[str, str]: ...Synchronous and asynchronous prediction capabilities with comprehensive job management, including status tracking, result retrieval, and cancellation support.
def predict(self, *data, api_name: str | None = None, fn_index: int | None = None) -> Any: ...
def submit(self, *data, api_name: str | None = None, fn_index: int | None = None, result_callbacks: list[Callable] | None = None) -> Job: ...
class Job:
def result(self, timeout: float | None = None) -> Any: ...
def status(self) -> StatusUpdate: ...
def cancel(self) -> bool: ...
def outputs(self) -> list[tuple | Any]: ...Hugging Face Space operations including duplication for private use, hardware configuration, and deployment as Discord bots.
@classmethod
def duplicate(
cls,
from_id: str,
to_id: str | None = None,
hf_token: str | None = None,
duplicate_from: str = "spaces",
**kwargs
) -> Client: ...
def deploy_discord(
self,
discord_bot_token: str,
api_names: list[str] | str | None = None,
to_id: str | None = None,
hf_token: str | None = None,
**kwargs
) -> None: ...File upload, download, and processing utilities with automatic encoding/decoding, MIME type detection, and support for various file formats and sources.
def file(filepath_or_url: str | Path) -> Any: ...
def handle_file(filepath_or_url: str | Path) -> Any: ...
class FileData(TypedDict):
name: str | None # filename
data: str | None # base64 encoded data
size: NotRequired[int | None] # size in bytes
is_file: NotRequired[bool] # whether the data corresponds to a file or base64 encoded data
orig_name: NotRequired[str] # original filename
mime_type: NotRequired[str]
is_stream: NotRequired[bool]Real-time message streaming and bidirectional communication with Gradio applications using WebSocket and Server-Sent Events protocols.
def stream_messages(
self,
*data,
api_name: str | None = None,
fn_index: int | None = None
) -> Iterator[Any]: ...
def send_data(self, data: dict, hash_data: dict, protocol: str, request_headers: dict) -> Any: ...Comprehensive exception system for handling authentication errors, application errors, and communication failures with detailed error information.
class AuthenticationError(ValueError):
"""Raised when authentication fails"""
pass
class AppError(ValueError):
"""Raised when the upstream Gradio app throws an error"""
def __init__(
self,
message: str = "Error raised.",
duration: float | None = 10,
visible: bool = True,
title: str = "Error",
print_exception: bool = True,
): ...from typing_extensions import NotRequired
StatusUpdate = dict[str, Any]
class ParameterInfo(TypedDict):
label: str
parameter_name: str
parameter_has_default: NotRequired[bool]
parameter_default: NotRequired[Any]
type: dict
python_type: dict
component: str
example_input: Any