Handle model output files with FileOutput
mainWhen a model outputs files, replicate.run() returns FileOutput objects. These are file-like objects that allow you to read data directly into memory or stream it in chunks.
Key features:
.read(): Reads the entire file into memory (synchronous)..aread(): Reads the entire file into memory (asynchronous).- Iterator Protocol: Supports
for chunk in output:to stream data in chunks, which is ideal for large files. .url: Provides the underlying data source URL (though using the object's methods is recommended).
To opt out of this behavior and receive raw data instead, pass use_file_output=False to replicate.run().
import replicate
from PIL import Image
output = replicate.run(
"stability-ai/stable-diffusion:27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478",
input={"prompt": "wavy colorful abstract patterns, oceans"}
)
# Read binary data
with open("my_output.png", "wb") as file:
file.write(output[0].read())
# Use as an iterator (e.g., with PIL)
background = Image.open(output[0])