{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "411c59b3-f177-4a10-8925-d931ce572eaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import StableDiffusionXLPipeline\n",
    "from PIL import Image\n",
    "\n",
    "from ip_adapter import IPAdapterPlusXL\n",
    "from ip_adapter.custom_pipelines import StableDiffusionXLCustomPipeline"
   ]
  },
  {
   "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",
    "\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/models/image_encoder/\"\n",
    "ip_ckpt = f\"{current_dir}/pretrained_models/sdxl_models/ip-adapter-plus-face_sdxl_vit-h.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": "code",
   "execution_count": 4,
   "id": "3849f9d0-5f68-4a49-9190-69dd50720cae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "55439a8d32b84ed6815f767870b720ab",
       "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 = StableDiffusionXLCustomPipeline.from_pretrained(\n",
    "    base_model_path,\n",
    "    torch_dtype=torch.float16,\n",
    "    add_watermarker=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "81b1ab06-d3ed-4a7e-a356-9ddf1a2eecd6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# load ip-adapter\n",
    "ip_model = IPAdapterPlusXL(pipe, image_encoder_path, ip_ckpt, device, num_tokens=16)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a36055a-32fe-4d47-ba05-3ed143672daf",
   "metadata": {},
   "source": [
    "## Generate Image conditioned on face images\n",
    "- You should use a cropped face image (you can the adjust the cropped area size to get different results)\n",
    "- Since the background will have an impact on the resulting image, you'd better segment the face"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b040d962-7025-4393-9db5-cd60ac9a97dc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 120656 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGBA size=224x224>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# case 1\n",
    "image = Image.open(\"assets/images/ai_face.png\")\n",
    "image.resize((224, 224))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b77f52de-a9e4-44e1-aeec-8165414f1273",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b7470c3883b34c2181fd9b653e5691f4",
       "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, 307784 characters]",
      "image/png": "[encoded data, 4101824 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=2048x1024>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "images = ip_model.generate(pil_image=image, num_samples=2, num_inference_steps=30, seed=42,\n",
    "        prompt=\"photo of a beautiful girl wearing casual shirt in a garden\")\n",
    "grid = image_grid(images, 1, 2)\n",
    "grid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "36ec1dce-7861-4ce2-90de-0de36bb28569",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 132312 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGBA size=224x224>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# case 2\n",
    "image = Image.open(\"assets/images/ai_face2.png\")\n",
    "image.resize((224, 224))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7fb2114c-a3f8-4d5c-946a-89c5828626d3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9639d5bb6c244b959f9fd22f80912725",
       "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, 182916 characters]",
      "image/png": "[encoded data, 3116196 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=2048x1024>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "images = ip_model.generate(pil_image=image, num_samples=2, num_inference_steps=30, seed=42,\n",
    "        prompt=\"photo of a beautiful girl wearing casual shirt in a garden\")\n",
    "grid = image_grid(images, 1, 2)\n",
    "grid"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82a09df1-3bc9-43ff-976e-c095402b1225",
   "metadata": {},
   "source": [
    "## Post-Conditioning\n",
    "Use post-condition to generate more diverse images (like inpainting but you don't draw mask)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c346f01f-cb18-41c7-abaa-5cbdb3ecea0d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "00ba1a1170514b22a014030c15afa88f",
       "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, 343044 characters]",
      "image/png": "[encoded data, 4636352 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=2048x1024>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# generate the image only conditioned text\n",
    "images = ip_model.generate(pil_image=image, num_samples=2, num_inference_steps=30, seed=2023,\n",
    "        prompt=\"photo of a beautiful girl wearing casual shirt in a garden\", control_guidance_start=1.)\n",
    "grid = image_grid(images, 1, 2)\n",
    "grid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "eb4600bf-f36e-4678-9253-3adf0be2af9f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1375a9fe256d402e9d2954e77b476f61",
       "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, 286304 characters]",
      "image/png": "[encoded data, 3911556 characters]",
      "text/plain": [
       "<PIL.Image.Image image mode=RGB size=2048x1024>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# add face image condition\n",
    "images = ip_model.generate(pil_image=image, num_samples=2, num_inference_steps=30, seed=2023,\n",
    "        prompt=\"photo of a beautiful girl wearing casual shirt in a garden\", control_guidance_start=0.5)\n",
    "grid = image_grid(images, 1, 2)\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
}
