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

file-handling.mddocs/

File Handling

File upload, download, and processing utilities with automatic encoding/decoding, MIME type detection, and support for various file formats and sources.

Capabilities

File Processing Functions

Utility functions for handling file paths, URLs, and file objects with automatic processing and format detection.

def file(filepath_or_url: str | Path) -> Any:
    """
    Process a file path or URL for use with Gradio predictions.

    Parameters:
    - filepath_or_url: Local file path or URL to a file

    Returns:
    Processed file object suitable for Gradio API calls

    Raises:
    - FileNotFoundError: If local file path does not exist
    - ValueError: If URL is invalid or inaccessible
    """

def handle_file(filepath_or_url: str | Path) -> Any:
    """
    Handle and process file objects for Gradio compatibility.

    Parameters:
    - filepath_or_url: File path or URL to process

    Returns:
    Processed file object with proper encoding and metadata

    Raises:
    - IOError: If file cannot be read or processed
    """

File Data Structure

Comprehensive file data structure for representing files with metadata, encoding, and processing information.

class FileData(TypedDict):
    name: str | None          # Original filename
    data: str | None          # Base64 encoded file data
    size: int | None          # File size in bytes (optional)
    is_file: bool             # Whether this represents a file (optional)
    orig_name: str            # Original filename before processing (optional)
    mime_type: str            # MIME type of the file (optional)
    is_stream: bool           # Whether this is a streaming file (optional)

File Utility Functions

Internal utility functions for file processing, encoding, and format handling.

def encode_file_to_base64(f: str | Path) -> str:
    """
    Encode a file to base64 string.

    Parameters:
    - f: File path to encode

    Returns:
    Base64 encoded string representation of the file
    """

def encode_url_to_base64(url: str) -> str:
    """
    Download and encode a URL to base64.

    Parameters:
    - url: URL to download and encode

    Returns:
    Base64 encoded string of the downloaded content
    """

def decode_base64_to_file(
    encoding: str,
    file_path: str | None = None,
    dir: str | Path | None = None
) -> str:
    """
    Decode base64 string to a file.

    Parameters:
    - encoding: Base64 encoded string
    - file_path: Target file path (auto-generated if None)
    - dir: Directory to save the file

    Returns:
    Path to the decoded file
    """

def get_mimetype(filename: str) -> str | None:
    """
    Get MIME type for a filename.

    Parameters:
    - filename: Name of the file

    Returns:
    MIME type string or None if unknown
    """

def is_filepath(s: Any) -> bool:
    """
    Check if a string represents a file path.

    Parameters:
    - s: String to check

    Returns:
    True if string appears to be a file path
    """

Usage Examples

Basic File Handling

from gradio_client import Client, file

client = Client("abidlabs/whisper-large-v2")

# Handle local file
audio_file = file("my_recording.wav")
result = client.predict(audio_file, api_name="/predict")

# Handle file from URL
url_file = file("https://example.com/audio.mp3")
result = client.predict(url_file, api_name="/predict")

File Upload with Metadata

from gradio_client import Client, FileData
from pathlib import Path

client = Client("abidlabs/image-classifier")

# Create FileData with metadata
image_data: FileData = {
    "name": "my_image.jpg",
    "data": None,  # Will be populated automatically
    "size": Path("my_image.jpg").stat().st_size,
    "is_file": True,
    "orig_name": "original_name.jpg",
    "mime_type": "image/jpeg",
    "is_stream": False
}

# Use in prediction
result = client.predict(image_data, api_name="/classify")

Batch File Processing

from gradio_client import Client, file
import os

client = Client("abidlabs/document-processor")

# Process multiple files
input_dir = "documents/"
results = []

for filename in os.listdir(input_dir):
    if filename.endswith(('.pdf', '.txt', '.docx')):
        file_path = os.path.join(input_dir, filename)
        processed_file = file(file_path)
        
        result = client.predict(processed_file, api_name="/process")
        results.append({
            'filename': filename,
            'result': result
        })

print(f"Processed {len(results)} files")

File Download and Local Processing

from gradio_client import Client, file
import tempfile
import os

client = Client("abidlabs/image-generator")

# Generate an image
prompt = "a beautiful sunset over mountains"
result = client.predict(prompt, api_name="/generate")

# If result contains a file, it will be automatically downloaded
# to the client's download directory
if isinstance(result, str) and os.path.exists(result):
    print(f"Image saved to: {result}")
    
    # Process the downloaded file
    with open(result, 'rb') as f:
        image_data = f.read()
        print(f"Downloaded image size: {len(image_data)} bytes")

Custom Download Directory

from gradio_client import Client, file
from pathlib import Path

# Set custom download directory
download_dir = Path("./my_downloads")
download_dir.mkdir(exist_ok=True)

client = Client(
    "abidlabs/file-processor",
    download_files=str(download_dir)
)

# Files will be downloaded to the custom directory
input_file = file("input.pdf")
result = client.predict(input_file, api_name="/process")

# Result files are saved in the custom directory
print(f"Output saved in: {download_dir}")

Disable File Downloads

from gradio_client import Client, FileData

# Disable automatic file downloads
client = Client(
    "abidlabs/image-processor",
    download_files=False  # Don't download files locally
)

# Predictions return FileData objects instead of local paths
result = client.predict("input.jpg", api_name="/process")

if isinstance(result, dict) and result.get('is_file'):
    file_data: FileData = result
    print(f"Remote file: {file_data['name']}")
    print(f"Size: {file_data.get('size', 'unknown')} bytes")
    print(f"MIME type: {file_data.get('mime_type', 'unknown')}")

File Type Validation

from gradio_client import Client, file
from gradio_client.utils import is_filepath, get_mimetype

client = Client("abidlabs/audio-processor")

def process_audio_file(file_path: str):
    # Validate file path
    if not is_filepath(file_path):
        raise ValueError("Invalid file path")
    
    # Check MIME type
    mime_type = get_mimetype(file_path)
    if not mime_type or not mime_type.startswith('audio/'):
        raise ValueError("File must be an audio file")
    
    # Process the file
    audio_file = file(file_path)
    return client.predict(audio_file, api_name="/transcribe")

# Use the validation function
try:
    result = process_audio_file("recording.mp3")
    print(f"Transcription: {result}")
except ValueError as e:
    print(f"Error: {e}")

Streaming File Upload

from gradio_client import Client, FileData

client = Client("abidlabs/streaming-processor")

# Create streaming file data
stream_data: FileData = {
    "name": "stream.data",
    "data": None,
    "is_stream": True,
    "mime_type": "application/octet-stream"
}

# Submit streaming job
job = client.submit(stream_data, api_name="/process_stream")

# Monitor progress
for output in job:
    print(f"Stream progress: {output}")

final_result = job.result()
print(f"Stream processing complete: {final_result}")