or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-management.mderror-handling.mdfile-handling.mdindex.mdpredictions-jobs.mdspace-management.mdstreaming.md
tile.json

tessl/pypi-gradio_client

Python library for easily interacting with trained machine learning models

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/gradio-client@1.12.x

To install, run

npx @tessl/cli install tessl/pypi-gradio_client@1.12.0

index.mddocs/

Gradio Client

A 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.

Package Information

  • Package Name: gradio_client
  • Language: Python
  • Installation: pip install gradio_client
  • Python Version: >=3.10

Core Imports

from gradio_client import Client

Common imports for file handling:

from gradio_client import Client, file, handle_file, FileData

All public imports:

from gradio_client import Client, file, handle_file, FileData, __version__

Basic Usage

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()

Architecture

The gradio_client architecture is built around several key components:

  • Client: The main interface for connecting to and interacting with Gradio apps
  • Job: Manages asynchronous predictions with status tracking and result retrieval
  • FileData: Handles file upload/download with automatic encoding/decoding
  • Endpoints: Internal representation of available API endpoints with parameter information
  • Communication protocols: Supports WebSocket, Server-Sent Events (SSE) for real-time interaction

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.

Capabilities

Client Management

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]: ...

Client Management

Prediction and Jobs

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]: ...

Predictions and Jobs

Space Management

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: ...

Space Management

File Handling

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]

File Handling

Streaming and Communication

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: ...

Streaming

Error Handling

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,
    ): ...

Error Handling

Types

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