app.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import os
  2. import json
  3. import torch
  4. import random
  5. import gradio as gr
  6. from glob import glob
  7. from omegaconf import OmegaConf
  8. from datetime import datetime
  9. from safetensors import safe_open
  10. from diffusers import AutoencoderKL
  11. from diffusers import DDIMScheduler, EulerDiscreteScheduler, PNDMScheduler
  12. from diffusers.utils.import_utils import is_xformers_available
  13. from transformers import CLIPTextModel, CLIPTokenizer
  14. from animatediff.models.unet import UNet3DConditionModel
  15. from animatediff.pipelines.pipeline_animation import AnimationPipeline
  16. from animatediff.utils.util import save_videos_grid
  17. from animatediff.utils.convert_from_ckpt import convert_ldm_unet_checkpoint, convert_ldm_clip_checkpoint, convert_ldm_vae_checkpoint
  18. from animatediff.utils.convert_lora_safetensor_to_diffusers import convert_lora
  19. sample_idx = 0
  20. scheduler_dict = {
  21. "Euler": EulerDiscreteScheduler,
  22. "PNDM": PNDMScheduler,
  23. "DDIM": DDIMScheduler,
  24. }
  25. css = """
  26. .toolbutton {
  27. margin-buttom: 0em 0em 0em 0em;
  28. max-width: 2.5em;
  29. min-width: 2.5em !important;
  30. height: 2.5em;
  31. }
  32. """
  33. class AnimateController:
  34. def __init__(self):
  35. # config dirs
  36. self.basedir = os.getcwd()
  37. self.stable_diffusion_dir = os.path.join(self.basedir, "models", "StableDiffusion")
  38. self.motion_module_dir = os.path.join(self.basedir, "models", "Motion_Module")
  39. self.personalized_model_dir = os.path.join(self.basedir, "models", "DreamBooth_LoRA")
  40. self.savedir = os.path.join(self.basedir, "samples", datetime.now().strftime("Gradio-%Y-%m-%dT%H-%M-%S"))
  41. self.savedir_sample = os.path.join(self.savedir, "sample")
  42. os.makedirs(self.savedir, exist_ok=True)
  43. self.stable_diffusion_list = []
  44. self.motion_module_list = []
  45. self.personalized_model_list = []
  46. self.refresh_stable_diffusion()
  47. self.refresh_motion_module()
  48. self.refresh_personalized_model()
  49. # config models
  50. self.tokenizer = None
  51. self.text_encoder = None
  52. self.vae = None
  53. self.unet = None
  54. self.pipeline = None
  55. self.lora_model_state_dict = {}
  56. self.inference_config = OmegaConf.load("configs/inference/inference.yaml")
  57. def refresh_stable_diffusion(self):
  58. self.stable_diffusion_list = glob(os.path.join(self.stable_diffusion_dir, "*/"))
  59. def refresh_motion_module(self):
  60. motion_module_list = glob(os.path.join(self.motion_module_dir, "*.ckpt"))
  61. self.motion_module_list = [os.path.basename(p) for p in motion_module_list]
  62. def refresh_personalized_model(self):
  63. personalized_model_list = glob(os.path.join(self.personalized_model_dir, "*.safetensors"))
  64. self.personalized_model_list = [os.path.basename(p) for p in personalized_model_list]
  65. def update_stable_diffusion(self, stable_diffusion_dropdown):
  66. self.tokenizer = CLIPTokenizer.from_pretrained(stable_diffusion_dropdown, subfolder="tokenizer")
  67. self.text_encoder = CLIPTextModel.from_pretrained(stable_diffusion_dropdown, subfolder="text_encoder").cuda()
  68. self.vae = AutoencoderKL.from_pretrained(stable_diffusion_dropdown, subfolder="vae").cuda()
  69. self.unet = UNet3DConditionModel.from_pretrained_2d(stable_diffusion_dropdown, subfolder="unet", unet_additional_kwargs=OmegaConf.to_container(self.inference_config.unet_additional_kwargs)).cuda()
  70. return gr.Dropdown.update()
  71. def update_motion_module(self, motion_module_dropdown):
  72. if self.unet is None:
  73. gr.Info(f"Please select a pretrained model path.")
  74. return gr.Dropdown.update(value=None)
  75. else:
  76. motion_module_dropdown = os.path.join(self.motion_module_dir, motion_module_dropdown)
  77. motion_module_state_dict = torch.load(motion_module_dropdown, map_location="cpu")
  78. missing, unexpected = self.unet.load_state_dict(motion_module_state_dict, strict=False)
  79. assert len(unexpected) == 0
  80. return gr.Dropdown.update()
  81. def update_base_model(self, base_model_dropdown):
  82. if self.unet is None:
  83. gr.Info(f"Please select a pretrained model path.")
  84. return gr.Dropdown.update(value=None)
  85. else:
  86. base_model_dropdown = os.path.join(self.personalized_model_dir, base_model_dropdown)
  87. base_model_state_dict = {}
  88. with safe_open(base_model_dropdown, framework="pt", device="cpu") as f:
  89. for key in f.keys():
  90. base_model_state_dict[key] = f.get_tensor(key)
  91. converted_vae_checkpoint = convert_ldm_vae_checkpoint(base_model_state_dict, self.vae.config)
  92. self.vae.load_state_dict(converted_vae_checkpoint)
  93. converted_unet_checkpoint = convert_ldm_unet_checkpoint(base_model_state_dict, self.unet.config)
  94. self.unet.load_state_dict(converted_unet_checkpoint, strict=False)
  95. self.text_encoder = convert_ldm_clip_checkpoint(base_model_state_dict)
  96. return gr.Dropdown.update()
  97. def update_lora_model(self, lora_model_dropdown):
  98. lora_model_dropdown = os.path.join(self.personalized_model_dir, lora_model_dropdown)
  99. self.lora_model_state_dict = {}
  100. if lora_model_dropdown == "none": pass
  101. else:
  102. with safe_open(lora_model_dropdown, framework="pt", device="cpu") as f:
  103. for key in f.keys():
  104. self.lora_model_state_dict[key] = f.get_tensor(key)
  105. return gr.Dropdown.update()
  106. def animate(
  107. self,
  108. stable_diffusion_dropdown,
  109. motion_module_dropdown,
  110. base_model_dropdown,
  111. lora_alpha_slider,
  112. prompt_textbox,
  113. negative_prompt_textbox,
  114. sampler_dropdown,
  115. sample_step_slider,
  116. width_slider,
  117. length_slider,
  118. height_slider,
  119. cfg_scale_slider,
  120. seed_textbox
  121. ):
  122. if self.unet is None:
  123. raise gr.Error(f"Please select a pretrained model path.")
  124. if motion_module_dropdown == "":
  125. raise gr.Error(f"Please select a motion module.")
  126. if base_model_dropdown == "":
  127. raise gr.Error(f"Please select a base DreamBooth model.")
  128. if is_xformers_available(): self.unet.enable_xformers_memory_efficient_attention()
  129. pipeline = AnimationPipeline(
  130. vae=self.vae, text_encoder=self.text_encoder, tokenizer=self.tokenizer, unet=self.unet,
  131. scheduler=scheduler_dict[sampler_dropdown](**OmegaConf.to_container(self.inference_config.noise_scheduler_kwargs))
  132. ).to("cuda")
  133. if self.lora_model_state_dict != {}:
  134. pipeline = convert_lora(pipeline, self.lora_model_state_dict, alpha=lora_alpha_slider)
  135. pipeline.to("cuda")
  136. if seed_textbox != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox))
  137. else: torch.seed()
  138. seed = torch.initial_seed()
  139. sample = pipeline(
  140. prompt_textbox,
  141. negative_prompt = negative_prompt_textbox,
  142. num_inference_steps = sample_step_slider,
  143. guidance_scale = cfg_scale_slider,
  144. width = width_slider,
  145. height = height_slider,
  146. video_length = length_slider,
  147. ).videos
  148. save_sample_path = os.path.join(self.savedir_sample, f"{sample_idx}.mp4")
  149. save_videos_grid(sample, save_sample_path)
  150. sample_config = {
  151. "prompt": prompt_textbox,
  152. "n_prompt": negative_prompt_textbox,
  153. "sampler": sampler_dropdown,
  154. "num_inference_steps": sample_step_slider,
  155. "guidance_scale": cfg_scale_slider,
  156. "width": width_slider,
  157. "height": height_slider,
  158. "video_length": length_slider,
  159. "seed": seed
  160. }
  161. json_str = json.dumps(sample_config, indent=4)
  162. with open(os.path.join(self.savedir, "logs.json"), "a") as f:
  163. f.write(json_str)
  164. f.write("\n\n")
  165. return gr.Video.update(value=save_sample_path)
  166. controller = AnimateController()
  167. def ui():
  168. with gr.Blocks(css=css) as demo:
  169. gr.Markdown(
  170. """
  171. # [AnimateDiff: Animate Your Personalized Text-to-Image Diffusion Models without Specific Tuning](https://arxiv.org/abs/2307.04725)
  172. Yuwei Guo, Ceyuan Yang*, Anyi Rao, Yaohui Wang, Yu Qiao, Dahua Lin, Bo Dai (*Corresponding Author)<br>
  173. [Arxiv Report](https://arxiv.org/abs/2307.04725) | [Project Page](https://animatediff.github.io/) | [Github](https://github.com/guoyww/animatediff/)
  174. """
  175. )
  176. with gr.Column(variant="panel"):
  177. gr.Markdown(
  178. """
  179. ### 1. Model checkpoints (select pretrained model path first).
  180. """
  181. )
  182. with gr.Row():
  183. stable_diffusion_dropdown = gr.Dropdown(
  184. label="Pretrained Model Path",
  185. choices=controller.stable_diffusion_list,
  186. interactive=True,
  187. )
  188. stable_diffusion_dropdown.change(fn=controller.update_stable_diffusion, inputs=[stable_diffusion_dropdown], outputs=[stable_diffusion_dropdown])
  189. stable_diffusion_refresh_button = gr.Button(value="\U0001F503", elem_classes="toolbutton")
  190. def update_stable_diffusion():
  191. controller.refresh_stable_diffusion()
  192. return gr.Dropdown.update(choices=controller.stable_diffusion_list)
  193. stable_diffusion_refresh_button.click(fn=update_stable_diffusion, inputs=[], outputs=[stable_diffusion_dropdown])
  194. with gr.Row():
  195. motion_module_dropdown = gr.Dropdown(
  196. label="Select motion module",
  197. choices=controller.motion_module_list,
  198. interactive=True,
  199. )
  200. motion_module_dropdown.change(fn=controller.update_motion_module, inputs=[motion_module_dropdown], outputs=[motion_module_dropdown])
  201. motion_module_refresh_button = gr.Button(value="\U0001F503", elem_classes="toolbutton")
  202. def update_motion_module():
  203. controller.refresh_motion_module()
  204. return gr.Dropdown.update(choices=controller.motion_module_list)
  205. motion_module_refresh_button.click(fn=update_motion_module, inputs=[], outputs=[motion_module_dropdown])
  206. base_model_dropdown = gr.Dropdown(
  207. label="Select base Dreambooth model (required)",
  208. choices=controller.personalized_model_list,
  209. interactive=True,
  210. )
  211. base_model_dropdown.change(fn=controller.update_base_model, inputs=[base_model_dropdown], outputs=[base_model_dropdown])
  212. lora_model_dropdown = gr.Dropdown(
  213. label="Select LoRA model (optional)",
  214. choices=["none"] + controller.personalized_model_list,
  215. value="none",
  216. interactive=True,
  217. )
  218. lora_model_dropdown.change(fn=controller.update_lora_model, inputs=[lora_model_dropdown], outputs=[lora_model_dropdown])
  219. lora_alpha_slider = gr.Slider(label="LoRA alpha", value=0.8, minimum=0, maximum=2, interactive=True)
  220. personalized_refresh_button = gr.Button(value="\U0001F503", elem_classes="toolbutton")
  221. def update_personalized_model():
  222. controller.refresh_personalized_model()
  223. return [
  224. gr.Dropdown.update(choices=controller.personalized_model_list),
  225. gr.Dropdown.update(choices=["none"] + controller.personalized_model_list)
  226. ]
  227. personalized_refresh_button.click(fn=update_personalized_model, inputs=[], outputs=[base_model_dropdown, lora_model_dropdown])
  228. with gr.Column(variant="panel"):
  229. gr.Markdown(
  230. """
  231. ### 2. Configs for AnimateDiff.
  232. """
  233. )
  234. prompt_textbox = gr.Textbox(label="Prompt", lines=2)
  235. negative_prompt_textbox = gr.Textbox(label="Negative prompt", lines=2)
  236. with gr.Row().style(equal_height=False):
  237. with gr.Column():
  238. with gr.Row():
  239. sampler_dropdown = gr.Dropdown(label="Sampling method", choices=list(scheduler_dict.keys()), value=list(scheduler_dict.keys())[0])
  240. sample_step_slider = gr.Slider(label="Sampling steps", value=25, minimum=10, maximum=100, step=1)
  241. width_slider = gr.Slider(label="Width", value=512, minimum=256, maximum=1024, step=64)
  242. height_slider = gr.Slider(label="Height", value=512, minimum=256, maximum=1024, step=64)
  243. length_slider = gr.Slider(label="Animation length", value=16, minimum=8, maximum=24, step=1)
  244. cfg_scale_slider = gr.Slider(label="CFG Scale", value=7.5, minimum=0, maximum=20)
  245. with gr.Row():
  246. seed_textbox = gr.Textbox(label="Seed", value=-1)
  247. seed_button = gr.Button(value="\U0001F3B2", elem_classes="toolbutton")
  248. seed_button.click(fn=lambda: gr.Textbox.update(value=random.randint(1, 1e8)), inputs=[], outputs=[seed_textbox])
  249. generate_button = gr.Button(value="Generate", variant='primary')
  250. result_video = gr.Video(label="Generated Animation", interactive=False)
  251. generate_button.click(
  252. fn=controller.animate,
  253. inputs=[
  254. stable_diffusion_dropdown,
  255. motion_module_dropdown,
  256. base_model_dropdown,
  257. lora_alpha_slider,
  258. prompt_textbox,
  259. negative_prompt_textbox,
  260. sampler_dropdown,
  261. sample_step_slider,
  262. width_slider,
  263. length_slider,
  264. height_slider,
  265. cfg_scale_slider,
  266. seed_textbox,
  267. ],
  268. outputs=[result_video]
  269. )
  270. return demo
  271. if __name__ == "__main__":
  272. demo = ui()
  273. demo.launch(share=True)