├── README.md
└── S2_GAN_Art_Generator_(VQGAN,_CLIP,_Guided_Diffusion).ipynb
/README.md:
--------------------------------------------------------------------------------
1 | ## Testing the ability to save
2 |
3 |
--------------------------------------------------------------------------------
/S2_GAN_Art_Generator_(VQGAN,_CLIP,_Guided_Diffusion).ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 2,
4 | "metadata": {
5 | "colab": {
6 | "name": "Copy of Copy of S2 GAN Art Generator (VQGAN, CLIP, Guided Diffusion) ",
7 | "private_outputs": true,
8 | "provenance": [],
9 | "collapsed_sections": [],
10 | "machine_shape": "hm",
11 | "include_colab_link": true
12 | },
13 | "kernelspec": {
14 | "name": "python3",
15 | "display_name": "Python 3"
16 | },
17 | "language_info": {
18 | "name": "python"
19 | },
20 | "accelerator": "GPU"
21 | },
22 | "cells": [
23 | {
24 | "cell_type": "markdown",
25 | "source": [
26 | "
"
27 | ],
28 | "metadata": {
29 | "id": "view-in-github",
30 | "colab_type": "text"
31 | }
32 | },
33 | {
34 | "cell_type": "markdown",
35 | "source": [
36 | "### *changelog/updates (twitter: @somewheresy if you have any revision requests)*\n",
37 | "\n",
38 | "##### August 18, 2021: Forked notebook from the original copy. Integrated Katherine Crowson's CLIP-guided diffusion method as a secondary mode to the notebook. Removed automatic video naming and exposed it as a parameter instead.\n",
39 | "##### July 21, 2021: Changed video generation file name to use the prompt if provided\n",
40 | "---\n",
41 | "##### July 19, 2021: Fixed root path bug when opting out of Google Drive\n",
42 | "---\n",
43 | "##### July 18, 2021: Added Google Drive integration w/ support for project folders\n",
44 | "---\n",
45 | "\n",
46 | "\n"
47 | ],
48 | "metadata": {
49 | "id": "VyN-gqJKfLAu"
50 | }
51 | },
52 | {
53 | "cell_type": "markdown",
54 | "source": [
55 | "# Generate images from text phrases with VQGAN and CLIP (z+quantize method with augmentations)\n",
56 | "\n",
57 | "[How to use VQGAN+CLIP](https://docs.google.com/document/d/1Lu7XPRKlNhBQjcKr8k8qRzUzbBW7kzxb5Vu72GMRn2E/edit)\n",
58 | "\n",
59 | "The original idea behind CLIP came from this article:\n",
60 | "\n",
61 | "https://medium.com/@blaisea/physiognomys-new-clothes-f2d4b59fdd6a\n",
62 | "\n",
63 | "This notebook has been translated by [twitter.com/somewheresy](https://twitter.com/somewheresy) to English and has some improvements added like Google Drive support and some basic project management. Feel free to contact me with any revisions/suggestions.\n",
64 | "\n",
65 | "The last version of this notebook was authored by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). The original BigGAN + CLIP method was demonstrated by https://twitter.com/advadnoun. Translated (to Spanish) and added explanations, and modifications by Eleiber # 8347, and the friendly interface was made thanks to Abulafia # 3734.\n",
66 | "\n",
67 | "The CLIP Guided Diffusion feature is mostly from this notebook by Katherine Crowson as well:\n",
68 | "\n",
69 | "https://colab.research.google.com/drive/1QBsaDAZv8np29FPbvjffbE1eytoJcsgA#scrollTo=-_UVMZCIAq_r\n",
70 | "\n"
71 | ],
72 | "metadata": {
73 | "id": "CppIQlPhhwhs"
74 | }
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": null,
79 | "source": [
80 | "# @title Licensed under the MIT License\n",
81 | "\n",
82 | "# Copyright (c) 2021 Katherine Crowson\n",
83 | "\n",
84 | "# Permission is hereby granted, free of charge, to any person obtaining a copy\n",
85 | "# of this software and associated documentation files (the \"Software\"), to deal\n",
86 | "# in the Software without restriction, including without limitation the rights\n",
87 | "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
88 | "# copies of the Software, and to permit persons to whom the Software is\n",
89 | "# furnished to do so, subject to the following conditions:\n",
90 | "\n",
91 | "# The above copyright notice and this permission notice shall be included in\n",
92 | "# all copies or substantial portions of the Software.\n",
93 | "\n",
94 | "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
95 | "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
96 | "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
97 | "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
98 | "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
99 | "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n",
100 | "# THE SOFTWARE."
101 | ],
102 | "outputs": [],
103 | "metadata": {
104 | "id": "VA1PHoJrRiK9",
105 | "cellView": "form"
106 | }
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": null,
111 | "source": [
112 | "#@title Google Drive Integration (optional)\n",
113 | "#@markdown To connect Google Drive, set `root_path` to the relative drive folder path you want outputs to be saved to if you already made a directory, then execute this cell. Leaving the field blank or just not running this will have outputs save to the runtime temp storage.\n",
114 | "import os\n",
115 | "root_path = \"collab_gan\" #@param {type: \"string\"}\n",
116 | "abs_root_path = \"/content\"\n",
117 | "if len(root_path) > 0:\n",
118 | " abs_root_path = abs_root_path + \"/drive/MyDrive/\" + root_path\n",
119 | "\n",
120 | "from google.colab import drive\n",
121 | "drive.mount('/content/drive')\n",
122 | "\n",
123 | "def ensureProperRootPath():\n",
124 | " if len(abs_root_path) > 0:\n",
125 | " os.chdir(abs_root_path) # Changes directory to absolute root path\n",
126 | " print(\"Root path checked: \")\n",
127 | " !pwd\n",
128 | "\n",
129 | "ensureProperRootPath()"
130 | ],
131 | "outputs": [],
132 | "metadata": {
133 | "id": "KqgIZS75GU-O",
134 | "cellView": "form"
135 | }
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": null,
140 | "source": [
141 | "#@title Make a new folder & set root path to that folder (optional)\n",
142 | "#@markdown Saves a step if you don't have a folder in your Google Drive for this. Makes one, sets the root_path to that new folder. You can name it whatever you'd like:\n",
143 | "\n",
144 | "folder_name = \"AI_ART\" #@param {type: \"string\"}\n",
145 | "abs_root_path = \"/content\"\n",
146 | "if len(folder_name) > 0:\n",
147 | " path_tmp = abs_root_path + \"/drive/MyDrive/\" + folder_name\n",
148 | " if not os.path.exists(path_tmp):\n",
149 | " os.mkdir(path_tmp)\n",
150 | " abs_root_path = path_tmp\n",
151 | "\n",
152 | "print(\"Created folder & set root path to: \" + abs_root_path)\n",
153 | "\n",
154 | "#@markdown Make & assign path to a project subfolder (optional)\n",
155 | "\n",
156 | "project_name = \"moto_space2\" #@param {type: \"string\"}\n",
157 | "if len(project_name) > 0:\n",
158 | " path_tmp = abs_root_path + \"/\" + project_name\n",
159 | " if not os.path.exists(path_tmp):\n",
160 | " os.mkdir(path_tmp)\n",
161 | " abs_root_path = path_tmp\n",
162 | "print(\"Created project subfolder & set root path to: \" + abs_root_path)\n",
163 | "\n",
164 | "ensureProperRootPath()"
165 | ],
166 | "outputs": [],
167 | "metadata": {
168 | "id": "pY2XJV_eGXUh",
169 | "cellView": "form"
170 | }
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": null,
175 | "source": [
176 | "# @title Setup, Installing Libraries\n",
177 | "# @markdown This cell might take some time due to installing several libraries.\n",
178 | "\n",
179 | "!nvidia-smi\n",
180 | "print(\"Downloading CLIP...\")\n",
181 | "!git clone https://github.com/openai/CLIP &> /dev/null\n",
182 | "!git clone https://github.com/crowsonkb/guided-diffusion &> /dev/null\n",
183 | "!pip install -e ./CLIP &> /dev/null\n",
184 | "print(\"Installing library for guided diffusion...\")\n",
185 | "!pip install -e ./guided-diffusion &> /dev/null\n",
186 | "\n",
187 | "print(\"Installing Python Libraries for AI\")\n",
188 | "!git clone https://github.com/CompVis/taming-transformers &> /dev/null\n",
189 | "!pip install ftfy regex tqdm omegaconf pytorch-lightning &> /dev/null\n",
190 | "!pip install kornia &> /dev/null\n",
191 | "!pip install einops &> /dev/null\n",
192 | "print(\"Installing transformers library...\")\n",
193 | "!pip install transformers &> /dev/null\n",
194 | " \n",
195 | "print(\"Installing libraries for managing metadata...\")\n",
196 | "!pip install stegano &> /dev/null\n",
197 | "!apt install exempi &> /dev/null\n",
198 | "!pip install python-xmp-toolkit &> /dev/null\n",
199 | "!pip install imgtag &> /dev/null\n",
200 | "!pip install pillow==7.1.2 &> /dev/null\n",
201 | "print(\"Installing taming.models...\")\n",
202 | "!pip install taming.models &> /dev/null\n",
203 | " \n",
204 | "print(\"Installing ffmpeg for creating videos...\")\n",
205 | "!pip install imageio-ffmpeg &> /dev/null\n",
206 | "!mkdir steps\n",
207 | "print(\"Installation finished.\")"
208 | ],
209 | "outputs": [],
210 | "metadata": {
211 | "id": "wSfISAhyPmyp",
212 | "cellView": "form"
213 | }
214 | },
215 | {
216 | "cell_type": "code",
217 | "execution_count": null,
218 | "source": [
219 | "#@title Selection of models to download\n",
220 | "#@markdown Ensure you select a model you've downloaded in the parameters block\n",
221 | "\n",
222 | "#@markdown *New!* It's CLIP-guided diffusion, a method that takes a bit longer to produce good results but generally makes more \"realistic\" interpretations of the prompt. If you'd like to use this, make sure to download Katherine Crowson's diffusion model. \n",
223 | "diffusion = True #@param {type: \"boolean\"}\n",
224 | "\n",
225 | "#@markdown Models for VQGAN+CLIP method\n",
226 | "imagenet_1024 = False #@param {type:\"boolean\"}\n",
227 | "imagenet_16384 = True #@param {type:\"boolean\"}\n",
228 | "coco = False #@param {type:\"boolean\"}\n",
229 | "faceshq = False #@param {type:\"boolean\"}\n",
230 | "wikiart_1024 = False #@param {type:\"boolean\"}\n",
231 | "wikiart_16384 = False #@param {type:\"boolean\"}\n",
232 | "sflckr = False #@param {type:\"boolean\"}\n",
233 | "\n",
234 | "\n",
235 | "if imagenet_1024:\n",
236 | " !curl -L -o vqgan_imagenet_f16_1024.yaml -C - 'http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_1024.yaml' #ImageNet 1024\n",
237 | " !curl -L -o vqgan_imagenet_f16_1024.ckpt -C - 'http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_1024.ckpt' #ImageNet 1024\n",
238 | "if imagenet_16384:\n",
239 | " !curl -L -o vqgan_imagenet_f16_16384.yaml -C - 'http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_16384.yaml' #ImageNet 16384\n",
240 | " !curl -L -o vqgan_imagenet_f16_16384.ckpt -C - 'http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_16384.ckpt' #ImageNet 16384\n",
241 | "if coco:\n",
242 | " !curl -L -o coco.yaml -C - 'https://dl.nmkd.de/ai/clip/coco/coco.yaml' #COCO\n",
243 | " !curl -L -o coco.ckpt -C - 'https://dl.nmkd.de/ai/clip/coco/coco.ckpt' #COCO\n",
244 | "if faceshq:\n",
245 | " !curl -L -o faceshq.yaml -C - 'https://drive.google.com/uc?export=download&id=1fHwGx_hnBtC8nsq7hesJvs-Klv-P0gzT' #FacesHQ\n",
246 | " !curl -L -o faceshq.ckpt -C - 'https://app.koofr.net/content/links/a04deec9-0c59-4673-8b37-3d696fe63a5d/files/get/last.ckpt?path=%2F2020-11-13T21-41-45_faceshq_transformer%2Fcheckpoints%2Flast.ckpt' #FacesHQ\n",
247 | "if wikiart_1024: \n",
248 | " !curl -L -o wikiart_1024.yaml -C - 'http://mirror.io.community/blob/vqgan/wikiart.yaml' #WikiArt 1024\n",
249 | " !curl -L -o wikiart_1024.ckpt -C - 'http://mirror.io.community/blob/vqgan/wikiart.ckpt' #WikiArt 1024\n",
250 | "if wikiart_16384: \n",
251 | " !curl -L -o wikiart_16384.yaml -C - 'http://mirror.io.community/blob/vqgan/wikiart_16384.yaml' #WikiArt 16384\n",
252 | " !curl -L -o wikiart_16384.ckpt -C - 'http://mirror.io.community/blob/vqgan/wikiart_16384.ckpt' #WikiArt 16384\n",
253 | "if sflckr:\n",
254 | " !curl -L -o sflckr.yaml -C - 'https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/files/?p=%2Fconfigs%2F2020-11-09T13-31-51-project.yaml&dl=1' #S-FLCKR\n",
255 | " !curl -L -o sflckr.ckpt -C - 'https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/files/?p=%2Fcheckpoints%2Flast.ckpt&dl=1' #S-FLCKR\n",
256 | "if diffusion:\n",
257 | " # Download the diffusion model\n",
258 | " !curl -OL --http1.1 'https://the-eye.eu/public/AI/models/512x512_diffusion_unconditional_ImageNet/512x512_diffusion_uncond_finetune_008100.pt' #DIFFUSION"
259 | ],
260 | "outputs": [],
261 | "metadata": {
262 | "id": "FhhdWrSxQhwg",
263 | "cellView": "form"
264 | }
265 | },
266 | {
267 | "cell_type": "code",
268 | "execution_count": null,
269 | "source": [
270 | "# @title Loading libraries and definitions\n",
271 | " \n",
272 | "import argparse\n",
273 | "import math\n",
274 | "from pathlib import Path\n",
275 | "import io\n",
276 | "import sys\n",
277 | "\n",
278 | " \n",
279 | "sys.path.append('./taming-transformers')\n",
280 | "from IPython import display\n",
281 | "from base64 import b64encode\n",
282 | "from omegaconf import OmegaConf\n",
283 | "from PIL import Image\n",
284 | "from taming.models import cond_transformer, vqgan\n",
285 | "import torch\n",
286 | "from torch import nn, optim\n",
287 | "from torch.nn import functional as F\n",
288 | "from torchvision import transforms\n",
289 | "from torchvision.transforms import functional as TF\n",
290 | "from tqdm.notebook import tqdm\n",
291 | " \n",
292 | "from CLIP import clip\n",
293 | "import kornia.augmentation as K\n",
294 | "import numpy as np\n",
295 | "import imageio\n",
296 | "from PIL import ImageFile, Image\n",
297 | "from imgtag import ImgTag # metadata\n",
298 | "from libxmp import * # metadata\n",
299 | "import libxmp # metadata\n",
300 | "from stegano import lsb\n",
301 | "import json\n",
302 | "ImageFile.LOAD_TRUNCATED_IMAGES = True\n",
303 | "\n",
304 | "sys.path.append('./CLIP')\n",
305 | "sys.path.append('./guided-diffusion')\n",
306 | "\n",
307 | "import clip\n",
308 | "from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults\n",
309 | "\n",
310 | "def sinc(x):\n",
311 | " return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))\n",
312 | " \n",
313 | " \n",
314 | "def lanczos(x, a):\n",
315 | " cond = torch.logical_and(-a < x, x < a)\n",
316 | " out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))\n",
317 | " return out / out.sum()\n",
318 | " \n",
319 | " \n",
320 | "def ramp(ratio, width):\n",
321 | " n = math.ceil(width / ratio + 1)\n",
322 | " out = torch.empty([n])\n",
323 | " cur = 0\n",
324 | " for i in range(out.shape[0]):\n",
325 | " out[i] = cur\n",
326 | " cur += ratio\n",
327 | " return torch.cat([-out[1:].flip([0]), out])[1:-1]\n",
328 | " \n",
329 | " \n",
330 | "def resample(input, size, align_corners=True):\n",
331 | " n, c, h, w = input.shape\n",
332 | " dh, dw = size\n",
333 | " \n",
334 | " input = input.view([n * c, 1, h, w])\n",
335 | " \n",
336 | " if dh < h:\n",
337 | " kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)\n",
338 | " pad_h = (kernel_h.shape[0] - 1) // 2\n",
339 | " input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')\n",
340 | " input = F.conv2d(input, kernel_h[None, None, :, None])\n",
341 | " \n",
342 | " if dw < w:\n",
343 | " kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)\n",
344 | " pad_w = (kernel_w.shape[0] - 1) // 2\n",
345 | " input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')\n",
346 | " input = F.conv2d(input, kernel_w[None, None, None, :])\n",
347 | " \n",
348 | " input = input.view([n, c, h, w])\n",
349 | " return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)\n",
350 | " \n",
351 | " \n",
352 | "class ReplaceGrad(torch.autograd.Function):\n",
353 | " @staticmethod\n",
354 | " def forward(ctx, x_forward, x_backward):\n",
355 | " ctx.shape = x_backward.shape\n",
356 | " return x_forward\n",
357 | " \n",
358 | " @staticmethod\n",
359 | " def backward(ctx, grad_in):\n",
360 | " return None, grad_in.sum_to_size(ctx.shape)\n",
361 | " \n",
362 | " \n",
363 | "replace_grad = ReplaceGrad.apply\n",
364 | " \n",
365 | " \n",
366 | "class ClampWithGrad(torch.autograd.Function):\n",
367 | " @staticmethod\n",
368 | " def forward(ctx, input, min, max):\n",
369 | " ctx.min = min\n",
370 | " ctx.max = max\n",
371 | " ctx.save_for_backward(input)\n",
372 | " return input.clamp(min, max)\n",
373 | " \n",
374 | " @staticmethod\n",
375 | " def backward(ctx, grad_in):\n",
376 | " input, = ctx.saved_tensors\n",
377 | " return grad_in * (grad_in * (input - input.clamp(ctx.min, ctx.max)) >= 0), None, None\n",
378 | " \n",
379 | " \n",
380 | "clamp_with_grad = ClampWithGrad.apply\n",
381 | " \n",
382 | " \n",
383 | "def vector_quantize(x, codebook):\n",
384 | " d = x.pow(2).sum(dim=-1, keepdim=True) + codebook.pow(2).sum(dim=1) - 2 * x @ codebook.T\n",
385 | " indices = d.argmin(-1)\n",
386 | " x_q = F.one_hot(indices, codebook.shape[0]).to(d.dtype) @ codebook\n",
387 | " return replace_grad(x_q, x)\n",
388 | " \n",
389 | " \n",
390 | "class Prompt(nn.Module):\n",
391 | " def __init__(self, embed, weight=1., stop=float('-inf')):\n",
392 | " super().__init__()\n",
393 | " self.register_buffer('embed', embed)\n",
394 | " self.register_buffer('weight', torch.as_tensor(weight))\n",
395 | " self.register_buffer('stop', torch.as_tensor(stop))\n",
396 | " \n",
397 | " def forward(self, input):\n",
398 | " input_normed = F.normalize(input.unsqueeze(1), dim=2)\n",
399 | " embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2)\n",
400 | " dists = input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)\n",
401 | " dists = dists * self.weight.sign()\n",
402 | " return self.weight.abs() * replace_grad(dists, torch.maximum(dists, self.stop)).mean()\n",
403 | " \n",
404 | " \n",
405 | "def parse_prompt(prompt):\n",
406 | " vals = prompt.rsplit(':', 2)\n",
407 | " vals = vals + ['', '1', '-inf'][len(vals):]\n",
408 | " return vals[0], float(vals[1]), float(vals[2])\n",
409 | " \n",
410 | " \n",
411 | "class MakeCutouts(nn.Module):\n",
412 | " def __init__(self, cut_size, cutn, cut_pow=1.):\n",
413 | " super().__init__()\n",
414 | " self.cut_size = cut_size\n",
415 | " self.cutn = cutn\n",
416 | " self.cut_pow = cut_pow\n",
417 | " self.augs = nn.Sequential(\n",
418 | " K.RandomHorizontalFlip(p=0.5),\n",
419 | " # K.RandomSolarize(0.01, 0.01, p=0.7),\n",
420 | " K.RandomSharpness(0.3,p=0.4),\n",
421 | " K.RandomAffine(degrees=30, translate=0.1, p=0.8, padding_mode='border'),\n",
422 | " K.RandomPerspective(0.2,p=0.4),\n",
423 | " K.ColorJitter(hue=0.01, saturation=0.01, p=0.7))\n",
424 | " self.noise_fac = 0.1\n",
425 | " \n",
426 | " \n",
427 | " def forward(self, input):\n",
428 | " sideY, sideX = input.shape[2:4]\n",
429 | " max_size = min(sideX, sideY)\n",
430 | " min_size = min(sideX, sideY, self.cut_size)\n",
431 | " cutouts = []\n",
432 | " for _ in range(self.cutn):\n",
433 | " size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)\n",
434 | " offsetx = torch.randint(0, sideX - size + 1, ())\n",
435 | " offsety = torch.randint(0, sideY - size + 1, ())\n",
436 | " cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]\n",
437 | " cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))\n",
438 | " batch = self.augs(torch.cat(cutouts, dim=0))\n",
439 | " if self.noise_fac:\n",
440 | " facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac)\n",
441 | " batch = batch + facs * torch.randn_like(batch)\n",
442 | " return batch\n",
443 | " \n",
444 | " \n",
445 | "def load_vqgan_model(config_path, checkpoint_path):\n",
446 | " config = OmegaConf.load(config_path)\n",
447 | " if config.model.target == 'taming.models.vqgan.VQModel':\n",
448 | " model = vqgan.VQModel(**config.model.params)\n",
449 | " model.eval().requires_grad_(False)\n",
450 | " model.init_from_ckpt(checkpoint_path)\n",
451 | " elif config.model.target == 'taming.models.cond_transformer.Net2NetTransformer':\n",
452 | " parent_model = cond_transformer.Net2NetTransformer(**config.model.params)\n",
453 | " parent_model.eval().requires_grad_(False)\n",
454 | " parent_model.init_from_ckpt(checkpoint_path)\n",
455 | " model = parent_model.first_stage_model\n",
456 | " else:\n",
457 | " raise ValueError(f'unknown model type: {config.model.target}')\n",
458 | " del model.loss\n",
459 | " return model\n",
460 | " \n",
461 | " \n",
462 | "def resize_image(image, out_size):\n",
463 | " ratio = image.size[0] / image.size[1]\n",
464 | " area = min(image.size[0] * image.size[1], out_size[0] * out_size[1])\n",
465 | " size = round((area * ratio)**0.5), round((area / ratio)**0.5)\n",
466 | " return image.resize(size, Image.LANCZOS)\n",
467 | "\n",
468 | "# Define necessary functions for CLIP guided diffusion\n",
469 | "\n",
470 | "def fetch(url_or_path):\n",
471 | " if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):\n",
472 | " r = requests.get(url_or_path)\n",
473 | " r.raise_for_status()\n",
474 | " fd = io.BytesIO()\n",
475 | " fd.write(r.content)\n",
476 | " fd.seek(0)\n",
477 | " return fd\n",
478 | " return open(url_or_path, 'rb')\n",
479 | "\n",
480 | "class MakeCutouts(nn.Module):\n",
481 | " def __init__(self, cut_size, cutn, cut_pow=1.):\n",
482 | " super().__init__()\n",
483 | " self.cut_size = cut_size\n",
484 | " self.cutn = cutn\n",
485 | " self.cut_pow = cut_pow\n",
486 | "\n",
487 | " def forward(self, input):\n",
488 | " sideY, sideX = input.shape[2:4]\n",
489 | " max_size = min(sideX, sideY)\n",
490 | " min_size = min(sideX, sideY, self.cut_size)\n",
491 | " cutouts = []\n",
492 | " for _ in range(self.cutn):\n",
493 | " size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)\n",
494 | " offsetx = torch.randint(0, sideX - size + 1, ())\n",
495 | " offsety = torch.randint(0, sideY - size + 1, ())\n",
496 | " cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]\n",
497 | " cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))\n",
498 | " return torch.cat(cutouts)\n",
499 | "\n",
500 | "\n",
501 | "def spherical_dist_loss(x, y):\n",
502 | " x = F.normalize(x, dim=-1)\n",
503 | " y = F.normalize(y, dim=-1)\n",
504 | " return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)\n",
505 | "\n",
506 | "\n",
507 | "def tv_loss(input):\n",
508 | " \"\"\"L2 total variation loss, as in Mahendran et al.\"\"\"\n",
509 | " input = F.pad(input, (0, 1, 0, 1), 'replicate')\n",
510 | " x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]\n",
511 | " y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]\n",
512 | " return (x_diff**2 + y_diff**2).mean([1, 2, 3])\n",
513 | "\n"
514 | ],
515 | "outputs": [],
516 | "metadata": {
517 | "id": "EXMSuW2EQWsd",
518 | "cellView": "form"
519 | }
520 | },
521 | {
522 | "cell_type": "markdown",
523 | "source": [
524 | "## Implementation tools\n",
525 | "Mainly what you will have to modify will be `texts:`, there you can place the text (s) you want to generate (separated with `|`). It is a list because you can put more than one text, and so the AI tries to 'mix' the images, giving the same priority to both texts.\n",
526 | "\n",
527 | "To use an initial image to the model, you just have to upload a file to the Colab environment (in the section on the left), and then modify `initial_image:` putting the exact name of the file. Example: `sample.png`\n",
528 | "\n",
529 | "You can also modify the model by changing the lines that say `model:`. Currently 1024, 16384, WikiArt, S-FLCKR and COCO-Stuff are available. To activate them you have to have downloaded them first, and then you can simply select it.\n",
530 | "\n",
531 | "You can also use `target_images`, which is basically putting one or more images on it that the AI will take as a\" target \", fulfilling the same function as using a text input. To put more than one you have to use `|` as a separator."
532 | ],
533 | "metadata": {
534 | "id": "1tthw0YaispD"
535 | }
536 | },
537 | {
538 | "cell_type": "code",
539 | "execution_count": null,
540 | "source": [
541 | "#@markdown #Shared Parameters\n",
542 | "seed = -1#@param {type:\"number\"}\n",
543 | "\n",
544 | "display_frequency = 50#@param {type:\"number\"}\n",
545 | "\n",
546 | "#@markdown #VQGAN+CLIP Parameters\n",
547 | "prompts = \"motorcycles ridden by cats in space\" #@param {type:\"string\"}\n",
548 | "width = 414#@param {type:\"number\"}\n",
549 | "height = 896#@param {type:\"number\"}\n",
550 | "model = \"vqgan_imagenet_f16_16384\" #@param [\"vqgan_imagenet_f16_16384\", \"vqgan_imagenet_f16_1024\", \"wikiart_1024\", \"wikiart_16384\", \"coco\", \"faceshq\", \"sflckr\"]\n",
551 | "initial_image = \"None\"#@param {type:\"string\"}\n",
552 | "target_images = \"\"#@param {type:\"string\"}\n",
553 | "seed = -1#@param {type:\"number\"}\n",
554 | "max_iterations = 10000#@param {type:\"number\"}\n",
555 | "input_images = \"\"\n",
556 | "\n",
557 | "#@markdown # CLIP Guided Diffusion Parameters\n",
558 | "#@markdown ### To use CLIP guided diffusion in place of the method above, check the box below. WARNING: This requires access to 16GB of VRAM reliably, so may not work for users not using Colab Pro/+\n",
559 | "usingDiffusion = False#@param {type:\"boolean\"}\n",
560 | "\n",
561 | "prompt = 'A hand model whose hands are made of paper, demonstrating shadow puppets'#@param {type:\"string\"}\n",
562 | "batch_size = 1#@param {type:\"number\"}\n",
563 | " #@markdown Controls how much the image should look like the prompt.\n",
564 | "clip_guidance_scale = 1000#@param {type:\"number\"} \n",
565 | " #@markdown Controls the smoothness of the final output.\n",
566 | "tv_scale = 150#@param {type:\"number\"} \n",
567 | "cutn = 40#@param {type:\"number\"}\n",
568 | "cut_pow = 0.5#@param {type:\"number\"}\n",
569 | "n_batches = 1#@param {type:\"number\"}\n",
570 | " #@markdown This can be an URL or Colab local path and must be in quotes.\n",
571 | "init_image = \"\" #@param {type:\"string\"}\n",
572 | " #@markdown This needs to be between approx. 200 and 500 when using an init image. \n",
573 | " #@markdown Higher values make the output look more like the init.\n",
574 | "skip_timesteps = 350#@param {type:\"number\"} \n",
575 | " \n",
576 | "\n",
577 | "\n",
578 | "model_names={\"vqgan_imagenet_f16_16384\": 'ImageNet 16384',\"vqgan_imagenet_f16_1024\":\"ImageNet 1024\", \n",
579 | " \"wikiart_1024\":\"WikiArt 1024\", \"wikiart_16384\":\"WikiArt 16384\", \"coco\":\"COCO-Stuff\", \"faceshq\":\"FacesHQ\", \"sflckr\":\"S-FLCKR\"}\n",
580 | "model_name = model_names[model] \n",
581 | "\n",
582 | "if seed == -1:\n",
583 | " seed = None\n",
584 | "if initial_image == \"None\":\n",
585 | " initial_image = None\n",
586 | "if target_images == \"None\" or not target_images:\n",
587 | " target_images = []\n",
588 | "else:\n",
589 | " target_images = target_images.split(\"|\")\n",
590 | " target_images = [image.strip() for image in target_images]\n",
591 | "\n",
592 | "if initial_image or target_images != []:\n",
593 | " input_images = True\n",
594 | "\n",
595 | "prompts = [frase.strip() for frase in prompts.split(\"|\")]\n",
596 | "if prompts == ['']:\n",
597 | " prompts = []\n",
598 | "\n",
599 | "\n",
600 | "args = argparse.Namespace(\n",
601 | " prompts=prompts,\n",
602 | " image_prompts=target_images,\n",
603 | " noise_prompt_seeds=[],\n",
604 | " noise_prompt_weights=[],\n",
605 | " size=[width, height],\n",
606 | " init_image=initial_image,\n",
607 | " init_weight=0.,\n",
608 | " clip_model='ViT-B/32',\n",
609 | " vqgan_config=f'{model}.yaml',\n",
610 | " vqgan_checkpoint=f'{model}.ckpt',\n",
611 | " step_size=0.1,\n",
612 | " cutn=64,\n",
613 | " cut_pow=1.,\n",
614 | " display_freq=display_frequency,\n",
615 | " seed=seed,\n",
616 | ")"
617 | ],
618 | "outputs": [],
619 | "metadata": {
620 | "id": "ZdlpRFL8UAlW",
621 | "cellView": "form"
622 | }
623 | },
624 | {
625 | "cell_type": "code",
626 | "execution_count": null,
627 | "source": [
628 | "#@title Execution\n",
629 | "\n",
630 | "model_config = model_and_diffusion_defaults()\n",
631 | "model_config.update({\n",
632 | " 'attention_resolutions': '32, 16, 8',\n",
633 | " 'class_cond': False,\n",
634 | " 'diffusion_steps': 1000,\n",
635 | " 'rescale_timesteps': True,\n",
636 | " 'timestep_respacing': '1000', # Modify this value to decrease the number of\n",
637 | " # timesteps.\n",
638 | " 'image_size': 512,\n",
639 | " 'learn_sigma': True,\n",
640 | " 'noise_schedule': 'linear',\n",
641 | " 'num_channels': 256,\n",
642 | " 'num_head_channels': 64,\n",
643 | " 'num_res_blocks': 2,\n",
644 | " 'resblock_updown': True,\n",
645 | " 'use_fp16': True,\n",
646 | " 'use_scale_shift_norm': True,\n",
647 | "})\n",
648 | "\n",
649 | "\n",
650 | "device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
651 | "\n",
652 | "if (usingDiffusion == False):\n",
653 | " print('Executing using VQGAN+CLIP method')\n",
654 | " print('Using device:', device)\n",
655 | " if prompts:\n",
656 | " print('Using text prompt:', prompts)\n",
657 | " if target_images:\n",
658 | " print('Using image prompts:', target_images)\n",
659 | " if args.seed is None:\n",
660 | " seed = torch.seed()\n",
661 | " else:\n",
662 | " seed = args.seed\n",
663 | " torch.manual_seed(seed)\n",
664 | " print('Using seed:', seed)\n",
665 | "\n",
666 | " model = load_vqgan_model(args.vqgan_config, args.vqgan_checkpoint).to(device)\n",
667 | " perceptor = clip.load(args.clip_model, jit=False)[0].eval().requires_grad_(False).to(device)\n",
668 | "\n",
669 | " cut_size = perceptor.visual.input_resolution\n",
670 | " e_dim = model.quantize.e_dim\n",
671 | " f = 2**(model.decoder.num_resolutions - 1)\n",
672 | " make_cutouts = MakeCutouts(cut_size, args.cutn, cut_pow=args.cut_pow)\n",
673 | " n_toks = model.quantize.n_e\n",
674 | " toksX, toksY = args.size[0] // f, args.size[1] // f\n",
675 | " sideX, sideY = toksX * f, toksY * f\n",
676 | " z_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]\n",
677 | " z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]\n",
678 | "\n",
679 | "\n",
680 | " if args.init_image:\n",
681 | " pil_image = Image.open(args.init_image).convert('RGB')\n",
682 | " pil_image = pil_image.resize((sideX, sideY), Image.LANCZOS)\n",
683 | " z, *_ = model.encode(TF.to_tensor(pil_image).to(device).unsqueeze(0) * 2 - 1)\n",
684 | " else:\n",
685 | " one_hot = F.one_hot(torch.randint(n_toks, [toksY * toksX], device=device), n_toks).float()\n",
686 | " z = one_hot @ model.quantize.embedding.weight\n",
687 | " z = z.view([-1, toksY, toksX, e_dim]).permute(0, 3, 1, 2)\n",
688 | " z_orig = z.clone()\n",
689 | " z.requires_grad_(True)\n",
690 | " opt = optim.Adam([z], lr=args.step_size)\n",
691 | "\n",
692 | " normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],\n",
693 | " std=[0.26862954, 0.26130258, 0.27577711])\n",
694 | "\n",
695 | " pMs = []\n",
696 | "\n",
697 | " for prompt in args.prompts:\n",
698 | " txt, weight, stop = parse_prompt(prompt)\n",
699 | " embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()\n",
700 | " pMs.append(Prompt(embed, weight, stop).to(device))\n",
701 | "\n",
702 | " for prompt in args.image_prompts:\n",
703 | " path, weight, stop = parse_prompt(prompt)\n",
704 | " img = resize_image(Image.open(path).convert('RGB'), (sideX, sideY))\n",
705 | " batch = make_cutouts(TF.to_tensor(img).unsqueeze(0).to(device))\n",
706 | " embed = perceptor.encode_image(normalize(batch)).float()\n",
707 | " pMs.append(Prompt(embed, weight, stop).to(device))\n",
708 | "\n",
709 | " for seed, weight in zip(args.noise_prompt_seeds, args.noise_prompt_weights):\n",
710 | " gen = torch.Generator().manual_seed(seed)\n",
711 | " embed = torch.empty([1, perceptor.visual.output_dim]).normal_(generator=gen)\n",
712 | " pMs.append(Prompt(embed, weight).to(device))\n",
713 | "\n",
714 | " def synth(z):\n",
715 | " z_q = vector_quantize(z.movedim(1, 3), model.quantize.embedding.weight).movedim(3, 1)\n",
716 | " return clamp_with_grad(model.decode(z_q).add(1).div(2), 0, 1)\n",
717 | "\n",
718 | " def add_xmp_data(nombrefichero):\n",
719 | " image = ImgTag(filename=nombrefichero)\n",
720 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'creator', 'VQGAN+CLIP', {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
721 | " if args.prompts:\n",
722 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'title', \" | \".join(args.prompts), {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
723 | " else:\n",
724 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'title', 'None', {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
725 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'i', str(i), {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
726 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'model', model_name, {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
727 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'seed',str(seed) , {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
728 | " image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'input_images',str(input_images) , {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
729 | " #for frases in args.prompts:\n",
730 | " # image.xmp.append_array_item(libxmp.consts.XMP_NS_DC, 'Prompt' ,frases, {\"prop_array_is_ordered\":True, \"prop_value_is_array\":True})\n",
731 | " image.close()\n",
732 | "\n",
733 | " def add_stegano_data(filename):\n",
734 | " data = {\n",
735 | " \"title\": \" | \".join(args.prompts) if args.prompts else None,\n",
736 | " \"notebook\": \"VQGAN+CLIP\",\n",
737 | " \"i\": i,\n",
738 | " \"model\": model_name,\n",
739 | " \"seed\": str(seed),\n",
740 | " \"input_images\": input_images\n",
741 | " }\n",
742 | " lsb.hide(filename, json.dumps(data)).save(filename)\n",
743 | "\n",
744 | " @torch.no_grad()\n",
745 | " def checkin(i, losses):\n",
746 | " losses_str = ', '.join(f'{loss.item():g}' for loss in losses)\n",
747 | " tqdm.write(f'i: {i}, loss: {sum(losses).item():g}, losses: {losses_str}')\n",
748 | " out = synth(z)\n",
749 | " TF.to_pil_image(out[0].cpu()).save('progress.png')\n",
750 | " add_stegano_data('progress.png')\n",
751 | " add_xmp_data('progress.png')\n",
752 | " display.display(display.Image('progress.png'))\n",
753 | "\n",
754 | " def ascend_txt():\n",
755 | " global i\n",
756 | " out = synth(z)\n",
757 | " iii = perceptor.encode_image(normalize(make_cutouts(out))).float()\n",
758 | "\n",
759 | " result = []\n",
760 | "\n",
761 | " if args.init_weight:\n",
762 | " result.append(F.mse_loss(z, z_orig) * args.init_weight / 2)\n",
763 | "\n",
764 | " for prompt in pMs:\n",
765 | " result.append(prompt(iii))\n",
766 | " img = np.array(out.mul(255).clamp(0, 255)[0].cpu().detach().numpy().astype(np.uint8))[:,:,:]\n",
767 | " img = np.transpose(img, (1, 2, 0))\n",
768 | " filename = f\"steps/{i:04}.png\"\n",
769 | " imageio.imwrite(filename, np.array(img))\n",
770 | " add_stegano_data(filename)\n",
771 | " add_xmp_data(filename)\n",
772 | " return result\n",
773 | "\n",
774 | " def train(i):\n",
775 | " opt.zero_grad()\n",
776 | " lossAll = ascend_txt()\n",
777 | " if i % args.display_freq == 0:\n",
778 | " checkin(i, lossAll)\n",
779 | " loss = sum(lossAll)\n",
780 | " loss.backward()\n",
781 | " opt.step()\n",
782 | " with torch.no_grad():\n",
783 | " z.copy_(z.maximum(z_min).minimum(z_max))\n",
784 | "\n",
785 | " i = 0\n",
786 | " try:\n",
787 | " with tqdm() as pbar:\n",
788 | " while True:\n",
789 | " train(i)\n",
790 | " if i == max_iterations:\n",
791 | " break\n",
792 | " i += 1\n",
793 | " pbar.update()\n",
794 | " except KeyboardInterrupt:\n",
795 | " pass\n",
796 | "else:\n",
797 | " device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
798 | " print('Executing using CLIP guided diffusion method')\n",
799 | " if (prompt != None):\n",
800 | " print('Using prompt: '+ prompt)\n",
801 | "\n",
802 | " print('Using device:', device)\n",
803 | "\n",
804 | " model, diffusion = create_model_and_diffusion(**model_config)\n",
805 | " model.load_state_dict(torch.load('512x512_diffusion_uncond_finetune_008100.pt', map_location='cpu'))\n",
806 | " model.requires_grad_(False).eval().to(device)\n",
807 | " for name, param in model.named_parameters():\n",
808 | " if 'qkv' in name or 'norm' in name or 'proj' in name:\n",
809 | " param.requires_grad_()\n",
810 | " if model_config['use_fp16']:\n",
811 | " model.convert_to_fp16()\n",
812 | "\n",
813 | " clip_model = clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device)\n",
814 | " clip_size = clip_model.visual.input_resolution\n",
815 | " normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],\n",
816 | " std=[0.26862954, 0.26130258, 0.27577711])\n",
817 | " def do_run():\n",
818 | " if seed is not None:\n",
819 | " torch.manual_seed(seed)\n",
820 | "\n",
821 | " text_embed = clip_model.encode_text(clip.tokenize(prompt).to(device)).float()\n",
822 | "\n",
823 | " init = None\n",
824 | " # if init_image is not None:\n",
825 | " # init = Image.open(fetch(init_image)).convert('RGB')\n",
826 | " # init = init.resize((model_config['image_size'], model_config['image_size']), Image.LANCZOS)\n",
827 | " # init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)\n",
828 | "\n",
829 | " make_cutouts = MakeCutouts(clip_size, cutn, cut_pow)\n",
830 | "\n",
831 | " cur_t = None\n",
832 | "\n",
833 | " def cond_fn(x, t, y=None):\n",
834 | " with torch.enable_grad():\n",
835 | " x = x.detach().requires_grad_()\n",
836 | " n = x.shape[0]\n",
837 | " my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t\n",
838 | " out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})\n",
839 | " fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]\n",
840 | " x_in = out['pred_xstart'] * fac + x * (1 - fac)\n",
841 | " clip_in = normalize(make_cutouts(x_in.add(1).div(2)))\n",
842 | " image_embeds = clip_model.encode_image(clip_in).float().view([cutn, n, -1])\n",
843 | " dists = spherical_dist_loss(image_embeds, text_embed.unsqueeze(0))\n",
844 | " losses = dists.mean(0)\n",
845 | " tv_losses = tv_loss(x_in)\n",
846 | " loss = losses.sum() * clip_guidance_scale + tv_losses.sum() * tv_scale\n",
847 | " return -torch.autograd.grad(loss, x)[0]\n",
848 | "\n",
849 | " if model_config['timestep_respacing'].startswith('ddim'):\n",
850 | " sample_fn = diffusion.ddim_sample_loop_progressive\n",
851 | " else:\n",
852 | " sample_fn = diffusion.p_sample_loop_progressive\n",
853 | "\n",
854 | " for i in range(n_batches):\n",
855 | " cur_t = diffusion.num_timesteps - skip_timesteps - 1\n",
856 | "\n",
857 | " samples = sample_fn(\n",
858 | " model,\n",
859 | " (batch_size, 3, model_config['image_size'], model_config['image_size']),\n",
860 | " clip_denoised=False,\n",
861 | " model_kwargs={},\n",
862 | " cond_fn=cond_fn,\n",
863 | " progress=True,\n",
864 | " skip_timesteps=skip_timesteps,\n",
865 | " init_image=init,\n",
866 | " randomize_class=True,\n",
867 | " )\n",
868 | "\n",
869 | " for j, sample in enumerate(samples):\n",
870 | " cur_t -= 1\n",
871 | " if j % display_frequency == 0 or cur_t == -1:\n",
872 | " print()\n",
873 | " for k, image in enumerate(sample['pred_xstart']):\n",
874 | " filename = f'progress_{i * batch_size + k:05}.png'\n",
875 | " TF.to_pil_image(image.add(1).div(2).clamp(0, 1)).save(filename)\n",
876 | " tqdm.write(f'Batch {i}, step {j}, output {k}:')\n",
877 | " display.display(display.Image(filename))\n",
878 | "\n",
879 | " do_run()"
880 | ],
881 | "outputs": [],
882 | "metadata": {
883 | "id": "g7EDme5RYCrt",
884 | "cellView": "form"
885 | }
886 | },
887 | {
888 | "cell_type": "markdown",
889 | "source": [
890 | "## Generate a video with the results (VQGAN+CLIP method only)\n",
891 | "\n",
892 | "If you want to generate a video with the images as frames, just click below. You can modify the number of FPS, the initial frame, the last frame, etc."
893 | ],
894 | "metadata": {
895 | "id": "02ZbcWw5YYnU"
896 | }
897 | },
898 | {
899 | "cell_type": "code",
900 | "execution_count": null,
901 | "source": [
902 | "#@title Generate video using ffmpeg\n",
903 | "init_frame = 50 # This is the frame where the video will start\n",
904 | "last_frame = 150 # You can change i to the number of the last frame you want to generate. It will raise an error if that number of frames does not exist.\n",
905 | "\n",
906 | "min_fps = 30\n",
907 | "max_fps = 30\n",
908 | "\n",
909 | "total_frames = last_frame-init_frame\n",
910 | "\n",
911 | "length = 3 # Desired video runtime in seconds\n",
912 | "\n",
913 | "frames = []\n",
914 | "tqdm.write('Generating video...')\n",
915 | "for i in range(init_frame,last_frame): #\n",
916 | " filename = f\"steps/{i:04}.png\"\n",
917 | " frames.append(Image.open(filename))\n",
918 | "\n",
919 | "#fps = last_frame/10\n",
920 | "fps = np.clip(total_frames/length,min_fps,max_fps)\n",
921 | "\n",
922 | "# Names the video after the prompt if there is one, if not, defaults to video.mp4\n",
923 | "def listToString(s): \n",
924 | " \n",
925 | " # initialize an empty string\n",
926 | " str1 = \"\" \n",
927 | " \n",
928 | " # traverse in the string \n",
929 | " for ele in s: \n",
930 | " str1 += ele \n",
931 | " \n",
932 | " # return string \n",
933 | " return str1 \n",
934 | " \n",
935 | "\n",
936 | "video_filename = \"video\" #@param {type: \"string\"}\n",
937 | "\n",
938 | "\n",
939 | "video_filename = listToString(video_filename).replace(\" \",\"_\")\n",
940 | "print(\"Video filename: \"+ video_filename)\n",
941 | "\n",
942 | "video_filename = video_filename + \".mp4\"\n",
943 | "\n",
944 | "from subprocess import Popen, PIPE\n",
945 | "p = Popen(['ffmpeg', '-y', '-f', 'image2pipe', '-vcodec', 'png', '-r', str(fps), '-i', '-', '-vcodec', 'libx264', '-r', str(fps), '-pix_fmt', 'yuv420p', '-crf', '17', '-preset', 'veryslow', video_filename], stdin=PIPE)\n",
946 | "for im in tqdm(frames):\n",
947 | " im.save(p.stdin, 'PNG')\n",
948 | "p.stdin.close()\n",
949 | "\n",
950 | "print(\"Compressing video...\")\n",
951 | "p.wait()\n",
952 | "print(\"Video ready\")"
953 | ],
954 | "outputs": [],
955 | "metadata": {
956 | "id": "mFo5vz0UYBrF",
957 | "cellView": "form"
958 | }
959 | },
960 | {
961 | "cell_type": "code",
962 | "execution_count": null,
963 | "source": [
964 | "# @title View video in browser\n",
965 | "# @markdown This process may take a little longer. If you don't want to wait, download it by executing the next cell instead of using this cell.\n",
966 | "mp4 = open(video_filename,'rb').read()\n",
967 | "data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n",
968 | "display.HTML(\"\"\"\n",
969 | "\n",
972 | "\"\"\" % data_url)"
973 | ],
974 | "outputs": [],
975 | "metadata": {
976 | "id": "E8lvN6b0mb-b",
977 | "cellView": "form"
978 | }
979 | },
980 | {
981 | "cell_type": "code",
982 | "execution_count": null,
983 | "source": [
984 | "# @title Download video\n",
985 | "from google.colab import files\n",
986 | "files.download(video_filename)"
987 | ],
988 | "outputs": [],
989 | "metadata": {
990 | "id": "Y0e8pHyJmi7s"
991 | }
992 | }
993 | ]
994 | }
--------------------------------------------------------------------------------