commit c63baf98858ee844998cda9d31daf00e56d1ac17 Author: space-nuko <24979496+space-nuko@users.noreply.github.com> Date: Sun May 14 22:10:51 2023 -0500 first diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..931a5c7 --- /dev/null +++ b/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python + +from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS + +__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] diff --git a/diffuse.py b/diffuse.py new file mode 100644 index 0000000..35442fc --- /dev/null +++ b/diffuse.py @@ -0,0 +1,276 @@ +import pathlib, shutil, os, sys +from dataclasses import dataclass +from functools import partial +import cv2 +import pandas as pd +import gc +import io +import math +import lpips +from PIL import Image, ImageOps +import requests +from glob import glob +import json +from types import SimpleNamespace +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +from datetime import datetime +import numpy as np +import random +import hashlib +from functools import partial +from numpy import asarray +import time +import warnings +import os + +import comfy.model_management +from . import disco_utils +from .settings import DiscoDiffusionSettings +from .do_run import do_run + + +# %% +# !! {"metadata":{ +# !! "id": "DoTheRun" +# !! }} +#@title Do the Run! +#@markdown `n_batches` ignored with animation modes. +def diffuse(clip, args: DiscoDiffusionSettings, batchNum): + args.display_rate = 20 #@param{type: 'number'} + args.n_batches = 50 #@param{type: 'number'} + + if args.animation_mode == 'Video Input': + args.steps = args.video_init_steps + + #Update Model Settings + timestep_respacing = f'ddim{args.steps}' + diffusion_steps = (1000//args.steps)*args.steps if args.steps < 1000 else args.steps + args.MS.model_config.update({ + 'timestep_respacing': timestep_respacing, + 'diffusion_steps': diffusion_steps, + }) + + args.batch_size = 1 + + def move_files(start_num, end_num, old_folder, new_folder): + for i in range(start_num, end_num): + old_file = old_folder + f'/{args.batch_name}({batchNum})_{i:04}.png' + new_file = new_folder + f'/{args.batch_name}({batchNum})_{i:04}.png' + os.rename(old_file, new_file) + + #@markdown --- + + + args.resume_run = False #@param{type: 'boolean'} + run_to_resume = 'latest' #@param{type: 'string'} + resume_from_frame = 'latest' #@param{type: 'string'} + retain_overwritten_frames = False #@param{type: 'boolean'} + if retain_overwritten_frames: + retainFolder = f'{args.batchFolder}/retained' + os.makedirs(retainFolder, exist_ok=True) + + skip_step_ratio = int(args.frames_skip_steps.rstrip("%")) / 100 + args.calc_frames_skip_steps = math.floor(args.steps * skip_step_ratio) + + if args.animation_mode == 'Video Input': + frames = sorted(glob(args.in_path+'/*.*')); + if len(frames)==0: + sys.exit("ERROR: 0 frames found.\nPlease check your video input path and rerun the video settings cell.") + flows = glob(args.flo_folder+'/*.*') + if (len(flows)==0) and args.video_init_flow_warp: + sys.exit("ERROR: 0 flow files found.\nPlease rerun the flow generation cell.") + + if args.steps <= args.calc_frames_skip_steps: + sys.exit("ERROR: You can't skip more steps than your total steps") + + if args.resume_run: + if run_to_resume == 'latest': + try: + batchNum + except: + batchNum = len(glob(f"{args.batchFolder}/{args.batch_name}(*)_settings.txt"))-1 + else: + batchNum = int(run_to_resume) + if resume_from_frame == 'latest': + start_frame = len(glob(args.batchFolder+f"/{args.batch_name}({batchNum})_*.png")) + if args.animation_mode != '3D' and args.turbo_mode == True and start_frame > args.turbo_preroll and start_frame % int(args.turbo_steps) != 0: + start_frame = start_frame - (start_frame % int(args.turbo_steps)) + else: + start_frame = int(resume_from_frame)+1 + if args.animation_mode != '3D' and args.turbo_mode == True and start_frame > args.turbo_preroll and start_frame % int(args.turbo_steps) != 0: + start_frame = start_frame - (start_frame % int(args.turbo_steps)) + if retain_overwritten_frames is True: + existing_frames = len(glob(args.batchFolder+f"/{args.batch_name}({batchNum})_*.png")) + frames_to_save = existing_frames - start_frame + print(f'Moving {frames_to_save} frames to the Retained folder') + move_files(start_frame, existing_frames, args.batchFolder, retainFolder) + else: + start_frame = 0 + batchNum = len(glob(args.batchFolder+"/*.txt")) + while os.path.isfile(f"{args.batchFolder}/{args.batch_name}({batchNum})_settings.txt") or os.path.isfile(f"{args.batchFolder}/{args.batch_name}-{batchNum}_settings.txt"): + batchNum += 1 + + print(f'Starting Run: {args.batch_name}({batchNum}) at frame {start_frame}') + + if args.set_seed == 'random_seed': + random.seed() + seed = random.randint(0, 2**32) + # print(f'Using seed: {seed}') + else: + seed = int(args.set_seed) + + args.n_batches = args.n_batches if args.animation_mode == 'None' else 1 + args.max_frames = args.max_frames if args.animation_mode == 'None' else 1 + args.start_frame = start_frame + args.seed = seed + args.prompts_series = disco_utils.split_prompts(args.text_prompts, args.max_frames) if args.text_prompts else None, + args.image_prompts_series = disco_utils.split_prompts(args.image_prompts, args.max_frames) if args.image_prompts else None, + + # args = { + # 'batchNum': batchNum, + # 'prompts_series':split_prompts(text_prompts) if text_prompts else None, + # 'image_prompts_series':split_prompts(image_prompts) if image_prompts else None, + # 'seed': seed, + # 'display_rate':display_rate, + # 'n_batches':n_batches if animation_mode == 'None' else 1, + # 'batch_size':batch_size, + # 'batch_name': batch_name, + # 'steps': steps, + # 'diffusion_sampling_mode': diffusion_sampling_mode, + # 'width_height': width_height, + # 'clip_guidance_scale': clip_guidance_scale, + # 'tv_scale': tv_scale, + # 'range_scale': range_scale, + # 'sat_scale': sat_scale, + # 'cutn_batches': cutn_batches, + # 'init_image': init_image, + # 'init_scale': init_scale, + # 'skip_steps': skip_steps, + # 'side_x': side_x, + # 'side_y': side_y, + # 'timestep_respacing': timestep_respacing, + # 'diffusion_steps': diffusion_steps, + # 'animation_mode': animation_mode, + # 'video_init_path': video_init_path, + # 'extract_nth_frame': extract_nth_frame, + # 'video_init_seed_continuity': video_init_seed_continuity, + # 'key_frames': key_frames, + # 'max_frames': max_frames if animation_mode != "None" else 1, + # 'interp_spline': interp_spline, + # 'start_frame': start_frame, + # 'angle': angle, + # 'zoom': zoom, + # 'translation_x': translation_x, + # 'translation_y': translation_y, + # 'translation_z': translation_z, + # 'rotation_3d_x': rotation_3d_x, + # 'rotation_3d_y': rotation_3d_y, + # 'rotation_3d_z': rotation_3d_z, + # 'midas_depth_model': midas_depth_model, + # 'midas_weight': midas_weight, + # 'near_plane': near_plane, + # 'far_plane': far_plane, + # 'fov': fov, + # 'padding_mode': padding_mode, + # 'sampling_mode': sampling_mode, + # 'angle_series':angle_series, + # 'zoom_series':zoom_series, + # 'translation_x_series':translation_x_series, + # 'translation_y_series':translation_y_series, + # 'translation_z_series':translation_z_series, + # 'rotation_3d_x_series':rotation_3d_x_series, + # 'rotation_3d_y_series':rotation_3d_y_series, + # 'rotation_3d_z_series':rotation_3d_z_series, + # 'frames_scale': frames_scale, + # 'skip_step_ratio': skip_step_ratio, + # 'calc_frames_skip_steps': calc_frames_skip_steps, + # 'text_prompts': text_prompts, + # 'image_prompts': image_prompts, + # 'cut_overview': eval(cut_overview), + # 'cut_innercut': eval(cut_innercut), + # 'cut_ic_pow': eval(cut_ic_pow), + # 'cut_icgray_p': eval(cut_icgray_p), + # 'intermediate_saves': intermediate_saves, + # 'intermediates_in_subfolder': intermediates_in_subfolder, + # 'steps_per_checkpoint': steps_per_checkpoint, + # 'perlin_init': perlin_init, + # 'perlin_mode': perlin_mode, + # 'set_seed': set_seed, + # 'eta': eta, + # 'clamp_grad': clamp_grad, + # 'clamp_max': clamp_max, + # 'skip_augs': skip_augs, + # 'randomize_class': randomize_class, + # 'clip_denoised': clip_denoised, + # 'fuzzy_prompt': fuzzy_prompt, + # 'rand_mag': rand_mag, + # 'turbo_mode':turbo_mode, + # 'turbo_steps':turbo_steps, + # 'turbo_preroll':turbo_preroll, + # 'use_vertical_symmetry': use_vertical_symmetry, + # 'use_horizontal_symmetry': use_horizontal_symmetry, + # 'transformation_percent': transformation_percent, + # #video init settings + # 'video_init_steps': video_init_steps, + # 'video_init_clip_guidance_scale': video_init_clip_guidance_scale, + # 'video_init_tv_scale': video_init_tv_scale, + # 'video_init_range_scale': video_init_range_scale, + # 'video_init_sat_scale': video_init_sat_scale, + # 'video_init_cutn_batches': video_init_cutn_batches, + # 'video_init_skip_steps': video_init_skip_steps, + # 'video_init_frames_scale': video_init_frames_scale, + # 'video_init_frames_skip_steps': video_init_frames_skip_steps, + # #warp settings + # 'video_init_flow_warp':video_init_flow_warp, + # 'video_init_flow_blend':video_init_flow_blend, + # 'video_init_check_consistency':video_init_check_consistency, + # 'video_init_blend_mode':video_init_blend_mode + # } + + # if animation_mode == 'Video Input': + # # This isn't great in terms of what will get saved to the settings.. but it should work. + # args['steps'] = args['video_init_steps'] + # args['clip_guidance_scale'] = args['video_init_clip_guidance_scale'] + # args['tv_scale'] = args['video_init_tv_scale'] + # args['range_scale'] = args['video_init_range_scale'] + # args['sat_scale'] = args['video_init_sat_scale'] + # args['cutn_batches'] = args['video_init_cutn_batches'] + # args['skip_steps'] = args['video_init_skip_steps'] + # args['frames_scale'] = args['video_init_frames_scale'] + # args['frames_skip_steps'] = args['video_init_frames_skip_steps'] + + # args = SimpleNamespace(**args) + + device = comfy.model_management.get_torch_device() + + print('Prepping model...') + model, diffusion = create_model_and_diffusion(**args.MS.model_config) + if args.MS.diffusion_model == 'custom': + model.load_state_dict(torch.load(args.MS.custom_path, map_location='cpu')) + else: + model.load_state_dict(torch.load(f'{args.MS.model_path}/{args.MS.get_model_filename(args.MS.diffusion_model)}', map_location='cpu')) + model.requires_grad_(False).eval().to(device) + for name, param in model.named_parameters(): + if 'qkv' in name or 'norm' in name or 'proj' in name: + param.requires_grad_() + if args.MS.model_config['use_fp16']: + model.convert_to_fp16() + + gc.collect() + torch.cuda.empty_cache() + try: + do_run(diffusion, model, clip, args, batchNum) + except KeyboardInterrupt: + pass + finally: + print('Seed used:', seed) + gc.collect() + torch.cuda.empty_cache() diff --git a/disco.py b/disco.py new file mode 100644 index 0000000..8f5c59b --- /dev/null +++ b/disco.py @@ -0,0 +1,36 @@ +PROJECT_DIR = os.path.abspath(os.getcwd()) +USE_ADABINS = False + +import pathlib, shutil, os, sys +from dataclasses import dataclass +from functools import partial +import cv2 +import pandas as pd +import gc +import io +import math +import lpips +from PIL import Image, ImageOps +import requests +from glob import glob +import json +from types import SimpleNamespace +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +from datetime import datetime +import numpy as np +import random +import hashlib +from functools import partial +from numpy import asarray +import time +import warnings + +warnings.filterwarnings("ignore", category=UserWarning) diff --git a/disco_utils.py b/disco_utils.py new file mode 100644 index 0000000..237327c --- /dev/null +++ b/disco_utils.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python + +from . import py3d_tools as p3dT +from . import disco_xform_utils as dxf +import torchvision.transforms as T +import cv2 +import pandas as pd +import gc +import io +import math +import lpips +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision.transforms.functional as TF +import subprocess +from importlib import util as importlibutil +import numpy as np + +import comfy.model_management + +def split_prompts(prompts, max_frames): + prompt_series = pd.Series([np.nan for a in range(max_frames)]) + for i, prompt in prompts.items(): + prompt_series[i] = prompt + # prompt_series = prompt_series.astype(str) + prompt_series = prompt_series.ffill().bfill() + return prompt_series + +# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869 + +def interp(t): + return 3 * t**2 - 2 * t ** 3 + +def perlin(width, height, scale=10, device=None): + gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device) + xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device) + ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device) + wx = 1 - interp(xs) + wy = 1 - interp(ys) + dots = 0 + dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys) + dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys) + dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys)) + dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys)) + return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale) + +def perlin_ms(octaves, width, height, grayscale, device=None): + if not device: + device = comfy.model_management.get_torch_device() + out_array = [0.5] if grayscale else [0.5, 0.5, 0.5] + # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0] + for i in range(1 if grayscale else 3): + scale = 2 ** len(octaves) + oct_width = width + oct_height = height + for oct in octaves: + p = perlin(oct_width, oct_height, scale, device) + out_array[i] += p * oct + scale //= 2 + oct_width *= 2 + oct_height *= 2 + return torch.cat(out_array) + +def create_perlin_noise(side_x, side_y, octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True): + out = perlin_ms(octaves, width, height, grayscale) + if grayscale: + out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0)) + out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB') + else: + out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1]) + out = TF.resize(size=(side_y, side_x), img=out) + out = TF.to_pil_image(out.clamp(0, 1).squeeze()) + + out = ImageOps.autocontrast(out) + return out + +def regen_perlin(perlin_mode, batch_size, expand=False): + if perlin_mode == 'color': + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) + elif perlin_mode == 'gray': + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) + else: + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) + + device = comfy.model_management.get_torch_device() + init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) + del init2 + if expand: + return init.expand(batch_size, -1, -1, -1) + return init + +def fetch(url_or_path): + if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'): + r = requests.get(url_or_path) + r.raise_for_status() + fd = io.BytesIO() + fd.write(r.content) + fd.seek(0) + return fd + return open(url_or_path, 'rb') + +def read_image_workaround(path): + """OpenCV reads images as BGR, Pillow saves them as RGB. Work around + this incompatibility to avoid colour inversions.""" + im_tmp = cv2.imread(path) + return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB) + +def parse_prompt(prompt): + if prompt.startswith('http://') or prompt.startswith('https://'): + vals = prompt.rsplit(':', 2) + vals = [vals[0] + ':' + vals[1], *vals[2:]] + else: + vals = prompt.rsplit(':', 1) + vals = vals + ['', '1'][len(vals):] + return vals[0], float(vals[1]) + +def sinc(x): + return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([])) + +def lanczos(x, a): + cond = torch.logical_and(-a < x, x < a) + out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([])) + return out / out.sum() + +def ramp(ratio, width): + n = math.ceil(width / ratio + 1) + out = torch.empty([n]) + cur = 0 + for i in range(out.shape[0]): + out[i] = cur + cur += ratio + return torch.cat([-out[1:].flip([0]), out])[1:-1] + +def resample(input, size, align_corners=True): + n, c, h, w = input.shape + dh, dw = size + + input = input.reshape([n * c, 1, h, w]) + + if dh < h: + kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype) + pad_h = (kernel_h.shape[0] - 1) // 2 + input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect') + input = F.conv2d(input, kernel_h[None, None, :, None]) + + if dw < w: + kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype) + pad_w = (kernel_w.shape[0] - 1) // 2 + input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect') + input = F.conv2d(input, kernel_w[None, None, None, :]) + + input = input.reshape([n, c, h, w]) + return F.interpolate(input, size, mode='bicubic', align_corners=align_corners) + +def spherical_dist_loss(x, y): + x = F.normalize(x, dim=-1) + y = F.normalize(y, dim=-1) + return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) + +def tv_loss(input): + """L2 total variation loss, as in Mahendran et al.""" + input = F.pad(input, (0, 1, 0, 1), 'replicate') + x_diff = input[..., :-1, 1:] - input[..., :-1, :-1] + y_diff = input[..., 1:, :-1] - input[..., :-1, :-1] + return (x_diff**2 + y_diff**2).mean([1, 2, 3]) + + +def range_loss(input): + return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3]) + + +normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) + + +def module_exists(module_name): + return importlibutil.find_spec(module_name) + +def gitclone(url, targetdir=None): + if targetdir: + res = subprocess.run(['git', 'clone', url, targetdir], stdout=subprocess.PIPE).stdout.decode('utf-8') + else: + res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +def pipi(modulestr): + res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +def pipie(modulestr): + res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +def wget(url, outputdir): + res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) diff --git a/disco_xform_utils.py b/disco_xform_utils.py new file mode 100644 index 0000000..86d3227 --- /dev/null +++ b/disco_xform_utils.py @@ -0,0 +1,150 @@ +import torch +import torchvision +from . import py3d_tools as p3d +import midas_utils +from PIL import Image +import numpy as np +import sys, math +import cv2 +import pandas as pd +import gc +import math +import lpips +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from numpy import asarray + +MAX_ADABINS_AREA = 500000 +MIN_ADABINS_AREA = 448*448 + +@torch.no_grad() +def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_mat=torch.eye(3).unsqueeze(0), translate=(0.,0.,-0.04), near=2000, far=20000, fov_deg=60, padding_mode='border', sampling_mode='bicubic', midas_weight = 0.3,spherical=False): + img_pil = Image.open(open(img_filepath, 'rb')).convert('RGB') + w, h = img_pil.size + image_tensor = torchvision.transforms.functional.to_tensor(img_pil).to(device) + + use_adabins = midas_weight < 1.0 + + if use_adabins: + try: + from infer import InferenceHelper + except: + print("disco_xform_utils.py failed to import InferenceHelper. Please ensure that AdaBins directory is in the path (i.e. via sys.path.append('./AdaBins') or other means).") + sys.exit() + + # AdaBins + """ + predictions using nyu dataset + """ + print("Running AdaBins depth estimation implementation...") + infer_helper = InferenceHelper(dataset='nyu', device=device) + + image_pil_area = w*h + if image_pil_area > MAX_ADABINS_AREA: + scale = math.sqrt(MAX_ADABINS_AREA) / math.sqrt(image_pil_area) + depth_input = img_pil.resize((int(w*scale), int(h*scale)), Image.LANCZOS) # LANCZOS is supposed to be good for downsampling. + elif image_pil_area < MIN_ADABINS_AREA: + scale = math.sqrt(MIN_ADABINS_AREA) / math.sqrt(image_pil_area) + depth_input = img_pil.resize((int(w*scale), int(h*scale)), Image.BICUBIC) + else: + depth_input = img_pil + try: + _, adabins_depth = infer_helper.predict_pil(depth_input) + if image_pil_area != MAX_ADABINS_AREA: + adabins_depth = torchvision.transforms.functional.resize(torch.from_numpy(adabins_depth), image_tensor.shape[-2:], interpolation=torchvision.transforms.functional.InterpolationMode.BICUBIC).squeeze().to(device) + else: + adabins_depth = torch.from_numpy(adabins_depth).squeeze().to(device) + adabins_depth_np = adabins_depth.cpu().numpy() + except: + pass + + torch.cuda.empty_cache() + + # MiDaS + img_midas = midas_utils.read_image(img_filepath) + img_midas_input = midas_transform({"image": img_midas})["image"] + midas_optimize = True + + # MiDaS depth estimation implementation + print("Running MiDaS depth estimation implementation...") + sample = torch.from_numpy(img_midas_input).float().to(device).unsqueeze(0) + if midas_optimize==True and device == torch.device("cuda"): + sample = sample.to(memory_format=torch.channels_last) + sample = sample.half() + prediction_torch = midas_model.forward(sample) + prediction_torch = torch.nn.functional.interpolate( + prediction_torch.unsqueeze(1), + size=img_midas.shape[:2], + mode="bicubic", + align_corners=False, + ).squeeze() + prediction_np = prediction_torch.clone().cpu().numpy() + + print("Finished depth estimation.") + torch.cuda.empty_cache() + + # MiDaS makes the near values greater, and the far values lesser. Let's reverse that and try to align with AdaBins a bit better. + prediction_np = np.subtract(50.0, prediction_np) + prediction_np = prediction_np / 19.0 + + if use_adabins: + adabins_weight = 1.0 - midas_weight + depth_map = prediction_np*midas_weight + adabins_depth_np*adabins_weight + else: + depth_map = prediction_np + + depth_map = np.expand_dims(depth_map, axis=0) + depth_tensor = torch.from_numpy(depth_map).squeeze().to(device) + + pixel_aspect = 1.0 # really.. the aspect of an individual pixel! (so usually 1.0) + persp_cam_old = p3d.FoVPerspectiveCameras(near, far, pixel_aspect, fov=fov_deg, degrees=True, device=device) + persp_cam_new = p3d.FoVPerspectiveCameras(near, far, pixel_aspect, fov=fov_deg, degrees=True, R=rot_mat, T=torch.tensor([translate]), device=device) + + # range of [-1,1] is important to torch grid_sample's padding handling + y,x = torch.meshgrid(torch.linspace(-1.,1.,h,dtype=torch.float32,device=device),torch.linspace(-1.,1.,w,dtype=torch.float32,device=device)) + z = torch.as_tensor(depth_tensor, dtype=torch.float32, device=device) + xyz_old_world = torch.stack((x.flatten(), y.flatten(), z.flatten()), dim=1) + + # Transform the points using pytorch3d. With current functionality, this is overkill and prevents it from working on Windows. + # If you want it to run on Windows (without pytorch3d), then the transforms (and/or perspective if that's separate) can be done pretty easily without it. + xyz_old_cam_xy = persp_cam_old.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2] + xyz_new_cam_xy = persp_cam_new.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2] + + offset_xy = xyz_new_cam_xy - xyz_old_cam_xy + # affine_grid theta param expects a batch of 2D mats. Each is 2x3 to do rotation+translation. + identity_2d_batch = torch.tensor([[1.,0.,0.],[0.,1.,0.]], device=device).unsqueeze(0) + # coords_2d will have shape (N,H,W,2).. which is also what grid_sample needs. + coords_2d = torch.nn.functional.affine_grid(identity_2d_batch, [1,1,h,w], align_corners=False) + offset_coords_2d = coords_2d - torch.reshape(offset_xy, (h,w,2)).unsqueeze(0) + + if spherical: + spherical_grid = get_spherical_projection(h, w, torch.tensor([0,0], device=device), -0.4,device=device)#align_corners=False + stage_image = torch.nn.functional.grid_sample(image_tensor.add(1/512 - 0.0001).unsqueeze(0), offset_coords_2d, mode=sampling_mode, padding_mode=padding_mode, align_corners=True) + new_image = torch.nn.functional.grid_sample(stage_image, spherical_grid,align_corners=True) #, mode=sampling_mode, padding_mode=padding_mode, align_corners=False) + else: + new_image = torch.nn.functional.grid_sample(image_tensor.add(1/512 - 0.0001).unsqueeze(0), offset_coords_2d, mode=sampling_mode, padding_mode=padding_mode, align_corners=False) + + img_pil = torchvision.transforms.ToPILImage()(new_image.squeeze().clamp(0,1.)) + + torch.cuda.empty_cache() + + return img_pil + +def get_spherical_projection(H, W, center, magnitude,device): + xx, yy = torch.linspace(-1, 1, W,dtype=torch.float32,device=device), torch.linspace(-1, 1, H,dtype=torch.float32,device=device) + gridy, gridx = torch.meshgrid(yy, xx) + grid = torch.stack([gridx, gridy], dim=-1) + d = center - grid + d_sum = torch.sqrt((d**2).sum(axis=-1)) + grid += d * d_sum.unsqueeze(-1) * magnitude + return grid.unsqueeze(0) diff --git a/do_run.py b/do_run.py new file mode 100644 index 0000000..bbcae77 --- /dev/null +++ b/do_run.py @@ -0,0 +1,691 @@ +import shutil +import cv2 +import pandas as pd +import gc +import math +import lpips +import PIL +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +from datetime import datetime +import numpy as np +import random +from numpy import asarray +from . import py3d_tools as p3dT +from . import disco_xform_utils as dxf + +import comfy.model_management + +from . import disco_utils +from .make_cutouts import MakeCutouts, MakeCutoutsDango +from .midas_model import init_midas_depth_model +from .settings import DiscoDiffusionSettings + +# Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete +stop_on_next_loop = False +TRANSLATION_SCALE = 1.0/200.0 + +def do_3d_step(args: DiscoDiffusionSettings, img_filepath, frame_num, midas_model, midas_transform): + if args.key_frames: + translation_x = args.translation_x_series[frame_num] + translation_y = args.translation_y_series[frame_num] + translation_z = args.translation_z_series[frame_num] + rotation_3d_x = args.rotation_3d_x_series[frame_num] + rotation_3d_y = args.rotation_3d_y_series[frame_num] + rotation_3d_z = args.rotation_3d_z_series[frame_num] + print( + f'translation_x: {translation_x}', + f'translation_y: {translation_y}', + f'translation_z: {translation_z}', + f'rotation_3d_x: {rotation_3d_x}', + f'rotation_3d_y: {rotation_3d_y}', + f'rotation_3d_z: {rotation_3d_z}', + ) + + device = comfy.model_management.get_torch_device() + + translate_xyz = [-translation_x*TRANSLATION_SCALE, translation_y * + TRANSLATION_SCALE, -translation_z*TRANSLATION_SCALE] + rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z] + print('translation:', translate_xyz) + print('rotation:', rotate_xyz_degrees) + rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians( + rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])] + rot_mat = p3dT.euler_angles_to_matrix(torch.tensor( + rotate_xyz, device=device), "XYZ").unsqueeze(0) + print("rot_mat: " + str(rot_mat)) + next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, device, + rot_mat, translate_xyz, args.near_plane, args.far_plane, + args.fov, padding_mode=args.padding_mode, + sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) + return next_step_pil + + +def horiz_symmetry(x): + [n, c, h, w] = x.size() + x = torch.concat( + (x[:, :, :, :w//2], torch.flip(x[:, :, :, :w//2], [-1])), -1) + print("horizontal symmetry applied") + return x + + +def vert_symmetry(x): + [n, c, h, w] = x.size() + x = torch.concat( + (x[:, :, :h//2, :], torch.flip(x[:, :, :h//2, :], [-2])), -2) + print("vertical symmetry applied") + return x + + +def id(x): + return x + + +def do_run(diffusion, model, clip, args: DiscoDiffusionSettings, batchNum): + seed = args.seed + print(range(args.start_frame, args.max_frames)) + + if (args.animation_mode == "3D") and (args.midas_weight > 0.0): + midas_model, midas_transform, midas_net_w, midas_net_h, midas_resize_mode, midas_normalization = init_midas_depth_model( + args.midas_depth_model) + for frame_num in range(args.start_frame, args.max_frames): + if stop_on_next_loop: + break + + # display.clear_output(wait=True) + + # Print Frame progress if animation mode is on + if args.animation_mode != "None": + batchBar = tqdm(range(args.max_frames), desc="Frames") + batchBar.n = frame_num + batchBar.refresh() + + # Inits if not video frames + if args.animation_mode != "Video Input": + if args.init_image in ['', 'none', 'None', 'NONE']: + init_image = None + else: + init_image = args.init_image + init_scale = args.init_scale + skip_steps = args.skip_steps + + if args.animation_mode == "2D": + if args.key_frames: + angle = args.angle_series[frame_num] + zoom = args.zoom_series[frame_num] + translation_x = args.translation_x_series[frame_num] + translation_y = args.translation_y_series[frame_num] + print( + f'angle: {angle}', + f'zoom: {zoom}', + f'translation_x: {translation_x}', + f'translation_y: {translation_y}', + ) + + if frame_num > 0: + seed += 1 + if args.resume_run and frame_num == args.start_frame: + img_0 = cv2.imread( + args.batchFolder+f"/{args.batch_name}({batchNum})_{args.start_frame-1:04}.png") + else: + img_0 = cv2.imread('prevFrame.png') + center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2) + trans_mat = np.float32( + [[1, 0, translation_x], + [0, 1, translation_y]] + ) + rot_mat = cv2.getRotationMatrix2D(center, angle, zoom) + trans_mat = np.vstack([trans_mat, [0, 0, 1]]) + rot_mat = np.vstack([rot_mat, [0, 0, 1]]) + transformation_matrix = np.matmul(rot_mat, trans_mat) + img_0 = cv2.warpPerspective( + img_0, + transformation_matrix, + (img_0.shape[1], img_0.shape[0]), + borderMode=cv2.BORDER_WRAP + ) + + cv2.imwrite('prevFrameScaled.png', img_0) + init_image = 'prevFrameScaled.png' + init_scale = args.frames_scale + skip_steps = args.calc_frames_skip_steps + + if args.animation_mode == "3D": + if frame_num > 0: + seed += 1 + if args.resume_run and frame_num == args.start_frame: + img_filepath = args.batchFolder + \ + f"/{args.batch_name}({batchNum})_{args.start_frame-1:04}.png" + if args.turbo_mode and frame_num > args.turbo_preroll: + shutil.copyfile(img_filepath, 'oldFrameScaled.png') + else: + img_filepath = 'prevFrame.png' + + next_step_pil = do_3d_step( + args, img_filepath, frame_num, midas_model, midas_transform) + next_step_pil.save('prevFrameScaled.png') + + # Turbo mode - skip some diffusions, use 3d morph for clarity and to save time + if args.turbo_mode: + if frame_num == args.turbo_preroll: # start tracking oldframe + # stash for later blending + next_step_pil.save('oldFrameScaled.png') + elif frame_num > args.turbo_preroll: + # set up 2 warped image sequences, old & new, to blend toward new diff image + old_frame = do_3d_step( + args, 'oldFrameScaled.png', frame_num, midas_model, midas_transform) + old_frame.save('oldFrameScaled.png') + if frame_num % int(args.turbo_steps) != 0: + print( + 'turbo skip this frame: skipping clip diffusion steps') + filename = f'{args.batch_name}({batchNum})_{frame_num:04}.png' + blend_factor = ( + (frame_num % int(args.turbo_steps))+1)/int(args.turbo_steps) + print( + 'turbo skip this frame: skipping clip diffusion steps and saving blended frame') + # this is already updated.. + newWarpedImg = cv2.imread('prevFrameScaled.png') + oldWarpedImg = cv2.imread('oldFrameScaled.png') + blendedImage = cv2.addWeighted( + newWarpedImg, blend_factor, oldWarpedImg, 1-blend_factor, 0.0) + cv2.imwrite( + f'{args.batchFolder}/{filename}', blendedImage) + # save it also as prev_frame to feed next iteration + next_step_pil.save(f'{img_filepath}') + if args.vr_mode: + generate_eye_views( + TRANSLATION_SCALE, args.batchFolder, filename, frame_num, midas_model, midas_transform) + continue + else: + # if not a skip frame, will run diffusion and need to blend. + oldWarpedImg = cv2.imread('prevFrameScaled.png') + # swap in for blending later + cv2.imwrite(f'oldFrameScaled.png', oldWarpedImg) + print('clip/diff this frame - generate clip diff image') + + init_image = 'prevFrameScaled.png' + init_scale = args.frames_scale + skip_steps = args.calc_frames_skip_steps + + if args.animation_mode == "Video Input": + init_scale = args.video_init_frames_scale + skip_steps = args.calc_frames_skip_steps + if not args.video_init_seed_continuity: + seed += 1 + if args.video_init_flow_warp: + if frame_num == 0: + skip_steps = args.video_init_skip_steps + init_image = f'{args.videoFramesFolder}/{frame_num+1:04}.jpg' + if frame_num > 0: + prev = PIL.Image.open( + args.batchFolder+f"/{args.batch_name}({batchNum})_{frame_num-1:04}.png") + + frame1_path = f'{args.videoFramesFolder}/{frame_num:04}.jpg' + frame2 = PIL.Image.open( + f'{args.videoFramesFolder}/{frame_num+1:04}.jpg') + flo_path = f"/{args.flo_folder}/{frame1_path.split('/')[-1]}.npy" + + init_image = 'warped.png' + print(args.video_init_flow_blend) + weights_path = None + if args.video_init_check_consistency: + # TBD + pass + + import video_input + video_input.warp(prev, frame2, flo_path, blend=args.video_init_flow_blend, + weights_path=weights_path).save(init_image) + + else: + init_image = f'{args.videoFramesFolder}/{frame_num+1:04}.jpg' + + loss_values = [] + + if seed is not None: + np.random.seed(seed) + random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + + target_embeds, weights = [], [] + + if args.prompts_series is not None and frame_num >= len(args.prompts_series): + frame_prompt = args.prompts_series[-1] + elif args.prompts_series is not None: + frame_prompt = args.prompts_series[frame_num] + else: + frame_prompt = [] + + print(args.image_prompts_series) + if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series): + image_prompt = args.image_prompts_series[-1] + elif args.image_prompts_series is not None: + image_prompt = args.image_prompts_series[frame_num] + else: + image_prompt = [] + + device = comfy.model_management.get_torch_device() + + print(f'Frame {frame_num} Prompt: {frame_prompt}') + + clip_models = [clip] # TODO!!!!!!!!!!!!!!!!!!!!! + + model_stats = [] + for clip_model in clip_models: + cutn = 16 + model_stat = {"clip_model": None, "target_embeds": [], + "make_cutouts": None, "weights": []} + model_stat["clip_model"] = clip_model + + for prompt in frame_prompt: + txt, weight = disco_utils.parse_prompt(prompt) + txt = clip_model.encode(prompt).float() + + if args.fuzzy_prompt: + for i in range(25): + model_stat["target_embeds"].append( + (txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0, 1)) + model_stat["weights"].append(weight) + else: + model_stat["target_embeds"].append(txt) + model_stat["weights"].append(weight) + + if image_prompt: + model_stat["make_cutouts"] = MakeCutouts( + clip_model.visual.input_resolution, cutn, skip_augs=args.skip_augs) + for prompt in image_prompt: + path, weight = disco_utils.parse_prompt(prompt) + img = Image.open(disco_utils.fetch(path)).convert('RGB') + img = TF.resize( + img, min(args.side_x, args.side_y, *img.size), T.InterpolationMode.LANCZOS) + batch = model_stat["make_cutouts"](TF.to_tensor( + img).to(device).unsqueeze(0).mul(2).sub(1)) + embed = clip_model.encode_image( + disco_utils.normalize(batch)).float() + if args.fuzzy_prompt: + for i in range(25): + model_stat["target_embeds"].append( + (embed + torch.randn(embed.shape).cuda() * args.rand_mag).clamp(0, 1)) + weights.extend([weight / cutn] * cutn) + else: + model_stat["target_embeds"].append(embed) + model_stat["weights"].extend([weight / cutn] * cutn) + + model_stat["target_embeds"] = torch.cat( + model_stat["target_embeds"]) + model_stat["weights"] = torch.tensor( + model_stat["weights"], device=device) + if model_stat["weights"].sum().abs() < 1e-3: + raise RuntimeError('The weights must not sum to 0.') + model_stat["weights"] /= model_stat["weights"].sum().abs() + model_stats.append(model_stat) + + init = None + if init_image is not None: + init = Image.open(disco_utils.fetch(init_image)).convert('RGB') + init = init.resize((args.side_x, args.side_y), Image.LANCZOS) + init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1) + + if args.perlin_init: + init = disco_utils.regen_perlin() + + cur_t = None + + def cond_fn(x, t, y=None): + with torch.enable_grad(): + x_is_NaN = False + x = x.detach().requires_grad_() + n = x.shape[0] + if args.MS.use_secondary_model is True: + alpha = torch.tensor( + diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32) + sigma = torch.tensor( + diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32) + cosine_t = disco_utils.alpha_sigma_to_t(alpha, sigma) + out = args.MS.secondary_model( + x, cosine_t[None].repeat([n])).pred + fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] + x_in = out * fac + x * (1 - fac) + x_in_grad = torch.zeros_like(x_in) + else: + my_t = torch.ones([n], device=device, + dtype=torch.long) * cur_t + out = diffusion.p_mean_variance( + model, x, my_t, clip_denoised=False, model_kwargs={'y': y}) + fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] + x_in = out['pred_xstart'] * fac + x * (1 - fac) + x_in_grad = torch.zeros_like(x_in) + for model_stat in model_stats: + for i in range(args.cutn_batches): + # errors on last step without +1, need to find source + t_int = int(t.item())+1 + # when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution' + try: + input_resolution = model_stat["clip_model"].visual.input_resolution + except: + input_resolution = 224 + + cuts = MakeCutoutsDango(animation_mode=args.animation_mode, + skip_augs=args.skip_augs, + cut_size=input_resolution, + Overview=args.cut_overview[1000-t_int], + InnerCrop=args.cut_innercut[1000-t_int], + IC_Size_Pow=args.cut_ic_pow[1000-t_int], + IC_Grey_P=args.cut_icgray_p[1000-t_int] + ) + clip_in = disco_utils.normalize( + cuts(x_in.add(1).div(2))) + image_embeds = model_stat["clip_model"].encode_image( + clip_in).float() + dists = disco_utils.spherical_dist_loss(image_embeds.unsqueeze( + 1), model_stat["target_embeds"].unsqueeze(0)) + dists = dists.view( + [args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1]) + losses = dists.mul( + model_stat["weights"]).sum(2).mean(0) + # log loss, probably shouldn't do per cutn_batch + loss_values.append(losses.sum().item()) + x_in_grad += torch.autograd.grad(losses.sum() * args.clip_guidance_scale, x_in)[ + 0] / args.cutn_batches + tv_losses = args.tv_loss(x_in) + if args.MS.use_secondary_model is True: + range_losses = disco_utils.range_loss(out) + else: + range_losses = disco_utils.range_loss(out['pred_xstart']) + sat_losses = torch.abs(x_in - x_in.clamp(min=-1, max=1)).mean() + loss = tv_losses.sum() * args.tv_scale + range_losses.sum() * \ + args.range_scale + sat_losses.sum() * args.sat_scale + if init is not None and init_scale: + init_losses = args.MS.lpips_model(x_in, init) + loss = loss + init_losses.sum() * init_scale + x_in_grad += torch.autograd.grad(loss, x_in)[0] + if torch.isnan(x_in_grad).any() == False: + grad = -torch.autograd.grad(x_in, x, x_in_grad)[0] + else: + # print("NaN'd") + x_is_NaN = True + grad = torch.zeros_like(x) + if args.clamp_grad and x_is_NaN == False: + magnitude = grad.square().mean().sqrt() + # min=-0.02, min=-clamp_max, + return grad * magnitude.clamp(max=args.clamp_max) / magnitude + return grad + + if args.diffusion_sampling_mode == 'ddim': + sample_fn = diffusion.ddim_sample_loop_progressive + else: + sample_fn = diffusion.plms_sample_loop_progressive + + # image_display = Output() + for i in range(args.n_batches): + if args.animation_mode == 'None': + # display.clear_output(wait=True) + batchBar = tqdm(range(args.n_batches), desc="Batches") + batchBar.n = i + batchBar.refresh() + print('') + # display.display(image_display) + gc.collect() + torch.cuda.empty_cache() + cur_t = diffusion.num_timesteps - skip_steps - 1 + total_steps = cur_t + + if args.perlin_init: + init = disco_utils.regen_perlin( + args.perlin_mode, args.batch_size) + + symmetry_transformation_fn = id + if args.use_horizontal_symmetry: + symmetry_transformation_fn = horiz_symmetry + if args.use_vertical_symmetry: + symmetry_transformation_fn = vert_symmetry + + if args.diffusion_sampling_mode == 'ddim': + samples = sample_fn( + model, + (args.batch_size, 3, args.side_y, args.side_x), + clip_denoised=args.clip_denoised, + model_kwargs={}, + cond_fn=cond_fn, + progress=True, + skip_timesteps=skip_steps, + init_image=init, + randomize_class=args.randomize_class, + eta=args.eta, + transformation_fn=symmetry_transformation_fn, + transformation_percent=args.transformation_percent + ) + else: + samples = sample_fn( + model, + (args.batch_size, 3, args.side_y, args.side_x), + clip_denoised=args.clip_denoised, + model_kwargs={}, + cond_fn=cond_fn, + progress=True, + skip_timesteps=skip_steps, + init_image=init, + randomize_class=args.randomize_class, + order=2, + ) + + # with run_display: + # display.clear_output(wait=True) + for j, sample in enumerate(samples): + cur_t -= 1 + intermediateStep = False + if args.steps_per_checkpoint is not None: + if j % args.steps_per_checkpoint == 0 and j > 0: + intermediateStep = True + elif j in args.intermediate_saves: + intermediateStep = True + # with image_display: + if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True: + for k, image in enumerate(sample['pred_xstart']): + # tqdm.write(f'Batch {i}, step {j}, output {k}:') + datetime.now().strftime('%y%m%d-%H%M%S_%f') + percent = math.ceil(j/total_steps*100) + if args.n_batches > 0: + # if intermediates are saved to the subfolder, don't append a step or percentage to the name + if cur_t == -1 and args.intermediates_in_subfolder is True: + save_num = f'{frame_num:04}' if args.animation_mode != "None" else i + filename = f'{args.batch_name}({batchNum})_{save_num}.png' + else: + # If we're working with percentages, append it + if args.steps_per_checkpoint is not None: + filename = f'{args.batch_name}({batchNum})_{i:04}-{percent:02}%.png' + # Or else, iIf we're working with specific steps, append those + else: + filename = f'{args.batch_name}({batchNum})_{i:04}-{j:03}.png' + image = TF.to_pil_image( + image.add(1).div(2).clamp(0, 1)) + if j % args.display_rate == 0 or cur_t == -1: + image.save('progress.png') + # display.clear_output(wait=True) + # display.display(display.Image('progress.png')) + if args.steps_per_checkpoint is not None: + if j % args.steps_per_checkpoint == 0 and j > 0: + if args.intermediates_in_subfolder is True: + image.save( + f'{args.partialFolder}/{filename}') + else: + image.save( + f'{args.batchFolder}/{filename}') + else: + if j in args.intermediate_saves: + if args.intermediates_in_subfolder is True: + image.save( + f'{args.partialFolder}/{filename}') + else: + image.save( + f'{args.batchFolder}/{filename}') + if cur_t == -1: + # if frame_num == 0: + # save_settings() + if args.animation_mode != "None": + image.save('prevFrame.png') + image.save(f'{args.batchFolder}/{filename}') + if args.animation_mode == "3D": + # If turbo, save a blended image + if args.turbo_mode and frame_num > 0: + # Mix new image with prevFrameScaled + blend_factor = (1)/int(args.turbo_steps) + # This is already updated.. + newFrame = cv2.imread('prevFrame.png') + prev_frame_warped = cv2.imread( + 'prevFrameScaled.png') + blendedImage = cv2.addWeighted( + newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0) + cv2.imwrite( + f'{args.batchFolder}/{filename}', blendedImage) + else: + image.save( + f'{args.batchFolder}/{filename}') + + if args.vr_mode: + generate_eye_views( + TRANSLATION_SCALE, args.batchFolder, filename, frame_num, midas_model, midas_transform) + + # if frame_num != args.max_frames-1: + # display.clear_output() + + # plt.plot(np.array(loss_values), 'r') + + +def generate_eye_views(args, trans_scale, batchFolder, filename, frame_num, midas_model, midas_transform): + device = comfy.model_management.get_torch_device() + for i in range(2): + theta = args.vr_eye_angle * (math.pi/180) + ray_origin = math.cos(theta) * args.vr_ipd / \ + 2 * (-1.0 if i == 0 else 1.0) + ray_rotation = (theta if i == 0 else -theta) + translate_xyz = [-(ray_origin)*trans_scale, 0, 0] + rotate_xyz = [0, (ray_rotation), 0] + rot_mat = p3dT.euler_angles_to_matrix(torch.tensor( + rotate_xyz, device=device), "XYZ").unsqueeze(0) + transformed_image = dxf.transform_image_3d(f'{batchFolder}/{filename}', midas_model, midas_transform, device, + rot_mat, translate_xyz, args.near_plane, args.far_plane, + args.fov, padding_mode=args.padding_mode, + sampling_mode=args.sampling_mode, midas_weight=args.midas_weight, spherical=True) + eye_file_path = batchFolder + \ + f"/frame_{frame_num:04}" + ('_l' if i == 0 else '_r')+'.png' + transformed_image.save(eye_file_path) + +# def save_settings(): +# setting_list = { +# 'text_prompts': text_prompts, +# 'image_prompts': image_prompts, +# 'clip_guidance_scale': clip_guidance_scale, +# 'tv_scale': tv_scale, +# 'range_scale': range_scale, +# 'sat_scale': sat_scale, +# # 'cutn': cutn, +# 'cutn_batches': cutn_batches, +# 'max_frames': max_frames, +# 'interp_spline': interp_spline, +# # 'rotation_per_frame': rotation_per_frame, +# 'init_image': init_image, +# 'init_scale': init_scale, +# 'skip_steps': skip_steps, +# # 'zoom_per_frame': zoom_per_frame, +# 'frames_scale': frames_scale, +# 'frames_skip_steps': frames_skip_steps, +# 'perlin_init': perlin_init, +# 'perlin_mode': perlin_mode, +# 'skip_augs': skip_augs, +# 'randomize_class': randomize_class, +# 'clip_denoised': clip_denoised, +# 'clamp_grad': clamp_grad, +# 'clamp_max': clamp_max, +# 'seed': seed, +# 'fuzzy_prompt': fuzzy_prompt, +# 'rand_mag': rand_mag, +# 'eta': eta, +# 'width': width_height[0], +# 'height': width_height[1], +# 'diffusion_model': diffusion_model, +# 'use_secondary_model': use_secondary_model, +# 'steps': steps, +# 'diffusion_steps': diffusion_steps, +# 'diffusion_sampling_mode': diffusion_sampling_mode, +# 'ViTB32': ViTB32, +# 'ViTB16': ViTB16, +# 'ViTL14': ViTL14, +# 'ViTL14_336px': ViTL14_336px, +# 'RN101': RN101, +# 'RN50': RN50, +# 'RN50x4': RN50x4, +# 'RN50x16': RN50x16, +# 'RN50x64': RN50x64, +# 'ViTB32_laion2b_e16': ViTB32_laion2b_e16, +# 'ViTB32_laion400m_e31': ViTB32_laion400m_e31, +# 'ViTB32_laion400m_32': ViTB32_laion400m_32, +# 'ViTB32quickgelu_laion400m_e31': ViTB32quickgelu_laion400m_e31, +# 'ViTB32quickgelu_laion400m_e32': ViTB32quickgelu_laion400m_e32, +# 'ViTB16_laion400m_e31': ViTB16_laion400m_e31, +# 'ViTB16_laion400m_e32': ViTB16_laion400m_e32, +# 'RN50_yffcc15m': RN50_yffcc15m, +# 'RN50_cc12m': RN50_cc12m, +# 'RN50_quickgelu_yfcc15m': RN50_quickgelu_yfcc15m, +# 'RN50_quickgelu_cc12m': RN50_quickgelu_cc12m, +# 'RN101_yfcc15m': RN101_yfcc15m, +# 'RN101_quickgelu_yfcc15m': RN101_quickgelu_yfcc15m, +# 'cut_overview': str(cut_overview), +# 'cut_innercut': str(cut_innercut), +# 'cut_ic_pow': str(cut_ic_pow), +# 'cut_icgray_p': str(cut_icgray_p), +# 'key_frames': key_frames, +# 'max_frames': max_frames, +# 'angle': angle, +# 'zoom': zoom, +# 'translation_x': translation_x, +# 'translation_y': translation_y, +# 'translation_z': translation_z, +# 'rotation_3d_x': rotation_3d_x, +# 'rotation_3d_y': rotation_3d_y, +# 'rotation_3d_z': rotation_3d_z, +# 'midas_depth_model': midas_depth_model, +# 'midas_weight': midas_weight, +# 'near_plane': near_plane, +# 'far_plane': far_plane, +# 'fov': fov, +# 'padding_mode': padding_mode, +# 'sampling_mode': sampling_mode, +# 'video_init_path':video_init_path, +# 'extract_nth_frame':extract_nth_frame, +# 'video_init_seed_continuity': video_init_seed_continuity, +# 'turbo_mode':turbo_mode, +# 'turbo_steps':turbo_steps, +# 'turbo_preroll':turbo_preroll, +# 'use_horizontal_symmetry':use_horizontal_symmetry, +# 'use_vertical_symmetry':use_vertical_symmetry, +# 'transformation_percent':transformation_percent, +# #video init settings +# 'video_init_steps': video_init_steps, +# 'video_init_clip_guidance_scale': video_init_clip_guidance_scale, +# 'video_init_tv_scale': video_init_tv_scale, +# 'video_init_range_scale': video_init_range_scale, +# 'video_init_sat_scale': video_init_sat_scale, +# 'video_init_cutn_batches': video_init_cutn_batches, +# 'video_init_skip_steps': video_init_skip_steps, +# 'video_init_frames_scale': video_init_frames_scale, +# 'video_init_frames_skip_steps': video_init_frames_skip_steps, +# #warp settings +# 'video_init_flow_warp':video_init_flow_warp, +# 'video_init_flow_blend':video_init_flow_blend, +# 'video_init_check_consistency':video_init_check_consistency, +# 'video_init_blend_mode':video_init_blend_mode +# } +# # print('Settings:', setting_list) +# with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+", encoding="utf-8") as f: #save settings +# json.dump(setting_list, f, ensure_ascii=False, indent=4) diff --git a/make_cutouts.py b/make_cutouts.py new file mode 100644 index 0000000..75d7810 --- /dev/null +++ b/make_cutouts.py @@ -0,0 +1,165 @@ +import cv2 +import pandas as pd +import gc +import lpips +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from numpy import asarray + +from .settings import DiscoDiffusionSettings +from . import disco_utils + + +class MakeCutouts(nn.Module): + def __init__(self, cut_size, cutn, skip_augs=False): + super().__init__() + self.cut_size = cut_size + self.cutn = cutn + self.skip_augs = skip_augs + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.5), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=15, translate=(0.1, 0.1)), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomPerspective(distortion_scale=0.4, p=0.7), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.15), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), + ]) + + def forward(self, input): + input = T.Pad(input.shape[2]//4, fill=0)(input) + sideY, sideX = input.shape[2:4] + max_size = min(sideX, sideY) + + cutouts = [] + for ch in range(self.cutn): + if ch > self.cutn - self.cutn//4: + cutout = input.clone() + else: + size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.)) + offsetx = torch.randint(0, abs(sideX - size + 1), ()) + offsety = torch.randint(0, abs(sideY - size + 1), ()) + cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] + + if not self.skip_augs: + cutout = self.augs(cutout) + cutouts.append(disco_utils.resample(cutout, (self.cut_size, self.cut_size))) + del cutout + + cutouts = torch.cat(cutouts, dim=0) + return cutouts + +cutout_debug = False +padargs = {} + +class MakeCutoutsDango(nn.Module): + def __init__(self, + animation_mode: str, + skip_augs, + cut_size, Overview=4, + InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2 + ): + super().__init__() + self.cut_size = cut_size + self.skip_augs = skip_augs + self.Overview = Overview + self.InnerCrop = InnerCrop + self.IC_Size_Pow = IC_Size_Pow + self.IC_Grey_P = IC_Grey_P + if animation_mode == 'None': + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.5), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.1), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), + ]) + elif animation_mode == 'Video Input': + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.5), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=15, translate=(0.1, 0.1)), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomPerspective(distortion_scale=0.4, p=0.7), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.15), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), + ]) + elif animation_mode == '2D' or animation_mode == '3D': + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.4), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.1), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3), + ]) + + + def forward(self, input): + cutouts = [] + gray = T.Grayscale(3) + sideY, sideX = input.shape[2:4] + max_size = min(sideX, sideY) + min_size = min(sideX, sideY, self.cut_size) + max(sideX, sideY) + output_shape = [1,3,self.cut_size,self.cut_size] + [1,3,self.cut_size+2,self.cut_size+2] + pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs) + cutout = resize(pad_input, out_shape=output_shape) + + if self.Overview>0: + if self.Overview<=4: + if self.Overview>=1: + cutouts.append(cutout) + if self.Overview>=2: + cutouts.append(gray(cutout)) + if self.Overview>=3: + cutouts.append(TF.hflip(cutout)) + if self.Overview==4: + cutouts.append(gray(TF.hflip(cutout))) + else: + cutout = resize(pad_input, out_shape=output_shape) + for _ in range(self.Overview): + cutouts.append(cutout) + + if cutout_debug: + # if is_colab: + # TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99) + TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("cutout_overview0.jpg",quality=99) + + + if self.InnerCrop >0: + for i in range(self.InnerCrop): + size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size) + offsetx = torch.randint(0, sideX - size + 1, ()) + offsety = torch.randint(0, sideY - size + 1, ()) + cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] + if i <= int(self.IC_Grey_P * self.InnerCrop): + cutout = gray(cutout) + cutout = resize(cutout, out_shape=output_shape) + cutouts.append(cutout) + if cutout_debug: + # if is_colab: + # TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99) + # else: + TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("cutout_InnerCrop.jpg",quality=99) + cutouts = torch.cat(cutouts) + if self.skip_augs is not True: cutouts=self.augs(cutouts) + return cutouts diff --git a/midas_model.py b/midas_model.py new file mode 100644 index 0000000..a3df61b --- /dev/null +++ b/midas_model.py @@ -0,0 +1,122 @@ +import cv2 +import pandas as pd +import gc +import torch +import lpips +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from numpy import asarray + +from midas.dpt_depth import DPTDepthModel +from midas.midas_net import MidasNet +from midas.midas_net_custom import MidasNet_small +from midas.transforms import Resize, NormalizeImage, PrepareForNet + +import comfy.model_management + + +default_models = {} + + +def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): + global default_models + + midas_model = None + net_w = None + net_h = None + resize_mode = None + normalization = None + + print(f"Initializing MiDaS '{midas_model_type}' depth model...") + # load network + midas_model_path = default_models[midas_model_type] + assert False # TODO + + if midas_model_type == "dpt_large": # DPT-Large + midas_model = DPTDepthModel( + path=midas_model_path, + backbone="vitl16_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage( + mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + elif midas_model_type == "dpt_hybrid": # DPT-Hybrid + midas_model = DPTDepthModel( + path=midas_model_path, + backbone="vitb_rn50_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage( + mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + elif midas_model_type == "dpt_hybrid_nyu": # DPT-Hybrid-NYU + midas_model = DPTDepthModel( + path=midas_model_path, + backbone="vitb_rn50_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage( + mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + elif midas_model_type == "midas_v21": + midas_model = MidasNet(midas_model_path, non_negative=True) + net_w, net_h = 384, 384 + resize_mode = "upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + elif midas_model_type == "midas_v21_small": + midas_model = MidasNet_small(midas_model_path, features=64, backbone="efficientnet_lite3", + exportable=True, non_negative=True, blocks={'expand': True}) + net_w, net_h = 256, 256 + resize_mode = "upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + else: + print(f"midas_model_type '{midas_model_type}' not implemented") + assert False + + midas_transform = T.Compose( + [ + Resize( + net_w, + net_h, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method=resize_mode, + image_interpolation_method=cv2.INTER_CUBIC, + ), + normalization, + PrepareForNet(), + ] + ) + + midas_model.eval() + + device = comfy.model_management.get_torch_device() + + if optimize is True: + if device == torch.device("cuda"): + midas_model = midas_model.to(memory_format=torch.channels_last) + midas_model = midas_model.half() + + midas_model.to(device) + + print(f"MiDaS '{midas_model_type}' depth model initialized.") + return midas_model, midas_transform, net_w, net_h, resize_mode, normalization diff --git a/model_settings.py b/model_settings.py new file mode 100644 index 0000000..89df8d9 --- /dev/null +++ b/model_settings.py @@ -0,0 +1,239 @@ +from urllib.parse import urlparse +import os +import hashlib +import lpips +import torchvision.transforms as T +import os +import cv2 +import pandas as pd +import gc +import lpips +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +import hashlib +from numpy import asarray + +from .secondary_diffusion_model import SecondaryDiffusionImageNet2 +from . import disco_utils + +import comfy.model_management + +diff_model_map = { + '256x256_diffusion_uncond': { 'downloaded': False, 'sha': 'a37c32fffd316cd494cf3f35b339936debdc1576dad13fe57c42399a5dbc78b1', 'uri_list': ['https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt', 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt'] }, + '512x512_diffusion_uncond_finetune_008100': { 'downloaded': False, 'sha': '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648', 'uri_list': ['https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt', 'https://the-eye.eu/public/AI/models/512x512_diffusion_unconditional_ImageNet/512x512_diffusion_uncond_finetune_008100.pt'] }, + 'portrait_generator_v001': { 'downloaded': False, 'sha': 'b7e8c747af880d4480b6707006f1ace000b058dd0eac5bb13558ba3752d9b5b9', 'uri_list': ['https://huggingface.co/felipe3dartist/portrait_generator_v001/resolve/main/portrait_generator_v001_ema_0.9999_1MM.pt'] }, + 'pixelartdiffusion_expanded': { 'downloaded': False, 'sha': 'a73b40556634034bf43b5a716b531b46fb1ab890634d854f5bcbbef56838739a', 'uri_list': ['https://huggingface.co/KaliYuga/PADexpanded/resolve/main/PADexpanded.pt'] }, + 'pixel_art_diffusion_hard_256': { 'downloaded': False, 'sha': 'be4a9de943ec06eef32c65a1008c60ad017723a4d35dc13169c66bb322234161', 'uri_list': ['https://huggingface.co/KaliYuga/pixel_art_diffusion_hard_256/resolve/main/pixel_art_diffusion_hard_256.pt'] }, + 'pixel_art_diffusion_soft_256': { 'downloaded': False, 'sha': 'd321590e46b679bf6def1f1914b47c89e762c76f19ab3e3392c8ca07c791039c', 'uri_list': ['https://huggingface.co/KaliYuga/pixel_art_diffusion_soft_256/resolve/main/pixel_art_diffusion_soft_256.pt'] }, + 'pixelartdiffusion4k': { 'downloaded': False, 'sha': 'a1ba4f13f6dabb72b1064f15d8ae504d98d6192ad343572cc416deda7cccac30', 'uri_list': ['https://huggingface.co/KaliYuga/pixelartdiffusion4k/resolve/main/pixelartdiffusion4k.pt'] }, + 'watercolordiffusion_2': { 'downloaded': False, 'sha': '49c281b6092c61c49b0f1f8da93af9b94be7e0c20c71e662e2aa26fee0e4b1a9', 'uri_list': ['https://huggingface.co/KaliYuga/watercolordiffusion_2/resolve/main/watercolordiffusion_2.pt'] }, + 'watercolordiffusion': { 'downloaded': False, 'sha': 'a3e6522f0c8f278f90788298d66383b11ac763dd5e0d62f8252c962c23950bd6', 'uri_list': ['https://huggingface.co/KaliYuga/watercolordiffusion/resolve/main/watercolordiffusion.pt'] }, + 'PulpSciFiDiffusion': { 'downloaded': False, 'sha': 'b79e62613b9f50b8a3173e5f61f0320c7dbb16efad42a92ec94d014f6e17337f', 'uri_list': ['https://huggingface.co/KaliYuga/PulpSciFiDiffusion/resolve/main/PulpSciFiDiffusion.pt'] }, + 'secondary': { 'downloaded': False, 'sha': '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a', 'uri_list': ['https://huggingface.co/spaces/huggi/secondary_model_imagenet_2.pth/resolve/main/secondary_model_imagenet_2.pth', 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth', 'https://ipfs.pollinations.ai/ipfs/bafybeibaawhhk7fhyhvmm7x24zwwkeuocuizbqbcg5nqx64jq42j75rdiy/secondary_model_imagenet_2.pth'] }, +} + +class ModelSettings: + def __init__(self): + self.root_path = os.getcwd() + self.model_path = f'{self.root_path}/models' + #@markdown ####**Models Settings (note: For pixel art, the best is pixelartdiffusion_expanded):** + self.diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100", "portrait_generator_v001", "pixelartdiffusion_expanded", "pixel_art_diffusion_hard_256", "pixel_art_diffusion_soft_256", "pixelartdiffusion4k", "watercolordiffusion_2", "watercolordiffusion", "PulpSciFiDiffusion", "custom"] + + self.use_secondary_model = True #@param {type: 'boolean'} + self.diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] + #@markdown #####**Custom model:** + self.custom_path = '/content/drive/MyDrive/deep_learning/ddpm/ema_0.9999_058000.pt'#@param {type: 'string'} + + #@markdown #####**CLIP settings:** + self.use_checkpoint = True #@param {type: 'boolean'} + self.ViTB32 = True #@param{type:"boolean"} + self.ViTB16 = True #@param{type:"boolean"} + self.ViTL14 = False #@param{type:"boolean"} + self.ViTL14_336px = False #@param{type:"boolean"} + self.RN101 = False #@param{type:"boolean"} + self.RN50 = True #@param{type:"boolean"} + self.RN50x4 = False #@param{type:"boolean"} + self.RN50x16 = False #@param{type:"boolean"} + self.RN50x64 = False #@param{type:"boolean"} + + #@markdown #####**OpenCLIP settings:** + self.ViTB32_laion2b_e16 = False #@param{type:"boolean"} + self.ViTB32_laion400m_e31 = False #@param{type:"boolean"} + self.ViTB32_laion400m_32 = False #@param{type:"boolean"} + self.ViTB32quickgelu_laion400m_e31 = False #@param{type:"boolean"} + self.ViTB32quickgelu_laion400m_e32 = False #@param{type:"boolean"} + self.ViTB16_laion400m_e31 = False #@param{type:"boolean"} + self.ViTB16_laion400m_e32 = False #@param{type:"boolean"} + self.RN50_yffcc15m = False #@param{type:"boolean"} + self.RN50_cc12m = False #@param{type:"boolean"} + self.RN50_quickgelu_yfcc15m = False #@param{type:"boolean"} + self.RN50_quickgelu_cc12m = False #@param{type:"boolean"} + self.RN101_yfcc15m = False #@param{type:"boolean"} + self.RN101_quickgelu_yfcc15m = False #@param{type:"boolean"} + + #@markdown If you're having issues with model downloads, check this to compare SHA's: + self.check_model_SHA = False #@param{type:"boolean"} + + self.kaliyuga_pixel_art_model_names = ['pixelartdiffusion_expanded', 'pixel_art_diffusion_hard_256', 'pixel_art_diffusion_soft_256', 'pixelartdiffusion4k', 'PulpSciFiDiffusion'] + self.kaliyuga_watercolor_model_names = ['watercolordiffusion', 'watercolordiffusion_2'] + self.kaliyuga_pulpscifi_model_names = ['PulpSciFiDiffusion'] + self.diffusion_models_256x256_list = ['256x256_diffusion_uncond'] + self.kaliyuga_pixel_art_model_names + self.kaliyuga_watercolor_model_names + self.kaliyuga_pulpscifi_model_names + + + def get_model_filename(self, diffusion_model_name): + model_uri = diff_model_map[diffusion_model_name]['uri_list'][0] + model_filename = os.path.basename(urlparse(model_uri).path) + return model_filename + + def download_model(self, diffusion_model_name, uri_index=0): + if diffusion_model_name != 'custom': + model_filename = self.get_model_filename(diffusion_model_name) + model_local_path = os.path.join(self.model_path, model_filename) + if os.path.exists(model_local_path) and self.check_model_SHA: + print(f'Checking {diffusion_model_name} File') + with open(model_local_path, "rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest() + if hash == diff_model_map[diffusion_model_name]['sha']: + print(f'{diffusion_model_name} SHA matches') + diff_model_map[diffusion_model_name]['downloaded'] = True + else: + print(f"{diffusion_model_name} SHA doesn't match. Will redownload it.") + elif os.path.exists(model_local_path) and not self.check_model_SHA or diff_model_map[diffusion_model_name]['downloaded']: + print(f'{diffusion_model_name} already downloaded. If the file is corrupt, enable check_model_SHA.') + diff_model_map[diffusion_model_name]['downloaded'] = True + + if not diff_model_map[diffusion_model_name]['downloaded']: + for model_uri in diff_model_map[diffusion_model_name]['uri_list']: + disco_utils.wget(model_uri, self.model_path) + if os.path.exists(model_local_path): + diff_model_map[diffusion_model_name]['downloaded'] = True + return + else: + print(f'{diffusion_model_name} model download from {model_uri} failed. Will try any fallback uri.') + print(f'{diffusion_model_name} download failed.') + + def setup(self, S): + # Download the diffusion model(s) + self.download_model(self.diffusion_model) + if self.use_secondary_model: + self.download_model('secondary') + + self.model_config = model_and_diffusion_defaults() + if self.diffusion_model == '512x512_diffusion_uncond_finetune_008100': + self.model_config.update({ + 'attention_resolutions': '32, 16, 8', + 'class_cond': False, + 'diffusion_steps': 1000, #No need to edit this, it is taken care of later. + 'rescale_timesteps': True, + 'timestep_respacing': 250, #No need to edit this, it is taken care of later. + 'image_size': 512, + 'learn_sigma': True, + 'noise_schedule': 'linear', + 'num_channels': 256, + 'num_head_channels': 64, + 'num_res_blocks': 2, + 'resblock_updown': True, + 'use_checkpoint': self.use_checkpoint, + 'use_fp16': not S.useCPU, + 'use_scale_shift_norm': True, + }) + elif self.diffusion_model == '256x256_diffusion_uncond': + self.model_config.update({ + 'attention_resolutions': '32, 16, 8', + 'class_cond': False, + 'diffusion_steps': 1000, #No need to edit this, it is taken care of later. + 'rescale_timesteps': True, + 'timestep_respacing': 250, #No need to edit this, it is taken care of later. + 'image_size': 256, + 'learn_sigma': True, + 'noise_schedule': 'linear', + 'num_channels': 256, + 'num_head_channels': 64, + 'num_res_blocks': 2, + 'resblock_updown': True, + 'use_checkpoint': self.use_checkpoint, + 'use_fp16': not S.useCPU, + 'use_scale_shift_norm': True, + }) + elif self.diffusion_model == 'portrait_generator_v001': + self.model_config.update({ + 'attention_resolutions': '32, 16, 8', + 'class_cond': False, + 'diffusion_steps': 1000, + 'rescale_timesteps': True, + 'image_size': 512, + 'learn_sigma': True, + 'noise_schedule': 'linear', + 'num_channels': 128, + 'num_heads': 4, + 'num_res_blocks': 2, + 'resblock_updown': True, + 'use_checkpoint': self.use_checkpoint, + 'use_fp16': True, + 'use_scale_shift_norm': True, + }) + else: # E.g. A model finetuned by KaliYuga + self.model_config.update({ + 'attention_resolutions': '16', + 'class_cond': False, + 'diffusion_steps': 1000, + 'rescale_timesteps': True, + 'timestep_respacing': 'ddim100', + 'image_size': 256, + 'learn_sigma': True, + 'noise_schedule': 'linear', + 'num_channels': 128, + 'num_heads': 1, + 'num_res_blocks': 2, + 'use_checkpoint': self.use_checkpoint, + 'use_fp16': True, + 'use_scale_shift_norm': False, + }) + + self.model_default = self.model_config['image_size'] + + device = comfy.model_management.get_torch_device() + + if self.use_secondary_model: + self.secondary_model = SecondaryDiffusionImageNet2() + self.secondary_model.load_state_dict(torch.load(f'{self.model_path}/secondary_model_imagenet_2.pth', map_location='cpu')) + self.secondary_model.eval().requires_grad_(False).to(device) + + self.clip_models = [] + #if self.ViTB32: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.ViTB16: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.ViTL14: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.ViTL14_336px: clip_models.append(clip.load('ViT-L/14@336px', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.RN50: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.RN50x4: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.RN50x16: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.RN50x64: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.RN101: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) + #if self.ViTB32_laion2b_e16: clip_models.append(open_clip.create_model('ViT-B-32', pretrained='laion2b_e16').eval().requires_grad_(False).to(device)) + #if self.ViTB32_laion400m_e31: clip_models.append(open_clip.create_model('ViT-B-32', pretrained='laion400m_e31').eval().requires_grad_(False).to(device)) + #if self.ViTB32_laion400m_32: clip_models.append(open_clip.create_model('ViT-B-32', pretrained='laion400m_e32').eval().requires_grad_(False).to(device)) + #if self.ViTB32quickgelu_laion400m_e31: clip_models.append(open_clip.create_model('ViT-B-32-quickgelu', pretrained='laion400m_e31').eval().requires_grad_(False).to(device)) + #if self.ViTB32quickgelu_laion400m_e32: clip_models.append(open_clip.create_model('ViT-B-32-quickgelu', pretrained='laion400m_e32').eval().requires_grad_(False).to(device)) + #if self.ViTB16_laion400m_e31: clip_models.append(open_clip.create_model('ViT-B-16', pretrained='laion400m_e31').eval().requires_grad_(False).to(device)) + #if self.ViTB16_laion400m_e32: clip_models.append(open_clip.create_model('ViT-B-16', pretrained='laion400m_e32').eval().requires_grad_(False).to(device)) + #if self.RN50_yffcc15m: clip_models.append(open_clip.create_model('RN50', pretrained='yfcc15m').eval().requires_grad_(False).to(device)) + #if self.RN50_cc12m: clip_models.append(open_clip.create_model('RN50', pretrained='cc12m').eval().requires_grad_(False).to(device)) + #if self.RN50_quickgelu_yfcc15m: clip_models.append(open_clip.create_model('RN50-quickgelu', pretrained='yfcc15m').eval().requires_grad_(False).to(device)) + #if self.RN50_quickgelu_cc12m: clip_models.append(open_clip.create_model('RN50-quickgelu', pretrained='cc12m').eval().requires_grad_(False).to(device)) + #if self.RN101_yfcc15m: clip_models.append(open_clip.create_model('RN101', pretrained='yfcc15m').eval().requires_grad_(False).to(device)) + #if self.RN101_quickgelu_yfcc15m: clip_models.append(open_clip.create_model('RN101-quickgelu', pretrained='yfcc15m').eval().requires_grad_(False).to(device)) + + self.lpips_model = lpips.LPIPS(net='vgg').to(device) + + S.MS = self diff --git a/nodes.py b/nodes.py new file mode 100644 index 0000000..66c4f8f --- /dev/null +++ b/nodes.py @@ -0,0 +1,49 @@ +import os.path + +NODE_FILE = os.path.abspath(__file__) +DISCO_DIFFUSION_ROOT = os.path.dirname(NODE_FILE) + +import sys +sys.path.append(os.path.join(DISCO_DIFFUSION_ROOT, "MiDaS")) +sys.path.append(os.path.join(DISCO_DIFFUSION_ROOT, "ResizeRight")) +sys.path.append(os.path.join(DISCO_DIFFUSION_ROOT, "guided-diffusion")) +sys.path.append(os.path.join(DISCO_DIFFUSION_ROOT, "RAFT/core")) + + +from .settings import DiscoDiffusionSettings +from .model_settings import ModelSettings +from .diffuse import diffuse + + +class DiscoDiffusion: + @classmethod + def INPUT_TYPES(s): + return {"required": {"text": ("STRING", {"multiline": True}), + "clip": ("CLIP", ), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}), + }} + RETURN_TYPES = () + FUNCTION = "generate" + + CATEGORY = "sampling" + + OUTPUT_NODE = True + + def __init__(self): + self.settings = DiscoDiffusionSettings() + self.model_settings = ModelSettings() + self.settings.setup(self.model_settings) + self.model_settings.setup(self.settings) + + def generate(self, text, clip, seed): + diffuse(clip, self.settings, 0) + return { "ui": { "images": {} } } + + +NODE_CLASS_MAPPINGS = { + "ComfyUI_DiscoDiffusion": DiscoDiffusion, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ComfyUI_DiscoDiffusion": "Disco Diffusion", +} diff --git a/py3d_tools.py b/py3d_tools.py new file mode 100644 index 0000000..f299dd0 --- /dev/null +++ b/py3d_tools.py @@ -0,0 +1,1799 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import sys +import math +import warnings +from typing import List, Optional, Sequence, Tuple, Union, Any + +import numpy as np +import torch +import torch.nn.functional as F + +import copy +import inspect +import torch.nn as nn + +Device = Union[str, torch.device] + +# Default values for rotation and translation matrices. +_R = torch.eye(3)[None] # (1, 3, 3) +_T = torch.zeros(1, 3) # (1, 3) + + +# Provide get_origin and get_args even in Python 3.7. + +if sys.version_info >= (3, 8, 0): + from typing import get_args, get_origin +elif sys.version_info >= (3, 7, 0): + + def get_origin(cls): # pragma: no cover + return getattr(cls, "__origin__", None) + + def get_args(cls): # pragma: no cover + return getattr(cls, "__args__", None) + + +else: + raise ImportError("This module requires Python 3.7+") + +################################################################ +## ██████╗██╗ █████╗ ███████╗███████╗███████╗███████╗ ## +## ██╔════╝██║ ██╔══██╗██╔════╝██╔════╝██╔════╝██╔════╝ ## +## ██║ ██║ ███████║███████╗███████╗█████╗ ███████╗ ## +## ██║ ██║ ██╔══██║╚════██║╚════██║██╔══╝ ╚════██║ ## +## ╚██████╗███████╗██║ ██║███████║███████║███████╗███████║ ## +## ╚═════╝╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚══════╝ ## +################################################################ + +class Transform3d: + """ + A Transform3d object encapsulates a batch of N 3D transformations, and knows + how to transform points and normal vectors. Suppose that t is a Transform3d; + then we can do the following: + + .. code-block:: python + + N = len(t) + points = torch.randn(N, P, 3) + normals = torch.randn(N, P, 3) + points_transformed = t.transform_points(points) # => (N, P, 3) + normals_transformed = t.transform_normals(normals) # => (N, P, 3) + + + BROADCASTING + Transform3d objects supports broadcasting. Suppose that t1 and tN are + Transform3d objects with len(t1) == 1 and len(tN) == N respectively. Then we + can broadcast transforms like this: + + .. code-block:: python + + t1.transform_points(torch.randn(P, 3)) # => (P, 3) + t1.transform_points(torch.randn(1, P, 3)) # => (1, P, 3) + t1.transform_points(torch.randn(M, P, 3)) # => (M, P, 3) + tN.transform_points(torch.randn(P, 3)) # => (N, P, 3) + tN.transform_points(torch.randn(1, P, 3)) # => (N, P, 3) + + + COMBINING TRANSFORMS + Transform3d objects can be combined in two ways: composing and stacking. + Composing is function composition. Given Transform3d objects t1, t2, t3, + the following all compute the same thing: + + .. code-block:: python + + y1 = t3.transform_points(t2.transform_points(t1.transform_points(x))) + y2 = t1.compose(t2).compose(t3).transform_points(x) + y3 = t1.compose(t2, t3).transform_points(x) + + + Composing transforms should broadcast. + + .. code-block:: python + + if len(t1) == 1 and len(t2) == N, then len(t1.compose(t2)) == N. + + We can also stack a sequence of Transform3d objects, which represents + composition along the batch dimension; then the following should compute the + same thing. + + .. code-block:: python + + N, M = len(tN), len(tM) + xN = torch.randn(N, P, 3) + xM = torch.randn(M, P, 3) + y1 = torch.cat([tN.transform_points(xN), tM.transform_points(xM)], dim=0) + y2 = tN.stack(tM).transform_points(torch.cat([xN, xM], dim=0)) + + BUILDING TRANSFORMS + We provide convenience methods for easily building Transform3d objects + as compositions of basic transforms. + + .. code-block:: python + + # Scale by 0.5, then translate by (1, 2, 3) + t1 = Transform3d().scale(0.5).translate(1, 2, 3) + + # Scale each axis by a different amount, then translate, then scale + t2 = Transform3d().scale(1, 3, 3).translate(2, 3, 1).scale(2.0) + + t3 = t1.compose(t2) + tN = t1.stack(t3, t3) + + + BACKPROP THROUGH TRANSFORMS + When building transforms, we can also parameterize them by Torch tensors; + in this case we can backprop through the construction and application of + Transform objects, so they could be learned via gradient descent or + predicted by a neural network. + + .. code-block:: python + + s1_params = torch.randn(N, requires_grad=True) + t_params = torch.randn(N, 3, requires_grad=True) + s2_params = torch.randn(N, 3, requires_grad=True) + + t = Transform3d().scale(s1_params).translate(t_params).scale(s2_params) + x = torch.randn(N, 3) + y = t.transform_points(x) + loss = compute_loss(y) + loss.backward() + + with torch.no_grad(): + s1_params -= lr * s1_params.grad + t_params -= lr * t_params.grad + s2_params -= lr * s2_params.grad + + CONVENTIONS + We adopt a right-hand coordinate system, meaning that rotation about an axis + with a positive angle results in a counter clockwise rotation. + + This class assumes that transformations are applied on inputs which + are row vectors. The internal representation of the Nx4x4 transformation + matrix is of the form: + + .. code-block:: python + + M = [ + [Rxx, Ryx, Rzx, 0], + [Rxy, Ryy, Rzy, 0], + [Rxz, Ryz, Rzz, 0], + [Tx, Ty, Tz, 1], + ] + + To apply the transformation to points which are row vectors, the M matrix + can be pre multiplied by the points: + + .. code-block:: python + + points = [[0, 1, 2]] # (1 x 3) xyz coordinates of a point + transformed_points = points * M + + """ + + def __init__( + self, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", + matrix: Optional[torch.Tensor] = None, + ) -> None: + """ + Args: + dtype: The data type of the transformation matrix. + to be used if `matrix = None`. + device: The device for storing the implemented transformation. + If `matrix != None`, uses the device of input `matrix`. + matrix: A tensor of shape (4, 4) or of shape (minibatch, 4, 4) + representing the 4x4 3D transformation matrix. + If `None`, initializes with identity using + the specified `device` and `dtype`. + """ + + if matrix is None: + self._matrix = torch.eye(4, dtype=dtype, device=device).view(1, 4, 4) + else: + if matrix.ndim not in (2, 3): + raise ValueError('"matrix" has to be a 2- or a 3-dimensional tensor.') + if matrix.shape[-2] != 4 or matrix.shape[-1] != 4: + raise ValueError( + '"matrix" has to be a tensor of shape (minibatch, 4, 4)' + ) + # set dtype and device from matrix + dtype = matrix.dtype + device = matrix.device + self._matrix = matrix.view(-1, 4, 4) + + self._transforms = [] # store transforms to compose + self._lu = None + self.device = make_device(device) + self.dtype = dtype + + def __len__(self) -> int: + return self.get_matrix().shape[0] + + def __getitem__( + self, index: Union[int, List[int], slice, torch.Tensor] + ) -> "Transform3d": + """ + Args: + index: Specifying the index of the transform to retrieve. + Can be an int, slice, list of ints, boolean, long tensor. + Supports negative indices. + + Returns: + Transform3d object with selected transforms. The tensors are not cloned. + """ + if isinstance(index, int): + index = [index] + return self.__class__(matrix=self.get_matrix()[index]) + + def compose(self, *others: "Transform3d") -> "Transform3d": + """ + Return a new Transform3d representing the composition of self with the + given other transforms, which will be stored as an internal list. + + Args: + *others: Any number of Transform3d objects + + Returns: + A new Transform3d with the stored transforms + """ + out = Transform3d(dtype=self.dtype, device=self.device) + out._matrix = self._matrix.clone() + for other in others: + if not isinstance(other, Transform3d): + msg = "Only possible to compose Transform3d objects; got %s" + raise ValueError(msg % type(other)) + out._transforms = self._transforms + list(others) + return out + + def get_matrix(self) -> torch.Tensor: + """ + Return a matrix which is the result of composing this transform + with others stored in self.transforms. Where necessary transforms + are broadcast against each other. + For example, if self.transforms contains transforms t1, t2, and t3, and + given a set of points x, the following should be true: + + .. code-block:: python + + y1 = t1.compose(t2, t3).transform(x) + y2 = t3.transform(t2.transform(t1.transform(x))) + y1.get_matrix() == y2.get_matrix() + + Returns: + A transformation matrix representing the composed inputs. + """ + composed_matrix = self._matrix.clone() + if len(self._transforms) > 0: + for other in self._transforms: + other_matrix = other.get_matrix() + composed_matrix = _broadcast_bmm(composed_matrix, other_matrix) + return composed_matrix + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + return torch.inverse(self._matrix) + + def inverse(self, invert_composed: bool = False) -> "Transform3d": + """ + Returns a new Transform3d object that represents an inverse of the + current transformation. + + Args: + invert_composed: + - True: First compose the list of stored transformations + and then apply inverse to the result. This is + potentially slower for classes of transformations + with inverses that can be computed efficiently + (e.g. rotations and translations). + - False: Invert the individual stored transformations + independently without composing them. + + Returns: + A new Transform3d object containing the inverse of the original + transformation. + """ + + tinv = Transform3d(dtype=self.dtype, device=self.device) + + if invert_composed: + # first compose then invert + tinv._matrix = torch.inverse(self.get_matrix()) + else: + # self._get_matrix_inverse() implements efficient inverse + # of self._matrix + i_matrix = self._get_matrix_inverse() + + # 2 cases: + if len(self._transforms) > 0: + # a) Either we have a non-empty list of transforms: + # Here we take self._matrix and append its inverse at the + # end of the reverted _transforms list. After composing + # the transformations with get_matrix(), this correctly + # right-multiplies by the inverse of self._matrix + # at the end of the composition. + tinv._transforms = [t.inverse() for t in reversed(self._transforms)] + last = Transform3d(dtype=self.dtype, device=self.device) + last._matrix = i_matrix + tinv._transforms.append(last) + else: + # b) Or there are no stored transformations + # we just set inverted matrix + tinv._matrix = i_matrix + + return tinv + + def stack(self, *others: "Transform3d") -> "Transform3d": + """ + Return a new batched Transform3d representing the batch elements from + self and all the given other transforms all batched together. + + Args: + *others: Any number of Transform3d objects + + Returns: + A new Transform3d. + """ + transforms = [self] + list(others) + matrix = torch.cat([t.get_matrix() for t in transforms], dim=0) + out = Transform3d(dtype=self.dtype, device=self.device) + out._matrix = matrix + return out + + def transform_points(self, points, eps: Optional[float] = None) -> torch.Tensor: + """ + Use this transform to transform a set of 3D points. Assumes row major + ordering of the input points. + + Args: + points: Tensor of shape (P, 3) or (N, P, 3) + eps: If eps!=None, the argument is used to clamp the + last coordinate before performing the final division. + The clamping corresponds to: + last_coord := (last_coord.sign() + (last_coord==0)) * + torch.clamp(last_coord.abs(), eps), + i.e. the last coordinates that are exactly 0 will + be clamped to +eps. + + Returns: + points_out: points of shape (N, P, 3) or (P, 3) depending + on the dimensions of the transform + """ + points_batch = points.clone() + if points_batch.dim() == 2: + points_batch = points_batch[None] # (P, 3) -> (1, P, 3) + if points_batch.dim() != 3: + msg = "Expected points to have dim = 2 or dim = 3: got shape %r" + raise ValueError(msg % repr(points.shape)) + + N, P, _3 = points_batch.shape + ones = torch.ones(N, P, 1, dtype=points.dtype, device=points.device) + points_batch = torch.cat([points_batch, ones], dim=2) + + composed_matrix = self.get_matrix() + points_out = _broadcast_bmm(points_batch, composed_matrix) + denom = points_out[..., 3:] # denominator + if eps is not None: + denom_sign = denom.sign() + (denom == 0.0).type_as(denom) + denom = denom_sign * torch.clamp(denom.abs(), eps) + points_out = points_out[..., :3] / denom + + # When transform is (1, 4, 4) and points is (P, 3) return + # points_out of shape (P, 3) + if points_out.shape[0] == 1 and points.dim() == 2: + points_out = points_out.reshape(points.shape) + + return points_out + + def transform_normals(self, normals) -> torch.Tensor: + """ + Use this transform to transform a set of normal vectors. + + Args: + normals: Tensor of shape (P, 3) or (N, P, 3) + + Returns: + normals_out: Tensor of shape (P, 3) or (N, P, 3) depending + on the dimensions of the transform + """ + if normals.dim() not in [2, 3]: + msg = "Expected normals to have dim = 2 or dim = 3: got shape %r" + raise ValueError(msg % (normals.shape,)) + composed_matrix = self.get_matrix() + + # TODO: inverse is bad! Solve a linear system instead + mat = composed_matrix[:, :3, :3] + normals_out = _broadcast_bmm(normals, mat.transpose(1, 2).inverse()) + + # This doesn't pass unit tests. TODO investigate further + # if self._lu is None: + # self._lu = self._matrix[:, :3, :3].transpose(1, 2).lu() + # normals_out = normals.lu_solve(*self._lu) + + # When transform is (1, 4, 4) and normals is (P, 3) return + # normals_out of shape (P, 3) + if normals_out.shape[0] == 1 and normals.dim() == 2: + normals_out = normals_out.reshape(normals.shape) + + return normals_out + + def translate(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Translate(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def scale(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Scale(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def rotate(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Rotate(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def rotate_axis_angle(self, *args, **kwargs) -> "Transform3d": + return self.compose( + RotateAxisAngle(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def clone(self) -> "Transform3d": + """ + Deep copy of Transforms object. All internal tensors are cloned + individually. + + Returns: + new Transforms object. + """ + other = Transform3d(dtype=self.dtype, device=self.device) + if self._lu is not None: + other._lu = [elem.clone() for elem in self._lu] + other._matrix = self._matrix.clone() + other._transforms = [t.clone() for t in self._transforms] + return other + + def to( + self, + device: Device, + copy: bool = False, + dtype: Optional[torch.dtype] = None, + ) -> "Transform3d": + """ + Match functionality of torch.Tensor.to() + If copy = True or the self Tensor is on a different device, the + returned tensor is a copy of self with the desired torch.device. + If copy = False and the self Tensor already has the correct torch.device, + then self is returned. + + Args: + device: Device (as str or torch.device) for the new tensor. + copy: Boolean indicator whether or not to clone self. Default False. + dtype: If not None, casts the internal tensor variables + to a given torch.dtype. + + Returns: + Transform3d object. + """ + device_ = make_device(device) + dtype_ = self.dtype if dtype is None else dtype + skip_to = self.device == device_ and self.dtype == dtype_ + + if not copy and skip_to: + return self + + other = self.clone() + + if skip_to: + return other + + other.device = device_ + other.dtype = dtype_ + other._matrix = other._matrix.to(device=device_, dtype=dtype_) + other._transforms = [ + t.to(device_, copy=copy, dtype=dtype_) for t in other._transforms + ] + return other + + def cpu(self) -> "Transform3d": + return self.to("cpu") + + def cuda(self) -> "Transform3d": + return self.to("cuda") + +class Translate(Transform3d): + def __init__( + self, + x, + y=None, + z=None, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + ) -> None: + """ + Create a new Transform3d representing 3D translations. + + Option I: Translate(xyz, dtype=torch.float32, device='cpu') + xyz should be a tensor of shape (N, 3) + + Option II: Translate(x, y, z, dtype=torch.float32, device='cpu') + Here x, y, and z will be broadcast against each other and + concatenated to form the translation. Each can be: + - A python scalar + - A torch scalar + - A 1D torch tensor + """ + xyz = _handle_input(x, y, z, dtype, device, "Translate") + super().__init__(device=xyz.device, dtype=dtype) + N = xyz.shape[0] + + mat = torch.eye(4, dtype=dtype, device=self.device) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, 3, :3] = xyz + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + inv_mask = self._matrix.new_ones([1, 4, 4]) + inv_mask[0, 3, :3] = -1.0 + i_matrix = self._matrix * inv_mask + return i_matrix + +class Rotate(Transform3d): + def __init__( + self, + R: torch.Tensor, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + orthogonal_tol: float = 1e-5, + ) -> None: + """ + Create a new Transform3d representing 3D rotation using a rotation + matrix as the input. + + Args: + R: a tensor of shape (3, 3) or (N, 3, 3) + orthogonal_tol: tolerance for the test of the orthogonality of R + + """ + device_ = get_device(R, device) + super().__init__(device=device_, dtype=dtype) + if R.dim() == 2: + R = R[None] + if R.shape[-2:] != (3, 3): + msg = "R must have shape (3, 3) or (N, 3, 3); got %s" + raise ValueError(msg % repr(R.shape)) + R = R.to(device=device_, dtype=dtype) + _check_valid_rotation_matrix(R, tol=orthogonal_tol) + N = R.shape[0] + mat = torch.eye(4, dtype=dtype, device=device_) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, :3, :3] = R + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + return self._matrix.permute(0, 2, 1).contiguous() + +class TensorAccessor(nn.Module): + """ + A helper class to be used with the __getitem__ method. This can be used for + getting/setting the values for an attribute of a class at one particular + index. This is useful when the attributes of a class are batched tensors + and one element in the batch needs to be modified. + """ + + def __init__(self, class_object, index: Union[int, slice]) -> None: + """ + Args: + class_object: this should be an instance of a class which has + attributes which are tensors representing a batch of + values. + index: int/slice, an index indicating the position in the batch. + In __setattr__ and __getattr__ only the value of class + attributes at this index will be accessed. + """ + self.__dict__["class_object"] = class_object + self.__dict__["index"] = index + + def __setattr__(self, name: str, value: Any): + """ + Update the attribute given by `name` to the value given by `value` + at the index specified by `self.index`. + Args: + name: str, name of the attribute. + value: value to set the attribute to. + """ + v = getattr(self.class_object, name) + if not torch.is_tensor(v): + msg = "Can only set values on attributes which are tensors; got %r" + raise AttributeError(msg % type(v)) + + # Convert the attribute to a tensor if it is not a tensor. + if not torch.is_tensor(value): + value = torch.tensor( + value, device=v.device, dtype=v.dtype, requires_grad=v.requires_grad + ) + + # Check the shapes match the existing shape and the shape of the index. + if v.dim() > 1 and value.dim() > 1 and value.shape[1:] != v.shape[1:]: + msg = "Expected value to have shape %r; got %r" + raise ValueError(msg % (v.shape, value.shape)) + if ( + v.dim() == 0 + and isinstance(self.index, slice) + and len(value) != len(self.index) + ): + msg = "Expected value to have len %r; got %r" + raise ValueError(msg % (len(self.index), len(value))) + self.class_object.__dict__[name][self.index] = value + + def __getattr__(self, name: str): + """ + Return the value of the attribute given by "name" on self.class_object + at the index specified in self.index. + Args: + name: string of the attribute name + """ + if hasattr(self.class_object, name): + return self.class_object.__dict__[name][self.index] + else: + msg = "Attribute %s not found on %r" + return AttributeError(msg % (name, self.class_object.__name__)) + +BROADCAST_TYPES = (float, int, list, tuple, torch.Tensor, np.ndarray) + +class TensorProperties(nn.Module): + """ + A mix-in class for storing tensors as properties with helper methods. + """ + + def __init__( + self, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", + **kwargs, + ) -> None: + """ + Args: + dtype: data type to set for the inputs + device: Device (as str or torch.device) + kwargs: any number of keyword arguments. Any arguments which are + of type (float/int/list/tuple/tensor/array) are broadcasted and + other keyword arguments are set as attributes. + """ + super().__init__() + self.device = make_device(device) + self._N = 0 + if kwargs is not None: + + # broadcast all inputs which are float/int/list/tuple/tensor/array + # set as attributes anything else e.g. strings, bools + args_to_broadcast = {} + for k, v in kwargs.items(): + if v is None or isinstance(v, (str, bool)): + setattr(self, k, v) + elif isinstance(v, BROADCAST_TYPES): + args_to_broadcast[k] = v + else: + msg = "Arg %s with type %r is not broadcastable" + warnings.warn(msg % (k, type(v))) + + names = args_to_broadcast.keys() + # convert from type dict.values to tuple + values = tuple(v for v in args_to_broadcast.values()) + + if len(values) > 0: + broadcasted_values = convert_to_tensors_and_broadcast( + *values, device=device + ) + + # Set broadcasted values as attributes on self. + for i, n in enumerate(names): + setattr(self, n, broadcasted_values[i]) + if self._N == 0: + self._N = broadcasted_values[i].shape[0] + + def __len__(self) -> int: + return self._N + + def isempty(self) -> bool: + return self._N == 0 + + def __getitem__(self, index: Union[int, slice]) -> TensorAccessor: + """ + Args: + index: an int or slice used to index all the fields. + Returns: + if `index` is an index int/slice return a TensorAccessor class + with getattribute/setattribute methods which return/update the value + at the index in the original class. + """ + if isinstance(index, (int, slice)): + return TensorAccessor(class_object=self, index=index) + + msg = "Expected index of type int or slice; got %r" + raise ValueError(msg % type(index)) + + # pyre-fixme[14]: `to` overrides method defined in `Module` inconsistently. + def to(self, device: Device = "cpu") -> "TensorProperties": + """ + In place operation to move class properties which are tensors to a + specified device. If self has a property "device", update this as well. + """ + device_ = make_device(device) + for k in dir(self): + v = getattr(self, k) + if k == "device": + setattr(self, k, device_) + if torch.is_tensor(v) and v.device != device_: + setattr(self, k, v.to(device_)) + return self + + def cpu(self) -> "TensorProperties": + return self.to("cpu") + + # pyre-fixme[14]: `cuda` overrides method defined in `Module` inconsistently. + def cuda(self, device: Optional[int] = None) -> "TensorProperties": + return self.to(f"cuda:{device}" if device is not None else "cuda") + + def clone(self, other) -> "TensorProperties": + """ + Update the tensor properties of other with the cloned properties of self. + """ + for k in dir(self): + v = getattr(self, k) + if inspect.ismethod(v) or k.startswith("__"): + continue + if torch.is_tensor(v): + v_clone = v.clone() + else: + v_clone = copy.deepcopy(v) + setattr(other, k, v_clone) + return other + + def gather_props(self, batch_idx) -> "TensorProperties": + """ + This is an in place operation to reformat all tensor class attributes + based on a set of given indices using torch.gather. This is useful when + attributes which are batched tensors e.g. shape (N, 3) need to be + multiplied with another tensor which has a different first dimension + e.g. packed vertices of shape (V, 3). + Example + .. code-block:: python + self.specular_color = (N, 3) tensor of specular colors for each mesh + A lighting calculation may use + .. code-block:: python + verts_packed = meshes.verts_packed() # (V, 3) + To multiply these two tensors the batch dimension needs to be the same. + To achieve this we can do + .. code-block:: python + batch_idx = meshes.verts_packed_to_mesh_idx() # (V) + This gives index of the mesh for each vertex in verts_packed. + .. code-block:: python + self.gather_props(batch_idx) + self.specular_color = (V, 3) tensor with the specular color for + each packed vertex. + torch.gather requires the index tensor to have the same shape as the + input tensor so this method takes care of the reshaping of the index + tensor to use with class attributes with arbitrary dimensions. + Args: + batch_idx: shape (B, ...) where `...` represents an arbitrary + number of dimensions + Returns: + self with all properties reshaped. e.g. a property with shape (N, 3) + is transformed to shape (B, 3). + """ + # Iterate through the attributes of the class which are tensors. + for k in dir(self): + v = getattr(self, k) + if torch.is_tensor(v): + if v.shape[0] > 1: + # There are different values for each batch element + # so gather these using the batch_idx. + # First clone the input batch_idx tensor before + # modifying it. + _batch_idx = batch_idx.clone() + idx_dims = _batch_idx.shape + tensor_dims = v.shape + if len(idx_dims) > len(tensor_dims): + msg = "batch_idx cannot have more dimensions than %s. " + msg += "got shape %r and %s has shape %r" + raise ValueError(msg % (k, idx_dims, k, tensor_dims)) + if idx_dims != tensor_dims: + # To use torch.gather the index tensor (_batch_idx) has + # to have the same shape as the input tensor. + new_dims = len(tensor_dims) - len(idx_dims) + new_shape = idx_dims + (1,) * new_dims + expand_dims = (-1,) + tensor_dims[1:] + _batch_idx = _batch_idx.view(*new_shape) + _batch_idx = _batch_idx.expand(*expand_dims) + + v = v.gather(0, _batch_idx) + setattr(self, k, v) + return self + +class CamerasBase(TensorProperties): + """ + `CamerasBase` implements a base class for all cameras. + For cameras, there are four different coordinate systems (or spaces) + - World coordinate system: This is the system the object lives - the world. + - Camera view coordinate system: This is the system that has its origin on the camera + and the and the Z-axis perpendicular to the image plane. + In PyTorch3D, we assume that +X points left, and +Y points up and + +Z points out from the image plane. + The transformation from world --> view happens after applying a rotation (R) + and translation (T) + - NDC coordinate system: This is the normalized coordinate system that confines + in a volume the rendered part of the object or scene. Also known as view volume. + For square images, given the PyTorch3D convention, (+1, +1, znear) + is the top left near corner, and (-1, -1, zfar) is the bottom right far + corner of the volume. + The transformation from view --> NDC happens after applying the camera + projection matrix (P) if defined in NDC space. + For non square images, we scale the points such that smallest side + has range [-1, 1] and the largest side has range [-u, u], with u > 1. + - Screen coordinate system: This is another representation of the view volume with + the XY coordinates defined in image space instead of a normalized space. + A better illustration of the coordinate systems can be found in + pytorch3d/docs/notes/cameras.md. + It defines methods that are common to all camera models: + - `get_camera_center` that returns the optical center of the camera in + world coordinates + - `get_world_to_view_transform` which returns a 3D transform from + world coordinates to the camera view coordinates (R, T) + - `get_full_projection_transform` which composes the projection + transform (P) with the world-to-view transform (R, T) + - `transform_points` which takes a set of input points in world coordinates and + projects to the space the camera is defined in (NDC or screen) + - `get_ndc_camera_transform` which defines the transform from screen/NDC to + PyTorch3D's NDC space + - `transform_points_ndc` which takes a set of points in world coordinates and + projects them to PyTorch3D's NDC space + - `transform_points_screen` which takes a set of points in world coordinates and + projects them to screen space + For each new camera, one should implement the `get_projection_transform` + routine that returns the mapping from camera view coordinates to camera + coordinates (NDC or screen). + Another useful function that is specific to each camera model is + `unproject_points` which sends points from camera coordinates (NDC or screen) + back to camera view or world coordinates depending on the `world_coordinates` + boolean argument of the function. + """ + + # Used in __getitem__ to index the relevant fields + # When creating a new camera, this should be set in the __init__ + _FIELDS: Tuple[str, ...] = () + + # Names of fields which are a constant property of the whole batch, rather + # than themselves a batch of data. + # When joining objects into a batch, they will have to agree. + _SHARED_FIELDS: Tuple[str, ...] = () + + def get_projection_transform(self): + """ + Calculate the projective transformation matrix. + Args: + **kwargs: parameters for the projection can be passed in as keyword + arguments to override the default values set in `__init__`. + Return: + a `Transform3d` object which represents a batch of projection + matrices of shape (N, 3, 3) + """ + raise NotImplementedError() + + def unproject_points(self, xy_depth: torch.Tensor, **kwargs): + """ + Transform input points from camera coodinates (NDC or screen) + to the world / camera coordinates. + Each of the input points `xy_depth` of shape (..., 3) is + a concatenation of the x, y location and its depth. + For instance, for an input 2D tensor of shape `(num_points, 3)` + `xy_depth` takes the following form: + `xy_depth[i] = [x[i], y[i], depth[i]]`, + for a each point at an index `i`. + The following example demonstrates the relationship between + `transform_points` and `unproject_points`: + .. code-block:: python + cameras = # camera object derived from CamerasBase + xyz = # 3D points of shape (batch_size, num_points, 3) + # transform xyz to the camera view coordinates + xyz_cam = cameras.get_world_to_view_transform().transform_points(xyz) + # extract the depth of each point as the 3rd coord of xyz_cam + depth = xyz_cam[:, :, 2:] + # project the points xyz to the camera + xy = cameras.transform_points(xyz)[:, :, :2] + # append depth to xy + xy_depth = torch.cat((xy, depth), dim=2) + # unproject to the world coordinates + xyz_unproj_world = cameras.unproject_points(xy_depth, world_coordinates=True) + print(torch.allclose(xyz, xyz_unproj_world)) # True + # unproject to the camera coordinates + xyz_unproj = cameras.unproject_points(xy_depth, world_coordinates=False) + print(torch.allclose(xyz_cam, xyz_unproj)) # True + Args: + xy_depth: torch tensor of shape (..., 3). + world_coordinates: If `True`, unprojects the points back to world + coordinates using the camera extrinsics `R` and `T`. + `False` ignores `R` and `T` and unprojects to + the camera view coordinates. + from_ndc: If `False` (default), assumes xy part of input is in + NDC space if self.in_ndc(), otherwise in screen space. If + `True`, assumes xy is in NDC space even if the camera + is defined in screen space. + Returns + new_points: unprojected points with the same shape as `xy_depth`. + """ + raise NotImplementedError() + + def get_camera_center(self, **kwargs) -> torch.Tensor: + """ + Return the 3D location of the camera optical center + in the world coordinates. + Args: + **kwargs: parameters for the camera extrinsics can be passed in + as keyword arguments to override the default values + set in __init__. + Setting T here will update the values set in init as this + value may be needed later on in the rendering pipeline e.g. for + lighting calculations. + Returns: + C: a batch of 3D locations of shape (N, 3) denoting + the locations of the center of each camera in the batch. + """ + w2v_trans = self.get_world_to_view_transform(**kwargs) + P = w2v_trans.inverse().get_matrix() + # the camera center is the translation component (the first 3 elements + # of the last row) of the inverted world-to-view + # transform (4x4 RT matrix) + C = P[:, 3, :3] + return C + + def get_world_to_view_transform(self, **kwargs) -> Transform3d: + """ + Return the world-to-view transform. + Args: + **kwargs: parameters for the camera extrinsics can be passed in + as keyword arguments to override the default values + set in __init__. + Setting R and T here will update the values set in init as these + values may be needed later on in the rendering pipeline e.g. for + lighting calculations. + Returns: + A Transform3d object which represents a batch of transforms + of shape (N, 3, 3) + """ + R: torch.Tensor = kwargs.get("R", self.R) + T: torch.Tensor = kwargs.get("T", self.T) + self.R = R # pyre-ignore[16] + self.T = T # pyre-ignore[16] + world_to_view_transform = get_world_to_view_transform(R=R, T=T) + return world_to_view_transform + + def get_full_projection_transform(self, **kwargs) -> Transform3d: + """ + Return the full world-to-camera transform composing the + world-to-view and view-to-camera transforms. + If camera is defined in NDC space, the projected points are in NDC space. + If camera is defined in screen space, the projected points are in screen space. + Args: + **kwargs: parameters for the projection transforms can be passed in + as keyword arguments to override the default values + set in __init__. + Setting R and T here will update the values set in init as these + values may be needed later on in the rendering pipeline e.g. for + lighting calculations. + Returns: + a Transform3d object which represents a batch of transforms + of shape (N, 3, 3) + """ + self.R: torch.Tensor = kwargs.get("R", self.R) # pyre-ignore[16] + self.T: torch.Tensor = kwargs.get("T", self.T) # pyre-ignore[16] + world_to_view_transform = self.get_world_to_view_transform(R=self.R, T=self.T) + view_to_proj_transform = self.get_projection_transform(**kwargs) + return world_to_view_transform.compose(view_to_proj_transform) + + def transform_points( + self, points, eps: Optional[float] = None, **kwargs + ) -> torch.Tensor: + """ + Transform input points from world to camera space with the + projection matrix defined by the camera. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the camera plane. + Args: + points: torch tensor of shape (..., 3). + eps: If eps!=None, the argument is used to clamp the + divisor in the homogeneous normalization of the points + transformed to the ndc space. Please see + `transforms.Transform3d.transform_points` for details. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the + camera plane. + Returns + new_points: transformed points with the same shape as the input. + """ + world_to_proj_transform = self.get_full_projection_transform(**kwargs) + return world_to_proj_transform.transform_points(points, eps=eps) + + def get_ndc_camera_transform(self, **kwargs) -> Transform3d: + """ + Returns the transform from camera projection space (screen or NDC) to NDC space. + For cameras that can be specified in screen space, this transform + allows points to be converted from screen to NDC space. + The default transform scales the points from [0, W]x[0, H] + to [-1, 1]x[-u, u] or [-u, u]x[-1, 1] where u > 1 is the aspect ratio of the image. + This function should be modified per camera definitions if need be, + e.g. for Perspective/Orthographic cameras we provide a custom implementation. + This transform assumes PyTorch3D coordinate system conventions for + both the NDC space and the input points. + This transform interfaces with the PyTorch3D renderer which assumes + input points to the renderer to be in NDC space. + """ + if self.in_ndc(): + return Transform3d(device=self.device, dtype=torch.float32) + else: + # For custom cameras which can be defined in screen space, + # users might might have to implement the screen to NDC transform based + # on the definition of the camera parameters. + # See PerspectiveCameras/OrthographicCameras for an example. + # We don't flip xy because we assume that world points are in + # PyTorch3D coordinates, and thus conversion from screen to ndc + # is a mere scaling from image to [-1, 1] scale. + image_size = kwargs.get("image_size", self.get_image_size()) + return get_screen_to_ndc_transform( + self, with_xyflip=False, image_size=image_size + ) + + def transform_points_ndc( + self, points, eps: Optional[float] = None, **kwargs + ) -> torch.Tensor: + """ + Transforms points from PyTorch3D world/camera space to NDC space. + Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up. + Output points are in NDC space: +X left, +Y up, origin at image center. + Args: + points: torch tensor of shape (..., 3). + eps: If eps!=None, the argument is used to clamp the + divisor in the homogeneous normalization of the points + transformed to the ndc space. Please see + `transforms.Transform3d.transform_points` for details. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the + camera plane. + Returns + new_points: transformed points with the same shape as the input. + """ + world_to_ndc_transform = self.get_full_projection_transform(**kwargs) + if not self.in_ndc(): + to_ndc_transform = self.get_ndc_camera_transform(**kwargs) + world_to_ndc_transform = world_to_ndc_transform.compose(to_ndc_transform) + + return world_to_ndc_transform.transform_points(points, eps=eps) + + def transform_points_screen( + self, points, eps: Optional[float] = None, **kwargs + ) -> torch.Tensor: + """ + Transforms points from PyTorch3D world/camera space to screen space. + Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up. + Output points are in screen space: +X right, +Y down, origin at top left corner. + Args: + points: torch tensor of shape (..., 3). + eps: If eps!=None, the argument is used to clamp the + divisor in the homogeneous normalization of the points + transformed to the ndc space. Please see + `transforms.Transform3d.transform_points` for details. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the + camera plane. + Returns + new_points: transformed points with the same shape as the input. + """ + points_ndc = self.transform_points_ndc(points, eps=eps, **kwargs) + image_size = kwargs.get("image_size", self.get_image_size()) + return get_ndc_to_screen_transform( + self, with_xyflip=True, image_size=image_size + ).transform_points(points_ndc, eps=eps) + + def clone(self): + """ + Returns a copy of `self`. + """ + cam_type = type(self) + other = cam_type(device=self.device) + return super().clone(other) + + def is_perspective(self): + raise NotImplementedError() + + def in_ndc(self): + """ + Specifies whether the camera is defined in NDC space + or in screen (image) space + """ + raise NotImplementedError() + + def get_znear(self): + return self.znear if hasattr(self, "znear") else None + + def get_image_size(self): + """ + Returns the image size, if provided, expected in the form of (height, width) + The image size is used for conversion of projected points to screen coordinates. + """ + return self.image_size if hasattr(self, "image_size") else None + + def __getitem__( + self, index: Union[int, List[int], torch.LongTensor] + ) -> "CamerasBase": + """ + Override for the __getitem__ method in TensorProperties which needs to be + refactored. + Args: + index: an int/list/long tensor used to index all the fields in the cameras given by + self._FIELDS. + Returns: + if `index` is an index int/list/long tensor return an instance of the current + cameras class with only the values at the selected index. + """ + + kwargs = {} + + if not isinstance(index, (int, list, torch.LongTensor, torch.cuda.LongTensor)): + msg = "Invalid index type, expected int, List[int] or torch.LongTensor; got %r" + raise ValueError(msg % type(index)) + + if isinstance(index, int): + index = [index] + + if max(index) >= len(self): + raise ValueError(f"Index {max(index)} is out of bounds for select cameras") + + for field in self._FIELDS: + val = getattr(self, field, None) + if val is None: + continue + + # e.g. "in_ndc" is set as attribute "_in_ndc" on the class + # but provided as "in_ndc" on initialization + if field.startswith("_"): + field = field[1:] + + if isinstance(val, (str, bool)): + kwargs[field] = val + elif isinstance(val, torch.Tensor): + # In the init, all inputs will be converted to + # tensors before setting as attributes + kwargs[field] = val[index] + else: + raise ValueError(f"Field {field} type is not supported for indexing") + + kwargs["device"] = self.device + return self.__class__(**kwargs) + +class FoVPerspectiveCameras(CamerasBase): + """ + A class which stores a batch of parameters to generate a batch of + projection matrices by specifying the field of view. + The definition of the parameters follow the OpenGL perspective camera. + + The extrinsics of the camera (R and T matrices) can also be set in the + initializer or passed in to `get_full_projection_transform` to get + the full transformation from world -> ndc. + + The `transform_points` method calculates the full world -> ndc transform + and then applies it to the input points. + + The transforms can also be returned separately as Transform3d objects. + + * Setting the Aspect Ratio for Non Square Images * + + If the desired output image size is non square (i.e. a tuple of (H, W) where H != W) + the aspect ratio needs special consideration: There are two aspect ratios + to be aware of: + - the aspect ratio of each pixel + - the aspect ratio of the output image + The `aspect_ratio` setting in the FoVPerspectiveCameras sets the + pixel aspect ratio. When using this camera with the differentiable rasterizer + be aware that in the rasterizer we assume square pixels, but allow + variable image aspect ratio (i.e rectangle images). + + In most cases you will want to set the camera `aspect_ratio=1.0` + (i.e. square pixels) and only vary the output image dimensions in pixels + for rasterization. + """ + + # For __getitem__ + _FIELDS = ( + "K", + "znear", + "zfar", + "aspect_ratio", + "fov", + "R", + "T", + "degrees", + ) + + _SHARED_FIELDS = ("degrees",) + + def __init__( + self, + znear=1.0, + zfar=100.0, + aspect_ratio=1.0, + fov=60.0, + degrees: bool = True, + R: torch.Tensor = _R, + T: torch.Tensor = _T, + K: Optional[torch.Tensor] = None, + device: Device = "cpu", + ) -> None: + """ + + Args: + znear: near clipping plane of the view frustrum. + zfar: far clipping plane of the view frustrum. + aspect_ratio: aspect ratio of the image pixels. + 1.0 indicates square pixels. + fov: field of view angle of the camera. + degrees: bool, set to True if fov is specified in degrees. + R: Rotation matrix of shape (N, 3, 3) + T: Translation matrix of shape (N, 3) + K: (optional) A calibration matrix of shape (N, 4, 4) + If provided, don't need znear, zfar, fov, aspect_ratio, degrees + device: Device (as str or torch.device) + """ + # The initializer formats all inputs to torch tensors and broadcasts + # all the inputs to have the same batch dimension where necessary. + super().__init__( + device=device, + znear=znear, + zfar=zfar, + aspect_ratio=aspect_ratio, + fov=fov, + R=R, + T=T, + K=K, + ) + + # No need to convert to tensor or broadcast. + self.degrees = degrees + + def compute_projection_matrix( + self, znear, zfar, fov, aspect_ratio, degrees: bool + ) -> torch.Tensor: + """ + Compute the calibration matrix K of shape (N, 4, 4) + + Args: + znear: near clipping plane of the view frustrum. + zfar: far clipping plane of the view frustrum. + fov: field of view angle of the camera. + aspect_ratio: aspect ratio of the image pixels. + 1.0 indicates square pixels. + degrees: bool, set to True if fov is specified in degrees. + + Returns: + torch.FloatTensor of the calibration matrix with shape (N, 4, 4) + """ + K = torch.zeros((self._N, 4, 4), device=self.device, dtype=torch.float32) + ones = torch.ones((self._N), dtype=torch.float32, device=self.device) + if degrees: + fov = (np.pi / 180) * fov + + if not torch.is_tensor(fov): + fov = torch.tensor(fov, device=self.device) + tanHalfFov = torch.tan((fov / 2)) + max_y = tanHalfFov * znear + min_y = -max_y + max_x = max_y * aspect_ratio + min_x = -max_x + + # NOTE: In OpenGL the projection matrix changes the handedness of the + # coordinate frame. i.e the NDC space positive z direction is the + # camera space negative z direction. This is because the sign of the z + # in the projection matrix is set to -1.0. + # In pytorch3d we maintain a right handed coordinate system throughout + # so the so the z sign is 1.0. + z_sign = 1.0 + + K[:, 0, 0] = 2.0 * znear / (max_x - min_x) + K[:, 1, 1] = 2.0 * znear / (max_y - min_y) + K[:, 0, 2] = (max_x + min_x) / (max_x - min_x) + K[:, 1, 2] = (max_y + min_y) / (max_y - min_y) + K[:, 3, 2] = z_sign * ones + + # NOTE: This maps the z coordinate from [0, 1] where z = 0 if the point + # is at the near clipping plane and z = 1 when the point is at the far + # clipping plane. + K[:, 2, 2] = z_sign * zfar / (zfar - znear) + K[:, 2, 3] = -(zfar * znear) / (zfar - znear) + + return K + + def get_projection_transform(self, **kwargs) -> Transform3d: + """ + Calculate the perspective projection matrix with a symmetric + viewing frustrum. Use column major order. + The viewing frustrum will be projected into ndc, s.t. + (max_x, max_y) -> (+1, +1) + (min_x, min_y) -> (-1, -1) + + Args: + **kwargs: parameters for the projection can be passed in as keyword + arguments to override the default values set in `__init__`. + + Return: + a Transform3d object which represents a batch of projection + matrices of shape (N, 4, 4) + + .. code-block:: python + + h1 = (max_y + min_y)/(max_y - min_y) + w1 = (max_x + min_x)/(max_x - min_x) + tanhalffov = tan((fov/2)) + s1 = 1/tanhalffov + s2 = 1/(tanhalffov * (aspect_ratio)) + + # To map z to the range [0, 1] use: + f1 = far / (far - near) + f2 = -(far * near) / (far - near) + + # Projection matrix + K = [ + [s1, 0, w1, 0], + [0, s2, h1, 0], + [0, 0, f1, f2], + [0, 0, 1, 0], + ] + """ + K = kwargs.get("K", self.K) + if K is not None: + if K.shape != (self._N, 4, 4): + msg = "Expected K to have shape of (%r, 4, 4)" + raise ValueError(msg % (self._N)) + else: + K = self.compute_projection_matrix( + kwargs.get("znear", self.znear), + kwargs.get("zfar", self.zfar), + kwargs.get("fov", self.fov), + kwargs.get("aspect_ratio", self.aspect_ratio), + kwargs.get("degrees", self.degrees), + ) + + # Transpose the projection matrix as PyTorch3D transforms use row vectors. + transform = Transform3d( + matrix=K.transpose(1, 2).contiguous(), device=self.device + ) + return transform + + def unproject_points( + self, + xy_depth: torch.Tensor, + world_coordinates: bool = True, + scaled_depth_input: bool = False, + **kwargs, + ) -> torch.Tensor: + """>! + FoV cameras further allow for passing depth in world units + (`scaled_depth_input=False`) or in the [0, 1]-normalized units + (`scaled_depth_input=True`) + + Args: + scaled_depth_input: If `True`, assumes the input depth is in + the [0, 1]-normalized units. If `False` the input depth is in + the world units. + """ + + # obtain the relevant transformation to ndc + if world_coordinates: + to_ndc_transform = self.get_full_projection_transform() + else: + to_ndc_transform = self.get_projection_transform() + + if scaled_depth_input: + # the input is scaled depth, so we don't have to do anything + xy_sdepth = xy_depth + else: + # parse out important values from the projection matrix + K_matrix = self.get_projection_transform(**kwargs.copy()).get_matrix() + # parse out f1, f2 from K_matrix + unsqueeze_shape = [1] * xy_depth.dim() + unsqueeze_shape[0] = K_matrix.shape[0] + f1 = K_matrix[:, 2, 2].reshape(unsqueeze_shape) + f2 = K_matrix[:, 3, 2].reshape(unsqueeze_shape) + # get the scaled depth + sdepth = (f1 * xy_depth[..., 2:3] + f2) / xy_depth[..., 2:3] + # concatenate xy + scaled depth + xy_sdepth = torch.cat((xy_depth[..., 0:2], sdepth), dim=-1) + + # unproject with inverse of the projection + unprojection_transform = to_ndc_transform.inverse() + return unprojection_transform.transform_points(xy_sdepth) + + def is_perspective(self): + return True + + def in_ndc(self): + return True + +####################################################################################### +## ██████╗ ███████╗███████╗██╗███╗ ██╗██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ ## +## ██╔══██╗██╔════╝██╔════╝██║████╗ ██║██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ ## +## ██║ ██║█████╗ █████╗ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ ## +## ██║ ██║██╔══╝ ██╔══╝ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ ## +## ██████╔╝███████╗██║ ██║██║ ╚████║██║ ██║ ██║╚██████╔╝██║ ╚████║███████║ ## +## ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ## +####################################################################################### + +def make_device(device: Device) -> torch.device: + """ + Makes an actual torch.device object from the device specified as + either a string or torch.device object. If the device is `cuda` without + a specific index, the index of the current device is assigned. + Args: + device: Device (as str or torch.device) + Returns: + A matching torch.device object + """ + device = torch.device(device) if isinstance(device, str) else device + if device.type == "cuda" and device.index is None: # pyre-ignore[16] + # If cuda but with no index, then the current cuda device is indicated. + # In that case, we fix to that device + device = torch.device(f"cuda:{torch.cuda.current_device()}") + return device + +def get_device(x, device: Optional[Device] = None) -> torch.device: + """ + Gets the device of the specified variable x if it is a tensor, or + falls back to a default CPU device otherwise. Allows overriding by + providing an explicit device. + Args: + x: a torch.Tensor to get the device from or another type + device: Device (as str or torch.device) to fall back to + Returns: + A matching torch.device object + """ + + # User overrides device + if device is not None: + return make_device(device) + + # Set device based on input tensor + if torch.is_tensor(x): + return x.device + + # Default device is cpu + return torch.device("cpu") + +def _axis_angle_rotation(axis: str, angle: torch.Tensor) -> torch.Tensor: + """ + Return the rotation matrices for one of the rotations about an axis + of which Euler angles describe, for each value of the angle given. + + Args: + axis: Axis label "X" or "Y or "Z". + angle: any shape tensor of Euler angles in radians + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + + cos = torch.cos(angle) + sin = torch.sin(angle) + one = torch.ones_like(angle) + zero = torch.zeros_like(angle) + + if axis == "X": + R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos) + elif axis == "Y": + R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos) + elif axis == "Z": + R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one) + else: + raise ValueError("letter must be either X, Y or Z.") + + return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3)) + +def euler_angles_to_matrix(euler_angles: torch.Tensor, convention: str) -> torch.Tensor: + """ + Convert rotations given as Euler angles in radians to rotation matrices. + + Args: + euler_angles: Euler angles in radians as tensor of shape (..., 3). + convention: Convention string of three uppercase letters from + {"X", "Y", and "Z"}. + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3: + raise ValueError("Invalid input euler angles.") + if len(convention) != 3: + raise ValueError("Convention must have 3 letters.") + if convention[1] in (convention[0], convention[2]): + raise ValueError(f"Invalid convention {convention}.") + for letter in convention: + if letter not in ("X", "Y", "Z"): + raise ValueError(f"Invalid letter {letter} in convention string.") + matrices = [ + _axis_angle_rotation(c, e) + for c, e in zip(convention, torch.unbind(euler_angles, -1)) + ] + # return functools.reduce(torch.matmul, matrices) + return torch.matmul(torch.matmul(matrices[0], matrices[1]), matrices[2]) + +def _broadcast_bmm(a, b) -> torch.Tensor: + """ + Batch multiply two matrices and broadcast if necessary. + + Args: + a: torch tensor of shape (P, K) or (M, P, K) + b: torch tensor of shape (N, K, K) + + Returns: + a and b broadcast multiplied. The output batch dimension is max(N, M). + + To broadcast transforms across a batch dimension if M != N then + expect that either M = 1 or N = 1. The tensor with batch dimension 1 is + expanded to have shape N or M. + """ + if a.dim() == 2: + a = a[None] + if len(a) != len(b): + if not ((len(a) == 1) or (len(b) == 1)): + msg = "Expected batch dim for bmm to be equal or 1; got %r, %r" + raise ValueError(msg % (a.shape, b.shape)) + if len(a) == 1: + a = a.expand(len(b), -1, -1) + if len(b) == 1: + b = b.expand(len(a), -1, -1) + return a.bmm(b) + +def _safe_det_3x3(t: torch.Tensor): + """ + Fast determinant calculation for a batch of 3x3 matrices. + Note, result of this function might not be the same as `torch.det()`. + The differences might be in the last significant digit. + Args: + t: Tensor of shape (N, 3, 3). + Returns: + Tensor of shape (N) with determinants. + """ + + det = ( + t[..., 0, 0] * (t[..., 1, 1] * t[..., 2, 2] - t[..., 1, 2] * t[..., 2, 1]) + - t[..., 0, 1] * (t[..., 1, 0] * t[..., 2, 2] - t[..., 2, 0] * t[..., 1, 2]) + + t[..., 0, 2] * (t[..., 1, 0] * t[..., 2, 1] - t[..., 2, 0] * t[..., 1, 1]) + ) + + return det + +def get_world_to_view_transform( + R: torch.Tensor = _R, T: torch.Tensor = _T +) -> Transform3d: + """ + This function returns a Transform3d representing the transformation + matrix to go from world space to view space by applying a rotation and + a translation. + PyTorch3D uses the same convention as Hartley & Zisserman. + I.e., for camera extrinsic parameters R (rotation) and T (translation), + we map a 3D point `X_world` in world coordinates to + a point `X_cam` in camera coordinates with: + `X_cam = X_world R + T` + Args: + R: (N, 3, 3) matrix representing the rotation. + T: (N, 3) matrix representing the translation. + Returns: + a Transform3d object which represents the composed RT transformation. + """ + # TODO: also support the case where RT is specified as one matrix + # of shape (N, 4, 4). + + if T.shape[0] != R.shape[0]: + msg = "Expected R, T to have the same batch dimension; got %r, %r" + raise ValueError(msg % (R.shape[0], T.shape[0])) + if T.dim() != 2 or T.shape[1:] != (3,): + msg = "Expected T to have shape (N, 3); got %r" + raise ValueError(msg % repr(T.shape)) + if R.dim() != 3 or R.shape[1:] != (3, 3): + msg = "Expected R to have shape (N, 3, 3); got %r" + raise ValueError(msg % repr(R.shape)) + + # Create a Transform3d object + T_ = Translate(T, device=T.device) + R_ = Rotate(R, device=R.device) + return R_.compose(T_) + +def _check_valid_rotation_matrix(R, tol: float = 1e-7) -> None: + """ + Determine if R is a valid rotation matrix by checking it satisfies the + following conditions: + + ``RR^T = I and det(R) = 1`` + + Args: + R: an (N, 3, 3) matrix + + Returns: + None + + Emits a warning if R is an invalid rotation matrix. + """ + N = R.shape[0] + eye = torch.eye(3, dtype=R.dtype, device=R.device) + eye = eye.view(1, 3, 3).expand(N, -1, -1) + orthogonal = torch.allclose(R.bmm(R.transpose(1, 2)), eye, atol=tol) + det_R = _safe_det_3x3(R) + no_distortion = torch.allclose(det_R, torch.ones_like(det_R)) + if not (orthogonal and no_distortion): + msg = "R is not a valid rotation matrix" + warnings.warn(msg) + return + +def format_tensor( + input, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", +) -> torch.Tensor: + """ + Helper function for converting a scalar value to a tensor. + Args: + input: Python scalar, Python list/tuple, torch scalar, 1D torch tensor + dtype: data type for the input + device: Device (as str or torch.device) on which the tensor should be placed. + Returns: + input_vec: torch tensor with optional added batch dimension. + """ + device_ = make_device(device) + if not torch.is_tensor(input): + input = torch.tensor(input, dtype=dtype, device=device_) + + if input.dim() == 0: + input = input.view(1) + + if input.device == device_: + return input + + input = input.to(device=device) + return input + +def convert_to_tensors_and_broadcast( + *args, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", +): + """ + Helper function to handle parsing an arbitrary number of inputs (*args) + which all need to have the same batch dimension. + The output is a list of tensors. + Args: + *args: an arbitrary number of inputs + Each of the values in `args` can be one of the following + - Python scalar + - Torch scalar + - Torch tensor of shape (N, K_i) or (1, K_i) where K_i are + an arbitrary number of dimensions which can vary for each + value in args. In this case each input is broadcast to a + tensor of shape (N, K_i) + dtype: data type to use when creating new tensors. + device: torch device on which the tensors should be placed. + Output: + args: A list of tensors of shape (N, K_i) + """ + # Convert all inputs to tensors with a batch dimension + args_1d = [format_tensor(c, dtype, device) for c in args] + + # Find broadcast size + sizes = [c.shape[0] for c in args_1d] + N = max(sizes) + + args_Nd = [] + for c in args_1d: + if c.shape[0] != 1 and c.shape[0] != N: + msg = "Got non-broadcastable sizes %r" % sizes + raise ValueError(msg) + + # Expand broadcast dim and keep non broadcast dims the same size + expand_sizes = (N,) + (-1,) * len(c.shape[1:]) + args_Nd.append(c.expand(*expand_sizes)) + + return args_Nd + +def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + """ + Helper function for _handle_input. + + Args: + c: Python scalar, torch scalar, or 1D torch tensor + + Returns: + c_vec: 1D torch tensor + """ + if not torch.is_tensor(c): + c = torch.tensor(c, dtype=dtype, device=device) + if c.dim() == 0: + c = c.view(1) + if c.device != device or c.dtype != dtype: + c = c.to(device=device, dtype=dtype) + return c + +def _handle_input( + x, + y, + z, + dtype: torch.dtype, + device: Optional[Device], + name: str, + allow_singleton: bool = False, +) -> torch.Tensor: + """ + Helper function to handle parsing logic for building transforms. The output + is always a tensor of shape (N, 3), but there are several types of allowed + input. + + Case I: Single Matrix + In this case x is a tensor of shape (N, 3), and y and z are None. Here just + return x. + + Case II: Vectors and Scalars + In this case each of x, y, and z can be one of the following + - Python scalar + - Torch scalar + - Torch tensor of shape (N, 1) or (1, 1) + In this case x, y and z are broadcast to tensors of shape (N, 1) + and concatenated to a tensor of shape (N, 3) + + Case III: Singleton (only if allow_singleton=True) + In this case y and z are None, and x can be one of the following: + - Python scalar + - Torch scalar + - Torch tensor of shape (N, 1) or (1, 1) + Here x will be duplicated 3 times, and we return a tensor of shape (N, 3) + + Returns: + xyz: Tensor of shape (N, 3) + """ + device_ = get_device(x, device) + # If x is actually a tensor of shape (N, 3) then just return it + if torch.is_tensor(x) and x.dim() == 2: + if x.shape[1] != 3: + msg = "Expected tensor of shape (N, 3); got %r (in %s)" + raise ValueError(msg % (x.shape, name)) + if y is not None or z is not None: + msg = "Expected y and z to be None (in %s)" % name + raise ValueError(msg) + return x.to(device=device_, dtype=dtype) + + if allow_singleton and y is None and z is None: + y = x + z = x + + # Convert all to 1D tensors + xyz = [_handle_coord(c, dtype, device_) for c in [x, y, z]] + + # Broadcast and concatenate + sizes = [c.shape[0] for c in xyz] + N = max(sizes) + for c in xyz: + if c.shape[0] != 1 and c.shape[0] != N: + msg = "Got non-broadcastable sizes %r (in %s)" % (sizes, name) + raise ValueError(msg) + xyz = [c.expand(N) for c in xyz] + xyz = torch.stack(xyz, dim=1) + return xyz diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..228e270 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +lpips +datetime +guided-diffusion@git+https://github.com/kostarion/guided-diffusion +imageio +imageio-ffmpeg==0.4.4 +lpips +datetime +pandas +opencv-python +regex diff --git a/secondary_diffusion_model.py b/secondary_diffusion_model.py new file mode 100644 index 0000000..3ff1dce --- /dev/null +++ b/secondary_diffusion_model.py @@ -0,0 +1,193 @@ +from dataclasses import dataclass +from functools import partial +import cv2 +import pandas as pd +import gc +import math +import lpips +from PIL import Image, ImageOps +import requests +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from functools import partial +from numpy import asarray + + +def append_dims(x, n): + return x[(Ellipsis, *(None,) * (n - x.ndim))] + + +def alpha_sigma_to_t(alpha, sigma): + return torch.atan2(sigma, alpha) * 2 / math.pi + + +def expand_to_planes(x, shape): + return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]]) + + +def t_to_alpha_sigma(t): + return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2) + + +@dataclass +class DiffusionOutput: + v: torch.Tensor + pred: torch.Tensor + eps: torch.Tensor + + +class ConvBlock(nn.Sequential): + def __init__(self, c_in, c_out): + super().__init__( + nn.Conv2d(c_in, c_out, 3, padding=1), + nn.ReLU(inplace=True), + ) + + +class SkipBlock(nn.Module): + def __init__(self, main, skip=None): + super().__init__() + self.main = nn.Sequential(*main) + self.skip = skip if skip else nn.Identity() + + def forward(self, input): + return torch.cat([self.main(input), self.skip(input)], dim=1) + + +class FourierFeatures(nn.Module): + def __init__(self, in_features, out_features, std=1.): + super().__init__() + assert out_features % 2 == 0 + self.weight = nn.Parameter(torch.randn( + [out_features // 2, in_features]) * std) + + def forward(self, input): + f = 2 * math.pi * input @ self.weight.T + return torch.cat([f.cos(), f.sin()], dim=-1) + + +class SecondaryDiffusionImageNet(nn.Module): + def __init__(self): + super().__init__() + c = 64 # The base channel count + + self.timestep_embed = FourierFeatures(1, 16) + + self.net = nn.Sequential( + ConvBlock(3 + 16, c), + ConvBlock(c, c), + SkipBlock([ + nn.AvgPool2d(2), + ConvBlock(c, c * 2), + ConvBlock(c * 2, c * 2), + SkipBlock([ + nn.AvgPool2d(2), + ConvBlock(c * 2, c * 4), + ConvBlock(c * 4, c * 4), + SkipBlock([ + nn.AvgPool2d(2), + ConvBlock(c * 4, c * 8), + ConvBlock(c * 8, c * 4), + nn.Upsample(scale_factor=2, mode='bilinear', + align_corners=False), + ]), + ConvBlock(c * 8, c * 4), + ConvBlock(c * 4, c * 2), + nn.Upsample(scale_factor=2, mode='bilinear', + align_corners=False), + ]), + ConvBlock(c * 4, c * 2), + ConvBlock(c * 2, c), + nn.Upsample(scale_factor=2, mode='bilinear', + align_corners=False), + ]), + ConvBlock(c * 2, c), + nn.Conv2d(c, 3, 3, padding=1), + ) + + def forward(self, input, t): + timestep_embed = expand_to_planes( + self.timestep_embed(t[:, None]), input.shape) + v = self.net(torch.cat([input, timestep_embed], dim=1)) + alphas, sigmas = map( + partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) + pred = input * alphas - v * sigmas + eps = input * sigmas + v * alphas + return DiffusionOutput(v, pred, eps) + + +class SecondaryDiffusionImageNet2(nn.Module): + def __init__(self): + super().__init__() + c = 64 # The base channel count + cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8] + + self.timestep_embed = FourierFeatures(1, 16) + self.down = nn.AvgPool2d(2) + self.up = nn.Upsample( + scale_factor=2, mode='bilinear', align_corners=False) + + self.net = nn.Sequential( + ConvBlock(3 + 16, cs[0]), + ConvBlock(cs[0], cs[0]), + SkipBlock([ + self.down, + ConvBlock(cs[0], cs[1]), + ConvBlock(cs[1], cs[1]), + SkipBlock([ + self.down, + ConvBlock(cs[1], cs[2]), + ConvBlock(cs[2], cs[2]), + SkipBlock([ + self.down, + ConvBlock(cs[2], cs[3]), + ConvBlock(cs[3], cs[3]), + SkipBlock([ + self.down, + ConvBlock(cs[3], cs[4]), + ConvBlock(cs[4], cs[4]), + SkipBlock([ + self.down, + ConvBlock(cs[4], cs[5]), + ConvBlock(cs[5], cs[5]), + ConvBlock(cs[5], cs[5]), + ConvBlock(cs[5], cs[4]), + self.up, + ]), + ConvBlock(cs[4] * 2, cs[4]), + ConvBlock(cs[4], cs[3]), + self.up, + ]), + ConvBlock(cs[3] * 2, cs[3]), + ConvBlock(cs[3], cs[2]), + self.up, + ]), + ConvBlock(cs[2] * 2, cs[2]), + ConvBlock(cs[2], cs[1]), + self.up, + ]), + ConvBlock(cs[1] * 2, cs[1]), + ConvBlock(cs[1], cs[0]), + self.up, + ]), + ConvBlock(cs[0] * 2, cs[0]), + nn.Conv2d(cs[0], 3, 3, padding=1), + ) + + def forward(self, input, t): + timestep_embed = expand_to_planes( + self.timestep_embed(t[:, None]), input.shape) + v = self.net(torch.cat([input, timestep_embed], dim=1)) + alphas, sigmas = map( + partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) + pred = input * alphas - v * sigmas + eps = input * sigmas + v * alphas + return DiffusionOutput(v, pred, eps) diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..34d5ad0 --- /dev/null +++ b/settings.py @@ -0,0 +1,611 @@ +from dataclasses import dataclass +import pathlib +import os +import pathlib +import os +from dataclasses import dataclass +import cv2 +import pandas as pd +import gc +import math +import lpips +from PIL import Image, ImageOps +import requests +from glob import glob +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from numpy import asarray +import subprocess + +from .video_input import setup_raft +from .video_input import setup_video_input_mode +from .video_input import generate_optical_flow +from .model_settings import ModelSettings + + +@dataclass +class DiscoDiffusionSettings: + def __init__(self): + self.root_path = os.getcwd() + self.initDirPath = f'{self.root_path}/init_images' + os.makedirs(self.initDirPath, exist_ok=True) + self.outDirPath = f'{self.root_path}/images_out' + os.makedirs(self.outDirPath, exist_ok=True) + + self.useCPU = False + + # %% + # !! {"metadata":{ + # !! "id": "BasicSettings" + # !! }} + # @markdown ####**Basic Settings:** + self.batch_name = 'TimeToDisco' # @param{type: 'string'} + # @param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} + self.steps = 250 + self.width_height_for_512x512_models = [ + 1280, 768] # @param{type: 'raw'} + self.clip_guidance_scale = 5000 # @param{type: 'number'} + self.tv_scale = 0 # @param{type: 'number'} + self.range_scale = 150 # @param{type: 'number'} + self.sat_scale = 0 # @param{type: 'number'} + self.cutn_batches = 4 # @param{type: 'number'} + self.skip_augs = False # @param{type: 'boolean'} + + # @markdown ####**Image dimensions to be used for 256x256 models (e.g. pixelart models):** + self.width_height_for_256x256_models = [ + 512, 448] # @param{type: 'raw'} + + # @markdown ####**Video Init Basic Settings:** + # @param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} + self.video_init_steps = 100 + self.video_init_clip_guidance_scale = 1000 # @param{type: 'number'} + self.video_init_tv_scale = 0.1 # @param{type: 'number'} + self.video_init_range_scale = 150 # @param{type: 'number'} + self.video_init_sat_scale = 300 # @param{type: 'number'} + self.video_init_cutn_batches = 4 # @param{type: 'number'} + self.video_init_skip_steps = 50 # @param{type: 'integer'} + + # @markdown --- + + # @markdown ####**Init Image Settings:** + self.init_image = None # @param{type: 'string'} + self.init_scale = 1000 # @param{type: 'integer'} + self.skip_steps = 10 # @param{type: 'integer'} + # @markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.* + + # Make folder for batch + self.batchFolder = f'{self.outDirPath}/{self.batch_name}' + os.makedirs(self.batchFolder, exist_ok=True) + + # @markdown ####**Animation Mode:** + # @param ['None', '2D', '3D', 'Video Input'] {type:'string'} + self.animation_mode = 'None' + # @markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.* + + self.video_init_path = "init.mp4" # @param {type: 'string'} + self.extract_nth_frame = 2 # @param {type: 'number'} + # @param {type: 'boolean'} + self.persistent_frame_output_in_batch_folder = True + self.video_init_seed_continuity = False # @param {type: 'boolean'} + # @markdown #####**Video Optical Flow Settings:** + self.video_init_flow_warp = True # @param {type: 'boolean'} + # Call optical flow from video frames and warp prev frame with flow + # @param {type: 'number'} #0 - take next frame, 1 - take prev warped frame + self.video_init_flow_blend = 0.999 + self.video_init_check_consistency = False # Insert param here when ready + # @param ['None', 'linear', 'optical flow'] + self.video_init_blend_mode = "optical flow" + + # @markdown --- + + # @markdown ####**2D Animation Settings:** + # @markdown `zoom` is a multiplier of dimensions, 1 is no zoom. + # @markdown All rotations are provided in degrees. + + self.key_frames = True # @param {type:"boolean"} + self.max_frames = 10000 # @param {type:"number"} + + # Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"} + self.interp_spline = 'Linear' + self.angle = "0:(0)" # @param {type:"string"} + self.zoom = "0: (1), 10: (1.05)" # @param {type:"string"} + self.translation_x = "0: (0)" # @param {type:"string"} + self.translation_y = "0: (0)" # @param {type:"string"} + self.translation_z = "0: (10.0)" # @param {type:"string"} + self.rotation_3d_x = "0: (0)" # @param {type:"string"} + self.rotation_3d_y = "0: (0)" # @param {type:"string"} + self.rotation_3d_z = "0: (0)" # @param {type:"string"} + self.midas_depth_model = "dpt_large" # @param {type:"string"} + self.midas_weight = 0.3 # @param {type:"number"} + self.near_plane = 200 # @param {type:"number"} + self.far_plane = 10000 # @param {type:"number"} + self.fov = 40 # @param {type:"number"} + self.padding_mode = 'border' # @param {type:"string"} + self.sampling_mode = 'bicubic' # @param {type:"string"} + + # ======= TURBO MODE + # @markdown --- + # @markdown ####**Turbo Mode (3D anim only):** + # @markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames. + # @markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. + # @markdown For different settings tuned for Turbo Mode, refer to the original Disco-Turbo Github: https://github.com/zippy731/disco-diffusion-turbo + + self.turbo_mode = False # @param {type:"boolean"} + self.turbo_steps = "3" # @param ["2","3","4","5","6"] {type:"string"} + self.turbo_preroll = 10 # frames + + # insist turbo be used only w 3d anim. + if self.turbo_mode and self.animation_mode != '3D': + print('=====') + print('Turbo mode only available with 3D animations. Disabling Turbo.') + print('=====') + self.turbo_mode = False + + # @markdown --- + + # @markdown ####**Coherency Settings:** + # @markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500. + self.frames_scale = 1500 # @param{type: 'integer'} + # @markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into. + # @param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'} + self.frames_skip_steps = '60%' + + # @markdown ####**Video Init Coherency Settings:** + # @markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500. + self.video_init_frames_scale = 15000 # @param{type: 'integer'} + # @markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into. + # @param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'} + self.video_init_frames_skip_steps = '70%' + + # ======= VR MODE + # @markdown --- + # @markdown ####**VR Mode (3D anim only):** + # @markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. + # @markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect + # @markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format. + # @markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download + # @markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly. + # @markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/ + # @markdown + # @markdown The command to get ffmpeg to concat your frames for each eye is in the form: `ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4` (repeat for r) + + self.vr_mode = False # @param {type:"boolean"} + # @markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center + self.vr_eye_angle = 0.5 # @param{type:"number"} + # @markdown interpupillary distance (between the eyes) + self.vr_ipd = 5.0 # @param{type:"number"} + + # %% + # !! {"metadata":{ + # !! "id": "ExtraSetTop" + # !! }} + # """ + # ### Extra Settings + # Partial Saves, Advanced Settings, Cutn Scheduling + # """ + + # %% + # !! {"metadata":{ + # !! "id": "ExtraSettings" + # !! }} + # @markdown ####**Saving:** + + self.intermediate_saves = 0 # @param{type: 'raw'} + self.intermediates_in_subfolder = True # @param{type: 'boolean'} + # @markdown Intermediate steps will save a copy at your specified intervals. You can either format it as a single integer or a list of specific steps + + # @markdown A value of `2` will save a copy at 33% and 66%. 0 will save none. + + # @markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets) + + # @markdown --- + + # @markdown ####**Advanced Settings:** + # @markdown *There are a few extra advanced settings available if you double click this cell.* + + # @markdown *Perlin init will replace your init, so uncheck if using one.* + + self.perlin_init = False # @param{type: 'boolean'} + self.perlin_mode = 'mixed' # @param ['mixed', 'color', 'gray'] + self.set_seed = 'random_seed' # @param{type: 'string'} + self.eta = 0.8 # @param{type: 'number'} + self.clamp_grad = True # @param{type: 'boolean'} + self.clamp_max = 0.05 # @param{type: 'number'} + + # EXTRA ADVANCED SETTINGS: + self.randomize_class = True + self.clip_denoised = False + self.fuzzy_prompt = False + self.rand_mag = 0.05 + + # @markdown --- + + # @markdown ####**Cutn Scheduling:** + # @markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000 + + # @markdown cut_overview and cut_innercut are cumulative for total cutn on any given step. Overview cuts see the entire image and are good for early structure, innercuts are your standard cutn. + + self.cut_overview = "[12]*400+[4]*600" # @param {type: 'string'} + self.cut_innercut = "[4]*400+[12]*600" # @param {type: 'string'} + self.cut_ic_pow = "[1]*1000" # @param {type: 'string'} + self.cut_icgray_p = "[0.2]*400+[0]*600" # @param {type: 'string'} + + # @markdown KaliYuga model settings. Refer to [cut_ic_pow](https://ezcharts.miraheze.org/wiki/Category:Cut_ic_pow) as a guide. Values between 1 and 100 all work. + # @param {type: 'string'} + self.pad_or_pulp_cut_overview = "[15]*100+[15]*100+[12]*100+[12]*100+[6]*100+[4]*100+[2]*200+[0]*200" + # @param {type: 'string'} + self.pad_or_pulp_cut_innercut = "[1]*100+[1]*100+[4]*100+[4]*100+[8]*100+[8]*100+[10]*200+[10]*200" + # @param {type: 'string'} + self.pad_or_pulp_cut_ic_pow = "[12]*300+[12]*100+[12]*50+[12]*50+[10]*100+[10]*100+[10]*300" + # @param {type: 'string'} + self.pad_or_pulp_cut_icgray_p = "[0.87]*100+[0.78]*50+[0.73]*50+[0.64]*60+[0.56]*40+[0.50]*50+[0.33]*100+[0.19]*150+[0]*400" + + # @param {type: 'string'} + self.watercolor_cut_overview = "[14]*200+[12]*200+[4]*400+[0]*200" + # @param {type: 'string'} + self.watercolor_cut_innercut = "[2]*200+[4]*200+[12]*400+[12]*200" + # @param {type: 'string'} + self.watercolor_cut_ic_pow = "[12]*300+[12]*100+[12]*50+[12]*50+[10]*100+[10]*100+[10]*300" + # @param {type: 'string'} + self.watercolor_cut_icgray_p = "[0.7]*100+[0.6]*100+[0.45]*100+[0.3]*100+[0]*600" + + # @markdown --- + + # @markdown ####**Transformation Settings:** + self.use_vertical_symmetry = False # @param {type:"boolean"} + self.use_horizontal_symmetry = False # @param {type:"boolean"} + self.transformation_percent = [0.09] # @param + + # %% + # !! {"metadata":{ + # !! "id": "PromptsTop" + # !! }} + """ + ### Prompts + `animation_mode: None` will only use the first set. `animation_mode: 2D / Video` will run through them per the set frames and hold on the last one. + """ + + # %% + # !! {"metadata":{ + # !! "id": "Prompts" + # !! }} + # Note: If using a pixelart diffusion model, try adding "#pixelart" to the end of the prompt for a stronger effect. It'll tend to work a lot better! + self.text_prompts = { + 0: ["A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.", "yellow color scheme"] + # 100: ["This set of prompts start at frame 100", "This prompt has weight five:5"], + } + + self.image_prompts = { + # 0:['ImagePromptsWorkButArentVeryGood.png:2',], + } + + def setup(self, MS: ModelSettings): + self.MS = MS + + if type(self.intermediate_saves) is not list: + if self.intermediate_saves: + self.steps_per_checkpoint = math.floor( + (self.steps - self.skip_steps - 1) // (self.intermediate_saves+1)) + self.steps_per_checkpoint = self.steps_per_checkpoint if self.steps_per_checkpoint > 0 else 1 + print(f'Will save every {self.steps_per_checkpoint} steps') + else: + self.steps_per_checkpoint = self.steps+10 + else: + self.steps_per_checkpoint = None + + if self.intermediate_saves and self.intermediates_in_subfolder is True: + self.partialFolder = f'{self.batchFolder}/partials' + os.makedirs(self.partialFolder, exist_ok=True) + + self.width_height = self.width_height_for_256x256_models if MS.diffusion_model in MS.diffusion_models_256x256_list else self.width_height_for_512x512_models + + # Get corrected sizes + self.side_x = (self.width_height[0]//64)*64 + self.side_y = (self.width_height[1]//64)*64 + if self.side_x != self.width_height[0] or self.side_y != self.width_height[1]: + print( + f'Changing output size to {self.side_x}x{self.side_y}. Dimensions must by multiples of 64.') + + if (MS.diffusion_model in MS.kaliyuga_pixel_art_model_names) or (MS.diffusion_model in MS.kaliyuga_pulpscifi_model_names): + self.cut_overview = self.pad_or_pulp_cut_overview + self.cut_innercut = self.pad_or_pulp_cut_innercut + self.cut_ic_pow = self.pad_or_pulp_cut_ic_pow + self.cut_icgray_p = self.pad_or_pulp_cut_icgray_p + elif MS.diffusion_model in MS.kaliyuga_watercolor_model_names: + self.cut_overview = self.watercolor_cut_overview + self.cut_innercut = self.watercolor_cut_innercut + self.cut_ic_pow = self.watercolor_cut_ic_pow + self.cut_icgray_p = self.watercolor_cut_icgray_p + + # insist VR be used only w 3d anim. + if self.vr_mode and self.animation_mode != '3D': + print('=====') + print('VR mode only available with 3D animations. Disabling VR.') + print('=====') + self.vr_mode = False + + if self.key_frames: + try: + self.angle_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.angle)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `angle` correctly for key frames.\n" + "Attempting to interpret `angle` as " + f'"0: ({self.angle})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.angle = f"0: ({self.angle})" + self.angle_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.angle)) + + try: + self.zoom_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.zoom)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `zoom` correctly for key frames.\n" + "Attempting to interpret `zoom` as " + f'"0: ({self.zoom})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.zoom = f"0: ({self.zoom})" + self.zoom_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.zoom)) + + try: + self.translation_x_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.translation_x)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `translation_x` correctly for key frames.\n" + "Attempting to interpret `translation_x` as " + f'"0: ({self.translation_x})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.translation_x = f"0: ({self.translation_x})" + self.translation_x_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.translation_x)) + + try: + self.translation_y_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.translation_y)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `translation_y` correctly for key frames.\n" + "Attempting to interpret `translation_y` as " + f'"0: ({self.translation_y})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.translation_y = f"0: ({self.translation_y})" + self.translation_y_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.translation_y)) + + try: + get_inbetweens(self.max_frames, self.interp_spline, + parse_key_frames(self.translation_z)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `translation_z` correctly for key frames.\n" + "Attempting to interpret `translation_z` as " + f'"0: ({self.translation_z})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.translation_z = f"0: ({self.translation_z})" + self.translation_z_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.translation_z)) + + try: + self.rotation_3d_x_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.rotation_3d_x)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `rotation_3d_x` correctly for key frames.\n" + "Attempting to interpret `rotation_3d_x` as " + f'"0: ({self.rotation_3d_x})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.rotation_3d_x = f"0: ({self.rotation_3d_x})" + self.rotation_3d_x_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.rotation_3d_x)) + + try: + self.rotation_3d_y_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.rotation_3d_y)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `rotation_3d_y` correctly for key frames.\n" + "Attempting to interpret `rotation_3d_y` as " + f'"0: ({self.rotation_3d_y})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.rotation_3d_y = f"0: ({self.rotation_3d_y})" + self.rotation_3d_y_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.rotation_3d_y)) + + try: + self.rotation_3d_z_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.rotation_3d_z)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `rotation_3d_z` correctly for key frames.\n" + "Attempting to interpret `rotation_3d_z` as " + f'"0: ({self.rotation_3d_z})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + self.rotation_3d_z = f"0: ({self.rotation_3d_z})" + self.rotation_3d_z_series = get_inbetweens( + self.max_frames, self.interp_spline, parse_key_frames(self.rotation_3d_z)) + + else: + self.angle = float(self.angle) + self.zoom = float(self.zoom) + self.translation_x = float(self.translation_x) + self.translation_y = float(self.translation_y) + self.translation_z = float(self.translation_z) + self.rotation_3d_x = float(self.rotation_3d_x) + self.rotation_3d_y = float(self.rotation_3d_y) + self.rotation_3d_z = float(self.rotation_3d_z) + + if self.animation_mode == 'Video Input': + self.max_frames = len(glob(f'{self.videoFramesFolder}/*.jpg')) + + # Call optical flow from video frames and warp prev frame with flow + if self.persistent_frame_output_in_batch_folder: # suggested by Chris the Wizard#8082 at discord + self.videoFramesFolder = f'{self.batchFolder}/videoFrames' + else: + self.videoFramesFolder = f'/content/videoFrames' + os.makedirs(self.videoFramesFolder, exist_ok=True) + print( + f"Exporting Video Frames (1 every {self.extract_nth_frame})...") + try: + for f in pathlib.Path(f'{self.videoFramesFolder}').glob('*.jpg'): + f.unlink() + except Exception as err: + print(err) + vf = f'select=not(mod(n\,{self.extract_nth_frame}))' + if os.path.exists(self.video_init_path): + subprocess.run(['ffmpeg', '-i', f'{self.video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', + 'error', '-stats', f'{self.videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8') + else: + print( + f'\nWARNING!\n\nVideo not found: {self.video_init_path}.\nPlease check your video path.\n') + #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg + + setup_raft() + setup_video_input_mode(self) + generate_optical_flow(self) + + +def parse_key_frames(string, prompt_parser=None): + """Given a string representing frame numbers paired with parameter values at that frame, + return a dictionary with the frame numbers as keys and the parameter values as the values. + + Parameters + ---------- + string: string + Frame numbers paired with parameter values at that frame number, in the format + 'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...' + prompt_parser: function or None, optional + If provided, prompt_parser will be applied to each string of parameter values. + + Returns + ------- + dict + Frame numbers as keys, parameter values at that frame number as values + + Raises + ------ + RuntimeError + If the input string does not match the expected format. + + Examples + -------- + >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)") + {10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'} + + >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)", prompt_parser=lambda x: x.lower())) + {10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'} + """ + import re + pattern = r'((?P[0-9]+):[\s]*[\(](?P[\S\s]*?)[\)])' + frames = dict() + for match_object in re.finditer(pattern, string): + frame = int(match_object.groupdict()['frame']) + param = match_object.groupdict()['param'] + if prompt_parser: + frames[frame] = prompt_parser(param) + else: + frames[frame] = param + + if frames == {} and len(string) != 0: + raise RuntimeError('Key Frame string not correctly formatted') + return frames + + +def get_inbetweens(max_frames, interp_method, key_frames, integer=False): + """Given a dict with frame numbers as keys and a parameter value as values, + return a pandas Series containing the value of the parameter at every frame from 0 to max_frames. + Any values not provided in the input dict are calculated by linear interpolation between + the values of the previous and next provided frames. If there is no previous provided frame, then + the value is equal to the value of the next provided frame, or if there is no next provided frame, + then the value is equal to the value of the previous provided frame. If no frames are provided, + all frame values are NaN. + + Parameters + ---------- + key_frames: dict + A dict with integer frame numbers as keys and numerical values of a particular parameter as values. + integer: Bool, optional + If True, the values of the output series are converted to integers. + Otherwise, the values are floats. + + Returns + ------- + pd.Series + A Series with length max_frames representing the parameter values for each frame. + + Examples + -------- + >>> max_frames = 5 + >>> get_inbetweens({1: 5, 3: 6}) + 0 5.0 + 1 5.0 + 2 5.5 + 3 6.0 + 4 6.0 + dtype: float64 + + >>> get_inbetweens({1: 5, 3: 6}, integer=True) + 0 5 + 1 5 + 2 5 + 3 6 + 4 6 + dtype: int64 + """ + key_frame_series = pd.Series([np.nan for a in range(max_frames)]) + + for i, value in key_frames.items(): + key_frame_series[i] = value + key_frame_series = key_frame_series.astype(float) + + if interp_method == 'Cubic' and len(key_frames.items()) <= 3: + interp_method = 'Quadratic' + + if interp_method == 'Quadratic' and len(key_frames.items()) <= 2: + interp_method = 'Linear' + + key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()] + key_frame_series[max_frames - + 1] = key_frame_series[key_frame_series.last_valid_index()] + # key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both') + key_frame_series = key_frame_series.interpolate( + method=interp_method.lower(), limit_direction='both') + if integer: + return key_frame_series.astype(int) + return key_frame_series diff --git a/video.py b/video.py new file mode 100644 index 0000000..03dd335 --- /dev/null +++ b/video.py @@ -0,0 +1,208 @@ +import shutil +import sys +import cv2 +import pandas as pd +import gc +import lpips +from PIL import Image, ImageOps +import requests +from glob import glob +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from numpy import asarray +import warnings +import PIL +from tqdm import trange +import os + +from .settings import DiscoDiffusionSettings + +skip_video_for_run_all = False # @param {type: 'boolean'} + +# @title ### **Create video** +# @markdown Video file will save in the same folder as your images. + + +def create_video(batchNum, args: DiscoDiffusionSettings): + if args.animation_mode == 'Video Input': + frames = sorted(glob(args.in_path+'/*.*')) + if len(frames) == 0: + sys.exit( + "ERROR: 0 frames found.\nPlease check your video input path and rerun the video settings cell.") + flows = glob(args.flo_folder+'/*.*') + if (len(flows) == 0) and args.video_init_flow_warp: + sys.exit( + "ERROR: 0 flow files found.\nPlease rerun the flow generation cell.") + + blend = 0.5 # @param {type: 'number'} + args.video_init_check_consistency = False # @param {type: 'boolean'} + if skip_video_for_run_all == True: + print( + 'Skipping video creation, uncheck skip_video_for_run_all if you want to run it') + + else: + # import subprocess in case this cell is run without the above cells + import subprocess + + latest_run = batchNum + + folder = args.batch_name # @param + run = latest_run # @param + final_frame = 'final_frame' + + # @param {type:"number"} This is the frame where the video will start + init_frame = 1 + # @param {type:"number"} 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. + last_frame = final_frame + fps = 12 # @param {type:"number"} + # view_video_in_cell = True #@param {type: 'boolean'} + + frames = [] + # tqdm.write('Generating video...') + + if last_frame == 'final_frame': + last_frame = len(glob(args.batchFolder+f"/{folder}({run})_*.png")) + print(f'Total frames: {last_frame}') + + image_path = f"{args.outDirPath}/{folder}/{folder}({run})_%04d.png" + filepath = f"{args.outDirPath}/{folder}/{folder}({run}).mp4" + + if (args.video_init_blend_mode == 'optical flow') and (args.animation_mode == 'Video Input'): + image_path = f"{args.outDirPath}/{folder}/flow/{folder}({run})_%04d.png" + filepath = f"{args.outDirPath}/{folder}/{folder}({run})_flow.mp4" + if last_frame == 'final_frame': + last_frame = len( + glob(args.batchFolder+f"/flow/{folder}({run})_*.png")) + flo_out = args.batchFolder+f"/flow" + args.createPath(flo_out) + frames_in = sorted( + glob(args.batchFolder+f"/{folder}({run})_*.png")) + shutil.copy(frames_in[0], flo_out) + for i in trange(init_frame, min(len(frames_in), last_frame)): + frame1_path = frames_in[i-1] + frame2_path = frames_in[i] + + frame1 = PIL.Image.open(frame1_path) + frame2 = PIL.Image.open(frame2_path) + frame1_stem = f"{(int(frame1_path.split('/')[-1].split('_')[-1][:-4])+1):04}.jpg" + flo_path = f"/{args.flo_folder}/{frame1_stem}.npy" + weights_path = None + if args.video_init_check_consistency: + # TBD + pass + import video_input + video_input.warp(frame1, frame2, flo_path, blend=blend, weights_path=weights_path).save( + args.batchFolder+f"/flow/{folder}({run})_{i:04}.png") + if args.video_init_blend_mode == 'linear': + image_path = f"{args.outDirPath}/{folder}/blend/{folder}({run})_%04d.png" + filepath = f"{args.outDirPath}/{folder}/{folder}({run})_blend.mp4" + if last_frame == 'final_frame': + last_frame = len( + glob(args.batchFolder+f"/blend/{folder}({run})_*.png")) + blend_out = args.batchFolder+f"/blend" + os.makedirs(blend_out, exist_ok=True) + frames_in = glob(args.batchFolder+f"/{folder}({run})_*.png") + shutil.copy(frames_in[0], blend_out) + for i in trange(1, len(frames_in)): + frame1_path = frames_in[i-1] + frame2_path = frames_in[i] + + frame1 = PIL.Image.open(frame1_path) + frame2 = PIL.Image.open(frame2_path) + + frame = PIL.Image.fromarray((np.array(frame1)*(1-blend) + np.array(frame2)*( + blend)).astype('uint8')).save(args.batchFolder+f"/blend/{folder}({run})_{i:04}.png") + + cmd = [ + 'ffmpeg', + '-y', + '-vcodec', + 'png', + '-r', + str(fps), + '-start_number', + str(init_frame), + '-i', + image_path, + '-frames:v', + str(last_frame+1), + '-c:v', + 'libx264', + '-vf', + f'fps={fps}', + '-pix_fmt', + 'yuv420p', + '-crf', + '17', + '-preset', + 'veryslow', + filepath + ] + + process = subprocess.Popen( + cmd, cwd=f'{args.batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + if process.returncode != 0: + print(stderr) + raise RuntimeError(stderr) + else: + print("The video is ready and saved to the images folder") + + # if view_video_in_cell: + # mp4 = open(filepath,'rb').read() + # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() + # display.HTML(f'') + + # %% + # !! {"main_metadata":{ + # !! "anaconda-cloud": {}, + # !! "accelerator": "GPU", + # !! "colab": { + # !! "collapsed_sections": [ + # !! "CreditsChTop", + # !! "TutorialTop", + # !! "CheckGPU", + # !! "InstallDeps", + # !! "DefMidasFns", + # !! "DefFns", + # !! "DefSecModel", + # !! "DefSuperRes", + # !! "AnimSetTop", + # !! "ExtraSetTop", + # !! "InstallRAFT", + # !! "CustModel", + # !! "FlowFns1", + # !! "FlowFns2" + # !! ], + # !! "machine_shape": "hm", + # !! "name": "Disco Diffusion v5.61 [Now with portrait_generator_v001]", + # !! "private_outputs": true, + # !! "provenance": [], + # !! "include_colab_link": true + # !! }, + # !! "kernelspec": { + # !! "display_name": "Python 3", + # !! "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.6.1" + # !! } + # !! }} diff --git a/video_input.py b/video_input.py new file mode 100644 index 0000000..d5c2aa0 --- /dev/null +++ b/video_input.py @@ -0,0 +1,229 @@ +import PIL +import argparse +from PIL import Image +import pathlib +import os +import cv2 +import pandas as pd +import gc +import subprocess +import lpips +from PIL import Image, ImageOps +import requests +from glob import glob +import torch +from torch import nn +from torch.nn import functional as F +import torchvision +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm import tqdm +from resize_right import resize +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +import numpy as np +from numpy import asarray +from raft import RAFT +from raftutils.utils import InputPadder +from raftutils import flow_viz + + +from folder_paths import models_dir + + +# %% +# !! {"metadata":{ +# !! "id": "InstallRAFT" +# !! }} +# @title Install RAFT for Video input animation mode only +# @markdown Run once per session. Doesn't download again if model path exists. +# @markdown Use force download to reload raft models if needed +force_download = False # @param {type:'boolean'} + + +def setup_raft(): + pass + +# @title Define optical flow functions for Video input animation mode only +def setup_video_input_mode(S): + S.in_path = S.videoFramesFolder + # f'{in_path}/out_flo_fwd' + # f'{models_dir}/RAFT/core' + + +args2 = argparse.Namespace() +args2.small = False +args2.mixed_precision = True + + +TAG_CHAR = np.array([202021.25], np.float32) + + +def writeFlow(filename, uv, v=None): + """ + https://github.com/NVIDIA/flownet2-pytorch/blob/master/utils/flow_utils.py + Copyright 2017 NVIDIA CORPORATION + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Write optical flow to file. + + If v is None, uv is assumed to contain both u and v channels, + stacked in depth. + Original code by Deqing Sun, adapted from Daniel Scharstein. + """ + nBands = 2 + + if v is None: + assert (uv.ndim == 3) + assert (uv.shape[2] == 2) + u = uv[:, :, 0] + v = uv[:, :, 1] + else: + u = uv + + assert (u.shape == v.shape) + height, width = u.shape + f = open(filename, 'wb') + # write the header + f.write(TAG_CHAR) + np.array(width).astype(np.int32).tofile(f) + np.array(height).astype(np.int32).tofile(f) + # arrange into matrix form + tmp = np.zeros((height, width*nBands)) + tmp[:, np.arange(width)*2] = u + tmp[:, np.arange(width)*2 + 1] = v + tmp.astype(np.float32).tofile(f) + f.close() + + +def load_img(img, size): + img = Image.open(img).convert('RGB').resize(size) + return torch.from_numpy(np.array(img)).permute(2, 0, 1).float()[None, ...].cuda() + + +def get_flow(frame1, frame2, model, iters=20): + padder = InputPadder(frame1.shape) + frame1, frame2 = padder.pad(frame1, frame2) + _, flow12 = model(frame1, frame2, iters=iters, test_mode=True) + flow12 = flow12[0].permute(1, 2, 0).detach().cpu().numpy() + + return flow12 + + +def warp_flow(img, flow): + h, w = flow.shape[:2] + flow = flow.copy() + flow[:, :, 0] += np.arange(w) + flow[:, :, 1] += np.arange(h)[:, np.newaxis] + res = cv2.remap(img, flow, None, cv2.INTER_LINEAR) + return res + + +def makeEven(_x): + return _x if (_x % 2 == 0) else _x+1 + + +def fit(img, maxsize=512): + maxdim = max(*img.size) + if maxdim > maxsize: + # if True: + ratio = maxsize/maxdim + x, y = img.size + size = (makeEven(int(x*ratio)), makeEven(int(y*ratio))) + img = img.resize(size) + return img + + +def warp(frame1, frame2, flo_path, blend=0.5, weights_path=None): + flow21 = np.load(flo_path) + frame1pil = np.array(frame1.convert('RGB').resize( + (flow21.shape[1], flow21.shape[0]))) + frame1_warped21 = warp_flow(frame1pil, flow21) + # frame2pil = frame1pil + frame2pil = np.array(frame2.convert('RGB').resize( + (flow21.shape[1], flow21.shape[0]))) + + if weights_path: + # TBD + pass + else: + blended_w = frame2pil*(1-blend) + frame1_warped21*(blend) + + return PIL.Image.fromarray(blended_w.astype('uint8')) + +# in_path = videoFramesFolder +# f'{in_path}/out_flo_fwd' + +# in_path+'/temp_flo' +# in_path+'/out_flo_fwd' +# TBD flow backwards! + +# os.chdir(models_dir) + +# @title Generate optical flow and consistency maps +# @markdown Run once per init video + + +def generate_optical_flow(S): + force_flow_generation = False # @param {type:'boolean'} + in_path = S.videoFramesFolder + flo_folder = f'{in_path}/out_flo_fwd' + + if not S.video_init_flow_warp: + print('video_init_flow_warp not set, skipping') + + if (S.animation_mode == 'Video Input') and (S.video_init_flow_warp): + flows = glob(flo_folder+'/*.*') + if (len(flows) > 0) and not force_flow_generation: + print( + f'Skipping flow generation:\nFound {len(flows)} existing flow files in current working folder: {flo_folder}.\nIf you wish to generate new flow files, check force_flow_generation and run this cell again.') + + if (len(flows) == 0) or force_flow_generation: + frames = sorted(glob(in_path+'/*.*')) + if len(frames) < 2: + print( + f'WARNING!\nCannot create flow maps: Found {len(frames)} frames extracted from your video input.\nPlease check your video path.') + if len(frames) >= 2: + + raft_model = torch.nn.DataParallel(RAFT(args2)) + raft_model.load_state_dict(torch.load( + f'{S.root_path}/RAFT/models/raft-things.pth')) + raft_model = raft_model.module.cuda().eval() + + for f in pathlib.Path(f'{S.flo_fwd_folder}').glob('*.*'): + f.unlink() + + temp_flo = in_path+'/temp_flo' + flo_fwd_folder = in_path+'/out_flo_fwd' + + os.makedirs(flo_fwd_folder, exist_ok=True) + os.makedirs(temp_flo, exist_ok=True) + + # TBD Call out to a consistency checker? + + for frame1, frame2 in tqdm(zip(frames[:-1], frames[1:]), total=len(frames)-1): + + out_flow21_fn = f"{flo_fwd_folder}/{frame1.split('/')[-1]}" + + frame1 = load_img(frame1, S.width_height) + frame2 = load_img(frame2, S.width_height) + + flow21 = get_flow(frame2, frame1, raft_model) + np.save(out_flow21_fn, flow21) + + if S.video_init_check_consistency: + # TBD + pass + + del raft_model + gc.collect()