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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MNIST Handwritten Digit Generation Web App
|
| 2 |
+
# TensorFlow/Keras version using VAE and Gradio for Google Colab
|
| 3 |
+
# Auto-training version - model trains on startup
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import tensorflow as tf
|
| 8 |
+
from tensorflow.keras import layers, Model
|
| 9 |
+
from tensorflow.keras.datasets import mnist
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import io
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
# =============================================================================
|
| 17 |
+
# PART 1: VAE MODEL DEFINITION
|
| 18 |
+
# =============================================================================
|
| 19 |
+
|
| 20 |
+
class Sampling(layers.Layer):
|
| 21 |
+
def call(self, inputs):
|
| 22 |
+
z_mean, z_log_var = inputs
|
| 23 |
+
batch = tf.shape(z_mean)[0]
|
| 24 |
+
dim = tf.shape(z_mean)[1]
|
| 25 |
+
epsilon = tf.random.normal(shape=(batch, dim))
|
| 26 |
+
return z_mean + tf.exp(0.5 * z_log_var) * epsilon
|
| 27 |
+
|
| 28 |
+
class VAE(Model):
|
| 29 |
+
def __init__(self, encoder, decoder, **kwargs):
|
| 30 |
+
super(VAE, self).__init__(**kwargs)
|
| 31 |
+
self.encoder = encoder
|
| 32 |
+
self.decoder = decoder
|
| 33 |
+
self.total_loss_tracker = tf.keras.metrics.Mean(name="total_loss")
|
| 34 |
+
self.reconstruction_loss_tracker = tf.keras.metrics.Mean(name="reconstruction_loss")
|
| 35 |
+
self.kl_loss_tracker = tf.keras.metrics.Mean(name="kl_loss")
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def metrics(self):
|
| 39 |
+
return [
|
| 40 |
+
self.total_loss_tracker,
|
| 41 |
+
self.reconstruction_loss_tracker,
|
| 42 |
+
self.kl_loss_tracker,
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
def train_step(self, data):
|
| 46 |
+
if isinstance(data, tuple):
|
| 47 |
+
data = data[0]
|
| 48 |
+
|
| 49 |
+
with tf.GradientTape() as tape:
|
| 50 |
+
z_mean, z_log_var, z = self.encoder(data)
|
| 51 |
+
reconstruction = self.decoder(z)
|
| 52 |
+
reconstruction_loss = tf.reduce_mean(
|
| 53 |
+
tf.reduce_sum(
|
| 54 |
+
tf.keras.losses.binary_crossentropy(data, reconstruction), axis=-1
|
| 55 |
+
)
|
| 56 |
+
)
|
| 57 |
+
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
|
| 58 |
+
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
|
| 59 |
+
total_loss = reconstruction_loss + kl_loss
|
| 60 |
+
grads = tape.gradient(total_loss, self.trainable_weights)
|
| 61 |
+
self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
|
| 62 |
+
self.total_loss_tracker.update_state(total_loss)
|
| 63 |
+
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
|
| 64 |
+
self.kl_loss_tracker.update_state(kl_loss)
|
| 65 |
+
return {
|
| 66 |
+
"loss": self.total_loss_tracker.result(),
|
| 67 |
+
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
|
| 68 |
+
"kl_loss": self.kl_loss_tracker.result(),
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
def build_vae(input_shape=(784,), latent_dim=20):
|
| 72 |
+
encoder_inputs = layers.Input(shape=input_shape)
|
| 73 |
+
x = layers.Dense(400, activation='relu')(encoder_inputs)
|
| 74 |
+
x = layers.Dense(400, activation='relu')(x)
|
| 75 |
+
z_mean = layers.Dense(latent_dim, name='z_mean')(x)
|
| 76 |
+
z_log_var = layers.Dense(latent_dim, name='z_log_var')(x)
|
| 77 |
+
z = Sampling()([z_mean, z_log_var])
|
| 78 |
+
encoder = Model(encoder_inputs, [z_mean, z_log_var, z], name='encoder')
|
| 79 |
+
|
| 80 |
+
latent_inputs = layers.Input(shape=(latent_dim,))
|
| 81 |
+
x = layers.Dense(400, activation='relu')(latent_inputs)
|
| 82 |
+
x = layers.Dense(400, activation='relu')(x)
|
| 83 |
+
decoder_outputs = layers.Dense(784, activation='sigmoid')(x)
|
| 84 |
+
decoder = Model(latent_inputs, decoder_outputs, name='decoder')
|
| 85 |
+
|
| 86 |
+
vae = VAE(encoder, decoder)
|
| 87 |
+
vae.compile(optimizer='adam')
|
| 88 |
+
|
| 89 |
+
return vae, encoder, decoder
|
| 90 |
+
|
| 91 |
+
# =============================================================================
|
| 92 |
+
# PART 2: DATA LOADING AND TRAINING
|
| 93 |
+
# =============================================================================
|
| 94 |
+
|
| 95 |
+
encoder = None
|
| 96 |
+
decoder = None
|
| 97 |
+
digit_latents = None
|
| 98 |
+
model_ready = False
|
| 99 |
+
training_progress = "Initializing..."
|
| 100 |
+
|
| 101 |
+
def train_model_background():
|
| 102 |
+
global encoder, decoder, digit_latents, model_ready, training_progress
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
training_progress = "Loading MNIST data..."
|
| 106 |
+
print("Loading MNIST data...")
|
| 107 |
+
(x_train, y_train), _ = mnist.load_data()
|
| 108 |
+
x_train = x_train.astype('float32') / 255.0
|
| 109 |
+
x_train = x_train.reshape((-1, 784))
|
| 110 |
+
x_train = x_train[:10000]
|
| 111 |
+
y_train = y_train[:10000]
|
| 112 |
+
|
| 113 |
+
training_progress = "Building VAE model..."
|
| 114 |
+
print("Building VAE model...")
|
| 115 |
+
vae, encoder_model, decoder_model = build_vae()
|
| 116 |
+
|
| 117 |
+
training_progress = "Training VAE model (20 epochs)..."
|
| 118 |
+
print("Training VAE model (20 epochs)...")
|
| 119 |
+
|
| 120 |
+
class ProgressCallback(tf.keras.callbacks.Callback):
|
| 121 |
+
def on_epoch_end(self, epoch, logs=None):
|
| 122 |
+
global training_progress
|
| 123 |
+
training_progress = f"Training... Epoch {epoch + 1}/20 (Loss: {logs.get('loss', 0):.4f})"
|
| 124 |
+
print(f"Epoch {epoch + 1}/20 completed")
|
| 125 |
+
|
| 126 |
+
history = vae.fit(
|
| 127 |
+
x_train, x_train,
|
| 128 |
+
epochs=20,
|
| 129 |
+
batch_size=128,
|
| 130 |
+
verbose=0,
|
| 131 |
+
callbacks=[ProgressCallback()]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
encoder = encoder_model
|
| 135 |
+
decoder = decoder_model
|
| 136 |
+
|
| 137 |
+
training_progress = "Computing digit latent representations..."
|
| 138 |
+
print("Computing digit latent representations...")
|
| 139 |
+
digit_latents = compute_digit_latents(encoder, x_train, y_train)
|
| 140 |
+
|
| 141 |
+
training_progress = "✅ Model ready! You can now generate digits."
|
| 142 |
+
model_ready = True
|
| 143 |
+
print("Model training completed successfully!")
|
| 144 |
+
|
| 145 |
+
except Exception as e:
|
| 146 |
+
training_progress = f"❌ Error training model: {str(e)}"
|
| 147 |
+
print(f"Error training model: {str(e)}")
|
| 148 |
+
|
| 149 |
+
def compute_digit_latents(encoder_model, x_train, y_train):
|
| 150 |
+
try:
|
| 151 |
+
digit_latents = {i: [] for i in range(10)}
|
| 152 |
+
z_means, _, _ = encoder_model.predict(x_train, verbose=0)
|
| 153 |
+
|
| 154 |
+
for i, label in enumerate(y_train):
|
| 155 |
+
digit_latents[label].append(z_means[i])
|
| 156 |
+
|
| 157 |
+
for i in range(10):
|
| 158 |
+
if len(digit_latents[i]) > 0:
|
| 159 |
+
digit_latents[i] = np.array(digit_latents[i])
|
| 160 |
+
else:
|
| 161 |
+
digit_latents[i] = np.random.normal(0, 1, (1, 20))
|
| 162 |
+
|
| 163 |
+
return digit_latents
|
| 164 |
+
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"Error computing digit latents: {str(e)}")
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
def get_training_status():
|
| 170 |
+
return training_progress
|
| 171 |
+
|
| 172 |
+
# =============================================================================
|
| 173 |
+
# PART 3: IMAGE GENERATION
|
| 174 |
+
# =============================================================================
|
| 175 |
+
|
| 176 |
+
def generate_digit_images(digit, num_images):
|
| 177 |
+
global encoder, decoder, digit_latents, model_ready
|
| 178 |
+
|
| 179 |
+
if not model_ready:
|
| 180 |
+
return None, "⏳ Model is still training. Please wait..."
|
| 181 |
+
|
| 182 |
+
if encoder is None or decoder is None or digit_latents is None:
|
| 183 |
+
return None, "❌ Model not ready yet. Please wait for training to complete."
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
latent_vectors = digit_latents[digit]
|
| 187 |
+
|
| 188 |
+
if len(latent_vectors) == 0:
|
| 189 |
+
selected_latents = np.random.normal(0, 1, (num_images, 20))
|
| 190 |
+
else:
|
| 191 |
+
if len(latent_vectors) >= num_images:
|
| 192 |
+
indices = np.random.choice(len(latent_vectors), num_images, replace=False)
|
| 193 |
+
else:
|
| 194 |
+
indices = np.random.choice(len(latent_vectors), num_images, replace=True)
|
| 195 |
+
|
| 196 |
+
selected_latents = latent_vectors[indices]
|
| 197 |
+
noise = np.random.normal(0, 0.1, selected_latents.shape)
|
| 198 |
+
selected_latents = selected_latents + noise
|
| 199 |
+
|
| 200 |
+
generated = decoder.predict(selected_latents, verbose=0)
|
| 201 |
+
images = (generated.reshape(-1, 28, 28) * 255).astype(np.uint8)
|
| 202 |
+
|
| 203 |
+
if num_images == 1:
|
| 204 |
+
grid_img = Image.fromarray(images[0], mode='L')
|
| 205 |
+
else:
|
| 206 |
+
cols = min(5, num_images)
|
| 207 |
+
rows = (num_images + cols - 1) // cols
|
| 208 |
+
grid_width = cols * 28
|
| 209 |
+
grid_height = rows * 28
|
| 210 |
+
grid_img = Image.new('L', (grid_width, grid_height), color=255)
|
| 211 |
+
|
| 212 |
+
for i, img in enumerate(images):
|
| 213 |
+
row = i // cols
|
| 214 |
+
col = i % cols
|
| 215 |
+
x = col * 28
|
| 216 |
+
y = row * 28
|
| 217 |
+
grid_img.paste(Image.fromarray(img, mode='L'), (x, y))
|
| 218 |
+
|
| 219 |
+
success_msg = f"✅ Generated {len(images)} images of digit {digit}!"
|
| 220 |
+
return grid_img, success_msg
|
| 221 |
+
|
| 222 |
+
except Exception as e:
|
| 223 |
+
error_msg = f"❌ Error generating images: {str(e)}"
|
| 224 |
+
return None, error_msg
|
| 225 |
+
|
| 226 |
+
# =============================================================================
|
| 227 |
+
# PART 4: GRADIO INTERFACE
|
| 228 |
+
# =============================================================================
|
| 229 |
+
|
| 230 |
+
def create_interface():
|
| 231 |
+
with gr.Blocks(title="MNIST VAE Digit Generator", theme=gr.themes.Soft()) as app:
|
| 232 |
+
gr.Markdown("# 🔢 TensorFlow VAE Handwritten Digit Generator")
|
| 233 |
+
gr.Markdown("Generate MNIST-style handwritten digits using a Variational Autoencoder (VAE).")
|
| 234 |
+
|
| 235 |
+
with gr.Row():
|
| 236 |
+
with gr.Column(scale=1):
|
| 237 |
+
gr.Markdown("## Training Status")
|
| 238 |
+
training_status = gr.Textbox(
|
| 239 |
+
label="Model Status",
|
| 240 |
+
value="Initializing...",
|
| 241 |
+
interactive=False
|
| 242 |
+
)
|
| 243 |
+
refresh_btn = gr.Button("🔄 Refresh Status", size="sm")
|
| 244 |
+
|
| 245 |
+
gr.Markdown("## Generation Controls")
|
| 246 |
+
selected_digit = gr.Dropdown(
|
| 247 |
+
choices=list(range(10)),
|
| 248 |
+
value=0,
|
| 249 |
+
label="Select Digit to Generate"
|
| 250 |
+
)
|
| 251 |
+
num_images = gr.Slider(
|
| 252 |
+
minimum=1,
|
| 253 |
+
maximum=10,
|
| 254 |
+
value=5,
|
| 255 |
+
step=1,
|
| 256 |
+
label="Number of Images"
|
| 257 |
+
)
|
| 258 |
+
generate_btn = gr.Button("🎲 Generate Images", variant="primary", size="lg")
|
| 259 |
+
|
| 260 |
+
with gr.Column(scale=2):
|
| 261 |
+
gr.Markdown("## Generated Images")
|
| 262 |
+
output_image = gr.Image(label="Generated Digits", type="pil")
|
| 263 |
+
generation_status = gr.Textbox(
|
| 264 |
+
label="Generation Status",
|
| 265 |
+
value="Model is training... Please wait before generating images.",
|
| 266 |
+
interactive=False
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
with gr.Accordion("ℹ️ About this App", open=False):
|
| 270 |
+
gr.Markdown("""
|
| 271 |
+
This app uses a **Variational Autoencoder (VAE)** to generate handwritten digits similar to the MNIST dataset.
|
| 272 |
+
- Wait for training to finish
|
| 273 |
+
- Select digit & number of images
|
| 274 |
+
- Click 'Generate'
|
| 275 |
+
""")
|
| 276 |
+
|
| 277 |
+
refresh_btn.click(fn=get_training_status, outputs=training_status)
|
| 278 |
+
generate_btn.click(fn=generate_digit_images, inputs=[selected_digit, num_images],
|
| 279 |
+
outputs=[output_image, generation_status]).then(
|
| 280 |
+
fn=get_training_status, outputs=training_status
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
app.load(fn=get_training_status, outputs=training_status)
|
| 284 |
+
|
| 285 |
+
return app
|
| 286 |
+
|
| 287 |
+
# =============================================================================
|
| 288 |
+
# PART 5: MAIN EXECUTION
|
| 289 |
+
# =============================================================================
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
print("Starting MNIST VAE Digit Generator...")
|
| 293 |
+
print("Model will train automatically in the background...")
|
| 294 |
+
|
| 295 |
+
training_thread = threading.Thread(target=train_model_background, daemon=True)
|
| 296 |
+
training_thread.start()
|
| 297 |
+
|
| 298 |
+
app = create_interface()
|
| 299 |
+
app.launch(share=True, debug=True, show_error=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
tensorflow
|
| 3 |
+
Pillow
|
| 4 |
+
numpy
|
| 5 |
+
matplotlib
|