0
# File Handling
1
2
Efficient handling of file inputs and outputs with FileOutput objects that provide streaming, URL access, and metadata management.
3
4
## Capabilities
5
6
### File Management
7
8
Upload, retrieve, and manage files on the Replicate platform.
9
10
```python { .api }
11
class Files:
12
def create(
13
self,
14
file: BinaryIO,
15
*,
16
filename: Optional[str] = None,
17
content_type: Optional[str] = None,
18
**params
19
) -> File:
20
"""
21
Upload a file to Replicate.
22
23
Parameters:
24
- file: File object or binary data to upload
25
- filename: Name for the uploaded file
26
- content_type: MIME type of the file
27
28
Returns:
29
File object with metadata and URLs
30
"""
31
32
def get(self, id: str) -> File:
33
"""
34
Get a file by ID.
35
36
Parameters:
37
- id: File ID
38
39
Returns:
40
File object with metadata and URLs
41
"""
42
43
def list(self, **params) -> Page[File]:
44
"""
45
List uploaded files.
46
47
Returns:
48
Paginated list of File objects
49
"""
50
51
def delete(self, id: str) -> None:
52
"""
53
Delete a file.
54
55
Parameters:
56
- id: File ID to delete
57
"""
58
```
59
60
### File Objects
61
62
Files represent uploaded files with metadata, checksums, and access URLs.
63
64
```python { .api }
65
class File:
66
id: str
67
"""The ID of the file."""
68
69
name: str
70
"""The name of the file."""
71
72
content_type: str
73
"""The content type of the file."""
74
75
size: int
76
"""The size of the file in bytes."""
77
78
etag: str
79
"""The ETag of the file."""
80
81
checksums: Dict[str, str]
82
"""The checksums of the file."""
83
84
metadata: Dict[str, Any]
85
"""The metadata of the file."""
86
87
created_at: str
88
"""The time the file was created."""
89
90
expires_at: Optional[str]
91
"""The time the file will expire."""
92
93
urls: Dict[str, str]
94
"""The URLs of the file (get, delete)."""
95
```
96
97
### FileOutput Objects
98
99
FileOutput objects provide efficient access to model output files with streaming and URL capabilities.
100
101
```python { .api }
102
class FileOutput:
103
def read(self) -> bytes:
104
"""
105
Read the entire file content into memory.
106
107
Returns:
108
Complete file content as bytes
109
"""
110
111
@property
112
def url(self) -> str:
113
"""
114
Get the URL of the file.
115
116
Returns:
117
Direct URL to access the file
118
"""
119
120
def __iter__(self) -> Iterator[bytes]:
121
"""
122
Iterate over file content in bytes.
123
124
Returns:
125
Iterator yielding file content chunks
126
"""
127
128
async def aread(self) -> bytes:
129
"""
130
Read the entire file content into memory asynchronously.
131
132
Returns:
133
Complete file content as bytes
134
"""
135
136
async def __aiter__(self) -> AsyncIterator[bytes]:
137
"""
138
Asynchronously iterate over file content.
139
140
Returns:
141
AsyncIterator yielding file content chunks
142
"""
143
```
144
145
### File Encoding Strategies
146
147
Control how files are processed and transmitted.
148
149
```python { .api }
150
FileEncodingStrategy = Literal["base64", "url"]
151
```
152
153
### Usage Examples
154
155
#### File Upload
156
157
```python
158
import replicate
159
160
# Upload a local file
161
with open("input.jpg", "rb") as f:
162
file = replicate.files.create(f, filename="input.jpg")
163
164
print(f"File ID: {file.id}")
165
print(f"File URL: {file.urls['get']}")
166
167
# Use uploaded file in model
168
output = replicate.run(
169
"andreasjansson/blip-2",
170
input={"image": file.urls['get']}
171
)
172
```
173
174
#### Direct File Input
175
176
```python
177
import replicate
178
179
# Pass file directly to model
180
with open("mystery.jpg", "rb") as f:
181
output = replicate.run(
182
"andreasjansson/blip-2",
183
input={"image": f}
184
)
185
186
print(output) # "an astronaut riding a horse"
187
```
188
189
#### FileOutput Handling
190
191
```python
192
import replicate
193
194
# Run model that produces file outputs
195
outputs = replicate.run(
196
"black-forest-labs/flux-schnell",
197
input={"prompt": "astronaut riding a rocket"}
198
)
199
200
# Handle single file output
201
if hasattr(outputs, 'read'):
202
with open("output.webp", "wb") as f:
203
f.write(outputs.read())
204
205
# Handle multiple file outputs
206
if hasattr(outputs, '__iter__'):
207
for index, output in enumerate(outputs):
208
with open(f"output_{index}.webp", "wb") as f:
209
f.write(output.read())
210
```
211
212
#### Streaming File Content
213
214
```python
215
import replicate
216
217
# Get file output from prediction
218
prediction = replicate.predictions.create(
219
model="stability-ai/stable-diffusion-3",
220
input={"prompt": "beautiful landscape"}
221
)
222
prediction.wait()
223
224
# Stream file content efficiently
225
output = prediction.output
226
with open("landscape.png", "wb") as f:
227
for chunk in output:
228
f.write(chunk)
229
230
# Or access URL directly
231
print(f"Direct URL: {output.url}")
232
```
233
234
#### File Metadata Access
235
236
```python
237
import replicate
238
239
# Upload and examine file metadata
240
with open("document.pdf", "rb") as f:
241
file = replicate.files.create(f, filename="document.pdf")
242
243
print(f"File ID: {file.id}")
244
print(f"Size: {file.size} bytes")
245
print(f"Content Type: {file.content_type}")
246
print(f"Created: {file.created_at}")
247
print(f"Checksums: {file.checksums}")
248
print(f"Expires: {file.expires_at}")
249
250
# List all uploaded files
251
files = replicate.files.list()
252
for file in files.results:
253
print(f"{file.name} ({file.size} bytes)")
254
```
255
256
#### File Cleanup
257
258
```python
259
import replicate
260
261
# Upload temporary file
262
with open("temp_input.jpg", "rb") as f:
263
file = replicate.files.create(f)
264
265
# Use file in model
266
output = replicate.run("some-model", input={"image": file.urls['get']})
267
268
# Clean up file
269
replicate.files.delete(file.id)
270
```
271
272
#### Legacy URL Handling
273
274
```python
275
import replicate
276
277
# Disable FileOutput for legacy compatibility
278
output = replicate.run(
279
"black-forest-labs/flux-schnell",
280
input={"prompt": "astronaut"},
281
use_file_output=False
282
)
283
284
# Output will be URL strings instead of FileOutput objects
285
print(type(output)) # <class 'str'>
286
print(output) # https://replicate.delivery/...
287
```
288
289
#### Iterating Over File Outputs
290
291
```python
292
import replicate
293
294
# Model that produces multiple outputs
295
outputs = replicate.run(
296
"pixray/text2image",
297
input={"prompts": "sunset over mountains"}
298
)
299
300
# Iterate and save each output
301
for index, output in enumerate(outputs):
302
filename = f"output_{index}.png"
303
304
# Method 1: Direct read
305
with open(filename, "wb") as f:
306
f.write(output.read())
307
308
# Method 2: Streaming (more memory efficient)
309
with open(f"stream_{index}.png", "wb") as f:
310
for chunk in output:
311
f.write(chunk)
312
313
print(f"Saved {filename} ({output.size} bytes)")
314
```
315
316
#### File Validation
317
318
```python
319
import replicate
320
import hashlib
321
322
# Upload file with validation
323
with open("input.jpg", "rb") as f:
324
content = f.read()
325
expected_md5 = hashlib.md5(content).hexdigest()
326
327
f.seek(0) # Reset file pointer
328
file = replicate.files.create(f, filename="input.jpg")
329
330
# Verify checksum
331
if 'md5' in file.checksums:
332
if file.checksums['md5'] == expected_md5:
333
print("File uploaded successfully and verified")
334
else:
335
print("Checksum mismatch!")
336
```