Huertas97 commited on
Commit
7a37c2a
·
1 Parent(s): f0d7d81

New: app and requirements

Browse files
Files changed (2) hide show
  1. app.py +135 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import torch
4
+ import torchvision
5
+ from torch import nn
6
+ from diffusers import UNet2DModel, DDPMScheduler
7
+ import safetensors
8
+ from huggingface_hub import hf_hub_download
9
+
10
+ ### GPU SETUP
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+
13
+ ## LOAD THE UNET MODEL AND DDPM SCHEDULER FROM HUGGINGFACE HUB
14
+ class ClassConditionedUnet(nn.Module):
15
+ def __init__(self, num_classes=10, class_emb_size=10):
16
+ super().__init__()
17
+
18
+ # The embedding layer will map the class label to a vector of size class_emb_size
19
+ self.class_emb = nn.Embedding(num_classes, class_emb_size)
20
+
21
+ # Self.model is an unconditional UNet with extra input channels
22
+ # to accept the conditioning information (the class embedding)
23
+ self.model = UNet2DModel(
24
+ sample_size=28, # output image resolution. Equal to input resolution
25
+ in_channels=1 + class_emb_size, # Additional input channels for class cond
26
+ out_channels=1, # the number of output channels. Equal to input
27
+ layers_per_block=3, # three residual connections (ResNet) per block
28
+ block_out_channels=(128, 256, 512), # N of output channels for each block. Inverse for upsampling
29
+ down_block_types=(
30
+ "DownBlock2D", # a regular ResNet downsampling block
31
+ "AttnDownBlock2D",
32
+ "AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention
33
+ ),
34
+ up_block_types=(
35
+ "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
36
+ "AttnUpBlock2D",
37
+ "UpBlock2D", # a regular ResNet upsampling block
38
+ ),
39
+ dropout = 0.1, # Dropout prob between Conv1 and Conv2 in a block. From Improved DDPM paper
40
+ )
41
+
42
+ # Forward method takes the class labels as an additional argument
43
+ def forward(self, x, t, class_labels):
44
+ bs, ch, w, h = x.shape # x is shape (bs, 1, 28, 28)
45
+
46
+ # class conditioning embedding to add as additional input channels
47
+ class_cond = self.class_emb(class_labels) # Map to embedding dimension
48
+ class_cond = class_cond.view(bs, class_cond.shape[1], 1, 1).expand(bs, class_cond.shape[1], w, h)
49
+ # class_cond final shape (bs, 4, 28, 28)
50
+
51
+ # Model input is now x and class cond concatenated together along dimension 1
52
+ # We need provide additional information (the class label)
53
+ # to every spatial location (pixel) in the image. Not changing the original
54
+ # pixels of the images, but adding new channels.
55
+ net_input = torch.cat((x, class_cond), 1) # (bs, 5, 28, 28)
56
+
57
+ # Feed this to the UNet alongside the timestep and return the prediction
58
+ # with image output size
59
+ return self.model(net_input, t).sample # (bs, 1, 28, 28)
60
+
61
+ # Define paths to download the model and scheduler
62
+ repo_name = "Huertas97/conditioned-unet-fashion-mnist-non-ema"
63
+
64
+ ### UNET MODEL
65
+ # Download the safetensors model file
66
+ model_file_path = hf_hub_download(repo_id=repo_name, filename="fashion_class_cond_unet_model_best.safetensors")
67
+
68
+ # Load the Class Conditioned UNet model state dictionary
69
+ state_dict = safetensors.torch.load_file(model_file_path)
70
+ model_classcond_native = ClassConditionedUnet()
71
+ model_classcond_native.load_state_dict(state_dict)
72
+ model_classcond_native.to(device)
73
+
74
+ ### DDPM SCHEDULER
75
+ # Download and load the scheduler configuration file
76
+ scheduler_file_path = hf_hub_download(repo_id=repo_name, filename="scheduler_config.json")
77
+
78
+ with open(scheduler_file_path, 'r') as f:
79
+ scheduler_config = json.load(f)
80
+
81
+ noise_scheduler = DDPMScheduler.from_config(scheduler_config)
82
+
83
+
84
+
85
+
86
+ # Define the classes
87
+ class_labels = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
88
+
89
+
90
+ def generate_images(selected_class, num_images, progress=gr.Progress()):
91
+ """
92
+ Generate images using the trained model.
93
+
94
+ Parameters:
95
+ - selected_class: The class label as a string.
96
+ - num_images: Number of images to generate.
97
+
98
+ Returns:
99
+ - A list of generated images.
100
+ """
101
+ # Convert class label to corresponding index
102
+ class_idx = class_labels.index(selected_class)
103
+
104
+ # Prepare random x to start from
105
+ x = torch.randn(num_images, 1, 28, 28).to(device)
106
+ y = torch.tensor([class_idx] * num_images).to(device)
107
+
108
+ for t in progress.tqdm(noise_scheduler.timesteps, desc="Generating image", total=noise_scheduler.config.num_train_timesteps): #
109
+ with torch.no_grad():
110
+ residual = model_classcond_native(x, t, y)
111
+ x = noise_scheduler.step(residual, t, x).prev_sample
112
+
113
+ # Post-process the generated images
114
+ # Clamp the values to [0, 1] and convert to [0, 255] uint8
115
+ # Also move the tensor to CPU and convert to numpy for plotting
116
+ x = (x.clamp(-1, 1) + 1) / 2
117
+ x = (x * 255).type(torch.uint8).cpu()
118
+
119
+ # Convert to list of images
120
+ images = [img.squeeze(0).numpy() for img in x]
121
+ return images
122
+
123
+ # Create the Gradio interface
124
+ demo = gr.Interface(
125
+ fn=generate_images,
126
+ inputs=[
127
+ gr.Dropdown(class_labels, label="Select Class", value="T-shirt/top"),
128
+ gr.Slider(minimum=1, maximum=8, step=1, value=1, label="Number of Images")
129
+ ],
130
+ outputs=gr.Gallery(type="numpy", label="Generated Images"),
131
+ live=False,
132
+ description="Generate images using a class-conditioned UNet model."
133
+ )
134
+
135
+ demo.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch==2.3.1
2
+ transformers
3
+ diffusers==0.29.2
4
+ safetensors==0.4.3
5
+ huggingface_hub==0.23.4
6
+ accelerate==0.32.1
7
+ numpy==1.26.4
8
+ json==2.0.9