{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "411c59b3-f177-4a10-8925-d931ce572eaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, StableDiffusionXLPipeline\n",
    "from PIL import Image\n",
    "\n",
    "from ip_adapter import IPAdapterXL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6b6dc69c-192d-4d74-8b1e-f0d9ccfbdb49",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/modelzoo/IP-Adapter\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "current_dir = os.getcwd()\n",
    "print(current_dir)\n",
    "\n",
    "base_model_path = f\"{current_dir}/pretrained_models/stable-diffusion-xl-base-1.0\"\n",
    "image_encoder_path =  f\"{current_dir}/pretrained_models/sdxl_models/image_encoder/\"\n",
    "ip_ckpt =  f\"{current_dir}/pretrained_models/sdxl_models/ip-adapter_sdxl.safetensors\"\n",
    "device = \"cuda\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "63ec542f-8474-4f38-9457-073425578073",
   "metadata": {},
   "outputs": [],
   "source": [
    "def image_grid(imgs, rows, cols):\n",
    "    assert len(imgs) == rows*cols\n",
    "\n",
    "    w, h = imgs[0].size\n",
    "    grid = Image.new('RGB', size=(cols*w, rows*h))\n",
    "    grid_w, grid_h = grid.size\n",
    "    \n",
    "    for i, img in enumerate(imgs):\n",
    "        grid.paste(img, box=(i%cols*w, i//cols*h))\n",
    "    return grid"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f907096-d919-424a-be56-7008a89fdb25",
   "metadata": {},
   "source": [
    "## Image Variations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "50186b61-9fe8-4f6f-be55-5c65608560f1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "237f8fd894d1436898967cfb4b9c5f9b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading pipeline components...:   0%|          | 0/7 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# load SDXL pipeline\n",
    "pipe = StableDiffusionXLPipeline.from_pretrained(\n",
    "    base_model_path,\n",
    "    torch_dtype=torch.float16,\n",
    "    add_watermarker=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ea85a3e7-ac1d-40c1-b5cd-a250d1ea4baa",
   "metadata": {},
   "outputs": [],
   "source": [
    "# load ip-adapter\n",
    "ip_model = IPAdapterXL(pipe, image_encoder_path, ip_ckpt, device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a6a0300d-299e-4cb6-b64e-839e2f4373a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 33292 characters]",
      "image/png": "[encoded data, 260676 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=512x512>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# read image prompt\n",
    "image = Image.open(\"assets/images/statue.png\")\n",
    "image.resize((512, 512))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b21410c4-465e-4c33-9ede-44fbc4591003",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "692470b98dbd4c47ac32b4d33eaa3f84",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/30 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/jpeg": "[encoded data, 261840 characters]",
      "image/png": "[encoded data, 3390980 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=2048x1024>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# generate image variations\n",
    "num_samples = 2\n",
    "images = ip_model.generate(pil_image=image, num_samples=num_samples, num_inference_steps=30, seed=4)\n",
    "grid = image_grid(images, 1, num_samples)\n",
    "grid"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eaabb012-b2fc-4451-a26a-42b2b31e8d5d",
   "metadata": {},
   "source": [
    "## ControlNet Depth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "3849f9d0-5f68-4a49-9190-69dd50720cae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e757cf7bb842499ab5085eb7962bd021",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading pipeline components...:   0%|          | 0/7 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "del pipe, ip_model\n",
    "torch.cuda.empty_cache()\n",
    "\n",
    "controlnet_path = f\"{current_dir}/pretrained_models/sdxl_models/controlnet\"\n",
    "# load SDXL pipeline\n",
    "controlnet = ControlNetModel.from_pretrained(controlnet_path, variant=\"fp16\", use_safetensors=True, torch_dtype=torch.float16).to(device)\n",
    "pipe = StableDiffusionXLControlNetPipeline.from_pretrained(\n",
    "    base_model_path,\n",
    "    controlnet=controlnet,\n",
    "    use_safetensors=True,\n",
    "    torch_dtype=torch.float16,\n",
    "    add_watermarker=False,\n",
    ").to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "81b1ab06-d3ed-4a7e-a356-9ddf1a2eecd6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# load ip-adapter\n",
    "ip_model = IPAdapterXL(pipe, image_encoder_path, ip_ckpt, device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b040d962-7025-4393-9db5-cd60ac9a97dc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 15380 characters]",
      "image/png": "[encoded data, 118644 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=512x256>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# read image prompt\n",
    "image = Image.open(\"assets/images/statue.png\")\n",
    "depth_map = Image.open(\"assets/structure_controls/depth.png\").resize((1024, 1024))\n",
    "image_grid([image.resize((256, 256)), depth_map.resize((256, 256))], 1, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "b77f52de-a9e4-44e1-aeec-8165414f1273",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dcf20e4838a94262aded52bd41a42a6f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/30 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/jpeg": "[encoded data, 677892 characters]",
      "image/png": "[encoded data, 6259164 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=2048x1024>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# generate image with structural control\n",
    "num_samples = 2\n",
    "images = ip_model.generate(pil_image=image, image=depth_map, controlnet_conditioning_scale=0.7, num_samples=num_samples, num_inference_steps=30, seed=42)\n",
    "grid = image_grid(images, 1, num_samples)\n",
    "grid"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
