image_gen / app.py
RagedKrish's picture
Updating files
987fa23
Raw History Blame Contribute Delete
22.2 kB
import gradio as gr
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
from PIL import Image
import io
import time
import math
# Configuration (same as training)
img_size = 32
img_channels = 3
clip_min = -1.0
clip_max = 1.0
total_timesteps = 1000
first_conv_channels = 64
channel_multiplier = [1, 2, 4, 8]
widths = [first_conv_channels * mult for mult in channel_multiplier]
has_attention = [False, False, True, True]
num_res_blocks = 2
norm_groups = 8
num_classes = 4
class_names = ["Airplane", "Automobile", "Bird", "Cat"]
# All the necessary classes and functions from the training script
class GaussianDiffusion:
def __init__(
self,
beta_start=1e-4,
beta_end=0.02,
timesteps=1000,
clip_min=-1.0,
clip_max=1.0,
):
self.beta_start = beta_start
self.beta_end = beta_end
self.timesteps = timesteps
self.clip_min = clip_min
self.clip_max = clip_max
# Define the linear variance schedule
self.betas = betas = np.linspace(
beta_start, beta_end, timesteps, dtype=np.float64
)
self.num_timesteps = int(timesteps)
alphas = 1.0 - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
self.betas = tf.constant(betas, dtype=tf.float32)
self.alphas_cumprod = tf.constant(alphas_cumprod, dtype=tf.float32)
self.alphas_cumprod_prev = tf.constant(alphas_cumprod_prev, dtype=tf.float32)
self.sqrt_alphas_cumprod = tf.constant(
np.sqrt(alphas_cumprod), dtype=tf.float32
)
self.sqrt_one_minus_alphas_cumprod = tf.constant(
np.sqrt(1.0 - alphas_cumprod), dtype=tf.float32
)
self.log_one_minus_alphas_cumprod = tf.constant(
np.log(1.0 - alphas_cumprod), dtype=tf.float32
)
self.sqrt_recip_alphas_cumprod = tf.constant(
np.sqrt(1.0 / alphas_cumprod), dtype=tf.float32
)
self.sqrt_recipm1_alphas_cumprod = tf.constant(
np.sqrt(1.0 / alphas_cumprod - 1), dtype=tf.float32
)
posterior_variance = (
betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
)
self.posterior_variance = tf.constant(posterior_variance, dtype=tf.float32)
self.posterior_log_variance_clipped = tf.constant(
np.log(np.maximum(posterior_variance, 1e-20)), dtype=tf.float32
)
self.posterior_mean_coef1 = tf.constant(
betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod),
dtype=tf.float32,
)
self.posterior_mean_coef2 = tf.constant(
(1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod),
dtype=tf.float32,
)
def _extract(self, a, t, x_shape):
batch_size = x_shape[0]
out = tf.gather(a, t)
return tf.reshape(out, [batch_size, 1, 1, 1])
def predict_start_from_noise(self, x_t, t, noise):
x_t_shape = tf.shape(x_t)
return (
self._extract(self.sqrt_recip_alphas_cumprod, t, x_t_shape) * x_t
- self._extract(self.sqrt_recipm1_alphas_cumprod, t, x_t_shape) * noise
)
def q_posterior(self, x_start, x_t, t):
x_t_shape = tf.shape(x_t)
posterior_mean = (
self._extract(self.posterior_mean_coef1, t, x_t_shape) * x_start
+ self._extract(self.posterior_mean_coef2, t, x_t_shape) * x_t
)
posterior_variance = self._extract(self.posterior_variance, t, x_t_shape)
posterior_log_variance_clipped = self._extract(
self.posterior_log_variance_clipped, t, x_t_shape
)
return posterior_mean, posterior_variance, posterior_log_variance_clipped
def p_mean_variance(self, pred_noise, x, t, clip_denoised=True):
x_recon = self.predict_start_from_noise(x, t=t, noise=pred_noise)
if clip_denoised:
x_recon = tf.clip_by_value(x_recon, self.clip_min, self.clip_max)
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(
x_start=x_recon, x_t=x, t=t
)
return model_mean, posterior_variance, posterior_log_variance
def p_sample(self, pred_noise, x, t, clip_denoised=True):
model_mean, _, model_log_variance = self.p_mean_variance(
pred_noise, x=x, t=t, clip_denoised=clip_denoised
)
noise = tf.random.normal(shape=x.shape, dtype=x.dtype)
nonzero_mask = tf.reshape(
1 - tf.cast(tf.equal(t, 0), tf.float32), [tf.shape(x)[0], 1, 1, 1]
)
return model_mean + nonzero_mask * tf.exp(0.5 * model_log_variance) * noise
def kernel_init(scale):
scale = max(scale, 1e-10)
return keras.initializers.VarianceScaling(
scale, mode="fan_avg", distribution="uniform"
)
class AttentionBlock(layers.Layer):
def __init__(self, units, groups=8, **kwargs):
self.units = units
self.groups = groups
super().__init__(**kwargs)
self.norm = layers.GroupNormalization(groups=groups)
self.query = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.key = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.value = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.proj = layers.Dense(units, kernel_initializer=kernel_init(0.0))
def call(self, inputs):
batch_size = tf.shape(inputs)[0]
height = tf.shape(inputs)[1]
width = tf.shape(inputs)[2]
scale = tf.cast(self.units, tf.float32) ** (-0.5)
inputs = self.norm(inputs)
q = self.query(inputs)
k = self.key(inputs)
v = self.value(inputs)
attn_score = tf.einsum("bhwc, bHWc->bhwHW", q, k) * scale
attn_score = tf.reshape(attn_score, [batch_size, height, width, height * width])
attn_score = tf.nn.softmax(attn_score, -1)
attn_score = tf.reshape(attn_score, [batch_size, height, width, height, width])
proj = tf.einsum("bhwHW,bHWc->bhwc", attn_score, v)
proj = self.proj(proj)
return inputs + proj
class TimeEmbedding(layers.Layer):
def __init__(self, dim, **kwargs):
super().__init__(**kwargs)
self.dim = dim
self.half_dim = dim // 2
self.emb = math.log(10000) / (self.half_dim - 1)
self.emb = tf.exp(tf.range(self.half_dim, dtype=tf.float32) * -self.emb)
def call(self, inputs):
inputs = tf.cast(inputs, dtype=tf.float32)
emb = inputs[:, None] * self.emb[None, :]
emb = tf.concat([tf.sin(emb), tf.cos(emb)], axis=-1)
return emb
class ClassEmbedding(layers.Layer):
def __init__(self, num_classes, dim, **kwargs):
super().__init__(**kwargs)
self.num_classes = num_classes
self.dim = dim
self.embedding = layers.Embedding(num_classes, dim)
def call(self, inputs):
return self.embedding(inputs)
def ResidualBlock(width, groups=8, activation_fn=keras.activations.swish):
def apply(inputs):
x, t, c = inputs
input_width = x.shape[3]
if input_width == width:
residual = x
else:
residual = layers.Conv2D(
width, kernel_size=1, kernel_initializer=kernel_init(1.0)
)(x)
temb = activation_fn(t)
temb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(temb)[
:, None, None, :
]
cemb = activation_fn(c)
cemb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(cemb)[
:, None, None, :
]
x = layers.GroupNormalization(groups=groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
width, kernel_size=3, padding="same", kernel_initializer=kernel_init(1.0)
)(x)
x = layers.Add()([x, temb, cemb])
x = layers.GroupNormalization(groups=groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
width, kernel_size=3, padding="same", kernel_initializer=kernel_init(0.0)
)(x)
x = layers.Add()([x, residual])
return x
return apply
def DownSample(width):
def apply(x):
x = layers.Conv2D(
width, kernel_size=3, strides=2, padding="same",
kernel_initializer=kernel_init(1.0)
)(x)
return x
return apply
def UpSample(width, interpolation="nearest"):
def apply(x):
x = layers.UpSampling2D(size=2, interpolation=interpolation)(x)
x = layers.Conv2D(
width, kernel_size=3, padding="same", kernel_initializer=kernel_init(1.0)
)(x)
return x
return apply
def TimeMLP(units, activation_fn=keras.activations.swish):
def apply(inputs):
temb = layers.Dense(
units, activation=activation_fn, kernel_initializer=kernel_init(1.0)
)(inputs)
temb = layers.Dense(units, kernel_initializer=kernel_init(1.0))(temb)
return temb
return apply
def build_model(
img_size, img_channels, num_classes, widths, has_attention,
num_res_blocks=2, norm_groups=8, interpolation="nearest",
activation_fn=keras.activations.swish,
):
image_input = layers.Input(
shape=(img_size, img_size, img_channels), name="image_input"
)
time_input = keras.Input(shape=(), dtype=tf.int64, name="time_input")
class_input = keras.Input(shape=(), dtype=tf.int64, name="class_input")
x = layers.Conv2D(
first_conv_channels, kernel_size=(3, 3), padding="same",
kernel_initializer=kernel_init(1.0),
)(image_input)
temb = TimeEmbedding(dim=first_conv_channels * 4)(time_input)
temb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(temb)
cemb = ClassEmbedding(num_classes, dim=first_conv_channels * 4)(class_input)
cemb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(cemb)
skips = [x]
# DownBlock
for i in range(len(widths)):
for _ in range(num_res_blocks):
x = ResidualBlock(
widths[i], groups=norm_groups, activation_fn=activation_fn
)([x, temb, cemb])
if has_attention[i]:
x = AttentionBlock(widths[i], groups=norm_groups)(x)
skips.append(x)
if widths[i] != widths[-1]:
x = DownSample(widths[i])(x)
skips.append(x)
# MiddleBlock
x = ResidualBlock(widths[-1], groups=norm_groups, activation_fn=activation_fn)(
[x, temb, cemb]
)
x = AttentionBlock(widths[-1], groups=norm_groups)(x)
x = ResidualBlock(widths[-1], groups=norm_groups, activation_fn=activation_fn)(
[x, temb, cemb]
)
# UpBlock
for i in reversed(range(len(widths))):
for _ in range(num_res_blocks + 1):
x = layers.Concatenate(axis=-1)([x, skips.pop()])
x = ResidualBlock(
widths[i], groups=norm_groups, activation_fn=activation_fn
)([x, temb, cemb])
if has_attention[i]:
x = AttentionBlock(widths[i], groups=norm_groups)(x)
if i != 0:
x = UpSample(widths[i], interpolation=interpolation)(x)
# End block
x = layers.GroupNormalization(groups=norm_groups)(x)
x = activation_fn(x)
x = layers.Conv2D(3, (3, 3), padding="same", kernel_initializer=kernel_init(0.0))(x)
return keras.Model([image_input, time_input, class_input], x, name="conditional_unet")
# Initialize model and load weights
def load_model():
"""Load the trained model"""
try:
# Build model
network = build_model(
img_size=img_size,
img_channels=img_channels,
num_classes=num_classes,
widths=widths,
has_attention=has_attention,
num_res_blocks=num_res_blocks,
norm_groups=norm_groups,
activation_fn=keras.activations.swish,
)
# Try to load weights (adjust path as needed)
try:
network.load_weights("final_ema_network.h5")
print("βœ… Loaded final EMA model")
except:
print("No model found")
# Initialize diffusion utilities
gdf_util = GaussianDiffusion(timesteps=total_timesteps)
return network, gdf_util
except Exception as e:
print(f"❌ Error loading model: {e}")
return None, None
# Global variables
model_network, gdf_util = load_model()
def tensor_to_pil(tensor):
"""Convert tensor to PIL Image"""
# Convert from [-1, 1] to [0, 255]
tensor = tf.clip_by_value(tensor * 127.5 + 127.5, 0.0, 255.0)
tensor = tf.cast(tensor, tf.uint8)
# Convert to numpy and then PIL
numpy_img = tensor.numpy()
if len(numpy_img.shape) == 4: # Batch dimension
numpy_img = numpy_img[0]
return Image.fromarray(numpy_img)
def generate_step_by_step(class_choice, show_every_n_steps=50):
"""Generate image step by step showing the denoising process"""
if model_network is None or gdf_util is None:
yield "❌ Model not loaded. Please ensure the model is trained and weights are available.", None
return
class_id = class_names.index(class_choice)
# Start with pure noise
sample = tf.random.normal(shape=(1, img_size, img_size, img_channels), dtype=tf.float32)
class_tensor = tf.constant([class_id], dtype=tf.int64)
yield f"🎲 Starting generation for: {class_choice}...", tensor_to_pil(sample)
# Reverse diffusion process
for step, t in enumerate(reversed(range(0, total_timesteps))):
tt = tf.cast(tf.fill(1, t), dtype=tf.int64)
# Predict noise
pred_noise = model_network([sample, tt, class_tensor], training=False)
# Denoise one step
sample = gdf_util.p_sample(pred_noise, sample, tt, clip_denoised=True)
# Show progress every N steps
if step % show_every_n_steps == 0 or t == 0:
progress = ((total_timesteps - t) / total_timesteps) * 100
status = f"πŸ”„ Denoising... Step {step+1}/{total_timesteps} ({progress:.1f}%)"
if t == 0:
status = f"βœ… IMAGE READY! Generated {class_choice} in {step+1} steps"
yield status, tensor_to_pil(sample)
# Final result
yield f"πŸŽ‰ **IMAGE READY!** Final {class_choice} generated successfully!", tensor_to_pil(sample)
def generate_batch_images(class_choice, num_images=4):
"""Generate multiple images at once (final result only)"""
if model_network is None or gdf_util is None:
return "❌ Model not loaded.", None
class_id = class_names.index(class_choice)
# Generate multiple samples
samples = tf.random.normal(
shape=(num_images, img_size, img_size, img_channels), dtype=tf.float32
)
class_tensor = tf.constant([class_id] * num_images, dtype=tf.int64)
# Full reverse diffusion (no intermediate steps shown)
for t in reversed(range(0, total_timesteps)):
tt = tf.cast(tf.fill(num_images, t), dtype=tf.int64)
pred_noise = model_network([samples, tt, class_tensor], training=False)
samples = gdf_util.p_sample(pred_noise, samples, tt, clip_denoised=True)
# Create a grid of images
samples_np = tf.clip_by_value(samples * 127.5 + 127.5, 0.0, 255.0)
samples_np = tf.cast(samples_np, tf.uint8).numpy()
# Create 2x2 grid
grid_size = int(np.sqrt(num_images))
if grid_size * grid_size < num_images:
grid_size += 1
fig, axes = plt.subplots(grid_size, grid_size, figsize=(8, 8))
fig.suptitle(f'Generated {class_choice} Images', fontsize=16)
for i in range(num_images):
row, col = i // grid_size, i % grid_size
if grid_size == 1:
axes.imshow(samples_np[i])
axes.axis('off')
else:
axes[row, col].imshow(samples_np[i])
axes[row, col].axis('off')
# Hide empty subplots
for i in range(num_images, grid_size * grid_size):
row, col = i // grid_size, i % grid_size
if grid_size > 1:
axes[row, col].axis('off')
plt.tight_layout()
# Convert matplotlib figure to PIL Image
buf = io.BytesIO()
plt.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
grid_image = Image.open(buf)
plt.close()
return f"βœ… Generated {num_images} {class_choice} images!", grid_image
# Create Gradio interface
def create_interface():
with gr.Blocks(title="Conditional DDPM - CIFAR-10 Generator", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# 🎨 Conditional DDPM Image Generator
### CIFAR-10 Classes: Airplane, Automobile, Bird, Cat
Choose between **Step-by-Step** generation (watch the denoising process) or **Batch** generation (multiple images at once).
""")
with gr.Tabs():
# Tab 1: Step-by-step generation
with gr.TabItem("πŸ” Step-by-Step Generation"):
gr.Markdown("Watch the model denoise step by step!")
with gr.Row():
with gr.Column(scale=1):
class_input1 = gr.Dropdown(
choices=class_names,
value="Airplane",
label="Choose Class",
info="Select what you want to generate"
)
step_interval = gr.Slider(
minimum=10,
maximum=100,
value=50,
step=10,
label="Show Every N Steps",
info="How often to update the image (lower = more updates)"
)
generate_btn1 = gr.Button("🎲 Generate Step-by-Step", variant="primary", size="lg")
with gr.Column(scale=2):
status_text = gr.Textbox(
label="Generation Status",
interactive=False,
max_lines=2
)
output_image1 = gr.Image(
label="Generated Image",
type="pil",
height=400,
width=400
)
generate_btn1.click(
fn=generate_step_by_step,
inputs=[class_input1, step_interval],
outputs=[status_text, output_image1],
show_progress=True
)
# Tab 2: Batch generation
with gr.TabItem("🎯 Batch Generation"):
gr.Markdown("Generate multiple images at once (faster)!")
with gr.Row():
with gr.Column(scale=1):
class_input2 = gr.Dropdown(
choices=class_names,
value="Airplane",
label="Choose Class"
)
num_images = gr.Slider(
minimum=1,
maximum=9,
value=4,
step=1,
label="Number of Images",
info="How many images to generate"
)
generate_btn2 = gr.Button("πŸš€ Generate Batch", variant="primary", size="lg")
with gr.Column(scale=2):
batch_status = gr.Textbox(
label="Status",
interactive=False
)
output_image2 = gr.Image(
label="Generated Images Grid",
type="pil",
height=500,
width=500
)
generate_btn2.click(
fn=generate_batch_images,
inputs=[class_input2, num_images],
outputs=[batch_status, output_image2],
show_progress=True
)
# Footer
gr.Markdown("""
---
**Note:** Make sure you have trained the model and the weights are available in the `conditional_ddmp_cifar10/` directory.
- **Step-by-Step**: Shows the denoising process in real-time with enlarged images (32x32 β†’ 256x256)
- **Batch**: Generates multiple images quickly with enhanced grid display
- **Image Quality**: Images are upscaled using nearest-neighbor interpolation to preserve pixel details
πŸ” **Tip**: Use lower step intervals (10-20) for smoother real-time updates, higher intervals (50-100) for faster generation.
""")
return demo
if __name__ == "__main__":
# Check if model is loaded
if model_network is None:
print("⚠️ WARNING: Model not loaded. Make sure you have:")
print(" 1. Trained the conditional DDPM model")
print(" 2. Model weights saved in 'conditional_ddpm_cifar10/' directory")
print(" 3. Either 'final_ema_network.h5' or epoch checkpoints available")
print("\nπŸš€ Starting Gradio app anyway (will show error messages)...")
else:
print("βœ… Model loaded successfully!")
print("πŸš€ Starting Gradio app...")
# Create and launch the interface
demo = create_interface()
demo.launch(
share=False, # Set to True if you want a public link
server_name="0.0.0.0",
server_port=7860,
show_error=True
)