RagedKrish commited on
Commit
0f8d59f
Β·
1 Parent(s): 7370d26

Adding Files

Browse files
Files changed (3) hide show
  1. app.py +592 -0
  2. final_ema_network.h5 +3 -0
  3. requirements.txt +17 -0
app.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ from tensorflow import keras
5
+ from tensorflow.keras import layers
6
+ import matplotlib.pyplot as plt
7
+ from PIL import Image
8
+ import io
9
+ import time
10
+ import math
11
+
12
+ # Configuration (same as training)
13
+ img_size = 32
14
+ img_channels = 3
15
+ clip_min = -1.0
16
+ clip_max = 1.0
17
+ total_timesteps = 1000
18
+ first_conv_channels = 64
19
+ channel_multiplier = [1, 2, 4, 8]
20
+ widths = [first_conv_channels * mult for mult in channel_multiplier]
21
+ has_attention = [False, False, True, True]
22
+ num_res_blocks = 2
23
+ norm_groups = 8
24
+ num_classes = 4
25
+
26
+ class_names = ["Airplane", "Automobile", "Bird", "Cat"]
27
+
28
+ # All the necessary classes and functions from the training script
29
+ class GaussianDiffusion:
30
+ def __init__(
31
+ self,
32
+ beta_start=1e-4,
33
+ beta_end=0.02,
34
+ timesteps=1000,
35
+ clip_min=-1.0,
36
+ clip_max=1.0,
37
+ ):
38
+ self.beta_start = beta_start
39
+ self.beta_end = beta_end
40
+ self.timesteps = timesteps
41
+ self.clip_min = clip_min
42
+ self.clip_max = clip_max
43
+
44
+ # Define the linear variance schedule
45
+ self.betas = betas = np.linspace(
46
+ beta_start, beta_end, timesteps, dtype=np.float64
47
+ )
48
+ self.num_timesteps = int(timesteps)
49
+
50
+ alphas = 1.0 - betas
51
+ alphas_cumprod = np.cumprod(alphas, axis=0)
52
+ alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
53
+
54
+ self.betas = tf.constant(betas, dtype=tf.float32)
55
+ self.alphas_cumprod = tf.constant(alphas_cumprod, dtype=tf.float32)
56
+ self.alphas_cumprod_prev = tf.constant(alphas_cumprod_prev, dtype=tf.float32)
57
+
58
+ self.sqrt_alphas_cumprod = tf.constant(
59
+ np.sqrt(alphas_cumprod), dtype=tf.float32
60
+ )
61
+ self.sqrt_one_minus_alphas_cumprod = tf.constant(
62
+ np.sqrt(1.0 - alphas_cumprod), dtype=tf.float32
63
+ )
64
+ self.log_one_minus_alphas_cumprod = tf.constant(
65
+ np.log(1.0 - alphas_cumprod), dtype=tf.float32
66
+ )
67
+ self.sqrt_recip_alphas_cumprod = tf.constant(
68
+ np.sqrt(1.0 / alphas_cumprod), dtype=tf.float32
69
+ )
70
+ self.sqrt_recipm1_alphas_cumprod = tf.constant(
71
+ np.sqrt(1.0 / alphas_cumprod - 1), dtype=tf.float32
72
+ )
73
+
74
+ posterior_variance = (
75
+ betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
76
+ )
77
+ self.posterior_variance = tf.constant(posterior_variance, dtype=tf.float32)
78
+ self.posterior_log_variance_clipped = tf.constant(
79
+ np.log(np.maximum(posterior_variance, 1e-20)), dtype=tf.float32
80
+ )
81
+ self.posterior_mean_coef1 = tf.constant(
82
+ betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod),
83
+ dtype=tf.float32,
84
+ )
85
+ self.posterior_mean_coef2 = tf.constant(
86
+ (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod),
87
+ dtype=tf.float32,
88
+ )
89
+
90
+ def _extract(self, a, t, x_shape):
91
+ batch_size = x_shape[0]
92
+ out = tf.gather(a, t)
93
+ return tf.reshape(out, [batch_size, 1, 1, 1])
94
+
95
+ def predict_start_from_noise(self, x_t, t, noise):
96
+ x_t_shape = tf.shape(x_t)
97
+ return (
98
+ self._extract(self.sqrt_recip_alphas_cumprod, t, x_t_shape) * x_t
99
+ - self._extract(self.sqrt_recipm1_alphas_cumprod, t, x_t_shape) * noise
100
+ )
101
+
102
+ def q_posterior(self, x_start, x_t, t):
103
+ x_t_shape = tf.shape(x_t)
104
+ posterior_mean = (
105
+ self._extract(self.posterior_mean_coef1, t, x_t_shape) * x_start
106
+ + self._extract(self.posterior_mean_coef2, t, x_t_shape) * x_t
107
+ )
108
+ posterior_variance = self._extract(self.posterior_variance, t, x_t_shape)
109
+ posterior_log_variance_clipped = self._extract(
110
+ self.posterior_log_variance_clipped, t, x_t_shape
111
+ )
112
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
113
+
114
+ def p_mean_variance(self, pred_noise, x, t, clip_denoised=True):
115
+ x_recon = self.predict_start_from_noise(x, t=t, noise=pred_noise)
116
+ if clip_denoised:
117
+ x_recon = tf.clip_by_value(x_recon, self.clip_min, self.clip_max)
118
+
119
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(
120
+ x_start=x_recon, x_t=x, t=t
121
+ )
122
+ return model_mean, posterior_variance, posterior_log_variance
123
+
124
+ def p_sample(self, pred_noise, x, t, clip_denoised=True):
125
+ model_mean, _, model_log_variance = self.p_mean_variance(
126
+ pred_noise, x=x, t=t, clip_denoised=clip_denoised
127
+ )
128
+ noise = tf.random.normal(shape=x.shape, dtype=x.dtype)
129
+ nonzero_mask = tf.reshape(
130
+ 1 - tf.cast(tf.equal(t, 0), tf.float32), [tf.shape(x)[0], 1, 1, 1]
131
+ )
132
+ return model_mean + nonzero_mask * tf.exp(0.5 * model_log_variance) * noise
133
+
134
+ def kernel_init(scale):
135
+ scale = max(scale, 1e-10)
136
+ return keras.initializers.VarianceScaling(
137
+ scale, mode="fan_avg", distribution="uniform"
138
+ )
139
+
140
+ class AttentionBlock(layers.Layer):
141
+ def __init__(self, units, groups=8, **kwargs):
142
+ self.units = units
143
+ self.groups = groups
144
+ super().__init__(**kwargs)
145
+ self.norm = layers.GroupNormalization(groups=groups)
146
+ self.query = layers.Dense(units, kernel_initializer=kernel_init(1.0))
147
+ self.key = layers.Dense(units, kernel_initializer=kernel_init(1.0))
148
+ self.value = layers.Dense(units, kernel_initializer=kernel_init(1.0))
149
+ self.proj = layers.Dense(units, kernel_initializer=kernel_init(0.0))
150
+
151
+ def call(self, inputs):
152
+ batch_size = tf.shape(inputs)[0]
153
+ height = tf.shape(inputs)[1]
154
+ width = tf.shape(inputs)[2]
155
+ scale = tf.cast(self.units, tf.float32) ** (-0.5)
156
+
157
+ inputs = self.norm(inputs)
158
+ q = self.query(inputs)
159
+ k = self.key(inputs)
160
+ v = self.value(inputs)
161
+
162
+ attn_score = tf.einsum("bhwc, bHWc->bhwHW", q, k) * scale
163
+ attn_score = tf.reshape(attn_score, [batch_size, height, width, height * width])
164
+ attn_score = tf.nn.softmax(attn_score, -1)
165
+ attn_score = tf.reshape(attn_score, [batch_size, height, width, height, width])
166
+
167
+ proj = tf.einsum("bhwHW,bHWc->bhwc", attn_score, v)
168
+ proj = self.proj(proj)
169
+ return inputs + proj
170
+
171
+ class TimeEmbedding(layers.Layer):
172
+ def __init__(self, dim, **kwargs):
173
+ super().__init__(**kwargs)
174
+ self.dim = dim
175
+ self.half_dim = dim // 2
176
+ self.emb = math.log(10000) / (self.half_dim - 1)
177
+ self.emb = tf.exp(tf.range(self.half_dim, dtype=tf.float32) * -self.emb)
178
+
179
+ def call(self, inputs):
180
+ inputs = tf.cast(inputs, dtype=tf.float32)
181
+ emb = inputs[:, None] * self.emb[None, :]
182
+ emb = tf.concat([tf.sin(emb), tf.cos(emb)], axis=-1)
183
+ return emb
184
+
185
+ class ClassEmbedding(layers.Layer):
186
+ def __init__(self, num_classes, dim, **kwargs):
187
+ super().__init__(**kwargs)
188
+ self.num_classes = num_classes
189
+ self.dim = dim
190
+ self.embedding = layers.Embedding(num_classes, dim)
191
+
192
+ def call(self, inputs):
193
+ return self.embedding(inputs)
194
+
195
+ def ResidualBlock(width, groups=8, activation_fn=keras.activations.swish):
196
+ def apply(inputs):
197
+ x, t, c = inputs
198
+ input_width = x.shape[3]
199
+
200
+ if input_width == width:
201
+ residual = x
202
+ else:
203
+ residual = layers.Conv2D(
204
+ width, kernel_size=1, kernel_initializer=kernel_init(1.0)
205
+ )(x)
206
+
207
+ temb = activation_fn(t)
208
+ temb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(temb)[
209
+ :, None, None, :
210
+ ]
211
+
212
+ cemb = activation_fn(c)
213
+ cemb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(cemb)[
214
+ :, None, None, :
215
+ ]
216
+
217
+ x = layers.GroupNormalization(groups=groups)(x)
218
+ x = activation_fn(x)
219
+ x = layers.Conv2D(
220
+ width, kernel_size=3, padding="same", kernel_initializer=kernel_init(1.0)
221
+ )(x)
222
+
223
+ x = layers.Add()([x, temb, cemb])
224
+ x = layers.GroupNormalization(groups=groups)(x)
225
+ x = activation_fn(x)
226
+
227
+ x = layers.Conv2D(
228
+ width, kernel_size=3, padding="same", kernel_initializer=kernel_init(0.0)
229
+ )(x)
230
+ x = layers.Add()([x, residual])
231
+ return x
232
+
233
+ return apply
234
+
235
+ def DownSample(width):
236
+ def apply(x):
237
+ x = layers.Conv2D(
238
+ width, kernel_size=3, strides=2, padding="same",
239
+ kernel_initializer=kernel_init(1.0)
240
+ )(x)
241
+ return x
242
+ return apply
243
+
244
+ def UpSample(width, interpolation="nearest"):
245
+ def apply(x):
246
+ x = layers.UpSampling2D(size=2, interpolation=interpolation)(x)
247
+ x = layers.Conv2D(
248
+ width, kernel_size=3, padding="same", kernel_initializer=kernel_init(1.0)
249
+ )(x)
250
+ return x
251
+ return apply
252
+
253
+ def TimeMLP(units, activation_fn=keras.activations.swish):
254
+ def apply(inputs):
255
+ temb = layers.Dense(
256
+ units, activation=activation_fn, kernel_initializer=kernel_init(1.0)
257
+ )(inputs)
258
+ temb = layers.Dense(units, kernel_initializer=kernel_init(1.0))(temb)
259
+ return temb
260
+ return apply
261
+
262
+ def build_model(
263
+ img_size, img_channels, num_classes, widths, has_attention,
264
+ num_res_blocks=2, norm_groups=8, interpolation="nearest",
265
+ activation_fn=keras.activations.swish,
266
+ ):
267
+ image_input = layers.Input(
268
+ shape=(img_size, img_size, img_channels), name="image_input"
269
+ )
270
+ time_input = keras.Input(shape=(), dtype=tf.int64, name="time_input")
271
+ class_input = keras.Input(shape=(), dtype=tf.int64, name="class_input")
272
+
273
+ x = layers.Conv2D(
274
+ first_conv_channels, kernel_size=(3, 3), padding="same",
275
+ kernel_initializer=kernel_init(1.0),
276
+ )(image_input)
277
+
278
+ temb = TimeEmbedding(dim=first_conv_channels * 4)(time_input)
279
+ temb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(temb)
280
+
281
+ cemb = ClassEmbedding(num_classes, dim=first_conv_channels * 4)(class_input)
282
+ cemb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(cemb)
283
+
284
+ skips = [x]
285
+
286
+ # DownBlock
287
+ for i in range(len(widths)):
288
+ for _ in range(num_res_blocks):
289
+ x = ResidualBlock(
290
+ widths[i], groups=norm_groups, activation_fn=activation_fn
291
+ )([x, temb, cemb])
292
+ if has_attention[i]:
293
+ x = AttentionBlock(widths[i], groups=norm_groups)(x)
294
+ skips.append(x)
295
+
296
+ if widths[i] != widths[-1]:
297
+ x = DownSample(widths[i])(x)
298
+ skips.append(x)
299
+
300
+ # MiddleBlock
301
+ x = ResidualBlock(widths[-1], groups=norm_groups, activation_fn=activation_fn)(
302
+ [x, temb, cemb]
303
+ )
304
+ x = AttentionBlock(widths[-1], groups=norm_groups)(x)
305
+ x = ResidualBlock(widths[-1], groups=norm_groups, activation_fn=activation_fn)(
306
+ [x, temb, cemb]
307
+ )
308
+
309
+ # UpBlock
310
+ for i in reversed(range(len(widths))):
311
+ for _ in range(num_res_blocks + 1):
312
+ x = layers.Concatenate(axis=-1)([x, skips.pop()])
313
+ x = ResidualBlock(
314
+ widths[i], groups=norm_groups, activation_fn=activation_fn
315
+ )([x, temb, cemb])
316
+ if has_attention[i]:
317
+ x = AttentionBlock(widths[i], groups=norm_groups)(x)
318
+
319
+ if i != 0:
320
+ x = UpSample(widths[i], interpolation=interpolation)(x)
321
+
322
+ # End block
323
+ x = layers.GroupNormalization(groups=norm_groups)(x)
324
+ x = activation_fn(x)
325
+ x = layers.Conv2D(3, (3, 3), padding="same", kernel_initializer=kernel_init(0.0))(x)
326
+ return keras.Model([image_input, time_input, class_input], x, name="conditional_unet")
327
+
328
+ # Initialize model and load weights
329
+ def load_model():
330
+ """Load the trained model"""
331
+ try:
332
+ # Build model
333
+ network = build_model(
334
+ img_size=img_size,
335
+ img_channels=img_channels,
336
+ num_classes=num_classes,
337
+ widths=widths,
338
+ has_attention=has_attention,
339
+ num_res_blocks=num_res_blocks,
340
+ norm_groups=norm_groups,
341
+ activation_fn=keras.activations.swish,
342
+ )
343
+
344
+ # Try to load weights (adjust path as needed)
345
+ try:
346
+ network.load_weights("final_ema_network.h5")
347
+ print("βœ… Loaded final EMA model")
348
+ except:
349
+ print("No model found")
350
+ # Initialize diffusion utilities
351
+ gdf_util = GaussianDiffusion(timesteps=total_timesteps)
352
+
353
+ return network, gdf_util
354
+
355
+ except Exception as e:
356
+ print(f"❌ Error loading model: {e}")
357
+ return None, None
358
+
359
+ # Global variables
360
+ model_network, gdf_util = load_model()
361
+
362
+ def tensor_to_pil(tensor):
363
+ """Convert tensor to PIL Image"""
364
+ # Convert from [-1, 1] to [0, 255]
365
+ tensor = tf.clip_by_value(tensor * 127.5 + 127.5, 0.0, 255.0)
366
+ tensor = tf.cast(tensor, tf.uint8)
367
+
368
+ # Convert to numpy and then PIL
369
+ numpy_img = tensor.numpy()
370
+ if len(numpy_img.shape) == 4: # Batch dimension
371
+ numpy_img = numpy_img[0]
372
+
373
+ return Image.fromarray(numpy_img)
374
+
375
+ def generate_step_by_step(class_choice, show_every_n_steps=50):
376
+ """Generate image step by step showing the denoising process"""
377
+ if model_network is None or gdf_util is None:
378
+ yield "❌ Model not loaded. Please ensure the model is trained and weights are available.", None
379
+ return
380
+
381
+ class_id = class_names.index(class_choice)
382
+
383
+ # Start with pure noise
384
+ sample = tf.random.normal(shape=(1, img_size, img_size, img_channels), dtype=tf.float32)
385
+ class_tensor = tf.constant([class_id], dtype=tf.int64)
386
+
387
+ yield f"🎲 Starting generation for: {class_choice}...", tensor_to_pil(sample)
388
+
389
+ # Reverse diffusion process
390
+ for step, t in enumerate(reversed(range(0, total_timesteps))):
391
+ tt = tf.cast(tf.fill(1, t), dtype=tf.int64)
392
+
393
+ # Predict noise
394
+ pred_noise = model_network([sample, tt, class_tensor], training=False)
395
+
396
+ # Denoise one step
397
+ sample = gdf_util.p_sample(pred_noise, sample, tt, clip_denoised=True)
398
+
399
+ # Show progress every N steps
400
+ if step % show_every_n_steps == 0 or t == 0:
401
+ progress = ((total_timesteps - t) / total_timesteps) * 100
402
+ status = f"πŸ”„ Denoising... Step {step+1}/{total_timesteps} ({progress:.1f}%)"
403
+
404
+ if t == 0:
405
+ status = f"βœ… IMAGE READY! Generated {class_choice} in {step+1} steps"
406
+
407
+ yield status, tensor_to_pil(sample)
408
+
409
+ # Final result
410
+ yield f"πŸŽ‰ **IMAGE READY!** Final {class_choice} generated successfully!", tensor_to_pil(sample)
411
+
412
+ def generate_batch_images(class_choice, num_images=4):
413
+ """Generate multiple images at once (final result only)"""
414
+ if model_network is None or gdf_util is None:
415
+ return "❌ Model not loaded.", None
416
+
417
+ class_id = class_names.index(class_choice)
418
+
419
+ # Generate multiple samples
420
+ samples = tf.random.normal(
421
+ shape=(num_images, img_size, img_size, img_channels), dtype=tf.float32
422
+ )
423
+ class_tensor = tf.constant([class_id] * num_images, dtype=tf.int64)
424
+
425
+ # Full reverse diffusion (no intermediate steps shown)
426
+ for t in reversed(range(0, total_timesteps)):
427
+ tt = tf.cast(tf.fill(num_images, t), dtype=tf.int64)
428
+ pred_noise = model_network([samples, tt, class_tensor], training=False)
429
+ samples = gdf_util.p_sample(pred_noise, samples, tt, clip_denoised=True)
430
+
431
+ # Create a grid of images
432
+ samples_np = tf.clip_by_value(samples * 127.5 + 127.5, 0.0, 255.0)
433
+ samples_np = tf.cast(samples_np, tf.uint8).numpy()
434
+
435
+ # Create 2x2 grid
436
+ grid_size = int(np.sqrt(num_images))
437
+ if grid_size * grid_size < num_images:
438
+ grid_size += 1
439
+
440
+ fig, axes = plt.subplots(grid_size, grid_size, figsize=(8, 8))
441
+ fig.suptitle(f'Generated {class_choice} Images', fontsize=16)
442
+
443
+ for i in range(num_images):
444
+ row, col = i // grid_size, i % grid_size
445
+ if grid_size == 1:
446
+ axes.imshow(samples_np[i])
447
+ axes.axis('off')
448
+ else:
449
+ axes[row, col].imshow(samples_np[i])
450
+ axes[row, col].axis('off')
451
+
452
+ # Hide empty subplots
453
+ for i in range(num_images, grid_size * grid_size):
454
+ row, col = i // grid_size, i % grid_size
455
+ if grid_size > 1:
456
+ axes[row, col].axis('off')
457
+
458
+ plt.tight_layout()
459
+
460
+ # Convert matplotlib figure to PIL Image
461
+ buf = io.BytesIO()
462
+ plt.savefig(buf, format='png', bbox_inches='tight', dpi=100)
463
+ buf.seek(0)
464
+ grid_image = Image.open(buf)
465
+ plt.close()
466
+
467
+ return f"βœ… Generated {num_images} {class_choice} images!", grid_image
468
+
469
+ # Create Gradio interface
470
+ def create_interface():
471
+ with gr.Blocks(title="Conditional DDPM - CIFAR-10 Generator", theme=gr.themes.Soft()) as demo:
472
+ gr.Markdown("""
473
+ # 🎨 Conditional DDPM Image Generator
474
+ ### CIFAR-10 Classes: Airplane, Automobile, Bird, Cat
475
+
476
+ Choose between **Step-by-Step** generation (watch the denoising process) or **Batch** generation (multiple images at once).
477
+ """)
478
+
479
+ with gr.Tabs():
480
+ # Tab 1: Step-by-step generation
481
+ with gr.TabItem("πŸ” Step-by-Step Generation"):
482
+ gr.Markdown("Watch the model denoise step by step!")
483
+
484
+ with gr.Row():
485
+ with gr.Column(scale=1):
486
+ class_input1 = gr.Dropdown(
487
+ choices=class_names,
488
+ value="Airplane",
489
+ label="Choose Class",
490
+ info="Select what you want to generate"
491
+ )
492
+ step_interval = gr.Slider(
493
+ minimum=10,
494
+ maximum=100,
495
+ value=50,
496
+ step=10,
497
+ label="Show Every N Steps",
498
+ info="How often to update the image (lower = more updates)"
499
+ )
500
+ generate_btn1 = gr.Button("🎲 Generate Step-by-Step", variant="primary", size="lg")
501
+
502
+ with gr.Column(scale=2):
503
+ status_text = gr.Textbox(
504
+ label="Generation Status",
505
+ interactive=False,
506
+ max_lines=2
507
+ )
508
+ output_image1 = gr.Image(
509
+ label="Generated Image",
510
+ type="pil",
511
+ height=400,
512
+ width=400
513
+ )
514
+
515
+ generate_btn1.click(
516
+ fn=generate_step_by_step,
517
+ inputs=[class_input1, step_interval],
518
+ outputs=[status_text, output_image1],
519
+ show_progress=True
520
+ )
521
+
522
+ # Tab 2: Batch generation
523
+ with gr.TabItem("🎯 Batch Generation"):
524
+ gr.Markdown("Generate multiple images at once (faster)!")
525
+
526
+ with gr.Row():
527
+ with gr.Column(scale=1):
528
+ class_input2 = gr.Dropdown(
529
+ choices=class_names,
530
+ value="Airplane",
531
+ label="Choose Class"
532
+ )
533
+ num_images = gr.Slider(
534
+ minimum=1,
535
+ maximum=9,
536
+ value=4,
537
+ step=1,
538
+ label="Number of Images",
539
+ info="How many images to generate"
540
+ )
541
+ generate_btn2 = gr.Button("πŸš€ Generate Batch", variant="primary", size="lg")
542
+
543
+ with gr.Column(scale=2):
544
+ batch_status = gr.Textbox(
545
+ label="Status",
546
+ interactive=False
547
+ )
548
+ output_image2 = gr.Image(
549
+ label="Generated Images Grid",
550
+ type="pil",
551
+ height=500,
552
+ width=500
553
+ )
554
+
555
+ generate_btn2.click(
556
+ fn=generate_batch_images,
557
+ inputs=[class_input2, num_images],
558
+ outputs=[batch_status, output_image2],
559
+ show_progress=True
560
+ )
561
+
562
+ # Footer
563
+ gr.Markdown("""
564
+ ---
565
+ **Note:** Make sure you have trained the model and the weights are available in the `conditional_ddmp_cifar10/` directory.
566
+
567
+ - **Step-by-Step**: Shows the denoising process in real-time
568
+ - **Batch**: Generates multiple images quickly (final results only)
569
+ """)
570
+
571
+ return demo
572
+
573
+ if __name__ == "__main__":
574
+ # Check if model is loaded
575
+ if model_network is None:
576
+ print("⚠️ WARNING: Model not loaded. Make sure you have:")
577
+ print(" 1. Trained the conditional DDPM model")
578
+ print(" 2. Model weights saved in 'conditional_ddpm_cifar10/' directory")
579
+ print(" 3. Either 'final_ema_network.h5' or epoch checkpoints available")
580
+ print("\nπŸš€ Starting Gradio app anyway (will show error messages)...")
581
+ else:
582
+ print("βœ… Model loaded successfully!")
583
+ print("πŸš€ Starting Gradio app...")
584
+
585
+ # Create and launch the interface
586
+ demo = create_interface()
587
+ demo.launch(
588
+ share=False, # Set to True if you want a public link
589
+ server_name="0.0.0.0",
590
+ server_port=7860,
591
+ show_error=True
592
+ )
final_ema_network.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4be7ff30c2eac6802b7e4e2dec9e981c41ccee11f90a4aef52d45ad9a6f88491
3
+ size 260121280
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core Machine Learning Libraries
2
+ tensorflow>=2.11.0,<2.16.0
3
+ numpy>=1.21.0,<1.25.0
4
+
5
+ # Dataset Loading
6
+ tensorflow-datasets>=4.8.0
7
+
8
+ # Image Processing
9
+ Pillow>=9.0.0
10
+ matplotlib>=3.5.0
11
+
12
+ gradio>=4.0.0
13
+ scipy>=1.7.0
14
+ scikit-image>=0.19.0
15
+
16
+ # For potential memory optimization
17
+ psutil>=5.8.0