or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

file-handling.mddocs/

0

# File Handling

1

2

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

3

4

## Capabilities

5

6

### File Processing Functions

7

8

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

9

10

```python { .api }

11

def file(filepath_or_url: str | Path) -> Any:

12

"""

13

Process a file path or URL for use with Gradio predictions.

14

15

Parameters:

16

- filepath_or_url: Local file path or URL to a file

17

18

Returns:

19

Processed file object suitable for Gradio API calls

20

21

Raises:

22

- FileNotFoundError: If local file path does not exist

23

- ValueError: If URL is invalid or inaccessible

24

"""

25

26

def handle_file(filepath_or_url: str | Path) -> Any:

27

"""

28

Handle and process file objects for Gradio compatibility.

29

30

Parameters:

31

- filepath_or_url: File path or URL to process

32

33

Returns:

34

Processed file object with proper encoding and metadata

35

36

Raises:

37

- IOError: If file cannot be read or processed

38

"""

39

```

40

41

### File Data Structure

42

43

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

44

45

```python { .api }

46

class FileData(TypedDict):

47

name: str | None # Original filename

48

data: str | None # Base64 encoded file data

49

size: int | None # File size in bytes (optional)

50

is_file: bool # Whether this represents a file (optional)

51

orig_name: str # Original filename before processing (optional)

52

mime_type: str # MIME type of the file (optional)

53

is_stream: bool # Whether this is a streaming file (optional)

54

```

55

56

### File Utility Functions

57

58

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

59

60

```python { .api }

61

def encode_file_to_base64(f: str | Path) -> str:

62

"""

63

Encode a file to base64 string.

64

65

Parameters:

66

- f: File path to encode

67

68

Returns:

69

Base64 encoded string representation of the file

70

"""

71

72

def encode_url_to_base64(url: str) -> str:

73

"""

74

Download and encode a URL to base64.

75

76

Parameters:

77

- url: URL to download and encode

78

79

Returns:

80

Base64 encoded string of the downloaded content

81

"""

82

83

def decode_base64_to_file(

84

encoding: str,

85

file_path: str | None = None,

86

dir: str | Path | None = None

87

) -> str:

88

"""

89

Decode base64 string to a file.

90

91

Parameters:

92

- encoding: Base64 encoded string

93

- file_path: Target file path (auto-generated if None)

94

- dir: Directory to save the file

95

96

Returns:

97

Path to the decoded file

98

"""

99

100

def get_mimetype(filename: str) -> str | None:

101

"""

102

Get MIME type for a filename.

103

104

Parameters:

105

- filename: Name of the file

106

107

Returns:

108

MIME type string or None if unknown

109

"""

110

111

def is_filepath(s: Any) -> bool:

112

"""

113

Check if a string represents a file path.

114

115

Parameters:

116

- s: String to check

117

118

Returns:

119

True if string appears to be a file path

120

"""

121

```

122

123

## Usage Examples

124

125

### Basic File Handling

126

127

```python

128

from gradio_client import Client, file

129

130

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

131

132

# Handle local file

133

audio_file = file("my_recording.wav")

134

result = client.predict(audio_file, api_name="/predict")

135

136

# Handle file from URL

137

url_file = file("https://example.com/audio.mp3")

138

result = client.predict(url_file, api_name="/predict")

139

```

140

141

### File Upload with Metadata

142

143

```python

144

from gradio_client import Client, FileData

145

from pathlib import Path

146

147

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

148

149

# Create FileData with metadata

150

image_data: FileData = {

151

"name": "my_image.jpg",

152

"data": None, # Will be populated automatically

153

"size": Path("my_image.jpg").stat().st_size,

154

"is_file": True,

155

"orig_name": "original_name.jpg",

156

"mime_type": "image/jpeg",

157

"is_stream": False

158

}

159

160

# Use in prediction

161

result = client.predict(image_data, api_name="/classify")

162

```

163

164

### Batch File Processing

165

166

```python

167

from gradio_client import Client, file

168

import os

169

170

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

171

172

# Process multiple files

173

input_dir = "documents/"

174

results = []

175

176

for filename in os.listdir(input_dir):

177

if filename.endswith(('.pdf', '.txt', '.docx')):

178

file_path = os.path.join(input_dir, filename)

179

processed_file = file(file_path)

180

181

result = client.predict(processed_file, api_name="/process")

182

results.append({

183

'filename': filename,

184

'result': result

185

})

186

187

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

188

```

189

190

### File Download and Local Processing

191

192

```python

193

from gradio_client import Client, file

194

import tempfile

195

import os

196

197

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

198

199

# Generate an image

200

prompt = "a beautiful sunset over mountains"

201

result = client.predict(prompt, api_name="/generate")

202

203

# If result contains a file, it will be automatically downloaded

204

# to the client's download directory

205

if isinstance(result, str) and os.path.exists(result):

206

print(f"Image saved to: {result}")

207

208

# Process the downloaded file

209

with open(result, 'rb') as f:

210

image_data = f.read()

211

print(f"Downloaded image size: {len(image_data)} bytes")

212

```

213

214

### Custom Download Directory

215

216

```python

217

from gradio_client import Client, file

218

from pathlib import Path

219

220

# Set custom download directory

221

download_dir = Path("./my_downloads")

222

download_dir.mkdir(exist_ok=True)

223

224

client = Client(

225

"abidlabs/file-processor",

226

download_files=str(download_dir)

227

)

228

229

# Files will be downloaded to the custom directory

230

input_file = file("input.pdf")

231

result = client.predict(input_file, api_name="/process")

232

233

# Result files are saved in the custom directory

234

print(f"Output saved in: {download_dir}")

235

```

236

237

### Disable File Downloads

238

239

```python

240

from gradio_client import Client, FileData

241

242

# Disable automatic file downloads

243

client = Client(

244

"abidlabs/image-processor",

245

download_files=False # Don't download files locally

246

)

247

248

# Predictions return FileData objects instead of local paths

249

result = client.predict("input.jpg", api_name="/process")

250

251

if isinstance(result, dict) and result.get('is_file'):

252

file_data: FileData = result

253

print(f"Remote file: {file_data['name']}")

254

print(f"Size: {file_data.get('size', 'unknown')} bytes")

255

print(f"MIME type: {file_data.get('mime_type', 'unknown')}")

256

```

257

258

### File Type Validation

259

260

```python

261

from gradio_client import Client, file

262

from gradio_client.utils import is_filepath, get_mimetype

263

264

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

265

266

def process_audio_file(file_path: str):

267

# Validate file path

268

if not is_filepath(file_path):

269

raise ValueError("Invalid file path")

270

271

# Check MIME type

272

mime_type = get_mimetype(file_path)

273

if not mime_type or not mime_type.startswith('audio/'):

274

raise ValueError("File must be an audio file")

275

276

# Process the file

277

audio_file = file(file_path)

278

return client.predict(audio_file, api_name="/transcribe")

279

280

# Use the validation function

281

try:

282

result = process_audio_file("recording.mp3")

283

print(f"Transcription: {result}")

284

except ValueError as e:

285

print(f"Error: {e}")

286

```

287

288

### Streaming File Upload

289

290

```python

291

from gradio_client import Client, FileData

292

293

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

294

295

# Create streaming file data

296

stream_data: FileData = {

297

"name": "stream.data",

298

"data": None,

299

"is_stream": True,

300

"mime_type": "application/octet-stream"

301

}

302

303

# Submit streaming job

304

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

305

306

# Monitor progress

307

for output in job:

308

print(f"Stream progress: {output}")

309

310

final_result = job.result()

311

print(f"Stream processing complete: {final_result}")

312

```