|
import gradio as gr |
|
import inspect |
|
import warnings |
|
import numpy as np |
|
from typing import List, Optional, Union |
|
import requests |
|
from io import BytesIO |
|
from PIL import Image |
|
import torch |
|
from torch import autocast |
|
from tqdm.auto import tqdm |
|
from diffusers import StableDiffusionImg2ImgPipeline |
|
|
|
access_token = "TOKEN" |
|
|
|
|
|
|
|
device = "cuda" |
|
pipe = StableDiffusionImg2ImgPipeline.from_pretrained( |
|
"CompVis/stable-diffusion-v1-4", |
|
revision="fp16", |
|
torch_dtype=torch.float16, |
|
use_auth_token=access_token |
|
).to(device) |
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate(img, strength, seed, prompt): |
|
|
|
seed = int(seed) |
|
|
|
img1 = np.asarray(img) |
|
img2 = Image.fromarray(img1) |
|
|
|
|
|
if not isinstance(img2, Image.Image): |
|
raise ValueError("Invalid input image") |
|
|
|
|
|
init_image = img2.resize((768, 512)) |
|
|
|
|
|
images = [] |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
with autocast(device): |
|
|
|
for i in range(2): |
|
|
|
generator = torch.Generator(device=device).manual_seed(seed*i) |
|
|
|
|
|
output_image = pipe(prompt=prompt, init_image=init_image, strength=strength, guidance_scale=7.5, generator=generator, batch_size=128).images[0] |
|
|
|
|
|
if not isinstance(output_image, Image.Image): |
|
raise ValueError("Invalid output image") |
|
|
|
images.append(output_image) |
|
|
|
return [images[0], images[1]] |
|
|
|
|
|
gr.Interface( |
|
|
|
generate, |
|
title = 'Image to Image using Diffusers', |
|
inputs=[ |
|
gr.Image(elem_id = "input-image"), |
|
gr.Slider(0, 1, value=0.05, label ="Strength (keep close to 0 for minimal changes)"), |
|
gr.Slider(50, 700, value=75, label ="Seed"), |
|
gr.Textbox(label="Prompt (leave blank if you want minimal changes)"), |
|
], |
|
outputs = [ |
|
gr.Image(elem_id="output-image"), |
|
gr.Image(elem_id="output-image"), |
|
|
|
], css = "#output-image, #input-image, #image-preview {border-radius: 40px !important; background-color : gray !important;} " |
|
).launch(share=True, debug=True) |
|
|