{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":31235,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For exampleZZ, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2026-01-08T13:00:19.599789Z","iopub.execute_input":"2026-01-08T13:00:19.600519Z","iopub.status.idle":"2026-01-08T13:00:26.674988Z","shell.execute_reply.started":"2026-01-08T13:00:19.600489Z","shell.execute_reply":"2026-01-08T13:00:26.674163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\nIMAGE_SIZE = [256, 256]\n\n\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = (tf.cast(image, tf.float32) / 127.5) - 1\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\ndef read_tfrecord(example):\n    tfrecord_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    return decode_image(example['image'])\n\n\ndef get_dataset(filenames):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=tf.data.AUTOTUNE)\n    return dataset\n\n\nMONET_FILENAMES = tf.io.gfile.glob('/kaggle/input/gan-getting-started/monet_tfrec/*.tfrec')\nPHOTO_FILENAMES = tf.io.gfile.glob('/kaggle/input/gan-getting-started/photo_tfrec/*.tfrec')\n\n\nmonet_ds = get_dataset(MONET_FILENAMES).batch(1)\nphoto_ds = get_dataset(PHOTO_FILENAMES).batch(1)\n\nprint(f\"Monet files found: {len(MONET_FILENAMES)}\")\nprint(f\"Photo files found: {len(PHOTO_FILENAMES)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:00:26.676354Z","iopub.execute_input":"2026-01-08T13:00:26.676598Z","iopub.status.idle":"2026-01-08T13:00:26.782262Z","shell.execute_reply.started":"2026-01-08T13:00:26.676575Z","shell.execute_reply":"2026-01-08T13:00:26.781637Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, Model\nimport numpy as np\n\n\nclass InstanceNormalization(layers.Layer):\n    def __init__(self, epsilon=1e-5):\n        super(InstanceNormalization, self).__init__()\n        self.epsilon = epsilon\n    def build(self, input_shape):\n        self.scale = self.add_weight(name='scale', shape=input_shape[-1:], initializer='ones')\n        self.offset = self.add_weight(name='offset', shape=input_shape[-1:], initializer='zeros')\n    def call(self, x):\n        mean, variance = tf.nn.moments(x, axes=[1, 2], keepdims=True)\n        inv = tf.math.rsqrt(variance + self.epsilon)\n        normalized = (x - mean) * inv\n        return self.scale * normalized + self.offset\n\n# --- 2. U-NET GENERATOR COMPONENTS ---\ndef downsample(filters, size, apply_instancenorm=True):\n    result = tf.keras.Sequential()\n    result.add(layers.Conv2D(filters, size, strides=2, padding='same', use_bias=False))\n    if apply_instancenorm:\n        result.add(InstanceNormalization())\n    result.add(layers.LeakyReLU())\n    return result\n\ndef upsample(filters, size, apply_dropout=False):\n    result = tf.keras.Sequential()\n    result.add(layers.Conv2DTranspose(filters, size, strides=2, padding='same', use_bias=False))\n    result.add(InstanceNormalization())\n    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n    result.add(layers.ReLU())\n    return result\n\ndef Generator():\n    inputs = layers.Input(shape=[256, 256, 3])\n\n    # 1. Encoder (Downsampling)\n    d1 = downsample(64, 4, False)(inputs) # 128x128\n    d2 = downsample(128, 4)(d1)           # 64x64\n    d3 = downsample(256, 4)(d2)           # 32x32\n    d4 = downsample(512, 4)(d3)           # 16x16\n    d5 = downsample(512, 4)(d4)           # 8x8\n    d6 = downsample(512, 4)(d5)           # 4x4\n\n    d7 = downsample(512, 4)(d6)           # Shape: (batch, 2, 2, 512)\n\n   \n    def add_noise(x):\n        noise = tf.random.normal(shape=tf.shape(x))\n        return x + (noise * 0.1)\n\n   \n    d7 = layers.Lambda(add_noise)(d7)\n\n    # --- DECODER ---\n    u1 = upsample(512, 4, apply_dropout=True)(d7) \n    # ... rest of model\n    u1 = upsample(512, 4, apply_dropout=True)(d7) \n    u1 = layers.Concatenate()([u1, d6])\n   \n    \n    u2 = upsample(512, 4, apply_dropout=True)(u1) # 8x8\n    u2 = layers.Concatenate()([u2, d5])\n    \n    u3 = upsample(512, 4, apply_dropout=True)(u2) # 16x16\n    u3 = layers.Concatenate()([u3, d4])\n    \n    u4 = upsample(256, 4)(u3)                     # 32x32\n    u4 = layers.Concatenate()([u4, d3])\n    \n    u5 = upsample(128, 4)(u4)                     # 64x64\n    u5 = layers.Concatenate()([u5, d2])\n    \n    u6 = upsample(64, 4)(u5)                      # 128x128\n    u6 = layers.Concatenate()([u6, d1])\n\n \n    last = layers.Conv2DTranspose(3, 4, strides=2, padding='same', activation='tanh')\n    outputs = last(u6)\n\n    return Model(inputs=inputs, outputs=outputs)\n\ndef Discriminator():\n    inputs = layers.Input(shape=[256, 256, 3])\n    down1 = downsample(64, 4, False)(inputs)\n    down2 = downsample(128, 4)(down1)\n    last = layers.Conv2D(1, 4, strides=1, padding='same')(down2) \n    return Model(inputs=inputs, outputs=last)\n\n\nclass CycleGan(Model):\n    def __init__(self, gen_g, gen_f, disc_x, disc_y, lambda_cycle=7):\n        super(CycleGan, self).__init__()\n        self.gen_g, self.gen_f = gen_g, gen_f\n        self.disc_x, self.disc_y = disc_x, disc_y\n        self.lambda_cycle = lambda_cycle\n\n    def compile(self, g_opt, f_opt, x_opt, y_opt, gen_loss, disc_loss, cycle_loss, id_loss):\n        super(CycleGan, self).compile()\n        self.g_opt, self.f_opt = g_opt, f_opt\n        self.x_opt, self.y_opt = x_opt, y_opt\n        self.gen_loss, self.disc_loss = gen_loss, disc_loss\n        self.cycle_loss, self.id_loss = cycle_loss, id_loss\n\n    @tf.function\n    def train_step(self, batch):\n        real_monet, real_photo = batch\n        \n        with tf.GradientTape(persistent=True) as tape:\n           \n            fake_monet = self.gen_g(real_photo, training=True)\n            cycled_photo = self.gen_f(fake_monet, training=True)\n\n            fake_photo = self.gen_f(real_monet, training=True)\n            cycled_monet = self.gen_g(fake_photo, training=True)\n\n         \n            same_monet = self.gen_g(real_monet, training=True)\n            same_photo = self.gen_f(real_photo, training=True)\n\n   \n            gen_g_loss = self.gen_loss(self.disc_x(fake_monet))\n            gen_f_loss = self.gen_loss(self.disc_y(fake_photo))\n\n            \n            total_cycle_loss = self.cycle_loss(real_monet, cycled_monet, self.lambda_cycle) + \\\n                               self.cycle_loss(real_photo, cycled_photo, self.lambda_cycle)\n\n           \n            total_gen_g_loss = gen_g_loss + total_cycle_loss + self.id_loss(real_monet, same_monet, self.lambda_cycle)\n            total_gen_f_loss = gen_f_loss + total_cycle_loss + self.id_loss(real_photo, same_photo, self.lambda_cycle)\n\n      \n            disc_x_loss = self.disc_loss(self.disc_x(real_monet), self.disc_x(fake_monet))\n            disc_y_loss = self.disc_loss(self.disc_y(real_photo), self.disc_y(fake_photo))\n\n\n        grads_g = tape.gradient(total_gen_g_loss, self.gen_g.trainable_variables)\n        self.g_opt.apply_gradients(zip(grads_g, self.gen_g.trainable_variables))\n\n       \n        grads_f = tape.gradient(total_gen_f_loss, self.gen_f.trainable_variables)\n        self.f_opt.apply_gradients(zip(grads_f, self.gen_f.trainable_variables))\n\n        grads_x = tape.gradient(disc_x_loss, self.disc_x.trainable_variables)\n        self.x_opt.apply_gradients(zip(grads_x, self.disc_x.trainable_variables))\n\n  \n        grads_y = tape.gradient(disc_y_loss, self.disc_y.trainable_variables)\n        self.y_opt.apply_gradients(zip(grads_y, self.disc_y.trainable_variables))\n\n        return {\n            \"g_loss\": total_gen_g_loss,\n            \"f_loss\": total_gen_f_loss,\n            \"disc_x_loss\": disc_x_loss,\n            \"disc_y_loss\": disc_y_loss\n        }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:00:26.783135Z","iopub.execute_input":"2026-01-08T13:00:26.783441Z","iopub.status.idle":"2026-01-08T13:00:26.802679Z","shell.execute_reply.started":"2026-01-08T13:00:26.783418Z","shell.execute_reply":"2026-01-08T13:00:26.802040Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nloss_obj = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n\ndef discriminator_loss(real, generated):\n    real_loss = loss_obj(tf.ones_like(real), real)\n    generated_loss = loss_obj(tf.zeros_like(generated), generated)\n    total_disc_loss = real_loss + generated_loss\n    return total_disc_loss * 0.5\n\ndef generator_loss(generated):\n\n    return loss_obj(tf.ones_like(generated), generated)\n\ndef calc_cycle_loss(real_image, cycled_image, LAMBDA):\n    \n    loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))\n    return LAMBDA * loss1\n\ndef identity_loss(real_image, same_image, LAMBDA):\n  \n    loss = tf.reduce_mean(tf.abs(real_image - same_image))\n    return LAMBDA * 0.1 * loss","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:00:26.804363Z","iopub.execute_input":"2026-01-08T13:00:26.804597Z","iopub.status.idle":"2026-01-08T13:00:26.822125Z","shell.execute_reply.started":"2026-01-08T13:00:26.804577Z","shell.execute_reply":"2026-01-08T13:00:26.821498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\ntry:\n \n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\n    print(\"Running on TPU\")\nexcept ValueError:\n   \n    strategy = tf.distribute.get_strategy() \n    print(\"Running on GPU/CPU\")\n\n# 2. Start the Scope\nwith strategy.scope():\n\n    LAMBDA_VALUE = 5 \n\n\n    m_gen_opt = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    p_gen_opt = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    m_disc_opt = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    p_disc_opt = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n\n   \n    monet_generator = Generator()\n    photo_generator = Generator()\n    monet_discriminator = Discriminator()\n    photo_discriminator = Discriminator()\n\n \n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, \n        monet_discriminator, photo_discriminator,\n        lambda_cycle=LAMBDA_VALUE\n    )\n\n\n    cycle_gan_model.compile(\n        m_gen_opt,\n        p_gen_opt,\n        m_disc_opt,\n        p_disc_opt,\n        generator_loss,\n        discriminator_loss,\n        calc_cycle_loss,\n        identity_loss\n    )\n\n\n    checkpoint_path = \"./checkpoints/train\"\n    ckpt = tf.train.Checkpoint(\n        generator_g=monet_generator,\n        generator_f=photo_generator,\n        discriminator_x=monet_discriminator,\n        discriminator_y=photo_discriminator,\n        gen_g_optimizer=m_gen_opt,\n        gen_f_optimizer=p_gen_opt,\n        disc_x_optimizer=m_disc_opt,\n        disc_y_optimizer=p_disc_opt\n    )\n    ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)\n    \n    if ckpt_manager.latest_checkpoint:\n        ckpt.restore(ckpt_manager.latest_checkpoint)\n        print(\"Restored from checkpoint!\")\n\nMONET_FILENAMES = tf.io.gfile.glob('/kaggle/input/gan-getting-started/monet_tfrec/*.tfrec')\nPHOTO_FILENAMES = tf.io.gfile.glob('/kaggle/input/gan-getting-started/photo_tfrec/*.tfrec')\n\n\nfull_ds = tf.data.Dataset.zip((\n    get_dataset(MONET_FILENAMES).repeat().batch(1), \n    get_dataset(PHOTO_FILENAMES).repeat().batch(1)\n))\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:00:26.822882Z","iopub.execute_input":"2026-01-08T13:00:26.823548Z","iopub.status.idle":"2026-01-08T13:00:27.505675Z","shell.execute_reply.started":"2026-01-08T13:00:26.823527Z","shell.execute_reply":"2026-01-08T13:00:27.505060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nclass GANMonitor(tf.keras.callbacks.Callback):\n    \"\"\"A callback to visualize the model's progress every epoch.\"\"\"\n    \n    def __init__(self, sample_photo, generator_g):\n        self.sample_photo = sample_photo\n        self.generator_g = generator_g\n\n    def on_epoch_end(self, epoch, logs=None):\n\n        prediction = self.generator_g(self.sample_photo, training=False)[0].numpy()\n        \n        prediction = (prediction * 127.5 + 127.5) / 255.0\n        original = (self.sample_photo[0].numpy() * 127.5 + 127.5) / 255.0\n  \n        plt.figure(figsize=(10, 5))\n        \n        plt.subplot(1, 2, 1)\n        plt.title(\"Original Photo\")\n        plt.imshow(original)\n        plt.axis(\"off\")\n        \n        plt.subplot(1, 2, 2)\n        plt.title(f\"Generated Monet (Epoch {epoch+1})\")\n        plt.imshow(prediction)\n        plt.axis(\"off\")\n        \n        plt.show()\n        plt.close()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:00:27.506487Z","iopub.execute_input":"2026-01-08T13:00:27.506691Z","iopub.status.idle":"2026-01-08T13:00:27.513227Z","shell.execute_reply.started":"2026-01-08T13:00:27.506672Z","shell.execute_reply":"2026-01-08T13:00:27.512467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nsample_photo = next(iter(photo_ds.take(3))) \n\n\nplot_callback = GANMonitor(sample_photo, monet_generator)\n\n\ncycle_gan_model.fit(\n    full_ds,\n    epochs=30,\n    steps_per_epoch=300,\n    callbacks=[plot_callback]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:31:40.299837Z","iopub.execute_input":"2026-01-08T13:31:40.300584Z","iopub.status.idle":"2026-01-08T13:31:40.307422Z","shell.execute_reply.started":"2026-01-08T13:31:40.300552Z","shell.execute_reply":"2026-01-08T13:31:40.306310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport os\nimport shutil\nimport PIL\nimport numpy as np\n\n# 1. Reset the directory\noutput_dir = '../images'\nif os.path.exists(output_dir):\n    shutil.rmtree(output_dir)\nos.makedirs(output_dir)\n\nprint(\"Starting inference loop...\")\n\n# 2. Run inference\ni = 0\n# photo_ds must be the dataset you created from PHOTO_FILENAMES\nfor img in photo_ds:\n    # Generate\n    prediction = monet_generator(img, training=False)[0].numpy()\n    \n    # SCALE CHECK: Convert [-1, 1] to [0, 255]\n    # We use np.clip to ensure no values fall outside 0-255 due to float rounding\n    prediction = (prediction * 127.5 + 127.5)\n    prediction = np.clip(prediction, 0, 255).astype(np.uint8)\n    \n    # Save\n    im = PIL.Image.fromarray(prediction)\n    im.save(os.path.join(output_dir, f'{i}.jpg'))\n    \n    i += 1\n    if i % 1000 == 0:\n        print(f\"Generated {i} images...\")\n\nprint(f\"Success! Total images generated: {i}\")\n\n# 3. Create the ZIP (The 'base_dir' argument is key to avoiding subfolders)\nshutil.make_archive('/kaggle/working/images', 'zip', root_dir=output_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:21:08.386977Z","iopub.execute_input":"2026-01-08T13:21:08.387279Z","iopub.status.idle":"2026-01-08T13:26:20.409518Z","shell.execute_reply.started":"2026-01-08T13:21:08.387251Z","shell.execute_reply":"2026-01-08T13:26:20.408751Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimage_count = len(os.listdir('../images'))\nprint(f\"Total images: {image_count}\")\nif image_count != 7038:\n    print(f\"❌ Error: You have {image_count} images, but need 7038.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:30:32.495551Z","iopub.execute_input":"2026-01-08T13:30:32.495809Z","iopub.status.idle":"2026-01-08T13:30:32.505027Z","shell.execute_reply.started":"2026-01-08T13:30:32.495789Z","shell.execute_reply":"2026-01-08T13:30:32.504388Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import matplotlib.pyplot as plt\n# import os\n\n# def verify_submission(image_dir='../images'):\n#     files = os.listdir(image_dir)[20:25] # Get first 5 files\n#     plt.figure(figsize=(20, 10))\n    \n#     for i, file in enumerate(files):\n#         img = PIL.Image.open(os.path.join(image_dir, file))\n#         plt.subplot(1, 5, i + 1)\n#         plt.imshow(img)\n#         plt.title(f\"File: {file}\")\n#         plt.axis('off')\n#     plt.show()\n\n# verify_submission()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-08T13:30:56.963215Z","iopub.execute_input":"2026-01-08T13:30:56.964105Z","iopub.status.idle":"2026-01-08T13:30:56.985285Z","shell.execute_reply.started":"2026-01-08T13:30:56.964059Z","shell.execute_reply":"2026-01-08T13:30:56.984319Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}