Spaces:
Runtime error
Runtime error
Commit ·
7f5ec51
1
Parent(s): 2fc47c9
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import requests
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from torchvision.utils import save_image
|
| 7 |
+
from torchvision.transforms.functional import resize
|
| 8 |
+
from argparse import Namespace
|
| 9 |
+
|
| 10 |
+
# Load pre-trained StyleGAN2 model from Hugging Face
|
| 11 |
+
model = torch.hub.load('huggingface/pytorch-pretrained-StyleGAN2', 'StyleGAN2')
|
| 12 |
+
|
| 13 |
+
# Set device to GPU if available
|
| 14 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 15 |
+
model.to(device)
|
| 16 |
+
|
| 17 |
+
# Set seed for reproducibility
|
| 18 |
+
torch.manual_seed(0)
|
| 19 |
+
|
| 20 |
+
# Define function to generate image from text prompt
|
| 21 |
+
def generate_image(prompt):
|
| 22 |
+
# Convert text prompt to embeddings using StyleGAN2's tokenizer
|
| 23 |
+
embeddings = model.gen.encode(prompt)
|
| 24 |
+
|
| 25 |
+
# Generate image from embeddings
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
generated_image = model.gen.decode(embeddings, input_is_latent=True)
|
| 28 |
+
|
| 29 |
+
# Resize and save image
|
| 30 |
+
generated_image = generated_image.clamp(0, 1)
|
| 31 |
+
generated_image = resize(generated_image, (256, 256), interpolation=Image.LANCZOS)
|
| 32 |
+
image_tensor = transforms.ToTensor()(generated_image)
|
| 33 |
+
image_tensor = image_tensor.unsqueeze(0)
|
| 34 |
+
save_image(image_tensor, 'output.png')
|
| 35 |
+
|
| 36 |
+
# Example usage
|
| 37 |
+
generate_image("A peaceful countryside with a lake and mountains in the distance")
|
| 38 |
+
|
| 39 |
+
# Load generated image and display
|
| 40 |
+
image = Image.open('output.png')
|
| 41 |
+
image.show()
|