{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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 example, 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        if not filename.endswith('.jpg'):  # Skip files with '.jpg' extension\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\n\n# modal path: /kaggle/input/0731a/pytorch/default/1/view","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:35.950359Z","iopub.execute_input":"2024-12-19T08:54:35.952591Z","iopub.status.idle":"2024-12-19T08:54:39.213048Z","shell.execute_reply.started":"2024-12-19T08:54:35.952499Z","shell.execute_reply":"2024-12-19T08:54:39.211417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:39.216179Z","iopub.execute_input":"2024-12-19T08:54:39.216588Z","iopub.status.idle":"2024-12-19T08:54:39.223836Z","shell.execute_reply.started":"2024-12-19T08:54:39.216551Z","shell.execute_reply":"2024-12-19T08:54:39.222423Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n        if tf.config.list_physical_devices('GPU'):\n            strategy = tf.distribute.MirroredStrategy()\n            print(\"Running on GPU.\")\n        else:\n            strategy = tf.distribute.get_strategy()\n            print(\"Running on CPU.\")\n\nprint('Number of replicas:', strategy.num_replicas_in_sync)\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n    \nprint(tf.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:39.225708Z","iopub.execute_input":"2024-12-19T08:54:39.226180Z","iopub.status.idle":"2024-12-19T08:54:39.250470Z","shell.execute_reply.started":"2024-12-19T08:54:39.226140Z","shell.execute_reply":"2024-12-19T08:54:39.248840Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:39.252368Z","iopub.execute_input":"2024-12-19T08:54:39.252788Z","iopub.status.idle":"2024-12-19T08:54:39.656286Z","shell.execute_reply.started":"2024-12-19T08:54:39.252752Z","shell.execute_reply":"2024-12-19T08:54:39.654208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"MONET_FILENAMES = tf.io.gfile.glob(str(GCS_PATH + '/monet_tfrec/*.tfrec'))\nprint('Monet TFRecord Files:', len(MONET_FILENAMES))\n\nPHOTO_FILENAMES = tf.io.gfile.glob(str(GCS_PATH + '/photo_tfrec/*.tfrec'))\nprint('Photo TFRecord Files:', len(PHOTO_FILENAMES))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:39.659921Z","iopub.execute_input":"2024-12-19T08:54:39.660392Z","iopub.status.idle":"2024-12-19T08:54:41.278775Z","shell.execute_reply.started":"2024-12-19T08:54:39.660353Z","shell.execute_reply":"2024-12-19T08:54:41.277541Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = [256, 256]\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_name\": tf.io.FixedLenFeature([], tf.string),\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"target\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example['image'])\n    return image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:41.280619Z","iopub.execute_input":"2024-12-19T08:54:41.281157Z","iopub.status.idle":"2024-12-19T08:54:41.291931Z","shell.execute_reply.started":"2024-12-19T08:54:41.281101Z","shell.execute_reply":"2024-12-19T08:54:41.290375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dataset(filenames, labeled=True, ordered=False):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:41.293821Z","iopub.execute_input":"2024-12-19T08:54:41.294235Z","iopub.status.idle":"2024-12-19T08:54:41.307381Z","shell.execute_reply.started":"2024-12-19T08:54:41.294198Z","shell.execute_reply":"2024-12-19T08:54:41.305453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"monet_ds = load_dataset(MONET_FILENAMES, labeled=True).batch(1)\nphoto_ds = load_dataset(PHOTO_FILENAMES, labeled=True).batch(1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:41.308989Z","iopub.execute_input":"2024-12-19T08:54:41.310321Z","iopub.status.idle":"2024-12-19T08:54:41.458858Z","shell.execute_reply.started":"2024-12-19T08:54:41.310261Z","shell.execute_reply":"2024-12-19T08:54:41.457402Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# pick a monet picture and a photo from the data sets\nexample_monet = next(iter(monet_ds))\nexample_photo = next(iter(photo_ds))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:41.460512Z","iopub.execute_input":"2024-12-19T08:54:41.460877Z","iopub.status.idle":"2024-12-19T08:54:44.499987Z","shell.execute_reply.started":"2024-12-19T08:54:41.460842Z","shell.execute_reply":"2024-12-19T08:54:44.498265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.subplot(121)\nplt.title('Photo')\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(122)\nplt.title('Monet')\nplt.imshow(example_monet[0] * 0.5 + 0.5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:44.502749Z","iopub.execute_input":"2024-12-19T08:54:44.503307Z","iopub.status.idle":"2024-12-19T08:54:45.215982Z","shell.execute_reply.started":"2024-12-19T08:54:44.503264Z","shell.execute_reply":"2024-12-19T08:54:45.213821Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"MONET_JPG = tf.io.gfile.glob(str(GCS_PATH + '/monet_jpg/*.jpg'))\nPHOTO_JPG = tf.io.gfile.glob(str(GCS_PATH + '/photo_jpg/*.jpg')) \n\n# Display number of files in Monet and Photo directories\nprint('Number of images in Monet directory: ', len(MONET_JPG))\nprint('Number of images in photo directory: ', len(PHOTO_JPG))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:45.217791Z","iopub.execute_input":"2024-12-19T08:54:45.218356Z","iopub.status.idle":"2024-12-19T08:54:51.253212Z","shell.execute_reply.started":"2024-12-19T08:54:45.218301Z","shell.execute_reply":"2024-12-19T08:54:51.251466Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"OUTPUT_CHANNELS = 3\n\ndef downsample(filters, size, apply_instancenorm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2D(filters, size, strides=2, padding='same',\n                             kernel_initializer=initializer, use_bias=False))\n\n    if apply_instancenorm:\n        result.add(tf.keras.layers.GroupNormalization(gamma_initializer=gamma_init, groups = -1))\n\n    result.add(layers.LeakyReLU())\n\n    return result","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:51.255231Z","iopub.execute_input":"2024-12-19T08:54:51.255690Z","iopub.status.idle":"2024-12-19T08:54:51.263423Z","shell.execute_reply.started":"2024-12-19T08:54:51.255652Z","shell.execute_reply":"2024-12-19T08:54:51.262113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def upsample(filters, size, apply_dropout=False):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2DTranspose(filters, size, strides=2,\n                                      padding='same',\n                                      kernel_initializer=initializer,\n                                      use_bias=False))\n\n    result.add(tf.keras.layers.GroupNormalization(gamma_initializer=gamma_init, groups=-1))\n\n    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n\n    result.add(layers.ReLU())\n\n    return result","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:51.264957Z","iopub.execute_input":"2024-12-19T08:54:51.265379Z","iopub.status.idle":"2024-12-19T08:54:51.299529Z","shell.execute_reply.started":"2024-12-19T08:54:51.265341Z","shell.execute_reply":"2024-12-19T08:54:51.297934Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input(shape=[256,256,3])\n\n    # bs = batch size\n    down_stack = [\n        downsample(64, 4, apply_instancenorm=False), # (bs, 128, 128, 64)\n        downsample(128, 4), # (bs, 64, 64, 128)\n        downsample(256, 4), # (bs, 32, 32, 256)\n        downsample(512, 4), # (bs, 16, 16, 512)\n        downsample(512, 4), # (bs, 8, 8, 512)\n        downsample(512, 4), # (bs, 4, 4, 512)\n        downsample(512, 4), # (bs, 2, 2, 512)\n        downsample(512, 4), # (bs, 1, 1, 512)\n    ]\n\n    up_stack = [\n        upsample(512, 4, apply_dropout=True), # (bs, 2, 2, 1024)\n        upsample(512, 4, apply_dropout=True), # (bs, 4, 4, 1024)\n        upsample(512, 4, apply_dropout=True), # (bs, 8, 8, 1024)\n        upsample(512, 4), # (bs, 16, 16, 1024)\n        upsample(256, 4), # (bs, 32, 32, 512)\n        upsample(128, 4), # (bs, 64, 64, 256)\n        upsample(64, 4), # (bs, 128, 128, 128)\n    ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last = layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,\n                                  strides=2,\n                                  padding='same',\n                                  kernel_initializer=initializer,\n                                  activation='tanh') # (bs, 256, 256, 3)\n\n    x = inputs\n\n    # Downsampling through the model\n    skips = []\n    for down in down_stack:\n        x = down(x)\n        skips.append(x)\n\n    skips = reversed(skips[:-1])\n\n    # Upsampling and establishing the skip connections\n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = layers.Concatenate()([x, skip])\n\n    x = last(x)\n\n    return keras.Model(inputs=inputs, outputs=x)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:51.303053Z","iopub.execute_input":"2024-12-19T08:54:51.304283Z","iopub.status.idle":"2024-12-19T08:54:51.328437Z","shell.execute_reply.started":"2024-12-19T08:54:51.304224Z","shell.execute_reply":"2024-12-19T08:54:51.326984Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install pydot","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:54:51.330188Z","iopub.execute_input":"2024-12-19T08:54:51.330697Z","iopub.status.idle":"2024-12-19T08:55:03.547311Z","shell.execute_reply.started":"2024-12-19T08:54:51.330646Z","shell.execute_reply":"2024-12-19T08:55:03.545439Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"generator = Generator()\ntf.keras.utils.plot_model(generator, show_shapes=True, dpi=64)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:55:03.550054Z","iopub.execute_input":"2024-12-19T08:55:03.551687Z","iopub.status.idle":"2024-12-19T08:55:04.921235Z","shell.execute_reply.started":"2024-12-19T08:55:03.551609Z","shell.execute_reply":"2024-12-19T08:55:04.919455Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    inp = layers.Input(shape=[256, 256, 3], name='input_image')\n\n    x = inp\n\n    down1 = downsample(64, 4, False)(x) # (bs, 128, 128, 64)\n    down2 = downsample(128, 4)(down1) # (bs, 64, 64, 128)\n    down3 = downsample(256, 4)(down2) # (bs, 32, 32, 256)\n\n    zero_pad1 = layers.ZeroPadding2D()(down3) # (bs, 34, 34, 256)\n    conv = layers.Conv2D(512, 4, strides=1,\n                         kernel_initializer=initializer,\n                         use_bias=False)(zero_pad1) # (bs, 31, 31, 512)\n\n    norm1 = tf.keras.layers.GroupNormalization(gamma_initializer=gamma_init, groups=-1)(conv)\n\n    leaky_relu = layers.LeakyReLU()(norm1)\n\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu) # (bs, 33, 33, 512)\n\n    last = layers.Conv2D(1, 4, strides=1,\n                         kernel_initializer=initializer)(zero_pad2) # (bs, 30, 30, 1)\n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:55:04.922960Z","iopub.execute_input":"2024-12-19T08:55:04.924727Z","iopub.status.idle":"2024-12-19T08:55:04.940166Z","shell.execute_reply.started":"2024-12-19T08:55:04.924610Z","shell.execute_reply":"2024-12-19T08:55:04.938045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"discriminator = Discriminator()\ntf.keras.utils.plot_model(discriminator, show_shapes=True, dpi=64)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:55:04.941621Z","iopub.execute_input":"2024-12-19T08:55:04.942176Z","iopub.status.idle":"2024-12-19T08:55:05.213442Z","shell.execute_reply.started":"2024-12-19T08:55:04.942114Z","shell.execute_reply":"2024-12-19T08:55:05.212020Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator() # transforms photos to Monet-esque paintings\n    photo_generator = Generator() # transforms Monet paintings to be more like photos\n\n    monet_discriminator = Discriminator() # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = Discriminator() # differentiates real photos and generated photos","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:55:05.214963Z","iopub.execute_input":"2024-12-19T08:55:05.215455Z","iopub.status.idle":"2024-12-19T08:55:07.750200Z","shell.execute_reply.started":"2024-12-19T08:55:05.215405Z","shell.execute_reply":"2024-12-19T08:55:07.748060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"to_monet = monet_generator(example_photo)\n\nplt.subplot(1, 2, 1)\nplt.title(\"Original Photo\")\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(1, 2, 2)\nplt.title(\"Untrained Monet style Photo\")\nplt.imshow(to_monet[0] * 0.5 + 0.5)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:55:07.751993Z","iopub.execute_input":"2024-12-19T08:55:07.752440Z","iopub.status.idle":"2024-12-19T08:55:08.632481Z","shell.execute_reply.started":"2024-12-19T08:55:07.752402Z","shell.execute_reply":"2024-12-19T08:55:08.630982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\nshutil.make_archive(\"/kaggle/working/images\", 'zip', \"/kaggle/images\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-19T08:55:08.634694Z","iopub.execute_input":"2024-12-19T08:55:08.635273Z","iopub.status.idle":"2024-12-19T08:55:08.651285Z","shell.execute_reply.started":"2024-12-19T08:55:08.635219Z","shell.execute_reply":"2024-12-19T08:55:08.649829Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}