{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport shutil\nimport glob\nimport random\nimport tqdm\nimport numpy as np\nimport torch\nfrom torch import nn, Tensor\nfrom torchvision.utils import save_image, make_grid\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"","metadata":{"execution":{"iopub.status.busy":"2024-08-03T03:35:33.840852Z","iopub.execute_input":"2024-08-03T03:35:33.841183Z","iopub.status.idle":"2024-08-03T03:35:38.458700Z","shell.execute_reply.started":"2024-08-03T03:35:33.841158Z","shell.execute_reply":"2024-08-03T03:35:38.457865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if not os.path.exists('dataset'):\n  os.mkdir(\"dataset\")","metadata":{"execution":{"iopub.status.busy":"2024-08-03T03:35:38.460516Z","iopub.execute_input":"2024-08-03T03:35:38.461102Z","iopub.status.idle":"2024-08-03T03:35:38.465866Z","shell.execute_reply.started":"2024-08-03T03:35:38.461075Z","shell.execute_reply":"2024-08-03T03:35:38.464908Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\n\n# Define the directories for Monet and photo images\nmonet_images_dir = '/kaggle/input/gan-getting-started/monet_jpg'\nphoto_images_dir = '/kaggle/input/gan-getting-started/photo_jpg'\n\n# Create new directories for renamed images\nnew_monet_dir = 'monet_jpg'\nnew_photo_dir = 'photo_jpg'\n\nos.makedirs(new_monet_dir, exist_ok=True)\nos.makedirs(new_photo_dir, exist_ok=True)\n\n# Function to change file names\ndef change_file_name(folder_dir, new_folder_dir):\n    files = os.listdir(folder_dir)\n    for index, filename in enumerate(files):\n        old_filename = os.path.join(folder_dir, filename)\n        new_filename = os.path.join(new_folder_dir, f'{index}.jpg')\n        shutil.copyfile(old_filename, new_filename)\n\n# Change file names for Monet and photo images\nchange_file_name(monet_images_dir, new_monet_dir)\nchange_file_name(photo_images_dir, new_photo_dir)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-03T03:35:38.467112Z","iopub.execute_input":"2024-08-03T03:35:38.467449Z","iopub.status.idle":"2024-08-03T03:36:19.003807Z","shell.execute_reply.started":"2024-08-03T03:35:38.467420Z","shell.execute_reply":"2024-08-03T03:36:19.002955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(os.listdir('monet_jpg')))\nprint(len(os.listdir('photo_jpg')))","metadata":{"execution":{"iopub.status.busy":"2024-08-03T03:36:19.004856Z","iopub.execute_input":"2024-08-03T03:36:19.005131Z","iopub.status.idle":"2024-08-03T03:36:19.014875Z","shell.execute_reply.started":"2024-08-03T03:36:19.005107Z","shell.execute_reply":"2024-08-03T03:36:19.014033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\nimport random\n\n# Define the main dataset directory\ndataset_dir = 'dataset'\n\n# Create train and test directories\ntrain_dir = os.path.join(dataset_dir, 'train')\ntest_dir = os.path.join(dataset_dir, 'test')\n\nos.makedirs(train_dir, exist_ok=True)\nos.makedirs(test_dir, exist_ok=True)\n\ndef split_data(source_dir, train_dir, test_dir, train_ratio=0.8):\n    # Ensure destination directories exist\n    os.makedirs(train_dir, exist_ok=True)\n    os.makedirs(test_dir, exist_ok=True)\n\n    # List all files in the source directory\n    files = os.listdir(source_dir)\n    # Shuffle the files to ensure random distribution\n    random.shuffle(files)\n\n    # Calculate the split index\n    split_index = int(len(files) * train_ratio)\n\n    # Split the files into train and test sets\n    train_files = files[:split_index]\n    test_files = files[split_index:]\n\n    # Move files to the training directory\n    for file_name in train_files:\n        src_file = os.path.join(source_dir, file_name)\n        dst_file = os.path.join(train_dir, file_name)\n        shutil.move(src_file, dst_file)\n        print(f\"Moved '{file_name}' to train folder\")\n\n    # Move files to the testing directory\n    for file_name in test_files:\n        src_file = os.path.join(source_dir, file_name)\n        dst_file = os.path.join(test_dir, file_name)\n        shutil.move(src_file, dst_file)\n        print(f\"Moved '{file_name}' to test folder\")\n\n# Use the function with the path to the source, train, and test directories\n# Monet\nsource_monet_dir = 'monet_jpg'\ntrain_monet_dir = os.path.join(train_dir, 'monet')\ntest_monet_dir = os.path.join(test_dir, 'monet')\nsplit_data(source_monet_dir, train_monet_dir, test_monet_dir)\n\n# Photo\nsource_photo_dir = 'photo_jpg'\ntrain_photo_dir = os.path.join(train_dir, 'photo')\ntest_photo_dir = os.path.join(test_dir, 'photo')\nsplit_data(source_photo_dir, train_photo_dir, test_photo_dir)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-03T03:36:19.018138Z","iopub.execute_input":"2024-08-03T03:36:19.018698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(os.listdir(\"dataset\"))\nprint(os.listdir(\"dataset/train\"))\nprint(len(os.listdir(\"dataset/train/photo\")))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torchvision\nfrom torch.utils.data import Dataset\nfrom PIL import Image","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ImageDataset(Dataset):\n    def __init__(self, root, transforms=None, unaligned=False, split=\"train\"):\n        self.transform = torchvision.transforms.Compose(transforms)\n        self.unaligned = unaligned\n\n        self.files_A = sorted(glob.glob(os.path.join(root, f\"{split}/monet\") + \"/*.*\"))\n        self.files_B = sorted(glob.glob(os.path.join(root, f\"{split}/photo\") + \"/*.*\"))\n\n    def __getitem__(self, index):\n        image_A = Image.open(self.files_A[index % len(self.files_A)])\n\n        if self.unaligned:\n            image_B = Image.open(self.files_B[random.randint(0, len(self.files_B) - 1)])\n        else:\n            image_B = Image.open(self.files_B[index % len(self.files_B)])\n\n        # grayscale to rgb\n        if image_A.mode != \"RGB\":\n            image_A = self.to_rgb(image_A)\n        if image_B.mode != \"RGB\":\n            image_B = self.to_rgb(image_B)\n\n        item_A = self.transform(image_A)\n        item_B = self.transform(image_B)\n        return {\"A\": item_A, \"B\": item_B}\n\n    def __len__(self):\n        return max(len(self.files_A), len(self.files_B))\n\n\n    def _to_rgb(self, image):\n        rgb_image = Image.new(\"RGB\", image.size)\n        rgb_image.paste(image)\n        return rgb_image","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_height = 256\nimg_width = 256\n\ntransforms = [\n    torchvision.transforms.Resize(int(img_height * 1.12), Image.BICUBIC),\n    torchvision.transforms.RandomCrop((img_height, img_width)),\n    # torchvision.transforms.RandomHorizontalFlip(),\n    torchvision.transforms.ToTensor(),\n    torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n]\n\n\ntrain_set = ImageDataset(f\"dataset\", transforms=transforms, unaligned=True, split=\"train\")\ntest_set = ImageDataset(f\"dataset\", transforms=transforms, unaligned=True, split=\"test\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import DataLoader\n\nBATCH_SIZE = 8\ntrain_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\nval_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=2)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ResidualBlock(nn.Module):\n  def __init__(self,in_features):\n    super().__init__()\n    self.block = nn.Sequential(\n        nn.ReflectionPad2d(1),\n        nn.Conv2d(in_features,in_features,3),\n        nn.InstanceNorm2d(in_features),\n        nn.ReLU(inplace=True),\n        nn.ReflectionPad2d(1),\n        nn.Conv2d(in_features,in_features,3),\n        nn.InstanceNorm2d(in_features)\n    )\n  def forward(self,x):\n    return x + self.block(x)\n\nclass Generator(nn.Module):\n  def __init__(self,input_shape, num_residual_blocks):\n    super().__init__()\n    channels = input_shape[0]\n    out_features = 64\n    model = [nn.ReflectionPad2d(channels),\n             nn.Conv2d(channels,out_features,7),\n             nn.InstanceNorm2d(out_features),\n             nn.ReLU(inplace=True),]\n\n    in_features = out_features\n\n    # Downsampling\n    for _ in range(2):\n      out_features *= 2\n      model += [\n          nn.Conv2d(in_features,out_features, kernel_size=3, stride=2,padding=1),\n          nn.InstanceNorm2d(out_features),\n          nn.ReLU(inplace=True)\n      ]\n      in_features = out_features\n\n    # Residual blocks\n    for _ in range(num_residual_blocks):\n      model += [ResidualBlock(out_features)]\n\n    # Upsampling\n    for _ in range(2):\n      out_features //= 2\n      model += [\n          nn.Upsample(scale_factor=2),\n          nn.Conv2d(in_features,out_features, kernel_size=3, stride=1,padding=1),\n          nn.InstanceNorm2d(out_features),\n          nn.ReLU(inplace=True),\n      ]\n      in_features = out_features\n\n    model += [nn.ReflectionPad2d(channels),\n              nn.Conv2d(out_features,channels, kernel_size=7),\n              nn.Tanh()]\n    self.model = nn.Sequential(*model)\n\n  def forward(self,x):\n    return self.model(x)\n\nclass Discriminator(nn.Module):\n  def __init__(self,input_shape):\n    super().__init__()\n    channels, height, width = input_shape\n    self.output_shape = (1, height // 2 ** 4, width // 2 ** 4)\n\n    def discriminator_block(in_features, out_features, normalize=True):\n      layers = [nn.Conv2d(in_features,out_features,kernel_size=4,stride=2,padding=1)]\n      if normalize :\n        layers.append(nn.InstanceNorm2d(out_features))\n      layers.append(nn.LeakyReLU(0.2,inplace=True))\n      return layers\n\n    self.model = nn.Sequential(\n        *discriminator_block(channels,64,normalize=False),\n        *discriminator_block(64,128),\n        *discriminator_block(128,256),\n        *discriminator_block(256,512),\n        nn.ZeroPad2d((1,0,1,0)),\n        nn.Conv2d(512,1,4,padding=1),\n    )\n\n  def forward(self,image):\n    return self.model(image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape = (3,img_height,img_width)\nnum_residual_blocks = 3\n\nG_AB = Generator(input_shape,num_residual_blocks).to(device)\nG_BA = Generator(input_shape,num_residual_blocks).to(device)\nD_A = Discriminator(input_shape).to(device)\nD_B = Discriminator(input_shape).to(device)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ReplayBuffer:\n    def __init__(self, max_size=50):\n        assert max_size > 0, \"Empty buffer or trying to create a black hole. Be careful.\"\n        self.max_size = max_size\n        self.data = []\n\n    def push_and_pop(self, data):\n        to_return = []\n        for element in data.data:\n            element = torch.unsqueeze(element, 0)\n            if len(self.data) < self.max_size:\n                self.data.append(element)\n                to_return.append(element)\n            else:\n                if random.uniform(0, 1) > 0.5:\n                    i = random.randint(0, self.max_size - 1)\n                    to_return.append(self.data[i].clone())\n                    self.data[i] = element\n                else:\n                    to_return.append(element)\n        return torch.cat(to_return)\n\n\ndef sample_images(batches_done):\n    \"\"\"Saves a generated sample from the validation set\"\"\"\n    G_AB.eval()\n    G_BA.eval()\n    imgs = next(iter(val_loader))\n    real_A = imgs[\"B\"][:5, ...].to(device)\n    fake_B = G_AB(real_A)\n    real_B = imgs[\"A\"][:5, ...].to(device)\n    fake_A = G_BA(real_B)\n\n    real_A = make_grid(real_A, nrow=5, normalize=True)\n    real_B = make_grid(real_B, nrow=5, normalize=True)\n    fake_A = make_grid(fake_A, nrow=5, normalize=True)\n    fake_B = make_grid(fake_B, nrow=5, normalize=True)\n    image_grid = torch.cat((real_A, fake_B, real_B, fake_A), 1)\n    save_image(image_grid, f\"training_result/{batches_done}.png\", normalize=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import itertools\n\nLR = 0.0002\n\noptimizer_G = torch.optim.Adam(\n    itertools.chain(G_AB.parameters(), G_BA.parameters()),\n    lr=LR, betas=(0.5, 0.999)\n)\n\noptimizer_D_A = torch.optim.Adam(D_A.parameters(), lr=LR, betas=(0.5, 0.999))\noptimizer_D_B = torch.optim.Adam(D_B.parameters(), lr=LR, betas=(0.5, 0.999))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"criterion_GAN = torch.nn.MSELoss()\ncriterion_cycle = torch.nn.L1Loss()\ncriterion_identity = torch.nn.L1Loss()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 3\nsave_interval = 10\nlambda_cyc = 10\nlambda_id = 5\n\nfake_A_buffer = ReplayBuffer()\nfake_B_buffer = ReplayBuffer()\n\nhist = {\n        \"train_G_loss\": [],\n        \"train_D_loss\": [],\n}\n\nif not os.path.exists(\"training_result\"):\n    os.makedirs(\"training_result\")\n        \n        \nfor epoch in range(EPOCHS):\n    running_G_loss = 0.0\n    running_D_loss = 0.0\n\n    for batch in tqdm.tqdm(train_loader, total=len(train_loader)):\n\n        real_imgs_A = batch[\"B\"].to(device)\n        real_imgs_B = batch[\"A\"].to(device)\n\n        valid = Tensor(np.ones((real_imgs_A.size(0), *D_A.output_shape))).to(device)\n        fake = Tensor(np.zeros((real_imgs_A.size(0), *D_A.output_shape))).to(device)\n\n        # --- Train Generator ---\n        G_AB.train()\n        G_BA.train()\n        optimizer_G.zero_grad()\n\n        # Identity loss\n        loss_id_A = criterion_identity(G_BA(real_imgs_A), real_imgs_A)\n        loss_id_B = criterion_identity(G_AB(real_imgs_B), real_imgs_B)\n        loss_identity = (loss_id_A + loss_id_B) / 2\n\n        # GAN loss\n        fake_imgs_B = G_AB(real_imgs_A)\n        loss_GAN_AB = criterion_GAN(D_B(fake_imgs_B), valid)\n        fake_imgs_A = G_BA(real_imgs_B)\n        loss_GAN_BA = criterion_GAN(D_A(fake_imgs_A), valid)\n        loss_GAN = (loss_GAN_AB + loss_GAN_BA) / 2\n\n        # Cycle loss\n        recovered_imgs_A = G_BA(fake_imgs_B)\n        loss_cycle_A = criterion_cycle(recovered_imgs_A, real_imgs_A)\n        recovered_imgs_B = G_AB(fake_imgs_A)\n        loss_cycle_B = criterion_cycle(recovered_imgs_B, real_imgs_B)\n        loss_cycle = (loss_cycle_A + loss_cycle_B) / 2\n\n        # Total loss\n        loss_G = loss_GAN + loss_cycle*lambda_cyc + loss_identity*lambda_id\n        running_G_loss += loss_G.item()\n        loss_G.backward()\n        optimizer_G.step()\n\n\n        # --- Train Discriminator A ---\n        optimizer_D_A.zero_grad()\n\n        loss_real = criterion_GAN(D_A(real_imgs_A), valid)\n\n        fake_A_ = fake_A_buffer.push_and_pop(fake_imgs_A)\n        loss_fake = criterion_GAN(D_A(fake_A_), fake)\n\n        loss_D_A = (loss_real + loss_fake) / 2\n        loss_D_A.backward()\n        optimizer_D_A.step()\n\n        # --- Train Discriminator B ---\n        optimizer_D_B.zero_grad()\n\n        loss_real = criterion_GAN(D_B(real_imgs_B), valid)\n\n        fake_B_ = fake_B_buffer.push_and_pop(fake_imgs_B)\n        loss_fake = criterion_GAN(D_B(fake_B_), fake)\n\n        loss_D_B = (loss_real + loss_fake) / 2\n        loss_D_B.backward()\n        optimizer_D_B.step()\n\n        # Total loss\n        loss_D = (loss_D_A + loss_D_B) / 2\n        running_D_loss += loss_D.item()\n\n    epoch_G_loss = running_G_loss / len(train_loader)\n    epoch_D_loss = running_D_loss / len(train_loader)\n\n    print(f\"Epoch [{epoch + 1}/{EPOCHS}], Train G Loss: {epoch_G_loss:.4f}, Train D Loss: {epoch_D_loss:.4f}\")\n\n    hist[\"train_G_loss\"].append(epoch_G_loss)\n    hist[\"train_D_loss\"].append(epoch_D_loss)\n\n    if epoch % save_interval == 0:\n        sample_images(epoch)\n","metadata":{"execution":{"iopub.status.idle":"2024-08-03T05:16:47.901168Z","shell.execute_reply.started":"2024-08-03T03:36:19.860950Z","shell.execute_reply":"2024-08-03T05:16:47.900074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_images(50)","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:16:47.902834Z","iopub.execute_input":"2024-08-03T05:16:47.903197Z","iopub.status.idle":"2024-08-03T05:16:48.733833Z","shell.execute_reply.started":"2024-08-03T05:16:47.903164Z","shell.execute_reply":"2024-08-03T05:16:48.732829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs(\"saved_models\", exist_ok=True)\ntorch.save(G_AB.state_dict(), \"saved_models/G_AB_%d.pth\" % ( epoch))\ntorch.save(G_BA.state_dict(), \"saved_models/G_BA_%d.pth\" % ( epoch))\ntorch.save(D_A.state_dict(), \"saved_models/D_A_%d.pth\" % (epoch))\ntorch.save(D_B.state_dict(), \"saved_models/D_B_%d.pth\" % ( epoch))","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:16:48.735620Z","iopub.execute_input":"2024-08-03T05:16:48.736482Z","iopub.status.idle":"2024-08-03T05:16:48.827091Z","shell.execute_reply.started":"2024-08-03T05:16:48.736440Z","shell.execute_reply":"2024-08-03T05:16:48.826143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:16:48.828370Z","iopub.execute_input":"2024-08-03T05:16:48.828673Z","iopub.status.idle":"2024-08-03T05:16:48.833104Z","shell.execute_reply.started":"2024-08-03T05:16:48.828647Z","shell.execute_reply":"2024-08-03T05:16:48.832107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_, ax = plt.subplots(5, 2, figsize=(12, 12))\nfor i in range(5):\n    # Get a batch from the photo dataset\n    batch = next(iter(val_loader))  # Assuming 'val_loader' is your DataLoader\n    img = batch[\"B\"][i, ...].unsqueeze(0).to(device)  # Extract a single image\n\n    # Generate Monet-style image\n    G_AB.eval()  # Set generator to evaluation mode\n    with torch.no_grad():  # No need to track gradients for inference\n        prediction = G_AB(img)[0].cpu().numpy()  # Get prediction and move to CPU\n\n    # Denormalize and convert to uint8\n    prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n    img = (img[0].cpu().numpy() * 127.5 + 127.5).astype(np.uint8)  # Denormalize original image\n\n    # Display images\n    ax[i, 0].imshow(np.transpose(img, (1, 2, 0)))  # Transpose for matplotlib (H, W, C)\n    ax[i, 1].imshow(np.transpose(prediction, (1, 2, 0)))\n    ax[i, 0].set_title(\"Input Photo\")\n    ax[i, 1].set_title(\"Generated Monet\")\n    ax[i, 0].axis(\"off\")\n    ax[i, 1].axis(\"off\")\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:16:48.834330Z","iopub.execute_input":"2024-08-03T05:16:48.834670Z","iopub.status.idle":"2024-08-03T05:16:51.416663Z","shell.execute_reply.started":"2024-08-03T05:16:48.834647Z","shell.execute_reply":"2024-08-03T05:16:51.415209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if not os.path.exists(\"save\"):\n  os.makedirs(\"monet_images\")","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:16:51.418300Z","iopub.execute_input":"2024-08-03T05:16:51.418623Z","iopub.status.idle":"2024-08-03T05:16:51.423405Z","shell.execute_reply.started":"2024-08-03T05:16:51.418593Z","shell.execute_reply":"2024-08-03T05:16:51.422546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prompt: create image_set concat photo in train_set and val_set\n\n# Assuming 'train_set' and 'test_set' are your existing datasets\nimage_set = torch.utils.data.ConcatDataset([train_set, test_set])\n\n# Now you can use 'image_set' as a combined dataset\n# For example, to create a DataLoader:\nimage_loader = DataLoader(image_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\n\nprint((image_loader))","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:23:14.423291Z","iopub.execute_input":"2024-08-03T05:23:14.423722Z","iopub.status.idle":"2024-08-03T05:23:14.429911Z","shell.execute_reply.started":"2024-08-03T05:23:14.423693Z","shell.execute_reply":"2024-08-03T05:23:14.428988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prompt: generate image like code above with image_set\n\nimport numpy as np\nif not os.path.exists('images'):\n    os.mkdir('images')\n# Assuming 'image_set' is your combined dataset and 'G_AB' is a trained generator\ni = 1\nfor item in image_set:  # Iterate through your combined dataset\n    img = item[\"B\"].unsqueeze(0).to(device)  # Extract image and add batch dimension\n    G_AB.eval()  # Set generator to evaluation mode\n    with torch.no_grad():\n        prediction = G_AB(img)[0].cpu().numpy()  # Generate and move to CPU\n    prediction = (prediction * 127.5 + 127.5).astype(np.uint8)  # Denormalize\n    prediction = np.transpose(prediction, (1, 2, 0))  # Transpose for PIL\n    im = Image.fromarray(prediction)\n    im.save(f\"images/{i}.jpg\")  # Save generated image\n    i += 1","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:24:22.123243Z","iopub.execute_input":"2024-08-03T05:24:22.123649Z","iopub.status.idle":"2024-08-03T05:26:56.400995Z","shell.execute_reply.started":"2024-08-03T05:24:22.123618Z","shell.execute_reply":"2024-08-03T05:26:56.399993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(os.listdir(\"images\")))","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:26:56.402939Z","iopub.execute_input":"2024-08-03T05:26:56.403392Z","iopub.status.idle":"2024-08-03T05:26:56.413542Z","shell.execute_reply.started":"2024-08-03T05:26:56.403357Z","shell.execute_reply":"2024-08-03T05:26:56.412634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nshutil.make_archive(\"images\", 'zip', \"/kaggle/images\")","metadata":{"execution":{"iopub.status.busy":"2024-08-03T05:26:56.414722Z","iopub.execute_input":"2024-08-03T05:26:56.414969Z","iopub.status.idle":"2024-08-03T05:26:56.421497Z","shell.execute_reply.started":"2024-08-03T05:26:56.414948Z","shell.execute_reply":"2024-08-03T05:26:56.420633Z"},"trusted":true},"execution_count":null,"outputs":[]}]}