or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdauth-config.mdfile-processing.mdindex.mdrequest-management.mdsync-operations.md

file-processing.mddocs/

0

# File Processing

1

2

File upload to fal.media CDN and in-memory data URL encoding. Supports various file formats with automatic MIME type detection and provides both CDN upload for persistent storage and data URL encoding for immediate use.

3

4

## Capabilities

5

6

### CDN File Upload

7

8

Upload files to fal.media CDN for persistent storage and use in model inference. The CDN provides fast, globally distributed access to uploaded files.

9

10

```python { .api }

11

def upload_file(path: PathLike) -> str:

12

"""

13

Upload a file from the filesystem to fal.media CDN.

14

15

Parameters:

16

- path: Path to the file to upload (str or PathLike)

17

18

Returns:

19

str: URL of the uploaded file on fal.media CDN

20

"""

21

22

async def upload_file_async(path: PathLike) -> str:

23

"""

24

Upload a file from the filesystem to fal.media CDN asynchronously.

25

26

Parameters:

27

- path: Path to the file to upload (str or PathLike)

28

29

Returns:

30

str: URL of the uploaded file on fal.media CDN

31

"""

32

```

33

34

Usage example:

35

```python

36

import fal_client

37

38

# Upload an audio file

39

audio_url = fal_client.upload_file("path/to/audio.wav")

40

41

# Use in model inference

42

response = fal_client.run(

43

"fal-ai/whisper",

44

arguments={"audio_url": audio_url}

45

)

46

print(response["text"])

47

```

48

49

### Image Upload

50

51

Upload PIL Image objects directly to fal.media CDN with format specification.

52

53

```python { .api }

54

def upload_image(image: "Image.Image", format: str = "jpeg") -> str:

55

"""

56

Upload a PIL Image object to fal.media CDN.

57

58

Parameters:

59

- image: PIL Image object to upload

60

- format: Image format for upload ("jpeg", "png", "webp", etc.)

61

62

Returns:

63

str: URL of the uploaded image on fal.media CDN

64

"""

65

66

async def upload_image_async(image: "Image.Image", format: str = "jpeg") -> str:

67

"""

68

Upload a PIL Image object to fal.media CDN asynchronously.

69

70

Parameters:

71

- image: PIL Image object to upload

72

- format: Image format for upload ("jpeg", "png", "webp", etc.)

73

74

Returns:

75

str: URL of the uploaded image on fal.media CDN

76

"""

77

```

78

79

Usage example:

80

```python

81

from PIL import Image

82

import fal_client

83

84

# Load and process an image

85

image = Image.open("input.jpg")

86

image = image.resize((512, 512))

87

88

# Upload to CDN

89

image_url = fal_client.upload_image(image, format="png")

90

91

# Use in model inference

92

response = fal_client.run(

93

"fal-ai/image-processor",

94

arguments={"image_url": image_url}

95

)

96

```

97

98

### Binary Data Upload

99

100

Upload raw binary data to fal.media CDN with explicit content type specification.

101

102

```python { .api }

103

def upload(data: bytes | str, content_type: str) -> str:

104

"""

105

Upload binary data to fal.media CDN.

106

107

Parameters:

108

- data: The data to upload (bytes or string)

109

- content_type: MIME type of the data (e.g., "audio/wav", "image/jpeg")

110

111

Returns:

112

str: URL of the uploaded file on fal.media CDN

113

"""

114

115

async def upload_async(data: bytes | str, content_type: str) -> str:

116

"""

117

Upload binary data to fal.media CDN asynchronously.

118

119

Parameters:

120

- data: The data to upload (bytes or string)

121

- content_type: MIME type of the data (e.g., "audio/wav", "image/jpeg")

122

123

Returns:

124

str: URL of the uploaded file on fal.media CDN

125

"""

126

```

127

128

Usage example:

129

```python

130

import fal_client

131

132

# Upload binary audio data

133

with open("audio.wav", "rb") as f:

134

audio_data = f.read()

135

136

audio_url = fal_client.upload(audio_data, "audio/wav")

137

138

# Use in inference

139

response = fal_client.run(

140

"fal-ai/audio-processor",

141

arguments={"audio_url": audio_url}

142

)

143

```

144

145

### Data URL Encoding

146

147

Encode files and data as base64 data URLs for immediate use without CDN upload. This is ideal for small files and latency-sensitive applications.

148

149

```python { .api }

150

def encode_file(path: PathLike) -> str:

151

"""

152

Encode a file from the local filesystem to a data URL with inferred content type.

153

154

Parameters:

155

- path: Path to the file to encode (str or PathLike)

156

157

Returns:

158

str: Base64-encoded data URL (data:mime/type;base64,...)

159

"""

160

161

def encode_image(image: "Image.Image", format: str = "jpeg") -> str:

162

"""

163

Encode a PIL Image object to a data URL with the specified format.

164

165

Parameters:

166

- image: PIL Image object to encode

167

- format: Image format for encoding ("jpeg", "png", "webp", etc.)

168

169

Returns:

170

str: Base64-encoded data URL (data:image/format;base64,...)

171

"""

172

173

def encode(data: str | bytes, content_type: str) -> str:

174

"""

175

Encode raw data to a base64 data URL with specified content type.

176

177

Parameters:

178

- data: The data to encode (string or bytes)

179

- content_type: MIME type for the data URL

180

181

Returns:

182

str: Base64-encoded data URL (data:content_type;base64,...)

183

"""

184

```

185

186

Usage examples:

187

```python

188

import fal_client

189

from PIL import Image

190

191

# Encode a file directly

192

audio_data_url = fal_client.encode_file("path/to/audio.wav")

193

194

# Use immediately in inference (no CDN upload)

195

response = fal_client.run(

196

"fal-ai/whisper",

197

arguments={"audio_url": audio_data_url}

198

)

199

200

# Encode an image

201

image = Image.open("image.jpg")

202

image_data_url = fal_client.encode_image(image, format="png")

203

204

# Use in inference

205

response = fal_client.run(

206

"fal-ai/image-processor",

207

arguments={"image_url": image_data_url}

208

)

209

210

# Encode raw data

211

text_data = "Hello, world!"

212

text_data_url = fal_client.encode(text_data, "text/plain")

213

```

214

215

### File Processing Patterns

216

217

### Large File Upload vs. Data URL Encoding

218

219

Choose the appropriate method based on file size and use case:

220

221

```python

222

import os

223

import fal_client

224

225

def process_file(file_path, model_id, arguments):

226

"""Smart file processing based on file size."""

227

228

file_size = os.path.getsize(file_path)

229

230

# Use data URL for small files (< 1MB) for lower latency

231

if file_size < 1024 * 1024: # 1MB

232

file_url = fal_client.encode_file(file_path)

233

print(f"Using data URL for small file ({file_size} bytes)")

234

else:

235

# Use CDN upload for larger files

236

file_url = fal_client.upload_file(file_path)

237

print(f"Uploaded large file ({file_size} bytes) to CDN")

238

239

# Use in inference

240

arguments["file_url"] = file_url

241

return fal_client.run(model_id, arguments=arguments)

242

```

243

244

### Batch File Processing

245

246

Process multiple files efficiently with concurrent uploads:

247

248

```python

249

import asyncio

250

import fal_client

251

252

async def process_batch_files(file_paths, model_id):

253

"""Process multiple files concurrently."""

254

255

# Upload all files concurrently

256

upload_tasks = [

257

fal_client.upload_file_async(path)

258

for path in file_paths

259

]

260

file_urls = await asyncio.gather(*upload_tasks)

261

262

# Process all uploaded files concurrently

263

inference_tasks = [

264

fal_client.run_async(model_id, arguments={"file_url": url})

265

for url in file_urls

266

]

267

results = await asyncio.gather(*inference_tasks)

268

269

return list(zip(file_paths, results))

270

271

# Usage

272

file_paths = ["audio1.wav", "audio2.wav", "audio3.wav"]

273

results = asyncio.run(process_batch_files(file_paths, "fal-ai/whisper"))

274

275

for path, result in results:

276

print(f"{path}: {result['text']}")

277

```

278

279

### Image Preprocessing and Upload

280

281

Preprocess images before uploading for optimal model performance:

282

283

```python

284

from PIL import Image

285

import fal_client

286

287

def preprocess_and_upload_image(image_path, target_size=(512, 512)):

288

"""Preprocess image and upload to CDN."""

289

290

# Load and preprocess image

291

image = Image.open(image_path)

292

293

# Convert to RGB if needed

294

if image.mode != "RGB":

295

image = image.convert("RGB")

296

297

# Resize while maintaining aspect ratio

298

image.thumbnail(target_size, Image.Resampling.LANCZOS)

299

300

# Create new image with target size and paste centered

301

result = Image.new("RGB", target_size, (255, 255, 255))

302

offset = ((target_size[0] - image.width) // 2,

303

(target_size[1] - image.height) // 2)

304

result.paste(image, offset)

305

306

# Upload processed image

307

image_url = fal_client.upload_image(result, format="jpeg")

308

309

return image_url

310

311

# Usage

312

processed_image_url = preprocess_and_upload_image("input.jpg")

313

response = fal_client.run(

314

"fal-ai/image-model",

315

arguments={"image_url": processed_image_url}

316

)

317

```

318

319

### Error Handling

320

321

Handle common file processing errors:

322

323

```python

324

import fal_client

325

import os

326

from PIL import Image

327

328

def safe_file_upload(file_path):

329

"""Upload file with comprehensive error handling."""

330

331

try:

332

# Check if file exists

333

if not os.path.exists(file_path):

334

raise FileNotFoundError(f"File not found: {file_path}")

335

336

# Check file size (CDN has limits)

337

file_size = os.path.getsize(file_path)

338

max_size = 100 * 1024 * 1024 # 100MB

339

if file_size > max_size:

340

raise ValueError(f"File too large: {file_size} bytes (max: {max_size})")

341

342

# Upload file

343

return fal_client.upload_file(file_path)

344

345

except FileNotFoundError as e:

346

print(f"File error: {e}")

347

return None

348

except ValueError as e:

349

print(f"Size error: {e}")

350

return None

351

except Exception as e:

352

print(f"Upload error: {e}")

353

return None

354

355

def safe_image_upload(image_path):

356

"""Upload image with format validation."""

357

358

try:

359

# Validate image format

360

image = Image.open(image_path)

361

if image.format not in ["JPEG", "PNG", "WEBP", "GIF"]:

362

raise ValueError(f"Unsupported image format: {image.format}")

363

364

return fal_client.upload_image(image)

365

366

except Exception as e:

367

print(f"Image upload error: {e}")

368

return None

369

```