|
|
import gradio as gr |
|
|
import torch |
|
|
import numpy as np |
|
|
from PIL import Image |
|
|
import random |
|
|
from huggingface_hub import hf_hub_download |
|
|
from generator import Generator |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
wts = ['trial_0_G (1).pth' , 'trial_0_G (2).pth' , 'trial_0_G (3).pth' , 'trial_0_G (4).pth' , 'trial_0_G (5).pth' , 'trial_0_G.pth' ] |
|
|
random_wt = random.choice(wts) |
|
|
|
|
|
|
|
|
weights_path = hf_hub_download( |
|
|
repo_id="keysun89/image_generation", |
|
|
filename= random_wt |
|
|
) |
|
|
|
|
|
|
|
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
|
|
|
|
|
|
|
z_dim = 512 |
|
|
w_dim = 512 |
|
|
img_resolution = 256 |
|
|
img_channels = 3 |
|
|
|
|
|
model = Generator( |
|
|
z_dim=z_dim, |
|
|
w_dim=w_dim, |
|
|
img_resolution=img_resolution, |
|
|
img_channels=img_channels |
|
|
) |
|
|
|
|
|
|
|
|
model.load_state_dict(torch.load(weights_path, map_location=device)) |
|
|
model.to(device) |
|
|
model.eval() |
|
|
|
|
|
def generate(): |
|
|
"""Generate a random image""" |
|
|
with torch.no_grad(): |
|
|
|
|
|
z = torch.randn(1, z_dim, device=device) |
|
|
|
|
|
|
|
|
img = model(z, use_truncation=True, truncation_psi=0.7) |
|
|
|
|
|
|
|
|
img = img.squeeze(0).cpu().numpy() |
|
|
img = np.transpose(img, (1, 2, 0)) |
|
|
img = (img * 127.5 + 128).clip(0, 255).astype(np.uint8) |
|
|
|
|
|
return Image.fromarray(img) |
|
|
|
|
|
|
|
|
demo = gr.Interface( |
|
|
fn=generate, |
|
|
inputs=None, |
|
|
outputs=gr.Image(type="pil"), |
|
|
title="StyleGAN2 Image Generator", |
|
|
description="Click 'Submit' or refresh the page to generate a new random image", |
|
|
allow_flagging="never" |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |