{"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-20T03:20:42.284321Z","iopub.execute_input":"2024-12-20T03:20:42.284858Z","iopub.status.idle":"2024-12-20T03:20:53.937572Z","shell.execute_reply.started":"2024-12-20T03:20:42.284805Z","shell.execute_reply":"2024-12-20T03:20:53.936168Z"}},"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-20T03:20:53.939963Z","iopub.execute_input":"2024-12-20T03:20:53.940438Z","iopub.status.idle":"2024-12-20T03:21:16.105999Z","shell.execute_reply.started":"2024-12-20T03:20:53.940402Z","shell.execute_reply":"2024-12-20T03:21:16.104848Z"}},"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-20T03:21:16.107286Z","iopub.execute_input":"2024-12-20T03:21:16.107894Z","iopub.status.idle":"2024-12-20T03:21:16.119232Z","shell.execute_reply.started":"2024-12-20T03:21:16.107856Z","shell.execute_reply":"2024-12-20T03:21:16.118160Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T03:21:16.120619Z","iopub.execute_input":"2024-12-20T03:21:16.121060Z","iopub.status.idle":"2024-12-20T03:21:16.596187Z","shell.execute_reply.started":"2024-12-20T03:21:16.121017Z","shell.execute_reply":"2024-12-20T03:21:16.595120Z"}},"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-20T03:21:16.598691Z","iopub.execute_input":"2024-12-20T03:21:16.599097Z","iopub.status.idle":"2024-12-20T03:21:17.049933Z","shell.execute_reply.started":"2024-12-20T03:21:16.599062Z","shell.execute_reply":"2024-12-20T03:21:17.048628Z"}},"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-20T03:21:17.051199Z","iopub.execute_input":"2024-12-20T03:21:17.051520Z","iopub.status.idle":"2024-12-20T03:21:17.058954Z","shell.execute_reply.started":"2024-12-20T03:21:17.051489Z","shell.execute_reply":"2024-12-20T03:21:17.057749Z"}},"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-20T03:21:17.060390Z","iopub.execute_input":"2024-12-20T03:21:17.060766Z","iopub.status.idle":"2024-12-20T03:21:17.084605Z","shell.execute_reply.started":"2024-12-20T03:21:17.060734Z","shell.execute_reply":"2024-12-20T03:21:17.083484Z"}},"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-20T03:21:17.085816Z","iopub.execute_input":"2024-12-20T03:21:17.086114Z","iopub.status.idle":"2024-12-20T03:21:17.309545Z","shell.execute_reply.started":"2024-12-20T03:21:17.086086Z","shell.execute_reply":"2024-12-20T03:21:17.308340Z"}},"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-20T03:21:17.310780Z","iopub.execute_input":"2024-12-20T03:21:17.311129Z","iopub.status.idle":"2024-12-20T03:21:22.999195Z","shell.execute_reply.started":"2024-12-20T03:21:17.311096Z","shell.execute_reply":"2024-12-20T03:21:22.998102Z"}},"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-20T03:21:23.000542Z","iopub.execute_input":"2024-12-20T03:21:23.001460Z","iopub.status.idle":"2024-12-20T03:21:23.585620Z","shell.execute_reply.started":"2024-12-20T03:21:23.001420Z","shell.execute_reply":"2024-12-20T03:21:23.584139Z"}},"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-20T03:21:23.587402Z","iopub.execute_input":"2024-12-20T03:21:23.588010Z","iopub.status.idle":"2024-12-20T03:21:31.885276Z","shell.execute_reply.started":"2024-12-20T03:21:23.587958Z","shell.execute_reply":"2024-12-20T03:21:31.883875Z"}},"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-20T03:21:31.886915Z","iopub.execute_input":"2024-12-20T03:21:31.887414Z","iopub.status.idle":"2024-12-20T03:21:31.896233Z","shell.execute_reply.started":"2024-12-20T03:21:31.887362Z","shell.execute_reply":"2024-12-20T03:21:31.894747Z"}},"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-20T03:21:31.898021Z","iopub.execute_input":"2024-12-20T03:21:31.898368Z","iopub.status.idle":"2024-12-20T03:21:31.914252Z","shell.execute_reply.started":"2024-12-20T03:21:31.898325Z","shell.execute_reply":"2024-12-20T03:21:31.912980Z"}},"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-20T03:21:31.918098Z","iopub.execute_input":"2024-12-20T03:21:31.918463Z","iopub.status.idle":"2024-12-20T03:21:31.929966Z","shell.execute_reply.started":"2024-12-20T03:21:31.918411Z","shell.execute_reply":"2024-12-20T03:21:31.928716Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install pydot","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T03:21:31.931372Z","iopub.execute_input":"2024-12-20T03:21:31.931781Z","iopub.status.idle":"2024-12-20T03:21:44.770120Z","shell.execute_reply.started":"2024-12-20T03:21:31.931745Z","shell.execute_reply":"2024-12-20T03:21:44.768324Z"}},"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-20T03:21:44.772160Z","iopub.execute_input":"2024-12-20T03:21:44.772721Z","iopub.status.idle":"2024-12-20T03:21:46.239180Z","shell.execute_reply.started":"2024-12-20T03:21:44.772648Z","shell.execute_reply":"2024-12-20T03:21:46.237951Z"}},"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-20T03:21:46.240431Z","iopub.execute_input":"2024-12-20T03:21:46.240761Z","iopub.status.idle":"2024-12-20T03:21:46.250887Z","shell.execute_reply.started":"2024-12-20T03:21:46.240732Z","shell.execute_reply":"2024-12-20T03:21:46.249582Z"}},"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-20T03:21:46.252183Z","iopub.execute_input":"2024-12-20T03:21:46.252491Z","iopub.status.idle":"2024-12-20T03:21:46.472989Z","shell.execute_reply.started":"2024-12-20T03:21:46.252462Z","shell.execute_reply":"2024-12-20T03:21:46.471827Z"}},"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-20T03:21:46.474474Z","iopub.execute_input":"2024-12-20T03:21:46.474946Z","iopub.status.idle":"2024-12-20T03:21:48.442582Z","shell.execute_reply.started":"2024-12-20T03:21:46.474895Z","shell.execute_reply":"2024-12-20T03:21:48.441565Z"}},"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-20T03:21:48.443951Z","iopub.execute_input":"2024-12-20T03:21:48.444287Z","iopub.status.idle":"2024-12-20T03:21:49.335630Z","shell.execute_reply.started":"2024-12-20T03:21:48.444255Z","shell.execute_reply":"2024-12-20T03:21:49.334445Z"}},"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-20T03:21:49.337256Z","iopub.execute_input":"2024-12-20T03:21:49.337744Z","iopub.status.idle":"2024-12-20T03:21:49.347531Z","shell.execute_reply.started":"2024-12-20T03:21:49.337693Z","shell.execute_reply":"2024-12-20T03:21:49.346154Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}