import copy import json import os import os.path as osp import random from argparse import ArgumentParser from datetime import datetime import gradio as gr import moviepy.editor as mpy import numpy as np import torch from huggingface_hub import hf_hub_download from omegaconf import OmegaConf from PIL import Image, ImageDraw, ImageFont from animatediff.pipelines import I2VPipeline from animatediff.utils.util import RANGE_LIST, save_videos_grid sample_idx = 0 def convert_gif_to_mp4(gif_path, mp4_path): clip = mpy.VideoFileClip(gif_path) clip.write_videofile(mp4_path) def add_text(gif_file: str, mp4_file: str, text_index: int): image = Image.open(gif_file) frames = [] try: while True: frames.append(image.copy().convert('RGB')) image.seek(len(frames)) except EOFError: pass text = ['Happy New Year!', 'Happy New Year!', 'Happy New Year!', 'Happy New Year!'][text_index] size = [36, 36, 36, 36][text_index] for i, frame in enumerate(frames): font = ImageFont.truetype('zyhzx.ttf', size=size + i * 2) draw = ImageDraw.Draw(frame) text_width, text_height = draw.textsize(text, font=font) image_width, image_height = image.size x = (image_width - text_width) // 2 y = (image_height - text_height) - (image_height - text_height) // 8 draw.text((x, y), text, fill='red', font=font) frames[0].save(gif_file, save_all=True, append_images=frames[1:], loop=0) mp4_file = convert_gif_to_mp4(gif_file, mp4_file) return gif_file, mp4_file css = """ .toolbutton { margin-buttom: 0em 0em 0em 0em; max-width: 2.5em; min-width: 2.5em !important; height: 2.5em; } """ parser = ArgumentParser() parser.add_argument('--config', type=str, default='example/config/base.yaml') parser.add_argument('--server-name', type=str, default='0.0.0.0') parser.add_argument('--port', type=int, default=7860) parser.add_argument('--share', action='store_true') parser.add_argument('--local-debug', action='store_true') parser.add_argument('--save-path', default='samples') args = parser.parse_args() LOCAL_DEBUG = args.local_debug BASE_CONFIG = 'example/config/base.yaml' STYLE_CONFIG_LIST = { '3d_cartoon': './example/openxlab/3-3d.yaml', } # download models PIA_PATH = './models/PIA' VAE_PATH = './models/VAE' DreamBooth_LoRA_PATH = './models/DreamBooth_LoRA' def seed_everything(seed): import random import numpy as np torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed % (2**32)) random.seed(seed) if not LOCAL_DEBUG: CACHE_PATH = './models' PIA_PATH = osp.join(CACHE_PATH, 'PIA') VAE_PATH = osp.join(CACHE_PATH, 'VAE') DreamBooth_LoRA_PATH = osp.join(CACHE_PATH, 'DreamBooth_LoRA') STABLE_DIFFUSION_PATH = osp.join(CACHE_PATH, 'StableDiffusion') os.makedirs(PIA_PATH, exist_ok=True) os.makedirs(VAE_PATH, exist_ok=True) os.makedirs(DreamBooth_LoRA_PATH, exist_ok=True) os.makedirs(STABLE_DIFFUSION_PATH, exist_ok=True) PIA_PATH = hf_hub_download(repo_id='Leoxing/PIA', filename='pia.ckpt', cache_dir=PIA_PATH) PIA_PATH = '/'.join(PIA_PATH.split('/')[:-1]) os.system('bash download_bashscripts/2-RcnzCartoon.sh') print(os.listdir(DreamBooth_LoRA_PATH)) # unet unet_full_path = hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='unet', filename='diffusion_pytorch_model.bin', cache_dir='models/StableDiffusion') STABLE_DIFFUSION_PATH = '/'.join(unet_full_path.split('/')[:-2]) hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='unet', filename='config.json', cache_dir='models/StableDiffusion') # vae hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='vae', filename='config.json', cache_dir='models/StableDiffusion') hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='vae', filename='diffusion_pytorch_model.bin', cache_dir='models/StableDiffusion') # text encoder hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='text_encoder', filename='config.json', cache_dir='models/StableDiffusion') hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='text_encoder', filename='pytorch_model.bin', cache_dir='models/StableDiffusion') # tokenizer hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='tokenizer', filename='merges.txt', cache_dir='models/StableDiffusion') hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='tokenizer', filename='special_tokens_map.json', cache_dir='models/StableDiffusion') hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='tokenizer', filename='tokenizer_config.json', cache_dir='models/StableDiffusion') hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='tokenizer', filename='vocab.json', cache_dir='models/StableDiffusion') # scheduler hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', subfolder='scheduler', filename='scheduler_config.json', cache_dir='models/StableDiffusion') # model index hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', filename='model_index.json', cache_dir='models/StableDiffusion') else: PIA_PATH = './models/PIA' VAE_PATH = './models/VAE' DreamBooth_LoRA_PATH = './models/DreamBooth_LoRA' STABLE_DIFFUSION_PATH = './models/StableDiffusion/sd15' def preprocess_img(img_np, max_size: int = 512): ori_image = Image.fromarray(img_np).convert('RGB') width, height = ori_image.size short_edge = max(width, height) if short_edge > max_size: scale_factor = max_size / short_edge else: scale_factor = 1 width = int(width * scale_factor) height = int(height * scale_factor) ori_image = ori_image.resize((width, height)) if (width % 8 != 0) or (height % 8 != 0): in_width = (width // 8) * 8 in_height = (height // 8) * 8 else: in_width = width in_height = height in_image = ori_image in_image = ori_image.resize((in_width, in_height)) in_image_np = np.array(in_image) return in_image_np, in_height, in_width class AnimateController: def __init__(self): # config dirs self.basedir = os.getcwd() self.savedir = os.path.join( self.basedir, args.save_path, datetime.now().strftime("Gradio-%Y-%m-%dT%H-%M-%S")) self.savedir_sample = os.path.join(self.savedir, "sample") os.makedirs(self.savedir, exist_ok=True) self.inference_config = OmegaConf.load(args.config) self.style_configs = {k: OmegaConf.load( v) for k, v in STYLE_CONFIG_LIST.items()} self.pipeline_dict = self.load_model_list() def load_model_list(self): pipeline_dict = dict() for style, cfg in self.style_configs.items(): dreambooth_path = cfg.get('dreambooth', 'none') if dreambooth_path and dreambooth_path.upper() != 'NONE': dreambooth_path = osp.join( DreamBooth_LoRA_PATH, dreambooth_path) lora_path = cfg.get('lora', None) if lora_path is not None: lora_path = osp.join(DreamBooth_LoRA_PATH, lora_path) lora_alpha = cfg.get('lora_alpha', 0.0) vae_path = cfg.get('vae', None) if vae_path is not None: vae_path = osp.join(VAE_PATH, vae_path) pipeline_dict[style] = I2VPipeline.build_pipeline( self.inference_config, STABLE_DIFFUSION_PATH, unet_path=osp.join(PIA_PATH, 'pia.ckpt'), dreambooth_path=dreambooth_path, lora_path=lora_path, lora_alpha=lora_alpha, vae_path=vae_path, ip_adapter_path='h94/IP-Adapter', ip_adapter_scale=0.1) return pipeline_dict def fetch_default_n_prompt(self, style: str): cfg = self.style_configs[style] n_prompt = cfg.get('n_prompt', '') ip_adapter_scale = cfg.get('ip_adapter_scale', 0) gr.Info('Set default negative prompt and ip_adapter_scale.') print('Set default negative prompt and ip_adapter_scale.') return n_prompt, ip_adapter_scale def animate( self, init_img, motion_scale, prompt_textbox, negative_prompt_textbox, sample_step_slider, cfg_scale_slider, seed_textbox, ip_adapter_scale, style, example_img=None, with_text=False, text_idx=0, progress=gr.Progress(), ): global sample_idx if init_img is None: if example_img is None: gr.Warning('Please upload image or use example images.') else: gr.Info('Use exmaple image for fast try!') init_img = np.array(Image.open(example_img)) if seed_textbox != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox)) seed = int(seed_textbox) else: seed = torch.initial_seed() generator = torch.Generator(device='cuda') generator.manual_seed(seed) seed_everything(seed) print(f'Seed: {seed}') pipeline = self.pipeline_dict[style] init_img, h, w = preprocess_img(init_img) print(f'img size: {h, w}') sample = pipeline( image=init_img, prompt=prompt_textbox, negative_prompt=negative_prompt_textbox, generator=generator, num_inference_steps=sample_step_slider, guidance_scale=cfg_scale_slider, width=w, height=h, video_length=16, mask_sim_template_idx=motion_scale - 1, ip_adapter_scale=ip_adapter_scale, progress_fn=progress, ).videos save_sample_path_mp4 = os.path.join( self.savedir_sample, f"{sample_idx}.mp4") save_sample_path_gif = os.path.join( self.savedir_sample, f"{sample_idx}.gif") save_videos_grid(sample, save_sample_path_mp4) save_videos_grid(sample, save_sample_path_gif) sample_config = { "prompt": prompt_textbox, "n_prompt": negative_prompt_textbox, "num_inference_steps": sample_step_slider, "guidance_scale": cfg_scale_slider, "width": w, "height": h, "seed": seed, "motion": motion_scale, } print(sample_config) json_str = json.dumps(sample_config, indent=4) with open(os.path.join(self.savedir, "logs.json"), "a") as f: f.write(json_str) f.write("\n\n") if with_text: add_text(save_sample_path_gif, save_sample_path_mp4, text_idx) sample_idx += 1 # return (save_sample_path_mp4, # gr.update(link=f'file/{save_sample_path_mp4}'), # gr.update(link=f'file/{save_sample_path_gif}')) return (save_sample_path_mp4, [save_sample_path_mp4, save_sample_path_gif]) controller = AnimateController() def ui(): with gr.Blocks(css=css) as demo: # build state for default buttons example_img = gr.State( value='__assets__/image_animation/zhening/zhening.jpeg') default_motion = gr.State(value=1) default_prompt1 = gr.State( value='lift a red envelope, Chinese new year') default_prompt2 = gr.State( value='smiling, Chinese costume, Chinese new year') default_prompt3 = gr.State( value='angry, Chinese costume, Chinese new year') default_prompt4 = gr.State(value='sparklers, Chinese new year') default_n_prompt = gr.State(value='wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg') default_seed = gr.State(10201304011203481448) default_ip_adapter_scale = gr.State(0.2) default_style = gr.State('3d_cartoon') default_cfg = gr.State(7.5) default_1_idx = gr.State(0) default_2_idx = gr.State(1) default_3_idx = gr.State(2) default_4_idx = gr.State(3) gr.HTML( "