Ron1006's picture
modify
43cda70
Raw History Blame Contribute Delete
2.02 kB
# -*- coding: utf-8 -*-
import gradio as gr
from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image
import numpy as np
from huggingface_hub import login
import os
import torch
from transformers import utils
# 从环境变量中获取访问令牌
hf_token = os.getenv("hf_token")
# 使用令牌进行登录(如果不用Hugging Face的模型,可以跳过这一步)
if hf_token:
login(token=hf_token)
else:
print("Hugging Face token not found. Please set the 'hf_token' environment variable.")
# 检查是否有GPU可用,并选择相应的设备和数据类型
if torch.cuda.is_available():
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
)
pipe.to("cuda")
print("Using CUDA")
else:
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", torch_dtype=torch.float32
)
pipe.to("cpu")
print("CUDA not available, using CPU")
# 定义 Gradio 接口中调用的函数
def image_to_image(input_image, prompt):
# 如果输入图像是 numpy.ndarray,则将其转化为 PIL 图像
if isinstance(input_image, np.ndarray):
input_image = Image.fromarray(input_image)
# 将用户上传的输入图像转化为 RGB 格式
input_image = input_image.convert("RGB")
try:
# 使用预训练模型生成新图像
generated_image = pipe(
prompt=prompt, image=input_image, strength=0.75, guidance_scale=7.5
).images[0]
return generated_image # 返回生成的图像
except Exception as e:
print(f"Error during image generation: {e}")
return None
# 创建 Gradio 接口
demo = gr.Interface(
fn=image_to_image,
inputs=["image", "text"], # 接收一个图像和一个文本作为输入
outputs="image" # 输出图像
)
if __name__ == "__main__":
demo.launch(share=False) # 如果需要公开链接,可以设置 share=True