从函数返回文件和图像 Returning files and images from functions

将图像保存到持久目录并不总是一种方便的访问方式(您可以使用 fal Web UI 提供的文件资源管理器。)或者,在处理图像输入和输出时,您可以使用 fal 的文件和图像类来简化流程。

在无服务器函数上构建“Image”对象会自动将其上传到 fal 的块存储系统,并为您提供一个为期 2 天的签名链接,您可以在其中安全地查看或下载它,以便在需要时拥有它的副本。

py
import fal
from fal.toolkit import Image

MODEL_NAME = "google/ddpm-cat-256"

@fal.function(
    requirements=[
        "diffusers[torch]",
        "transformers",
        "pydantic<2",
    ],
    machine_type="GPU-A100",
)
def generate_image():
    from diffusers import DDPMPipeline

    pipe = DDPMPipeline.from_pretrained(MODEL_NAME, use_safetensors=True)
    pipe = pipe.to("cuda")
    result = pipe(num_inference_steps=25)
    return Image.from_pil(result.images[0])

if __name__ == "__main__":
    cat_image = generate_image()
    print(f"Here is your cat: {cat_image.url}")
还有更多...

在执行更通用的文件 I/O 时,请查看 File 的参考,以及 Image 的其他方法以查看所有支持的格式。

需要 Pydantic!

如果您想使用 Image 类,请不要忘记在您的函数中添加对 pydantic 版本 1.x(版本 2 尚不兼容)的依赖项。

最后更新于 2024 年 6 月 21 日