Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,29 +4,41 @@ import torch
|
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
def generate_image(prompt, steps=4, seed=42):
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
demo = gr.Interface(
|
| 19 |
fn=generate_image,
|
| 20 |
inputs=[
|
| 21 |
-
gr.Textbox(label="Prompt", placeholder="
|
| 22 |
-
gr.Slider(1, 10, value=4, label="
|
| 23 |
-
gr.Number(value=42, label="
|
| 24 |
],
|
| 25 |
-
outputs=gr.Image(label="
|
| 26 |
-
title="Flux
|
| 27 |
-
description="
|
| 28 |
)
|
| 29 |
|
| 30 |
-
# 修正 __main__ 判断的语法
|
| 31 |
if __name__ == "__main__":
|
| 32 |
-
demo.launch(share=True)
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
def generate_image(prompt, steps=4, seed=42):
|
| 7 |
+
try:
|
| 8 |
+
# 加载模型(仅首次调用时加载,后续复用)
|
| 9 |
+
if not hasattr(generate_image, "pipe"):
|
| 10 |
+
generate_image.pipe = FluxPipeline.from_pretrained(
|
| 11 |
+
"black-forest-labs/FLUX.1-schnell",
|
| 12 |
+
torch_dtype=torch.bfloat16
|
| 13 |
+
)
|
| 14 |
+
generate_image.pipe.enable_model_cpu_offload() # 节省显存
|
| 15 |
+
|
| 16 |
+
pipe = generate_image.pipe
|
| 17 |
+
generator = torch.Generator().manual_seed(seed)
|
| 18 |
+
|
| 19 |
+
# 生成图像
|
| 20 |
+
image = pipe(
|
| 21 |
+
prompt,
|
| 22 |
+
num_inference_steps=steps,
|
| 23 |
+
generator=generator
|
| 24 |
+
).images[0]
|
| 25 |
+
return image
|
| 26 |
+
|
| 27 |
+
except Exception as e:
|
| 28 |
+
# 捕获所有异常并返回错误信息
|
| 29 |
+
return f"生成失败:{str(e)}"
|
| 30 |
|
| 31 |
demo = gr.Interface(
|
| 32 |
fn=generate_image,
|
| 33 |
inputs=[
|
| 34 |
+
gr.Textbox(label="Prompt", placeholder="输入描述(如:a red watermelon)"),
|
| 35 |
+
gr.Slider(1, 10, value=4, label="生成步数(越小越快)"),
|
| 36 |
+
gr.Number(value=42, label="随机种子")
|
| 37 |
],
|
| 38 |
+
outputs=gr.Image(label="生成的图像", type="pil"), # 明确指定图像类型
|
| 39 |
+
title="Flux 图像生成器",
|
| 40 |
+
description="使用 FLUX.1-schnell 模型生成图像(首次使用需等待模型加载)"
|
| 41 |
)
|
| 42 |
|
|
|
|
| 43 |
if __name__ == "__main__":
|
| 44 |
+
demo.launch(share=True)
|