{"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":"gpu","dataSources":[{"sourceId":8109869,"sourceType":"datasetVersion","datasetId":4790518},{"sourceId":8149113,"sourceType":"datasetVersion","datasetId":4805885}],"dockerImageVersionId":30683,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!git clone \"https://github.com/timothybrooks/instruct-pix2pix/\"","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd /kaggle/working/instruct-pix2pix","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"\\nInstalling Dependencies ...\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!conda env create -f /kaggle/working/instruct-pix2pix/environment.yaml > /dev/null 2>&1","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"\\nDependencies Installed\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir /root/.kaggle/","metadata":{"execution":{"iopub.status.busy":"2024-04-17T21:42:47.289791Z","iopub.execute_input":"2024-04-17T21:42:47.290713Z","iopub.status.idle":"2024-04-17T21:42:48.315343Z","shell.execute_reply.started":"2024-04-17T21:42:47.290662Z","shell.execute_reply":"2024-04-17T21:42:48.313748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cp -r /kaggle/input/api-connections/kaggle2.json /root/.kaggle/kaggle.json","metadata":{"execution":{"iopub.status.busy":"2024-04-17T21:42:49.638661Z","iopub.execute_input":"2024-04-17T21:42:49.639066Z","iopub.status.idle":"2024-04-17T21:42:50.73111Z","shell.execute_reply.started":"2024-04-17T21:42:49.639033Z","shell.execute_reply":"2024-04-17T21:42:50.729935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cp -r /kaggle/input/api-connections/service_account.json /kaggle/working/instruct-pix2pix","metadata":{"execution":{"iopub.status.busy":"2024-04-17T21:42:51.962757Z","iopub.execute_input":"2024-04-17T21:42:51.963135Z","iopub.status.idle":"2024-04-17T21:42:52.986254Z","shell.execute_reply.started":"2024-04-17T21:42:51.963102Z","shell.execute_reply":"2024-04-17T21:42:52.984997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cp -r /kaggle/input/pix2pix-checkpoints/checkpoints /kaggle/working/instruct-pix2pix","metadata":{"execution":{"iopub.status.busy":"2024-04-17T21:42:54.554271Z","iopub.execute_input":"2024-04-17T21:42:54.554668Z","iopub.status.idle":"2024-04-17T21:44:02.002039Z","shell.execute_reply.started":"2024-04-17T21:42:54.554637Z","shell.execute_reply":"2024-04-17T21:44:02.000754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport subprocess\nimport shutil\nimport json\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom google.oauth2 import service_account\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaFileUpload, MediaIoBaseDownload\n\n\nDATASET_PATH = \"/kaggle/working/dataset\"\n\nclass GoogleDrive_API:\n def __init__(self):\n self.SCOPES = [\"https://www.googleapis.com/auth/drive\"]\n self.SERVICE_ACCOUNT_FILE = \"service_account.json\"\n self.PARENT_FOLDER_ID = \"1r-MlnEpWHx3b1fxHDnHcZ2-Wh_Y89676\"\n self.service = self.authenticate()\n\n def authenticate(self):\n credentials = service_account.Credentials.from_service_account_file(\n self.SERVICE_ACCOUNT_FILE, scopes=self.SCOPES\n )\n service = build(\"drive\", \"v3\", credentials=credentials)\n\n return service\n\n def get_files(self):\n # List all files in the folder\n results = (\n self.service.files()\n .list(\n q=f\"'{self.PARENT_FOLDER_ID}' in parents and trashed=false\",\n fields=\"files(id, name)\",\n )\n .execute()\n )\n return results.get(\"files\", [])\n\n def upload_file(self, file_path):\n file_metadata = {\n \"name\": os.path.basename(file_path),\n \"parents\": [self.PARENT_FOLDER_ID],\n }\n media = MediaFileUpload(file_path)\n file = (\n self.service.files()\n .create(body=file_metadata, media_body=media, fields=\"id\")\n .execute()\n )\n print(\"File uploaded. File ID:\", file.get(\"id\"))\n\n def download_file(self, file_name, file_path):\n results = (\n self.service.files()\n .list(\n q=f\"'{self.PARENT_FOLDER_ID}' in parents and name='{file_name}' and trashed=false\",\n fields=\"files(id)\",\n )\n .execute()\n )\n items = results.get(\"files\", [])\n\n if items:\n # Get the file ID\n file_id = items[0][\"id\"]\n\n request = self.service.files().get_media(fileId=file_id)\n\n with open(file_path, \"wb\") as file:\n downloader = MediaIoBaseDownload(file, request)\n done = False\n while not done:\n status, done = downloader.next_chunk()\n print(f\"Download {int(status.progress() * 100)}%.\")\n else:\n print(rf\"{file_name} is Not Found\")\n\ndef execute_terminal_command(command: str):\n try:\n process = subprocess.Popen(\n command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n output, error = process.communicate()\n output = str(output.decode(\"utf-8\"))\n error = str(error.decode(\"utf-8\"))\n print(rf\"Command executed successfully: {command}\")\n return output\n except Exception as e:\n print(\"Command Failed !\")\n return None, str(e)\n \ndef read_file(file_path: str):\n with open(file_path, 'r') as file:\n data = json.load(file)\n return data[0]\n\ndef write_file(data: list, file_path: str, file_name: str = \"\"):\n # Writing JSON data\n with open(rf\"{file_path}/{file_name}\", \"w\") as file:\n for idx in range(len(data)):\n json_string = json.dumps(data[idx]) + (\"\\n\" if idx < len(data) - 1 else \"\")\n file.write(json_string)\n \ndef read_image(image_path: str):\n try:\n image = Image.open(image_path)\n return image\n except IOError:\n print(\"Unable to load image\")\n return None\n \ndef generate_image(input_image, edit_instruction, output_path, steps, seed, cfgtext, cfgimage, resolution):\n inputs = fr'--input {input_image} --output {output_path} --edit \"{edit_instruction}\" --steps {steps} --seed {seed} --cfg-text {cfgtext} --cfg-image {cfgimage} --resolution {resolution}'\n command = fr\"/opt/conda/envs/ip2p/bin/python3 edit_cli.py {inputs}\"\n return execute_terminal_command(command)\n\n\ndef main():\n if not os.path.exists(DATASET_PATH):\n execute_terminal_command(rf\"mkdir {DATASET_PATH}\")\n \n # download dataset\n GoogleDrive_connection = GoogleDrive_API()\n GoogleDrive_connection.download_file(\"data.json\", rf\"{DATASET_PATH}/data.json\")\n \n # input\n data = read_file(rf\"{DATASET_PATH}/data.json\")\n # get data\n time = data[\"time\"]\n print(fr\"Start Time: {time}\")\n edit_instruction = data[\"edit_instruction\"]\n input_image_path = data[\"input_image_path\"]\n output_image_path = data[\"output_image_path\"]\n steps = data[\"steps\"]\n seed = data[\"seed\"]\n cfgtext = data[\"cfg-text\"]\n cfgimage = data[\"cfg-image\"]\n resolution = data[\"resolution\"]\n\n GoogleDrive_connection.download_file(input_image_path, rf\"{DATASET_PATH}/{input_image_path}\")\n\n input_image = read_image(rf\"{DATASET_PATH}/{input_image_path}\")\n # run model\n ######################################################\n generate_image(rf\"{DATASET_PATH}/{input_image_path}\", edit_instruction, rf\"{DATASET_PATH}/{output_image_path}\", steps, seed, cfgtext, cfgimage, resolution)\n ######################################################\n \n # update dataset\n GoogleDrive_connection.upload_file(rf\"{DATASET_PATH}/{output_image_path}\")\n \n # Load the images\n img1 = mpimg.imread(rf\"{DATASET_PATH}/{input_image_path}\")\n img2 = mpimg.imread(rf\"{DATASET_PATH}/{output_image_path}\")\n\n # Display the images side by side\n plt.figure(figsize=(10, 5))\n plt.subplot(1, 2, 1)\n plt.imshow(img1)\n plt.axis('off')\n plt.title('Input Image')\n\n plt.subplot(1, 2, 2)\n plt.imshow(img2)\n plt.axis('off')\n plt.title(rf\"Edited Image: {edit_instruction}\")\n \n plt.show()\n \nif __name__ == \"__main__\":\n main()","metadata":{"execution":{"iopub.status.busy":"2024-04-17T22:04:07.306536Z","iopub.execute_input":"2024-04-17T22:04:07.306923Z","iopub.status.idle":"2024-04-17T22:06:11.475935Z","shell.execute_reply.started":"2024-04-17T22:04:07.306896Z","shell.execute_reply":"2024-04-17T22:06:11.474759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}