├── LICENSE ├── README.md ├── config └── inference │ └── dice_talk.yaml ├── demo.py ├── demo.sh ├── dice_talk.py ├── examples ├── emo │ ├── angry.npy │ ├── contempt.npy │ ├── disgusted.npy │ ├── fear.npy │ ├── happy.npy │ ├── neutral.npy │ ├── sad.npy │ └── surprised.npy ├── img │ ├── female.png │ ├── hg.jpeg │ ├── nazha.png │ └── pyy.jpg └── wav │ ├── female-zh.wav │ ├── female.wav │ ├── male-zh.wav │ └── male.wav ├── gradio_app.py ├── requirements.txt └── src ├── dataset └── test_preprocess.py ├── models ├── audio_adapter │ ├── audio_proj.py │ └── pose_guider.py ├── base │ ├── __init__.py │ ├── attention_processor.py │ ├── unet_3d_blocks.py │ └── unet_spatio_temporal_condition.py └── emotion_adapter │ └── emo.py ├── pipelines └── pipeline_dicetalk.py └── utils ├── RIFE ├── IFNet_HDv3.py ├── RIFE_HDv3.py └── warplayer.py ├── face_align ├── align.py └── yoloface.py └── util.py /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 4 | 5 | Using Creative Commons Public Licenses 6 | 7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | 9 | Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors 10 | 11 | Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public : wiki.creativecommons.org/Considerations_for_licensees 12 | 13 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License 14 | 15 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 16 | 17 | Section 1 – Definitions. 18 | 19 | a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 20 | b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 21 | c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. 22 | d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 23 | e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 24 | f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 25 | g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. 26 | h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 27 | i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 28 | j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. 29 | k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 30 | l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 31 | m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 32 | n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 33 | Section 2 – Scope. 34 | 35 | a. License grant. 36 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 37 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 38 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 39 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 40 | 3. Term. The term of this Public License is specified in Section 6(a). 41 | 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 42 | 5. Downstream recipients. 43 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 44 | B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. 45 | C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 46 | 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 47 | b. Other rights. 48 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 49 | 2. Patent and trademark rights are not licensed under this Public License. 50 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 51 | Section 3 – License Conditions. 52 | 53 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 54 | 55 | a. Attribution. 56 | 1. If You Share the Licensed Material (including in modified form), You must: 57 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 58 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 59 | ii. a copyright notice; 60 | iii. a notice that refers to this Public License; 61 | iv. a notice that refers to the disclaimer of warranties; 62 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 63 | 64 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 65 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 66 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 67 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 68 | b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 69 | 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. 70 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 71 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 72 | Section 4 – Sui Generis Database Rights. 73 | 74 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 75 | 76 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 77 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 78 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 79 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 80 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 81 | 82 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 83 | b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 84 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 85 | Section 6 – Term and Termination. 86 | 87 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 88 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 89 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 90 | 2. upon express reinstatement by the Licensor. 91 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 92 | 93 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 94 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 95 | Section 7 – Other Terms and Conditions. 96 | 97 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 98 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 99 | Section 8 – Interpretation. 100 | 101 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 102 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 103 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 104 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 105 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 106 | 107 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DICE-Talk 2 | Disentangle Identity, Cooperate Emotion: Correlation-Aware Emotional Talking Portrait Generation. 3 | 4 | 5 | 6 | 7 | 8 | License 9 | 10 | 11 | 12 | 13 | 14 | ## 🔥🔥🔥 NEWS 15 | 16 | **`2025/04/29`**: We released the initial version of the inference code and models. Stay tuned for continuous updates! 17 | 18 | 19 | 20 | ## 🎥 Demo 21 | | Input | Neutral | Happy | Angry | Surprised 22 | |----------------------|-----------------------|----------------------|-----------------------|-----------------------| 23 | |||||| 24 | |||||| 25 | 26 | 27 | 28 | 29 | For more visual demos, please visit our [**Page**](https://toto222.github.io/DICE-Talk/). 30 | 31 | 32 | 33 | ## 📜 Requirements 34 | * It is recommended to use a GPU with `20GB` or more VRAM and have an independent `Python 3.10`. 35 | * Tested operating system: `Linux` 36 | 37 | ## 🔑 Inference 38 | 39 | ### Installtion 40 | - `ffmpeg` requires to be installed. 41 | - `PyTorch`: make sure to select the appropriate CUDA version based on your hardware, for example, 42 | ```shell 43 | pip install torch==2.2.2 torchvision==0.17.2 torchaudio==2.2.2 --index-url https://download.pytorch.org/whl/cu118 44 | ``` 45 | - `Dependencies`: 46 | ```shell 47 | pip install -r requirements.txt 48 | ``` 49 | - All models are stored in `checkpoints` by default, and the file structure is as follows: 50 | ```shell 51 | DICE-Talk 52 | ├──checkpoints 53 | │ ├──DICE-Talk 54 | │ │ ├──audio_linear.pth 55 | │ │ ├──emo_model.pth 56 | │ │ ├──pose_guider.pth 57 | │ │ ├──unet.pth 58 | │ ├──stable-video-diffusion-img2vid-xt 59 | │ │ ├──... 60 | │ ├──whisper-tiny 61 | │ │ ├──... 62 | │ ├──RIFE 63 | │ │ ├──flownet.pkl 64 | │ ├──yoloface_v5m.pt 65 | ├──... 66 | ``` 67 | Download by `huggingface-cli` follow 68 | ```shell 69 | python3 -m pip install "huggingface_hub[cli]" 70 | 71 | huggingface-cli download EEEELY/DICE-Talk --local-dir checkpoints 72 | huggingface-cli download stabilityai/stable-video-diffusion-img2vid-xt --local-dir checkpoints/stable-video-diffusion-img2vid-xt 73 | huggingface-cli download openai/whisper-tiny --local-dir checkpoints/whisper-tiny 74 | ``` 75 | 76 | or manully download [pretrain model](https://drive.google.com/drive/folders/1l1Ojt-4yMfYQCCnNs_NgkzQC2-OoAksN?usp=drive_link), [svd-xt](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt) and [whisper-tiny](https://huggingface.co/openai/whisper-tiny) to `checkpoints/`. 77 | 78 | 79 | ### Run demo 80 | ```shell 81 | python3 demo.py --image_path '/path/to/input_image' --audio_path '/path/to/input_audio'\ 82 | --emotion_path '/path/to/input_emotion' --output_path '/path/to/output_video' 83 | ``` 84 | 85 | ### Run GUI 86 | ```shell 87 | python3 gradio_app.py 88 | ``` 89 | 90 | gradio_demo 91 | 92 | 93 | 94 | On the left you need to: 95 | * Upload an image or take a photo 96 | * Upload or record an audio clip 97 | * Select the type of emotion to generate 98 | * Set the strength for identity preservation and emotion generation 99 | * Choose whether to crop the input image 100 | 101 | On the right are the generated videos. 102 | 103 | 104 | ## 🔗 Citation 105 | 106 | If you find our work helpful for your research, please consider citing our work. 107 | 108 | ```bibtex 109 | @article{tan2025dicetalk, 110 | title={Disentangle Identity, Cooperate Emotion: Correlation-Aware Emotional Talking Portrait Generation}, 111 | author={Tan, Weipeng and Lin, Chuming and Xu, Chengming and Xu, FeiFan and Hu, Xiaobin and Ji, Xiaozhong and Zhu, Junwei and Wang, Chengjie and Fu, Yanwei}, 112 | journal={arXiv preprint arXiv:2504.18087}, 113 | year={2025} 114 | } 115 | 116 | @article{ji2024sonic, 117 | title={Sonic: Shifting Focus to Global Audio Perception in Portrait Animation}, 118 | author={Ji, Xiaozhong and Hu, Xiaobin and Xu, Zhihong and Zhu, Junwei and Lin, Chuming and He, Qingdong and Zhang, Jiangning and Luo, Donghao and Chen, Yi and Lin, Qin and others}, 119 | journal={arXiv preprint arXiv:2411.16331}, 120 | year={2024} 121 | } 122 | 123 | @article{ji2024realtalk, 124 | title={Realtalk: Real-time and realistic audio-driven face generation with 3d facial prior-guided identity alignment network}, 125 | author={Ji, Xiaozhong and Lin, Chuming and Ding, Zhonggan and Tai, Ying and Zhu, Junwei and Hu, Xiaobin and Luo, Donghao and Ge, Yanhao and Wang, Chengjie}, 126 | journal={arXiv preprint arXiv:2406.18284}, 127 | year={2024} 128 | } 129 | ``` 130 | -------------------------------------------------------------------------------- /config/inference/dice_talk.yaml: -------------------------------------------------------------------------------- 1 | pretrained_model_name_or_path: "checkpoints/stable-video-diffusion-img2vid-xt" 2 | unet_checkpoint_path: "checkpoints/DICE-Talk/unet.pth" 3 | pose_guider_checkpoint_path: "checkpoints/DICE-Talk/pose_guider.pth" 4 | audio_linear_checkpoint_path: "checkpoints/DICE-Talk/audio_linear.pth" 5 | emo_model_checkpoint_path: "checkpoints/DICE-Talk/emo_model.pth" 6 | 7 | weight_dtype: 'fp16' # [fp16, fp32] 8 | 9 | num_inference_steps: 25 10 | n_sample_frames: 25 11 | fps: 12.5 12 | decode_chunk_size: 10 13 | motion_bucket_id: 8 14 | motion_bucket_id_exp: 16 15 | image_size: 512 16 | area: 1.1 17 | frame_num: 10000 18 | step: 2 19 | overlap: 0 20 | shift_offset: 7 21 | min_appearance_guidance_scale: 3.0 22 | max_appearance_guidance_scale: 3.0 23 | audio_guidance_scale: 6.0 24 | i2i_noise_strength: 1.0 25 | ip_audio_scale: 1.0 26 | ip_emo_scale: 1.0 27 | noise_aug_strength: 0.00 28 | retrieval: False 29 | 30 | use_interframe: True 31 | 32 | seed: 72589 33 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | from dice_talk import DICE_Talk 4 | pipe = DICE_Talk(0) 5 | 6 | 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument('--image_path') 9 | parser.add_argument('--audio_path') 10 | parser.add_argument('--emotion_path') 11 | parser.add_argument('--output_path') 12 | parser.add_argument('--ref_scale', type=float, default=3.0) 13 | parser.add_argument('--emo_scale', type=float, default=6.0) 14 | parser.add_argument('--crop', action='store_true') 15 | parser.add_argument('--seed', type=int, default=None) 16 | 17 | args = parser.parse_args() 18 | 19 | 20 | face_info = pipe.preprocess(args.image_path, expand_ratio=0.5) 21 | print(face_info) 22 | if face_info['face_num'] >= 0: 23 | if args.crop: 24 | crop_image_path = args.image_path + '.crop.png' 25 | pipe.crop_image(args.image_path, crop_image_path, face_info['crop_bbox']) 26 | args.image_path = crop_image_path 27 | os.makedirs(os.path.dirname(args.output_path), exist_ok=True) 28 | pipe.process(args.image_path, args.audio_path, args.emotion_path, args.output_path, min_resolution=512, inference_steps=25, ref_scale=args.ref_scale, emo_scale=args.emo_scale, seed=args.seed) -------------------------------------------------------------------------------- /demo.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | image_path=examples/img/female.png 4 | audio_path=examples/wav/female.wav 5 | emotion_path=examples/emo/happy.npy 6 | output_path=results/output.mp4 7 | 8 | python3 demo.py --image_path $image_path --audio_path $audio_path --emotion_path $emotion_path --output_path $output_path -------------------------------------------------------------------------------- /dice_talk.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import torch.utils.checkpoint 4 | from PIL import Image 5 | import numpy as np 6 | from omegaconf import OmegaConf 7 | from tqdm import tqdm 8 | import cv2 9 | 10 | from diffusers import AutoencoderKLTemporalDecoder 11 | from diffusers.schedulers import EulerDiscreteScheduler 12 | from transformers import WhisperModel, CLIPVisionModelWithProjection, AutoFeatureExtractor 13 | 14 | from src.utils.util import save_videos_grid, seed_everything 15 | from src.dataset.test_preprocess import process_bbox, image_audio_emo_to_tensor 16 | from src.models.base.unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel, add_ip_adapters 17 | from src.models.audio_adapter.pose_guider import PoseGuider 18 | from src.pipelines.pipeline_dicetalk import DicePipeline 19 | from src.models.audio_adapter.audio_proj import AudioProjModel 20 | from src.utils.RIFE.RIFE_HDv3 import RIFEModel 21 | from src.utils.face_align.align import AlignImage 22 | from src.models.emotion_adapter.emo import EmotionModel 23 | 24 | 25 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 26 | 27 | def test( 28 | pipe, 29 | config, 30 | wav_enc, 31 | audio_pe, 32 | emo_pe, 33 | width, 34 | height, 35 | batch=None, 36 | ): 37 | for k, v in batch.items(): 38 | if isinstance(v, torch.Tensor): 39 | batch[k] = v.unsqueeze(0).to(device="cuda").float() 40 | print(batch[k].shape) 41 | ref_img = batch['ref_img'] 42 | clip_img = batch['clip_images'] 43 | 44 | 45 | audio_feature = batch['audio_feature'] 46 | audio_len = batch['audio_len'] 47 | emo_prior = batch['emo_feature'] 48 | 49 | retrieval = config.retrieval 50 | step = int(config.step) 51 | 52 | window = 3000 53 | audio_prompts = [] 54 | for i in range(0, audio_feature.shape[-1], window): 55 | audio_prompt = wav_enc.encoder(audio_feature[:,:,i:i+window], output_hidden_states=True).hidden_states 56 | audio_prompt = torch.stack(audio_prompt, dim=2) 57 | audio_prompts.append(audio_prompt) 58 | audio_prompts = torch.cat(audio_prompts, dim=1) 59 | audio_prompts = audio_prompts[:,:audio_len*2] 60 | 61 | 62 | audio_prompts = torch.cat([torch.zeros_like(audio_prompts[:,:4]), audio_prompts, torch.zeros_like(audio_prompts[:,:6])], 1) 63 | 64 | 65 | pose_tensor_list = [] 66 | ref_tensor_list = [] 67 | audio_tensor_list = [] 68 | uncond_audio_tensor_list = [] 69 | emotion_tensor_list = [] 70 | uncond_emotion_tensor_list = [] 71 | 72 | 73 | 74 | 75 | 76 | 77 | for i in tqdm(range(audio_len//step)): 78 | 79 | pixel_values_pose = batch["face_mask"] 80 | 81 | audio_clip = audio_prompts[:,i*2*step:i*2*step+10].unsqueeze(0) 82 | cond_audio_clip = audio_pe(audio_clip).squeeze(0) 83 | uncond_audio_clip = audio_pe(torch.zeros_like(audio_clip)).squeeze(0) 84 | 85 | 86 | new_emo_hidden_states = emo_pe(emo_prior, retrieval=retrieval)[0].squeeze(0) 87 | new_uncond_emo_hidden_states = emo_pe(torch.zeros_like(emo_prior), retrieval=retrieval)[0].squeeze(0) 88 | 89 | 90 | pose_tensor_list.append(pixel_values_pose[0]) 91 | ref_tensor_list.append(ref_img[0]) 92 | audio_tensor_list.append(cond_audio_clip[0]) 93 | uncond_audio_tensor_list.append(uncond_audio_clip[0]) 94 | 95 | emotion_tensor_list.append(new_emo_hidden_states[0]) 96 | uncond_emotion_tensor_list.append(new_uncond_emo_hidden_states[0]) 97 | 98 | 99 | video = pipe( 100 | ref_img, 101 | clip_img, 102 | pose_tensor_list, 103 | audio_tensor_list, 104 | uncond_audio_tensor_list, 105 | emotion_tensor_list, 106 | uncond_emotion_tensor_list, 107 | height=height, 108 | width=width, 109 | num_frames=len(pose_tensor_list), 110 | decode_chunk_size=config.decode_chunk_size, 111 | motion_bucket_id=config.motion_bucket_id, 112 | motion_bucket_id_exp=config.motion_bucket_id_exp, 113 | fps=config.fps, 114 | noise_aug_strength=config.noise_aug_strength, 115 | min_guidance_scale1=config.min_appearance_guidance_scale, # 1.0, 116 | max_guidance_scale1=config.max_appearance_guidance_scale, 117 | min_guidance_scale2=config.audio_guidance_scale, # 1.0, 118 | max_guidance_scale2=config.audio_guidance_scale, 119 | overlap=config.overlap, 120 | shift_offset=config.shift_offset, 121 | frames_per_batch=config.n_sample_frames, 122 | num_inference_steps=config.num_inference_steps, 123 | i2i_noise_strength=config.i2i_noise_strength, 124 | ).frames 125 | 126 | # Concat it with pose tensor 127 | # pose_tensor = torch.stack(pose_tensor_list,1).unsqueeze(0) 128 | video = (video*0.5 + 0.5).clamp(0, 1) 129 | video = torch.cat([video.to(device="cuda")], dim=0).cpu() 130 | 131 | return video 132 | 133 | 134 | class DICE_Talk(): 135 | config_file = os.path.join(BASE_DIR, 'config/inference/dice_talk.yaml') 136 | config = OmegaConf.load(config_file) 137 | 138 | def __init__(self, 139 | device_id=0, 140 | enable_interpolate_frame=True, 141 | ): 142 | 143 | config = self.config 144 | config.use_interframe = enable_interpolate_frame 145 | 146 | device = 'cuda:{}'.format(device_id) if device_id > -1 else 'cpu' 147 | 148 | config.pretrained_model_name_or_path = os.path.join(BASE_DIR, config.pretrained_model_name_or_path) 149 | 150 | vae = AutoencoderKLTemporalDecoder.from_pretrained( 151 | config.pretrained_model_name_or_path, 152 | subfolder="vae", 153 | variant="fp16") 154 | 155 | val_noise_scheduler = EulerDiscreteScheduler.from_pretrained( 156 | config.pretrained_model_name_or_path, 157 | subfolder="scheduler") 158 | 159 | image_encoder = CLIPVisionModelWithProjection.from_pretrained( 160 | config.pretrained_model_name_or_path, 161 | subfolder="image_encoder", 162 | variant="fp16") 163 | unet = UNetSpatioTemporalConditionModel.from_pretrained( 164 | config.pretrained_model_name_or_path, 165 | subfolder="unet", 166 | variant="fp16") 167 | adapter_modules = add_ip_adapters(unet, [32, 32], [config.ip_audio_scale, config.ip_emo_scale]) 168 | pose_guider = PoseGuider( 169 | conditioning_embedding_channels=320, 170 | block_out_channels=(16, 32, 96, 256) 171 | ).to(device) 172 | audio_linear = AudioProjModel(seq_len=10, blocks=5, channels=384, intermediate_dim=1024, output_dim=1024, context_tokens=32).to(device) 173 | emo_model = EmotionModel().to(device) 174 | 175 | pose_guider_checkpoint_path = os.path.join(BASE_DIR, config.pose_guider_checkpoint_path) 176 | unet_checkpoint_path = os.path.join(BASE_DIR, config.unet_checkpoint_path) 177 | audio_linear_checkpoint_path = os.path.join(BASE_DIR, config.audio_linear_checkpoint_path) 178 | emo_model_checkpoint_path = os.path.join(BASE_DIR, config.emo_model_checkpoint_path) 179 | 180 | pose_guider.load_state_dict( 181 | torch.load(pose_guider_checkpoint_path, map_location="cpu"), 182 | strict=True, 183 | ) 184 | 185 | 186 | unet.load_state_dict( 187 | torch.load(unet_checkpoint_path, map_location="cpu"), 188 | strict=False, 189 | ) 190 | 191 | audio_linear.load_state_dict( 192 | torch.load(audio_linear_checkpoint_path, map_location="cpu"), 193 | strict=True, 194 | ) 195 | 196 | emo_model.load_state_dict( 197 | torch.load(emo_model_checkpoint_path, map_location="cpu"), 198 | strict=False, 199 | ) 200 | 201 | 202 | if config.weight_dtype == "fp16": 203 | weight_dtype = torch.float16 204 | elif config.weight_dtype == "fp32": 205 | weight_dtype = torch.float32 206 | elif config.weight_dtype == "bf16": 207 | weight_dtype = torch.bfloat16 208 | else: 209 | raise ValueError( 210 | f"Do not support weight dtype: {config.weight_dtype} during training" 211 | ) 212 | 213 | whisper = WhisperModel.from_pretrained(os.path.join(BASE_DIR, 'checkpoints/whisper-tiny/')).to(device).eval() 214 | 215 | whisper.requires_grad_(False) 216 | 217 | self.feature_extractor = AutoFeatureExtractor.from_pretrained(os.path.join(BASE_DIR, 'checkpoints/whisper-tiny/')) 218 | 219 | det_path = os.path.join(BASE_DIR, 'checkpoints/yoloface_v5m.pt') 220 | 221 | self.face_det = AlignImage(device, det_path=det_path) 222 | if config.use_interframe: 223 | rife = RIFEModel(device=device) 224 | rife.load_model(os.path.join(BASE_DIR, 'checkpoints', 'RIFE/')) 225 | self.rife = rife 226 | 227 | 228 | image_encoder.to(weight_dtype) 229 | vae.to(weight_dtype) 230 | unet.to(weight_dtype) 231 | 232 | pipe = DicePipeline( 233 | unet=unet, 234 | image_encoder=image_encoder, 235 | vae=vae, 236 | pose_guider=pose_guider, 237 | scheduler=val_noise_scheduler, 238 | ) 239 | pipe = pipe.to(device=device, dtype=weight_dtype) 240 | 241 | 242 | self.pipe = pipe 243 | self.whisper = whisper 244 | self.audio_linear = audio_linear 245 | self.emo_model = emo_model 246 | self.image_encoder = image_encoder 247 | self.device = device 248 | 249 | print('init done') 250 | 251 | 252 | def preprocess(self, 253 | image_path, expand_ratio=1.0): 254 | face_image = cv2.imread(image_path) 255 | h, w = face_image.shape[:2] 256 | _, _, bboxes = self.face_det(face_image, maxface=True) 257 | face_num = len(bboxes) 258 | bbox = [] 259 | if face_num > 0: 260 | x1, y1, ww, hh = bboxes[0] 261 | x2, y2 = x1 + ww, y1 + hh 262 | bbox = x1, y1, x2, y2 263 | bbox_s = process_bbox(bbox, expand_radio=expand_ratio, height=h, width=w) 264 | 265 | return { 266 | 'face_num': face_num, 267 | 'crop_bbox': bbox_s, 268 | } 269 | 270 | def crop_image(self, 271 | input_image_path, 272 | output_image_path, 273 | crop_bbox): 274 | face_image = cv2.imread(input_image_path) 275 | crop_image = face_image[crop_bbox[1]:crop_bbox[3], crop_bbox[0]:crop_bbox[2]] 276 | cv2.imwrite(output_image_path, crop_image) 277 | 278 | @torch.no_grad() 279 | def process(self, 280 | image_path, 281 | audio_path, 282 | emotion_path, 283 | output_path, 284 | min_resolution=512, 285 | inference_steps=25, 286 | ref_scale=None, 287 | emo_scale=None, 288 | keep_resolution=False, 289 | seed=None): 290 | 291 | config = self.config 292 | device = self.device 293 | pipe = self.pipe 294 | whisper = self.whisper 295 | audio_linear = self.audio_linear 296 | emo_model = self.emo_model 297 | image_encoder = self.image_encoder 298 | 299 | # specific parameters 300 | if seed: 301 | config.seed = seed 302 | 303 | config.num_inference_steps = inference_steps 304 | 305 | if ref_scale is not None: 306 | config.min_appearance_guidance_scale = ref_scale 307 | config.max_appearance_guidance_scale = ref_scale 308 | if emo_scale is not None: 309 | config.audio_guidance_scale = emo_scale 310 | 311 | 312 | seed_everything(config.seed) 313 | 314 | video_path = output_path.replace('.mp4', '_noaudio.mp4') 315 | audio_video_path = output_path 316 | 317 | imSrc_ = Image.open(image_path).convert('RGB') 318 | raw_w, raw_h = imSrc_.size 319 | 320 | test_data = image_audio_emo_to_tensor(self.face_det, self.feature_extractor, image_path, audio_path, emotion_path, limit=config.frame_num, image_size=min_resolution, area=config.area) 321 | if test_data is None: 322 | return -1 323 | height, width = test_data['ref_img'].shape[-2:] 324 | if keep_resolution: 325 | resolution = f'{raw_w//2*2}x{raw_h//2*2}' 326 | else: 327 | resolution = f'{width}x{height}' 328 | 329 | 330 | video = test( 331 | pipe, 332 | config, 333 | wav_enc=whisper, 334 | audio_pe=audio_linear, 335 | emo_pe=emo_model, 336 | width=width, 337 | height=height, 338 | batch=test_data, 339 | ) 340 | 341 | if config.use_interframe: 342 | rife = self.rife 343 | out = video.to(device) 344 | results = [] 345 | video_len = out.shape[2] 346 | for idx in tqdm(range(video_len-1), ncols=0): 347 | I1 = out[:, :, idx] 348 | I2 = out[:, :, idx+1] 349 | middle = rife.inference(I1, I2).clamp(0, 1).detach() 350 | results.append(out[:, :, idx]) 351 | results.append(middle) 352 | results.append(out[:, :, video_len-1]) 353 | video = torch.stack(results, 2).cpu() 354 | 355 | save_videos_grid(video, video_path, n_rows=video.shape[0], fps=config.fps * 2 if config.use_interframe else config.fps) 356 | ffmpeg_command = f'ffmpeg -i "{video_path}" -i "{audio_path}" -s {resolution} -vcodec libx264 -acodec aac -crf 18 -shortest -y "{audio_video_path}"' 357 | os.system(ffmpeg_command) 358 | os.remove(video_path) # Use os.remove instead of rm for Windows compatibility 359 | 360 | return 0 361 | -------------------------------------------------------------------------------- /examples/emo/angry.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/angry.npy -------------------------------------------------------------------------------- /examples/emo/contempt.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/contempt.npy -------------------------------------------------------------------------------- /examples/emo/disgusted.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/disgusted.npy -------------------------------------------------------------------------------- /examples/emo/fear.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/fear.npy -------------------------------------------------------------------------------- /examples/emo/happy.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/happy.npy -------------------------------------------------------------------------------- /examples/emo/neutral.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/neutral.npy -------------------------------------------------------------------------------- /examples/emo/sad.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/sad.npy -------------------------------------------------------------------------------- /examples/emo/surprised.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/emo/surprised.npy -------------------------------------------------------------------------------- /examples/img/female.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/img/female.png -------------------------------------------------------------------------------- /examples/img/hg.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/img/hg.jpeg -------------------------------------------------------------------------------- /examples/img/nazha.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/img/nazha.png -------------------------------------------------------------------------------- /examples/img/pyy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/img/pyy.jpg -------------------------------------------------------------------------------- /examples/wav/female-zh.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/wav/female-zh.wav -------------------------------------------------------------------------------- /examples/wav/female.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/wav/female.wav -------------------------------------------------------------------------------- /examples/wav/male-zh.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/wav/male-zh.wav -------------------------------------------------------------------------------- /examples/wav/male.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/examples/wav/male.wav -------------------------------------------------------------------------------- /gradio_app.py: -------------------------------------------------------------------------------- 1 | import gradio as gr 2 | import os 3 | import numpy as np 4 | from pydub import AudioSegment 5 | import hashlib 6 | from dice_talk import DICE_Talk 7 | import shutil 8 | 9 | pipe = DICE_Talk(0) 10 | 11 | 12 | def get_md5(content): 13 | md5hash = hashlib.md5(content) 14 | md5 = md5hash.hexdigest() 15 | return md5 16 | 17 | def get_video_res(img_path, audio_path, emotion_path, res_video_path, ref_scale=None, emo_scale=None, crop=False): 18 | 19 | expand_ratio = 0.5 20 | min_resolution = 512 21 | inference_steps = 25 22 | 23 | face_info = pipe.preprocess(img_path, expand_ratio=expand_ratio) 24 | print(face_info) 25 | if face_info['face_num'] > 0: 26 | if crop: 27 | crop_image_path = img_path + '.crop.png' 28 | pipe.crop_image(img_path, crop_image_path, face_info['crop_bbox']) 29 | img_path = crop_image_path 30 | os.makedirs(os.path.dirname(res_video_path), exist_ok=True) 31 | pipe.process(img_path, audio_path, emotion_path, res_video_path, min_resolution=min_resolution, inference_steps=inference_steps, ref_scale=ref_scale, emo_scale=emo_scale) 32 | else: 33 | return -1 34 | tmp_path = './tmp_path/' 35 | res_path = './res_path/' 36 | os.makedirs(tmp_path,exist_ok=1) 37 | os.makedirs(res_path,exist_ok=1) 38 | 39 | def process_dice(image,audio, emotion, s0, s1, crop=False): 40 | img_md5= get_md5(np.array(image)) 41 | audio_md5 = get_md5(audio[1]) 42 | 43 | print(img_md5,audio_md5) 44 | sampling_rate, arr = audio[:2] 45 | if len(arr.shape)==1: 46 | arr = arr[:,None] 47 | audio = AudioSegment( 48 | arr.tobytes(), 49 | frame_rate=sampling_rate, 50 | sample_width=arr.dtype.itemsize, 51 | channels=arr.shape[1] 52 | ) 53 | audio = audio.set_frame_rate(sampling_rate) 54 | image_path = os.path.abspath(tmp_path+'{0}.png'.format(img_md5)) 55 | audio_path = os.path.abspath(tmp_path+'{0}.wav'.format(audio_md5)) 56 | emotion_path = os.path.abspath(tmp_path+'{0}.npy'.format(emotion)) 57 | if not os.path.exists(image_path): 58 | image.save(image_path) 59 | if not os.path.exists(audio_path): 60 | audio.export(audio_path, format="wav") 61 | if not os.path.exists(emotion_path): 62 | shutil.copy(f'examples/emo/{emotion}.npy', emotion_path) 63 | res_video_path = os.path.abspath(res_path+f'{img_md5}_{audio_md5}_{emotion}_{s0}_{s1}_{int(crop)}.mp4') 64 | if os.path.exists(res_video_path): 65 | return res_video_path 66 | else: 67 | get_video_res(image_path, audio_path, emotion_path, res_video_path, s0, s1, crop=crop) 68 | return res_video_path 69 | 70 | inputs = [ 71 | gr.Image(type='pil',label="Upload Image"), 72 | gr.Audio(label="Upload Audio"), 73 | gr.Dropdown( 74 | choices=['contempt', 'sad', 'happy', 'surprised', 'angry', 'disgusted', 'fear', 'neutral'], 75 | label="Choose Emotion" 76 | ), 77 | gr.Slider(0.0, 10.0, value=3.0, step=0.1, label="Reference", info="Increase/decrease to obtain stronger/weaker identity preservation"), 78 | gr.Slider(0.0, 10.0, value=6.0, step=0.1, label="Emotion", info="Increase/decrease to obtain stronger/weaker emotions"), 79 | gr.Checkbox(label="Crop image", value=False) 80 | ] 81 | outputs = gr.Video(label="output.mp4") 82 | 83 | 84 | html_description = """ 85 |
86 | 87 | GitHub 88 | 89 | 90 | arxiv 91 | 92 | 93 | webpage 94 | 95 | 96 | License 97 | 98 |
99 | 100 | The demo can only be used for Non-commercial Use. 101 |
If you like our work, please star DICE-Talk. 102 | """ 103 | 104 | def get_example(): 105 | return [ 106 | ["examples/img/nazha.png", "examples/wav/female-zh.wav", "happy", 3.0, 6.0], 107 | ["examples/img/pyy.jpg", "examples/wav/male-zh.wav", "neutral", 4.0, 7.5], 108 | ["examples/img/female.png", "examples/wav/female.wav","happy", 3.0, 6.0], 109 | ["examples/img/hg.jpeg", "examples/wav/male.wav", "surprised", 3.0, 6.0], 110 | 111 | ] 112 | 113 | with gr.Blocks(title="DICE-Talk") as demo: 114 | gr.Interface(fn=process_dice, inputs=inputs, outputs=outputs, title="Disentangle Identity, Cooperate Emotion: Correlation-Aware\ 115 | Emotional Talking Portrait Generation", description=html_description) 116 | gr.Examples( 117 | examples=get_example(), 118 | fn=process_dice, 119 | inputs=inputs, 120 | outputs=outputs, 121 | cache_examples=False,) 122 | 123 | demo.queue() 124 | demo.launch(server_name='0.0.0.0', server_port=8081, share=False) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate==0.28.0 2 | av==11.0.0 3 | diffusers==0.29.0 4 | einops==0.7.0 5 | pydantic==2.10.6 6 | gradio==4.44.1 7 | imageio==2.31.1 8 | imageio-ffmpeg==0.5.1 9 | librosa==0.10.2.post1 10 | numpy==1.26.4 11 | omegaconf==2.3.0 12 | opencv-python==4.8.1.78 13 | sk-video==1.1.10 14 | tqdm==4.65.2 15 | transformers==4.43.2 16 | -------------------------------------------------------------------------------- /src/dataset/test_preprocess.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | from PIL import Image 4 | import torch 5 | import torchvision.transforms as transforms 6 | from transformers import CLIPImageProcessor 7 | import librosa 8 | 9 | 10 | def process_bbox(bbox, expand_radio, height, width): 11 | """ 12 | raw_vid_path: 13 | bbox: format: x1, y1, x2, y2 14 | radio: expand radio against bbox size 15 | height,width: source image height and width 16 | """ 17 | 18 | def expand(bbox, ratio, height, width): 19 | 20 | bbox_h = bbox[3] - bbox[1] 21 | bbox_w = bbox[2] - bbox[0] 22 | 23 | expand_x1 = max(bbox[0] - ratio * bbox_w, 0) 24 | expand_y1 = max(bbox[1] - ratio * bbox_h, 0) 25 | expand_x2 = min(bbox[2] + ratio * bbox_w, width) 26 | expand_y2 = min(bbox[3] + ratio * bbox_h, height) 27 | 28 | return [expand_x1,expand_y1,expand_x2,expand_y2] 29 | 30 | def to_square(bbox_src, bbox_expend, height, width): 31 | 32 | h = bbox_expend[3] - bbox_expend[1] 33 | w = bbox_expend[2] - bbox_expend[0] 34 | c_h = (bbox_expend[1] + bbox_expend[3]) / 2 35 | c_w = (bbox_expend[0] + bbox_expend[2]) / 2 36 | 37 | c = min(h, w) / 2 38 | 39 | c_src_h = (bbox_src[1] + bbox_src[3]) / 2 40 | c_src_w = (bbox_src[0] + bbox_src[2]) / 2 41 | 42 | s_h, s_w = 0, 0 43 | if w < h: 44 | d = abs((h - w) / 2) 45 | s_h = min(d, abs(c_src_h-c_h)) 46 | s_h = s_h if c_src_h > c_h else s_h * (-1) 47 | else: 48 | d = abs((h - w) / 2) 49 | s_w = min(d, abs(c_src_w-c_w)) 50 | s_w = s_w if c_src_w > c_w else s_w * (-1) 51 | 52 | 53 | c_h = (bbox_expend[1] + bbox_expend[3]) / 2 + s_h 54 | c_w = (bbox_expend[0] + bbox_expend[2]) / 2 + s_w 55 | 56 | square_x1 = c_w - c 57 | square_y1 = c_h - c 58 | square_x2 = c_w + c 59 | square_y2 = c_h + c 60 | 61 | x1, y1, x2, y2 = square_x1, square_y1, square_x2, square_y2 62 | ww = x2 - x1 63 | hh = y2 - y1 64 | cc_x = (x1 + x2)/2 65 | cc_y = (y1 + y2)/2 66 | # 1:1 67 | ww = hh = min(ww, hh) 68 | x1, x2 = round(cc_x - ww/2), round(cc_x + ww/2) 69 | y1, y2 = round(cc_y - hh/2), round(cc_y + hh/2) 70 | 71 | return [round(x1), round(y1), round(x2), round(y2)] 72 | 73 | 74 | bbox_expend = expand(bbox, expand_radio, height=height, width=width) 75 | processed_bbox = to_square(bbox, bbox_expend, height=height, width=width) 76 | 77 | return processed_bbox 78 | 79 | 80 | def get_audio_feature(audio_path, feature_extractor): 81 | audio_input, sampling_rate = librosa.load(audio_path, sr=16000) 82 | assert sampling_rate == 16000 83 | 84 | audio_features = [] 85 | window = 750*640 86 | for i in range(0, len(audio_input), window): 87 | audio_feature = feature_extractor(audio_input[i:i+window], 88 | sampling_rate=sampling_rate, 89 | return_tensors="pt", 90 | ).input_features 91 | audio_features.append(audio_feature) 92 | audio_features = torch.cat(audio_features, dim=-1) 93 | return audio_features, len(audio_input) // 640 94 | 95 | def image_audio_emo_to_tensor(align_instance, feature_extractor, image_path, audio_path, emotion_path, limit=100, image_size=512, area=1.25): 96 | 97 | clip_processor = CLIPImageProcessor() 98 | 99 | to_tensor = transforms.Compose([ 100 | transforms.ToTensor(), 101 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 102 | ]) 103 | mask_to_tensor = transforms.Compose([ 104 | transforms.ToTensor(), 105 | ]) 106 | 107 | 108 | imSrc_ = Image.open(image_path).convert('RGB') 109 | w, h = imSrc_.size 110 | 111 | _, _, bboxes_list = align_instance(np.array(imSrc_)[:,:,[2,1,0]], maxface=True) 112 | 113 | if len(bboxes_list) == 0: 114 | return None 115 | bboxSrc = bboxes_list[0] 116 | 117 | x1, y1, ww, hh = bboxSrc 118 | x2, y2 = x1 + ww, y1 + hh 119 | 120 | mask_img = np.zeros_like(np.array(imSrc_)) 121 | ww, hh = (x2-x1) * area, (y2-y1) * area 122 | center = [(x2+x1)//2, (y2+y1)//2] 123 | x1 = max(center[0] - ww//2, 0) 124 | y1 = max(center[1] - hh//2, 0) 125 | x2 = min(center[0] + ww//2, w) 126 | y2 = min(center[1] + hh//2, h) 127 | mask_img[int(y1):int(y2), int(x1):int(x2)] = 255 128 | mask_img = Image.fromarray(mask_img) 129 | 130 | w, h = imSrc_.size 131 | scale = image_size / min(w, h) 132 | new_w = round(w * scale / 64) * 64 133 | new_h = round(h * scale / 64) * 64 134 | if new_h != h or new_w != w: 135 | imSrc = imSrc_.resize((new_w, new_h), Image.LANCZOS) 136 | mask_img = mask_img.resize((new_w, new_h), Image.LANCZOS) 137 | else: 138 | imSrc = imSrc_ 139 | 140 | clip_image = clip_processor( 141 | images=imSrc.resize((224, 224), Image.LANCZOS), return_tensors="pt" 142 | ).pixel_values[0] 143 | audio_input, audio_len = get_audio_feature(audio_path, feature_extractor) 144 | 145 | audio_len = min(limit, audio_len) 146 | 147 | emotion_prior = torch.from_numpy(np.load(emotion_path, allow_pickle=True).item()['mu']).unsqueeze(0).unsqueeze(0) 148 | 149 | sample = dict( 150 | face_mask=mask_to_tensor(mask_img), 151 | ref_img=to_tensor(imSrc), 152 | clip_images=clip_image, 153 | audio_feature=audio_input[0], 154 | audio_len=audio_len, 155 | emo_feature=emotion_prior, 156 | ) 157 | 158 | return sample -------------------------------------------------------------------------------- /src/models/audio_adapter/audio_proj.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module provides the implementation of an Audio Projection Model, which is designed for 3 | audio processing tasks. The model takes audio embeddings as input and outputs context tokens 4 | that can be used for various downstream applications, such as audio analysis or synthesis. 5 | 6 | The AudioProjModel class is based on the ModelMixin class from the diffusers library, which 7 | provides a foundation for building custom models. This implementation includes multiple linear 8 | layers with ReLU activation functions and a LayerNorm for normalization. 9 | 10 | Key Features: 11 | - Audio embedding input with flexible sequence length and block structure. 12 | - Multiple linear layers for feature transformation. 13 | - ReLU activation for non-linear transformation. 14 | - LayerNorm for stabilizing and speeding up training. 15 | - Rearrangement of input embeddings to match the model's expected input shape. 16 | - Customizable number of blocks, channels, and context tokens for adaptability. 17 | 18 | The module is structured to be easily integrated into larger systems or used as a standalone 19 | component for audio feature extraction and processing. 20 | 21 | Classes: 22 | - AudioProjModel: A class representing the audio projection model with configurable parameters. 23 | 24 | Functions: 25 | - (none) 26 | 27 | Dependencies: 28 | - torch: For tensor operations and neural network components. 29 | - diffusers: For the ModelMixin base class. 30 | - einops: For tensor rearrangement operations. 31 | 32 | """ 33 | 34 | import torch 35 | from diffusers import ModelMixin 36 | from einops import rearrange 37 | from torch import nn 38 | 39 | 40 | class AudioProjModel(ModelMixin): 41 | """Audio Projection Model 42 | 43 | This class defines an audio projection model that takes audio embeddings as input 44 | and produces context tokens as output. The model is based on the ModelMixin class 45 | and consists of multiple linear layers and activation functions. It can be used 46 | for various audio processing tasks. 47 | 48 | Attributes: 49 | seq_len (int): The length of the audio sequence. 50 | blocks (int): The number of blocks in the audio projection model. 51 | channels (int): The number of channels in the audio projection model. 52 | intermediate_dim (int): The intermediate dimension of the model. 53 | context_tokens (int): The number of context tokens in the output. 54 | output_dim (int): The output dimension of the context tokens. 55 | 56 | Methods: 57 | __init__(self, seq_len=5, blocks=12, channels=768, intermediate_dim=512, context_tokens=32, output_dim=768): 58 | Initializes the AudioProjModel with the given parameters. 59 | forward(self, audio_embeds): 60 | Defines the forward pass for the AudioProjModel. 61 | Parameters: 62 | audio_embeds (torch.Tensor): The input audio embeddings with shape (batch_size, video_length, blocks, channels). 63 | Returns: 64 | context_tokens (torch.Tensor): The output context tokens with shape (batch_size, video_length, context_tokens, output_dim). 65 | 66 | """ 67 | 68 | def __init__( 69 | self, 70 | seq_len=5, 71 | blocks=12, # add a new parameter blocks 72 | channels=768, # add a new parameter channels 73 | intermediate_dim=512, 74 | output_dim=768, 75 | context_tokens=32, 76 | ): 77 | super().__init__() 78 | 79 | self.seq_len = seq_len 80 | self.blocks = blocks 81 | self.channels = channels 82 | self.input_dim = ( 83 | seq_len * blocks * channels 84 | ) # update input_dim to be the product of blocks and channels. 85 | self.intermediate_dim = intermediate_dim 86 | self.context_tokens = context_tokens 87 | self.output_dim = output_dim 88 | 89 | # define multiple linear layers 90 | self.proj1 = nn.Linear(self.input_dim, intermediate_dim) 91 | self.proj2 = nn.Linear(intermediate_dim, intermediate_dim) 92 | self.proj3 = nn.Linear(intermediate_dim, context_tokens * output_dim) 93 | 94 | self.norm = nn.LayerNorm(output_dim) 95 | 96 | def forward(self, audio_embeds): 97 | """ 98 | Defines the forward pass for the AudioProjModel. 99 | 100 | Parameters: 101 | audio_embeds (torch.Tensor): The input audio embeddings with shape (batch_size, video_length, blocks, channels). 102 | 103 | Returns: 104 | context_tokens (torch.Tensor): The output context tokens with shape (batch_size, video_length, context_tokens, output_dim). 105 | """ 106 | # merge 107 | video_length = audio_embeds.shape[1] 108 | audio_embeds = rearrange(audio_embeds, "bz f w b c -> (bz f) w b c") 109 | batch_size, window_size, blocks, channels = audio_embeds.shape 110 | audio_embeds = audio_embeds.view(batch_size, window_size * blocks * channels) 111 | 112 | audio_embeds = torch.relu(self.proj1(audio_embeds)) 113 | audio_embeds = torch.relu(self.proj2(audio_embeds)) 114 | 115 | context_tokens = self.proj3(audio_embeds).reshape( 116 | batch_size, self.context_tokens, self.output_dim 117 | ) 118 | 119 | context_tokens = self.norm(context_tokens) 120 | context_tokens = rearrange( 121 | context_tokens, "(bz f) m c -> bz f m c", f=video_length 122 | ) 123 | 124 | return context_tokens -------------------------------------------------------------------------------- /src/models/audio_adapter/pose_guider.py: -------------------------------------------------------------------------------- 1 | from typing import Tuple 2 | 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | import torch.nn.init as init 6 | from einops import rearrange 7 | from diffusers.models.modeling_utils import ModelMixin 8 | 9 | 10 | def zero_module(module): 11 | # Zero out the parameters of a module and return it. 12 | for p in module.parameters(): 13 | p.detach().zero_() 14 | return module 15 | 16 | 17 | class InflatedConv3d(nn.Conv2d): 18 | def forward(self, x): 19 | video_length = x.shape[2] 20 | 21 | x = rearrange(x, "b c f h w -> (b f) c h w") 22 | x = super().forward(x) 23 | x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length) 24 | 25 | return x 26 | 27 | 28 | class PoseGuider(ModelMixin): 29 | def __init__( 30 | self, 31 | conditioning_embedding_channels: int, 32 | conditioning_channels: int = 3, 33 | block_out_channels: Tuple[int] = (16, 32, 64, 128), 34 | ): 35 | super().__init__() 36 | self.conv_in = InflatedConv3d( 37 | conditioning_channels, block_out_channels[0], kernel_size=3, padding=1 38 | ) 39 | 40 | self.blocks = nn.ModuleList([]) 41 | 42 | for i in range(len(block_out_channels) - 1): 43 | channel_in = block_out_channels[i] 44 | channel_out = block_out_channels[i + 1] 45 | self.blocks.append( 46 | InflatedConv3d(channel_in, channel_in, kernel_size=3, padding=1) 47 | ) 48 | self.blocks.append( 49 | InflatedConv3d( 50 | channel_in, channel_out, kernel_size=3, padding=1, stride=2 51 | ) 52 | ) 53 | 54 | self.conv_out = zero_module( 55 | InflatedConv3d( 56 | block_out_channels[-1], 57 | conditioning_embedding_channels, 58 | kernel_size=3, 59 | padding=1, 60 | ) 61 | ) 62 | 63 | def forward(self, conditioning): 64 | embedding = self.conv_in(conditioning) 65 | embedding = F.silu(embedding) 66 | 67 | for block in self.blocks: 68 | embedding = block(embedding) 69 | embedding = F.silu(embedding) 70 | 71 | embedding = self.conv_out(embedding) 72 | 73 | return embedding 74 | -------------------------------------------------------------------------------- /src/models/base/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/toto222/DICE-Talk/74679d4078ac32af01f44e09c2235b5bed7e0bcf/src/models/base/__init__.py -------------------------------------------------------------------------------- /src/models/base/unet_spatio_temporal_condition.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Dict, Optional, Tuple, Union, Any 3 | 4 | import torch 5 | import torch.nn as nn 6 | 7 | from diffusers.configuration_utils import ConfigMixin, register_to_config 8 | from diffusers.loaders import UNet2DConditionLoadersMixin 9 | from diffusers.utils import BaseOutput, logging 10 | # from diffusers.models.attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor 11 | 12 | from diffusers.models.embeddings import TimestepEmbedding, Timesteps 13 | from diffusers.models.modeling_utils import ModelMixin 14 | from .unet_3d_blocks import UNetMidBlockSpatioTemporal, get_down_block, get_up_block 15 | from .attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor, AttnProcessor2_0, IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0 16 | 17 | logger = logging.get_logger(__name__) # pylint: disable=invalid-name 18 | 19 | 20 | @dataclass 21 | class UNetSpatioTemporalConditionOutput(BaseOutput): 22 | """ 23 | The output of [`UNetSpatioTemporalConditionModel`]. 24 | 25 | Args: 26 | sample (`torch.Tensor` of shape `(batch_size, num_frames, num_channels, height, width)`): 27 | The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. 28 | """ 29 | 30 | sample: torch.Tensor = None 31 | 32 | 33 | class UNetSpatioTemporalConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): 34 | r""" 35 | A conditional Spatio-Temporal UNet model that takes a noisy video frames, conditional state, and a timestep and 36 | returns a sample shaped output. 37 | 38 | This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented 39 | for all models (such as downloading or saving). 40 | 41 | Parameters: 42 | sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): 43 | Height and width of input/output sample. 44 | in_channels (`int`, *optional*, defaults to 8): Number of channels in the input sample. 45 | out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. 46 | down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal")`): 47 | The tuple of downsample blocks to use. 48 | up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal")`): 49 | The tuple of upsample blocks to use. 50 | block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): 51 | The tuple of output channels for each block. 52 | addition_time_embed_dim: (`int`, defaults to 256): 53 | Dimension to to encode the additional time ids. 54 | projection_class_embeddings_input_dim (`int`, defaults to 768): 55 | The dimension of the projection of encoded `added_time_ids`. 56 | layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. 57 | cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): 58 | The dimension of the cross attention features. 59 | transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1): 60 | The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for 61 | [`~models.unets.unet_3d_blocks.CrossAttnDownBlockSpatioTemporal`], 62 | [`~models.unets.unet_3d_blocks.CrossAttnUpBlockSpatioTemporal`], 63 | [`~models.unets.unet_3d_blocks.UNetMidBlockSpatioTemporal`]. 64 | num_attention_heads (`int`, `Tuple[int]`, defaults to `(5, 10, 10, 20)`): 65 | The number of attention heads. 66 | dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. 67 | """ 68 | 69 | _supports_gradient_checkpointing = True 70 | 71 | @register_to_config 72 | def __init__( 73 | self, 74 | sample_size: Optional[int] = None, 75 | in_channels: int = 8, 76 | out_channels: int = 4, 77 | down_block_types: Tuple[str] = ( 78 | "CrossAttnDownBlockSpatioTemporal", 79 | "CrossAttnDownBlockSpatioTemporal", 80 | "CrossAttnDownBlockSpatioTemporal", 81 | "DownBlockSpatioTemporal", 82 | ), 83 | up_block_types: Tuple[str] = ( 84 | "UpBlockSpatioTemporal", 85 | "CrossAttnUpBlockSpatioTemporal", 86 | "CrossAttnUpBlockSpatioTemporal", 87 | "CrossAttnUpBlockSpatioTemporal", 88 | ), 89 | block_out_channels: Tuple[int] = (320, 640, 1280, 1280), 90 | addition_time_embed_dim: int = 256, 91 | projection_class_embeddings_input_dim: int = 768, 92 | layers_per_block: Union[int, Tuple[int]] = 2, 93 | cross_attention_dim: Union[int, Tuple[int]] = 1024, 94 | transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1, 95 | num_attention_heads: Union[int, Tuple[int]] = (5, 10, 20, 20), 96 | num_frames: int = 25, 97 | ): 98 | super().__init__() 99 | 100 | self.sample_size = sample_size 101 | 102 | # Check inputs 103 | if len(down_block_types) != len(up_block_types): 104 | raise ValueError( 105 | f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." 106 | ) 107 | 108 | if len(block_out_channels) != len(down_block_types): 109 | raise ValueError( 110 | f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." 111 | ) 112 | 113 | if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): 114 | raise ValueError( 115 | f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." 116 | ) 117 | 118 | if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): 119 | raise ValueError( 120 | f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." 121 | ) 122 | 123 | if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): 124 | raise ValueError( 125 | f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." 126 | ) 127 | 128 | # input 129 | self.conv_in = nn.Conv2d( 130 | in_channels, 131 | block_out_channels[0], 132 | kernel_size=3, 133 | padding=1, 134 | ) 135 | 136 | # time 137 | time_embed_dim = block_out_channels[0] * 4 138 | 139 | self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0) 140 | timestep_input_dim = block_out_channels[0] 141 | 142 | self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) 143 | 144 | self.add_time_proj = Timesteps(addition_time_embed_dim, True, downscale_freq_shift=0) 145 | self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) 146 | 147 | self.down_blocks = nn.ModuleList([]) 148 | self.up_blocks = nn.ModuleList([]) 149 | 150 | if isinstance(num_attention_heads, int): 151 | num_attention_heads = (num_attention_heads,) * len(down_block_types) 152 | 153 | if isinstance(cross_attention_dim, int): 154 | cross_attention_dim = (cross_attention_dim,) * len(down_block_types) 155 | 156 | if isinstance(layers_per_block, int): 157 | layers_per_block = [layers_per_block] * len(down_block_types) 158 | 159 | if isinstance(transformer_layers_per_block, int): 160 | transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) 161 | 162 | blocks_time_embed_dim = time_embed_dim 163 | 164 | # down 165 | output_channel = block_out_channels[0] 166 | for i, down_block_type in enumerate(down_block_types): 167 | input_channel = output_channel 168 | output_channel = block_out_channels[i] 169 | is_final_block = i == len(block_out_channels) - 1 170 | 171 | down_block = get_down_block( 172 | down_block_type, 173 | num_layers=layers_per_block[i], 174 | transformer_layers_per_block=transformer_layers_per_block[i], 175 | in_channels=input_channel, 176 | out_channels=output_channel, 177 | temb_channels=blocks_time_embed_dim, 178 | add_downsample=not is_final_block, 179 | resnet_eps=1e-5, 180 | cross_attention_dim=cross_attention_dim[i], 181 | num_attention_heads=num_attention_heads[i], 182 | resnet_act_fn="silu", 183 | ) 184 | self.down_blocks.append(down_block) 185 | 186 | # mid 187 | self.mid_block = UNetMidBlockSpatioTemporal( 188 | block_out_channels[-1], 189 | temb_channels=blocks_time_embed_dim, 190 | transformer_layers_per_block=transformer_layers_per_block[-1], 191 | cross_attention_dim=cross_attention_dim[-1], 192 | num_attention_heads=num_attention_heads[-1], 193 | ) 194 | 195 | # count how many layers upsample the images 196 | self.num_upsamplers = 0 197 | 198 | # up 199 | reversed_block_out_channels = list(reversed(block_out_channels)) 200 | reversed_num_attention_heads = list(reversed(num_attention_heads)) 201 | reversed_layers_per_block = list(reversed(layers_per_block)) 202 | reversed_cross_attention_dim = list(reversed(cross_attention_dim)) 203 | reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block)) 204 | 205 | output_channel = reversed_block_out_channels[0] 206 | for i, up_block_type in enumerate(up_block_types): 207 | is_final_block = i == len(block_out_channels) - 1 208 | 209 | prev_output_channel = output_channel 210 | output_channel = reversed_block_out_channels[i] 211 | input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] 212 | 213 | # add upsample block for all BUT final layer 214 | if not is_final_block: 215 | add_upsample = True 216 | self.num_upsamplers += 1 217 | else: 218 | add_upsample = False 219 | 220 | up_block = get_up_block( 221 | up_block_type, 222 | num_layers=reversed_layers_per_block[i] + 1, 223 | transformer_layers_per_block=reversed_transformer_layers_per_block[i], 224 | in_channels=input_channel, 225 | out_channels=output_channel, 226 | prev_output_channel=prev_output_channel, 227 | temb_channels=blocks_time_embed_dim, 228 | add_upsample=add_upsample, 229 | resnet_eps=1e-5, 230 | resolution_idx=i, 231 | cross_attention_dim=reversed_cross_attention_dim[i], 232 | num_attention_heads=reversed_num_attention_heads[i], 233 | resnet_act_fn="silu", 234 | ) 235 | self.up_blocks.append(up_block) 236 | prev_output_channel = output_channel 237 | 238 | # out 239 | self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-5) 240 | self.conv_act = nn.SiLU() 241 | 242 | self.conv_out = nn.Conv2d( 243 | block_out_channels[0], 244 | out_channels, 245 | kernel_size=3, 246 | padding=1, 247 | ) 248 | 249 | @property 250 | def attn_processors(self) -> Dict[str, AttentionProcessor]: 251 | r""" 252 | Returns: 253 | `dict` of attention processors: A dictionary containing all attention processors used in the model with 254 | indexed by its weight name. 255 | """ 256 | # set recursively 257 | processors = {} 258 | 259 | def fn_recursive_add_processors( 260 | name: str, 261 | module: torch.nn.Module, 262 | processors: Dict[str, AttentionProcessor], 263 | ): 264 | if hasattr(module, "get_processor"): 265 | processors[f"{name}.processor"] = module.get_processor() 266 | 267 | for sub_name, child in module.named_children(): 268 | fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) 269 | 270 | return processors 271 | 272 | for name, module in self.named_children(): 273 | fn_recursive_add_processors(name, module, processors) 274 | 275 | return processors 276 | 277 | def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): 278 | r""" 279 | Sets the attention processor to use to compute attention. 280 | 281 | Parameters: 282 | processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): 283 | The instantiated processor class or a dictionary of processor classes that will be set as the processor 284 | for **all** `Attention` layers. 285 | 286 | If `processor` is a dict, the key needs to define the path to the corresponding cross attention 287 | processor. This is strongly recommended when setting trainable attention processors. 288 | 289 | """ 290 | count = len(self.attn_processors.keys()) 291 | 292 | if isinstance(processor, dict) and len(processor) != count: 293 | raise ValueError( 294 | f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" 295 | f" number of attention layers: {count}. Please make sure to pass {count} processor classes." 296 | ) 297 | 298 | def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): 299 | if hasattr(module, "set_processor"): 300 | if not isinstance(processor, dict): 301 | module.set_processor(processor) 302 | else: 303 | module.set_processor(processor.pop(f"{name}.processor")) 304 | 305 | for sub_name, child in module.named_children(): 306 | fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) 307 | 308 | for name, module in self.named_children(): 309 | fn_recursive_attn_processor(name, module, processor) 310 | 311 | def set_default_attn_processor(self): 312 | """ 313 | Disables custom attention processors and sets the default attention implementation. 314 | """ 315 | if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): 316 | processor = AttnProcessor() 317 | else: 318 | raise ValueError( 319 | f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}" 320 | ) 321 | 322 | self.set_attn_processor(processor) 323 | 324 | def _set_gradient_checkpointing(self, module, value=False): 325 | if hasattr(module, "gradient_checkpointing"): 326 | module.gradient_checkpointing = value 327 | 328 | # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking 329 | def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None: 330 | """ 331 | Sets the attention processor to use [feed forward 332 | chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers). 333 | 334 | Parameters: 335 | chunk_size (`int`, *optional*): 336 | The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually 337 | over each tensor of dim=`dim`. 338 | dim (`int`, *optional*, defaults to `0`): 339 | The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch) 340 | or dim=1 (sequence length). 341 | """ 342 | if dim not in [0, 1]: 343 | raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}") 344 | 345 | # By default chunk size is 1 346 | chunk_size = chunk_size or 1 347 | 348 | def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int): 349 | if hasattr(module, "set_chunk_feed_forward"): 350 | module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim) 351 | 352 | for child in module.children(): 353 | fn_recursive_feed_forward(child, chunk_size, dim) 354 | 355 | for module in self.children(): 356 | fn_recursive_feed_forward(module, chunk_size, dim) 357 | 358 | def forward( 359 | self, 360 | sample: torch.Tensor, 361 | timestep: Union[torch.Tensor, float, int], 362 | encoder_hidden_states: torch.Tensor, 363 | added_time_ids: torch.Tensor, 364 | spatial_condition: Optional[torch.Tensor] = None, 365 | cross_attention_kwargs: Optional[Dict[str, Any]] = None, 366 | return_dict: bool = True, 367 | ) -> Union[UNetSpatioTemporalConditionOutput, Tuple]: 368 | r""" 369 | The [`UNetSpatioTemporalConditionModel`] forward method. 370 | 371 | Args: 372 | sample (`torch.Tensor`): 373 | The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`. 374 | timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input. 375 | encoder_hidden_states (`torch.Tensor`): 376 | The encoder hidden states with shape `(batch*num_frames, sequence_length, cross_attention_dim)`. 377 | added_time_ids: (`torch.Tensor`): 378 | The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal 379 | embeddings and added to the time embeddings. 380 | spatial_condition (`torch.Tensor`, *optional*, defaults to `None`): 381 | The spatial_condition embedding with shape `(batch, num_frames, channel_in(320), height, width)`. 382 | return_dict (`bool`, *optional*, defaults to `True`): 383 | Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead 384 | of a plain tuple. 385 | Returns: 386 | [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`: 387 | If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is 388 | returned, otherwise a `tuple` is returned where the first element is the sample tensor. 389 | """ 390 | # 1. time 391 | timesteps = timestep 392 | if not torch.is_tensor(timesteps): 393 | # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can 394 | # This would be a good case for the `match` statement (Python 3.10+) 395 | is_mps = sample.device.type == "mps" 396 | if isinstance(timestep, float): 397 | dtype = torch.float32 if is_mps else torch.float64 398 | else: 399 | dtype = torch.int32 if is_mps else torch.int64 400 | timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) 401 | elif len(timesteps.shape) == 0: 402 | timesteps = timesteps[None].to(sample.device) 403 | 404 | # broadcast to batch dimension in a way that's compatible with ONNX/Core ML 405 | batch_size, num_frames = sample.shape[:2] 406 | timesteps = timesteps.expand(batch_size) 407 | 408 | t_emb = self.time_proj(timesteps) 409 | 410 | # `Timesteps` does not contain any weights and will always return f32 tensors 411 | # but time_embedding might actually be running in fp16. so we need to cast here. 412 | # there might be better ways to encapsulate this. 413 | t_emb = t_emb.to(dtype=sample.dtype) 414 | 415 | emb = self.time_embedding(t_emb) 416 | 417 | time_embeds = self.add_time_proj(added_time_ids.flatten()) 418 | time_embeds = time_embeds.reshape((batch_size, -1)) 419 | time_embeds = time_embeds.to(emb.dtype) 420 | aug_emb = self.add_embedding(time_embeds) 421 | emb = emb + aug_emb 422 | 423 | # Flatten the batch and frames dimensions 424 | # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width] 425 | sample = sample.flatten(0, 1) 426 | # Repeat the embeddings num_video_frames times 427 | # emb: [batch, channels] -> [batch * frames, channels] 428 | emb = emb.repeat_interleave(num_frames, dim=0) 429 | # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels] 430 | 431 | ### 20240731 process encoder_hidden_states ### 432 | if isinstance(encoder_hidden_states, tuple): 433 | # ip_hidden_states is a list 434 | encoder_hidden_states, ip_hidden_states = encoder_hidden_states 435 | if encoder_hidden_states.shape[0]==batch_size: 436 | encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0) 437 | encoder_hidden_states = (encoder_hidden_states, ip_hidden_states) 438 | elif encoder_hidden_states.shape[0]==batch_size: 439 | ### if framewised feature is not provided, repeat_interleave 440 | encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0) 441 | 442 | 443 | # 2. pre-process 444 | sample = self.conv_in(sample) 445 | 446 | ### 20240731 add spatial_condition here ### 447 | if spatial_condition is not None: 448 | sample = sample + spatial_condition.flatten(0,1) 449 | 450 | image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device) 451 | 452 | down_block_res_samples = (sample,) 453 | for downsample_block in self.down_blocks: 454 | if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention: 455 | sample, res_samples = downsample_block( 456 | hidden_states=sample, 457 | temb=emb, 458 | encoder_hidden_states=encoder_hidden_states, 459 | cross_attention_kwargs=cross_attention_kwargs, 460 | image_only_indicator=image_only_indicator, 461 | ) 462 | else: 463 | sample, res_samples = downsample_block( 464 | hidden_states=sample, 465 | temb=emb, 466 | image_only_indicator=image_only_indicator, 467 | ) 468 | 469 | down_block_res_samples += res_samples 470 | 471 | # 4. mid 472 | sample = self.mid_block( 473 | hidden_states=sample, 474 | temb=emb, 475 | encoder_hidden_states=encoder_hidden_states, 476 | cross_attention_kwargs=cross_attention_kwargs, 477 | image_only_indicator=image_only_indicator, 478 | ) 479 | 480 | # 5. up 481 | for i, upsample_block in enumerate(self.up_blocks): 482 | res_samples = down_block_res_samples[-len(upsample_block.resnets) :] 483 | down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] 484 | 485 | if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention: 486 | sample = upsample_block( 487 | hidden_states=sample, 488 | temb=emb, 489 | res_hidden_states_tuple=res_samples, 490 | encoder_hidden_states=encoder_hidden_states, 491 | cross_attention_kwargs=cross_attention_kwargs, 492 | image_only_indicator=image_only_indicator, 493 | ) 494 | else: 495 | sample = upsample_block( 496 | hidden_states=sample, 497 | temb=emb, 498 | res_hidden_states_tuple=res_samples, 499 | image_only_indicator=image_only_indicator, 500 | ) 501 | 502 | # 6. post-process 503 | sample = self.conv_norm_out(sample) 504 | sample = self.conv_act(sample) 505 | sample = self.conv_out(sample) 506 | 507 | # 7. Reshape back to original shape 508 | sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) 509 | 510 | if not return_dict: 511 | return (sample,) 512 | 513 | return UNetSpatioTemporalConditionOutput(sample=sample) 514 | 515 | 516 | 517 | def add_ip_adapters(unet, num_adapter_embeds=[32,], scale=[1.0,]): 518 | 519 | assert len(num_adapter_embeds)==len(scale) 520 | 521 | 522 | # init adapter modules 523 | attn_procs = {} 524 | unet_sd = unet.state_dict() 525 | for name in unet.attn_processors.keys(): 526 | cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim 527 | if name.startswith("mid_block"): 528 | hidden_size = unet.config.block_out_channels[-1] 529 | elif name.startswith("up_blocks"): 530 | block_id = int(name[len("up_blocks.")]) 531 | hidden_size = list(reversed(unet.config.block_out_channels))[block_id] 532 | elif name.startswith("down_blocks"): 533 | block_id = int(name[len("down_blocks.")]) 534 | hidden_size = unet.config.block_out_channels[block_id] 535 | # if cross_attention_dim is None or "temporal_transformer_blocks" in name: 536 | if cross_attention_dim is None: 537 | attn_processor_class = ( 538 | AttnProcessor2_0 if hasattr(torch.nn.functional, "scaled_dot_product_attention") else AttnProcessor 539 | ) 540 | attn_procs[name] = attn_processor_class() 541 | else: 542 | attn_processor_class = ( 543 | IPAdapterAttnProcessor2_0 if hasattr(torch.nn.functional, "scaled_dot_product_attention") else IPAdapterAttnProcessor 544 | ) 545 | 546 | attn_procs[name] = attn_processor_class( 547 | hidden_size=hidden_size, 548 | cross_attention_dim=cross_attention_dim, 549 | num_tokens=num_adapter_embeds, 550 | scale=scale 551 | ).to(device=unet.device, dtype=unet.dtype) 552 | 553 | layer_name = name.split(".processor")[0] 554 | weights = {} 555 | 556 | for i in range(len(num_adapter_embeds)): 557 | weights.update({f"to_k_ip.{i}.weight": unet_sd[layer_name + ".to_k.weight"]}) 558 | weights.update({f"to_v_ip.{i}.weight": unet_sd[layer_name + ".to_v.weight"]}) 559 | 560 | 561 | attn_procs[name].load_state_dict(weights) 562 | 563 | unet.set_attn_processor(attn_procs) 564 | 565 | adapter_modules = torch.nn.ModuleList([m for m in unet.attn_processors.values() if isinstance(m, IPAdapterAttnProcessor) or isinstance(m, IPAdapterAttnProcessor2_0)]) 566 | return adapter_modules 567 | 568 | 569 | def load_adapter_states(adapter_modules, state_dict_list): 570 | assert len(state_dict_list)>0 571 | 572 | merged_stete_dict = {} 573 | for state_dict in state_dict_list: 574 | for k, v in state_dict.items(): 575 | if k in merged_stete_dict.keys(): 576 | k_split = k.split('.') 577 | adapter_idx = int(k_split[2]) 578 | adapter_idx += 1 579 | k_split[2] = str(adapter_idx) 580 | new_k = '.'.join(k_split) 581 | while(new_k in merged_stete_dict.keys()): 582 | adapter_idx += 1 583 | k_split[2] = str(adapter_idx) 584 | new_k = '.'.join(k_split) 585 | merged_stete_dict[new_k] = v 586 | else: 587 | merged_stete_dict[k] = v 588 | 589 | info = adapter_modules.load_state_dict(merged_stete_dict, strict=True) 590 | return info 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | -------------------------------------------------------------------------------- /src/models/emotion_adapter/emo.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from src.models.audio_adapter.audio_proj import AudioProjModel as FeatureProjModel 5 | 6 | class EmotionModel(nn.Module): 7 | def __init__(self): 8 | super(EmotionModel, self).__init__() 9 | self.emo_linear = FeatureProjModel(seq_len=1, blocks=1, channels=256, intermediate_dim=1024, output_dim=1024, context_tokens=32) 10 | self.kv_tokens_linear = FeatureProjModel(seq_len=1, blocks=1, channels=1024, intermediate_dim=1024, output_dim=1024, context_tokens=32) 11 | 12 | self.codebook = emotion_bank(src_dim=1024, codebook_size=64) 13 | 14 | self.attention = QKVAttention(input_dim=1024, output_dim=1024, num_heads=8) 15 | self.classifier = Classifier(input_dim=1280, num_classes=22) 16 | 17 | 18 | 19 | 20 | def forward(self, emo_prompts, emo_prompt_mask=None, retrieval=True): 21 | 22 | emo_retrieval, vq_loss, encoding_indices = self.codebook(emo_prompts) 23 | 24 | if emo_prompt_mask is not None: 25 | emo_prompts = torch.where( 26 | emo_prompt_mask, torch.zeros_like(emo_prompts), emo_prompts) 27 | 28 | emo_retrieval = torch.where( 29 | emo_prompt_mask, torch.zeros_like(emo_retrieval), emo_retrieval) 30 | 31 | emo_prompts_q = self.emo_linear(emo_prompts) 32 | 33 | if retrieval: 34 | kv_tokens = self.kv_tokens_linear(emo_retrieval) 35 | else: 36 | f = emo_prompts.shape[1] 37 | num, d = self.codebook.codebook.weight.data.shape 38 | emo_retrieval = self.codebook.codebook.weight.data.view(1,num,1,1,d) 39 | kv_tokens = self.kv_tokens_linear(emo_retrieval) 40 | kv_tokens = kv_tokens.view(1,1,-1,1024).expand(1, f, -1, 1024) 41 | vq_loss = torch.zeros_like(vq_loss) 42 | 43 | final_emo_prompts , attn_weights = self.attention(emo_prompts_q, kv_tokens) 44 | 45 | return final_emo_prompts, vq_loss 46 | 47 | class QKVAttention(nn.Module): 48 | def __init__(self, input_dim, output_dim, num_heads=8): 49 | super(QKVAttention, self).__init__() 50 | self.num_heads = num_heads 51 | self.output_dim = output_dim 52 | 53 | self.fc_q = nn.Linear(input_dim, output_dim) 54 | self.fc_k = nn.Linear(input_dim, output_dim) 55 | self.fc_v = nn.Linear(input_dim, output_dim) 56 | 57 | 58 | 59 | def forward(self, x, y): 60 | 61 | Q = self.fc_q(x) 62 | K = self.fc_k(y) 63 | V = self.fc_v(y) 64 | 65 | 66 | Q = Q.view(Q.size(0), Q.size(1), Q.size(2), self.num_heads, -1).transpose(2, 3) 67 | K = K.view(K.size(0), K.size(1), K.size(2), self.num_heads, -1).transpose(2, 3) 68 | V = V.view(V.size(0), V.size(1), V.size(2), self.num_heads, -1).transpose(2, 3) 69 | 70 | 71 | attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / (K.size(-1) ** 0.5) 72 | attn_weights = F.softmax(attn_scores, dim=-1) 73 | 74 | 75 | attn_output = torch.matmul(attn_weights, V) 76 | 77 | 78 | attn_output = attn_output.transpose(2, 3).contiguous().view(attn_output.size(0), attn_output.size(1), attn_output.size(3), -1) 79 | 80 | 81 | 82 | return attn_output, attn_weights 83 | 84 | class emotion_bank(nn.Module): 85 | def __init__(self, src_dim=1024, codebook_size=512): 86 | super(emotion_bank, self).__init__() 87 | self.src_dim = src_dim 88 | self._commitment_cost = 0.25 89 | 90 | self.fc = nn.Linear(256, src_dim) 91 | self.codebook = nn.Embedding(codebook_size, src_dim) 92 | self.codebook_size = codebook_size 93 | self.codebook.weight.data.uniform_(-1/self.codebook_size, 1/self.codebook_size) 94 | 95 | 96 | 97 | def quantize(self, z): 98 | 99 | z = self.fc(z) 100 | b, l, d1, d2, c = z.shape 101 | flat_z = z.reshape(-1, c) 102 | # Calculate distances 103 | distances = (torch.sum(flat_z**2, dim=1, keepdim=True) 104 | + torch.sum(self.codebook.weight**2, dim=1) 105 | - 2 * torch.matmul(flat_z, self.codebook.weight.t())) 106 | 107 | 108 | encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1) 109 | 110 | encodings = torch.zeros(encoding_indices.shape[0], self.codebook_size, device=z.device) 111 | encodings.scatter_(1, encoding_indices, 1) 112 | 113 | # Quantize and unflatten 114 | quantized = torch.matmul(encodings, self.codebook.weight).view(b, l, d1, d2, c) 115 | # Loss 116 | e_latent_loss = F.mse_loss(quantized.detach(), z) 117 | q_latent_loss = F.mse_loss(quantized, z.detach()) 118 | loss = q_latent_loss + self._commitment_cost * e_latent_loss 119 | 120 | quantized = z + (quantized - z).detach() 121 | 122 | 123 | 124 | return quantized, loss, encoding_indices 125 | 126 | def forward(self, z): 127 | 128 | z, loss, encoding_indices= self.quantize(z) 129 | 130 | return z, loss, encoding_indices 131 | 132 | 133 | class Classifier(nn.Module): 134 | def __init__(self, input_dim, num_classes): 135 | super(Classifier, self).__init__() 136 | self.fc1 = nn.Linear(input_dim, 512) 137 | self.fc2 = nn.Linear(512, 256) 138 | self.fc3 = nn.Linear(256, num_classes) 139 | self.relu = nn.ReLU() 140 | self.dropout = nn.Dropout(0.1) 141 | self.adaptive_pool = nn.AdaptiveAvgPool2d(1) 142 | 143 | def forward(self, x): 144 | x = self.adaptive_pool(x) 145 | x = x.view(x.shape[0],-1) 146 | x = self.relu(self.fc1(x)) 147 | x = self.dropout(x) 148 | x = self.relu(self.fc2(x)) 149 | x = self.dropout(x) 150 | x = self.fc3(x) 151 | return x 152 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /src/pipelines/pipeline_dicetalk.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | from dataclasses import dataclass 3 | from typing import Callable, Dict, List, Optional, Union 4 | 5 | import numpy as np 6 | import PIL.Image 7 | import torch 8 | from transformers import CLIPVisionModelWithProjection 9 | 10 | from diffusers.image_processor import VaeImageProcessor 11 | from diffusers.utils import BaseOutput, logging 12 | from diffusers.utils.torch_utils import randn_tensor, is_compiled_module 13 | from diffusers.pipelines.pipeline_utils import DiffusionPipeline 14 | from diffusers import ( 15 | AutoencoderKLTemporalDecoder, 16 | EulerDiscreteScheduler, 17 | ) 18 | 19 | from src.models.audio_adapter.pose_guider import PoseGuider 20 | from src.models.base.unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel 21 | 22 | logger = logging.get_logger(__name__) 23 | 24 | 25 | @dataclass 26 | class Pose2VideoSVDPipelineOutput(BaseOutput): 27 | r""" 28 | Output class for zero-shot text-to-video pipeline. 29 | 30 | Args: 31 | frames (`[List[PIL.Image.Image]`, `np.ndarray`]): 32 | List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width, 33 | num_channels)`. 34 | """ 35 | 36 | frames: Union[List[PIL.Image.Image], np.ndarray] 37 | 38 | 39 | class DicePipeline(DiffusionPipeline): 40 | r""" 41 | Pipeline to generate video from an input image using Stable Video Diffusion. 42 | 43 | This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods 44 | implemented for all pipelines (downloading, saving, running on a particular device, etc.). 45 | 46 | Args: 47 | vae ([`AutoencoderKL`]): 48 | Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. 49 | image_encoder ([`~transformers.CLIPVisionModelWithProjection`]): 50 | Frozen CLIP image-encoder ([laion/CLIP-ViT-H-14-laion2B-s32B-b79K](https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K)). 51 | unet ([`UNetSpatioTemporalConditionModel`]): 52 | A `UNetSpatioTemporalConditionModel` to denoise the encoded image latents. 53 | scheduler ([`EulerDiscreteScheduler`]): 54 | A scheduler to be used in combination with `unet` to denoise the encoded image latents. 55 | feature_extractor ([`~transformers.CLIPImageProcessor`]): 56 | A `CLIPImageProcessor` to extract features from generated images. 57 | """ 58 | 59 | model_cpu_offload_seq = "image_encoder->unet->vae" 60 | _callback_tensor_inputs = ["latents"] 61 | 62 | def __init__( 63 | self, 64 | vae: AutoencoderKLTemporalDecoder, 65 | image_encoder: CLIPVisionModelWithProjection, 66 | unet: UNetSpatioTemporalConditionModel, 67 | pose_guider: PoseGuider, 68 | scheduler: EulerDiscreteScheduler, 69 | ): 70 | super().__init__() 71 | self.register_modules( 72 | vae=vae, 73 | image_encoder=image_encoder, 74 | unet=unet, 75 | pose_guider=pose_guider, 76 | scheduler=scheduler, 77 | ) 78 | 79 | self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) 80 | 81 | self.image_processor = VaeImageProcessor( 82 | vae_scale_factor=self.vae_scale_factor, 83 | do_convert_rgb=True) 84 | 85 | self.pose_image_processor = VaeImageProcessor( 86 | vae_scale_factor=self.vae_scale_factor, 87 | do_convert_rgb=True, 88 | do_normalize=False, 89 | ) 90 | 91 | 92 | def _clip_encode_image(self, image, audio_prompts, uncond_audio_prompts, emo_prompts, uncond_emo_prompts, 93 | num_frames, device, num_videos_per_prompt, do_classifier_free_guidance, frames_per_batch): 94 | dtype = next(self.image_encoder.parameters()).dtype 95 | 96 | image = image.to(device=device, dtype=dtype) 97 | image_embeddings = self.image_encoder(image).image_embeds 98 | image_embeddings = image_embeddings.unsqueeze(1) 99 | 100 | # duplicate image embeddings for each generation per prompt, using mps friendly method 101 | bs_embed, seq_len, _ = image_embeddings.shape 102 | image_embeddings = image_embeddings.repeat(1, num_videos_per_prompt, 1) 103 | image_embeddings = image_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1) 104 | 105 | image_embeddings = image_embeddings.unsqueeze(1).repeat((1, num_frames, 1, 1)) 106 | 107 | if do_classifier_free_guidance: 108 | negative_image_embeddings = torch.zeros_like(image_embeddings) 109 | 110 | 111 | audio_prompts = torch.stack(audio_prompts, dim=0).to(device=device, dtype=dtype) 112 | audio_prompts = audio_prompts.unsqueeze(0) 113 | image_embeddings = torch.cat([negative_image_embeddings, image_embeddings, image_embeddings]) 114 | 115 | 116 | uncond_audio_prompts = torch.stack(uncond_audio_prompts, dim=0).to(device=device, dtype=dtype) 117 | uncond_audio_prompts = uncond_audio_prompts.unsqueeze(0) 118 | 119 | pad_uncond_audio_prompt = uncond_audio_prompts[:,:1].repeat(1, frames_per_batch, 1, 1) 120 | audio_prompts = torch.cat([audio_prompts, pad_uncond_audio_prompt], dim=1) 121 | uncond_audio_prompts = torch.cat([uncond_audio_prompts, pad_uncond_audio_prompt], dim=1) 122 | 123 | emo_prompts = torch.stack(emo_prompts, dim=0).to(device=device, dtype=dtype) 124 | emo_prompts = emo_prompts.unsqueeze(0) 125 | 126 | 127 | uncond_emo_prompts = torch.stack(uncond_emo_prompts, dim=0).to(device=device, dtype=dtype) 128 | uncond_emo_prompts = uncond_emo_prompts.unsqueeze(0) 129 | 130 | pad_uncond_emo_prompt = uncond_emo_prompts[:,:1].repeat(1, frames_per_batch, 1, 1) 131 | emo_prompts = torch.cat([emo_prompts, pad_uncond_emo_prompt], dim=1) 132 | uncond_emo_prompts = torch.cat([uncond_emo_prompts, pad_uncond_emo_prompt], dim=1) 133 | 134 | 135 | # For classifier free guidance, we need to do two forward passes. 136 | # Here we concatenate the unconditional and text embeddings into a single batch 137 | # to avoid doing two forward passes 138 | audio_prompts = torch.cat([uncond_audio_prompts, uncond_audio_prompts, audio_prompts]) 139 | emo_prompts = torch.cat([uncond_emo_prompts, uncond_emo_prompts, emo_prompts]) 140 | # import pdb;pdb.set_trace() 141 | 142 | return image_embeddings, audio_prompts, emo_prompts 143 | 144 | def _encode_vae_image( 145 | self, 146 | image: torch.Tensor, 147 | device, 148 | num_videos_per_prompt, 149 | do_classifier_free_guidance, 150 | ): 151 | image = image.to(device=device) 152 | image_latents = self.vae.encode(image).latent_dist.mode() 153 | 154 | if do_classifier_free_guidance: 155 | negative_image_latents = torch.zeros_like(image_latents) 156 | 157 | # For classifier free guidance, we need to do two forward passes. 158 | # Here we concatenate the unconditional and text embeddings into a single batch 159 | # to avoid doing two forward passes 160 | image_latents = torch.cat([negative_image_latents, image_latents, image_latents]) 161 | 162 | # duplicate image_latents for each generation per prompt, using mps friendly method 163 | image_latents = image_latents.repeat(num_videos_per_prompt, 1, 1, 1) 164 | 165 | return image_latents 166 | 167 | def _get_add_time_ids( 168 | self, 169 | fps, 170 | motion_bucket_id, 171 | noise_aug_strength, 172 | dtype, 173 | batch_size, 174 | num_videos_per_prompt, 175 | do_classifier_free_guidance, 176 | ): 177 | add_time_ids = [fps, motion_bucket_id, noise_aug_strength] 178 | 179 | passed_add_embed_dim = self.unet.config.addition_time_embed_dim * len(add_time_ids) 180 | expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features 181 | 182 | if expected_add_embed_dim != passed_add_embed_dim: 183 | raise ValueError( 184 | f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`." 185 | ) 186 | 187 | add_time_ids = torch.tensor([add_time_ids], dtype=dtype) 188 | add_time_ids = add_time_ids.repeat(batch_size * num_videos_per_prompt, 1) 189 | 190 | if do_classifier_free_guidance: 191 | add_time_ids = torch.cat([add_time_ids, add_time_ids, add_time_ids]) 192 | 193 | return add_time_ids 194 | 195 | def decode_latents(self, latents, num_frames, decode_chunk_size=14): 196 | # [batch, frames, channels, height, width] -> [batch*frames, channels, height, width] 197 | latents = latents.flatten(0, 1) 198 | 199 | latents = 1 / self.vae.config.scaling_factor * latents 200 | 201 | forward_vae_fn = self.vae._orig_mod.forward if is_compiled_module(self.vae) else self.vae.forward 202 | accepts_num_frames = "num_frames" in set(inspect.signature(forward_vae_fn).parameters.keys()) 203 | 204 | # decode decode_chunk_size frames at a time to avoid OOM 205 | frames = [] 206 | for i in range(0, latents.shape[0], decode_chunk_size): 207 | num_frames_in = latents[i : i + decode_chunk_size].shape[0] 208 | decode_kwargs = {} 209 | if accepts_num_frames: 210 | # we only pass num_frames_in if it's expected 211 | decode_kwargs["num_frames"] = num_frames_in 212 | 213 | frame = self.vae.decode(latents[i : i + decode_chunk_size], **decode_kwargs).sample 214 | frames.append(frame) 215 | frames = torch.cat(frames, dim=0) 216 | 217 | # [batch*frames, channels, height, width] -> [batch, channels, frames, height, width] 218 | frames = frames.reshape(-1, num_frames, *frames.shape[1:]).permute(0, 2, 1, 3, 4) 219 | 220 | # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 221 | frames = frames.float() 222 | return frames 223 | 224 | def check_inputs(self, image, height, width): 225 | if ( 226 | not isinstance(image, torch.Tensor) 227 | and not isinstance(image, PIL.Image.Image) 228 | and not isinstance(image, list) 229 | ): 230 | raise ValueError( 231 | "`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is" 232 | f" {type(image)}" 233 | ) 234 | 235 | if height % 8 != 0 or width % 8 != 0: 236 | raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") 237 | 238 | def prepare_latents( 239 | self, 240 | batch_size, 241 | num_frames, 242 | num_channels_latents, 243 | height, 244 | width, 245 | dtype, 246 | device, 247 | generator, 248 | latents=None, 249 | ref_image_latents=None, 250 | timestep=None 251 | ): 252 | shape = ( 253 | batch_size, 254 | num_frames, 255 | num_channels_latents // 2, 256 | height // self.vae_scale_factor, 257 | width // self.vae_scale_factor, 258 | ) 259 | if isinstance(generator, list) and len(generator) != batch_size: 260 | raise ValueError( 261 | f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" 262 | f" size of {batch_size}. Make sure the batch size matches the length of the generators." 263 | ) 264 | 265 | if latents is None: 266 | noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) 267 | else: 268 | noise = latents.to(device) 269 | 270 | # scale the initial noise by the standard deviation required by the scheduler 271 | if timestep is not None: 272 | init_latents = ref_image_latents.unsqueeze(1) 273 | latents = self.scheduler.add_noise(init_latents, noise, timestep) 274 | else: 275 | latents = noise * self.scheduler.init_noise_sigma 276 | return latents 277 | 278 | def get_timesteps(self, num_inference_steps, strength, device): 279 | # get the original timestep using init_timestep 280 | init_timestep = min(int(num_inference_steps * strength), num_inference_steps) 281 | 282 | t_start = max(num_inference_steps - init_timestep, 0) 283 | timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] 284 | 285 | return timesteps, num_inference_steps - t_start 286 | 287 | @property 288 | def guidance_scale1(self): 289 | return self._guidance_scale1 290 | 291 | @property 292 | def guidance_scale2(self): 293 | return self._guidance_scale2 294 | 295 | # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) 296 | # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` 297 | # corresponds to doing no classifier free guidance. 298 | @property 299 | def do_classifier_free_guidance(self): 300 | return True 301 | 302 | @property 303 | def num_timesteps(self): 304 | return self._num_timesteps 305 | 306 | @torch.no_grad() 307 | def __call__( 308 | self, 309 | ref_image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 310 | clip_image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 311 | pose_images: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 312 | audio_prompts: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 313 | uncond_audio_prompts: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 314 | emo_prompts: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 315 | uncond_emo_prompts: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor], 316 | height: int = 576, 317 | width: int = 1024, 318 | num_frames: Optional[int] = None, 319 | num_inference_steps: int = 25, 320 | min_guidance_scale1=1.0, # 1.0, 321 | max_guidance_scale1=3.0, 322 | min_guidance_scale2=1.0, # 1.0, 323 | max_guidance_scale2=3.0, 324 | fps: int = 7, 325 | motion_bucket_id: int = 127, 326 | motion_bucket_id_exp: int = 127, 327 | noise_aug_strength: int = 0.02, 328 | decode_chunk_size: Optional[int] = None, 329 | num_videos_per_prompt: Optional[int] = 1, 330 | generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, 331 | latents: Optional[torch.FloatTensor] = None, 332 | output_type: Optional[str] = "pil", 333 | callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None, 334 | callback_on_step_end_tensor_inputs: List[str] = ["latents"], 335 | return_dict: bool = True, 336 | overlap=7, 337 | shift_offset=3, 338 | frames_per_batch=14, 339 | i2i_noise_strength=1.0, 340 | ): 341 | r""" 342 | The call function to the pipeline for generation. 343 | 344 | Args: 345 | image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`): 346 | Image or images to guide image generation. If you provide a tensor, it needs to be compatible with 347 | [`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json). 348 | height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): 349 | The height in pixels of the generated image. 350 | width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): 351 | The width in pixels of the generated image. 352 | num_frames (`int`, *optional*): 353 | The number of video frames to generate. Defaults to 14 for `stable-video-diffusion-img2vid` and to 25 for `stable-video-diffusion-img2vid-xt` 354 | num_inference_steps (`int`, *optional*, defaults to 25): 355 | The number of denoising steps. More denoising steps usually lead to a higher quality image at the 356 | expense of slower inference. This parameter is modulated by `strength`. 357 | min_guidance_scale (`float`, *optional*, defaults to 1.0): 358 | The minimum guidance scale. Used for the classifier free guidance with first frame. 359 | max_guidance_scale (`float`, *optional*, defaults to 3.0): 360 | The maximum guidance scale. Used for the classifier free guidance with last frame. 361 | fps (`int`, *optional*, defaults to 7): 362 | Frames per second. The rate at which the generated images shall be exported to a video after generation. 363 | Note that Stable Diffusion Video's UNet was micro-conditioned on fps-1 during training. 364 | motion_bucket_id (`int`, *optional*, defaults to 127): 365 | The motion bucket ID. Used as conditioning for the generation. The higher the number the more motion will be in the video. 366 | noise_aug_strength (`int`, *optional*, defaults to 0.02): 367 | The amount of noise added to the init image, the higher it is the less the video will look like the init image. Increase it for more motion. 368 | decode_chunk_size (`int`, *optional*): 369 | The number of frames to decode at a time. The higher the chunk size, the higher the temporal consistency 370 | between frames, but also the higher the memory consumption. By default, the decoder will decode all frames at once 371 | for maximal quality. Reduce `decode_chunk_size` to reduce memory usage. 372 | num_videos_per_prompt (`int`, *optional*, defaults to 1): 373 | The number of images to generate per prompt. 374 | generator (`torch.Generator` or `List[torch.Generator]`, *optional*): 375 | A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make 376 | generation deterministic. 377 | latents (`torch.FloatTensor`, *optional*): 378 | Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image 379 | generation. Can be used to tweak the same generation with different prompts. If not provided, a latents 380 | tensor is generated by sampling using the supplied random `generator`. 381 | output_type (`str`, *optional*, defaults to `"pil"`): 382 | The output format of the generated image. Choose between `PIL.Image` or `np.array`. 383 | callback_on_step_end (`Callable`, *optional*): 384 | A function that calls at the end of each denoising steps during the inference. The function is called 385 | with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, 386 | callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by 387 | `callback_on_step_end_tensor_inputs`. 388 | callback_on_step_end_tensor_inputs (`List`, *optional*): 389 | The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list 390 | will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the 391 | `._callback_tensor_inputs` attribute of your pipeline class. 392 | return_dict (`bool`, *optional*, defaults to `True`): 393 | Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a 394 | plain tuple. 395 | 396 | Returns: 397 | [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] or `tuple`: 398 | If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] is returned, 399 | otherwise a `tuple` is returned where the first element is a list of list with the generated frames. 400 | 401 | Examples: 402 | 403 | ```py 404 | from diffusers import StableVideoDiffusionPipeline 405 | from diffusers.utils import load_image, export_to_video 406 | 407 | pipe = StableVideoDiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16") 408 | pipe.to("cuda") 409 | 410 | image = load_image("https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200") 411 | image = image.resize((1024, 576)) 412 | 413 | frames = pipe(image, num_frames=25, decode_chunk_size=8).frames[0] 414 | export_to_video(frames, "generated.mp4", fps=7) 415 | ``` 416 | """ 417 | # 0. Default height and width to unet 418 | height = height or self.unet.config.sample_size * self.vae_scale_factor 419 | width = width or self.unet.config.sample_size * self.vae_scale_factor 420 | 421 | 422 | num_frames = num_frames if num_frames is not None else self.unet.config.num_frames 423 | decode_chunk_size = decode_chunk_size if decode_chunk_size is not None else num_frames 424 | 425 | # 1. Check inputs. Raise error if not correct 426 | self.check_inputs(ref_image, height, width) 427 | 428 | # 2. Define call parameters 429 | if isinstance(ref_image, PIL.Image.Image): 430 | batch_size = 1 431 | elif isinstance(ref_image, list): 432 | batch_size = len(ref_image) 433 | else: 434 | batch_size = ref_image.shape[0] 435 | 436 | device = self._execution_device 437 | # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) 438 | # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` 439 | # corresponds to doing no classifier free guidance. 440 | do_classifier_free_guidance = True 441 | 442 | # 3. Prepare clip image embeds 443 | image_embeddings, audio_prompts, emo_prompts = self._clip_encode_image( 444 | clip_image, 445 | audio_prompts, 446 | uncond_audio_prompts, 447 | emo_prompts, 448 | uncond_emo_prompts, 449 | num_frames + frames_per_batch, 450 | device, 451 | num_videos_per_prompt, 452 | do_classifier_free_guidance, 453 | frames_per_batch) 454 | 455 | # NOTE: Stable Diffusion Video was conditioned on fps - 1, which 456 | # is why it is reduced here. 457 | # See: https://github.com/Stability-AI/generative-models/blob/ed0997173f98eaf8f4edf7ba5fe8f15c6b877fd3/scripts/sampling/simple_video_sample.py#L188 458 | # fps = fps - 1 459 | 460 | # 4. Encode input image using VAE 461 | needs_upcasting = (self.vae.dtype == torch.float16 or self.vae.dtype == torch.bfloat16) and self.vae.config.force_upcast 462 | vae_dtype = self.vae.dtype 463 | if needs_upcasting: 464 | self.vae.to(dtype=torch.float32) 465 | 466 | # Prepare ref image latents 467 | ref_image_tensor = ref_image.to( 468 | dtype=self.vae.dtype, device=self.vae.device 469 | ) 470 | 471 | ref_image_latents = self.vae.encode(ref_image_tensor).latent_dist.mean 472 | ref_image_latents = ref_image_latents * 0.18215 # (b, 4, h, w) 473 | 474 | noise = randn_tensor( 475 | ref_image_tensor.shape, 476 | generator=generator, 477 | device=self.vae.device, 478 | dtype=self.vae.dtype) 479 | 480 | ref_image_tensor = ref_image_tensor + noise_aug_strength * noise 481 | 482 | image_latents = self._encode_vae_image( 483 | ref_image_tensor, 484 | device=device, 485 | num_videos_per_prompt=num_videos_per_prompt, 486 | do_classifier_free_guidance=do_classifier_free_guidance, 487 | ) 488 | image_latents = image_latents.to(image_embeddings.dtype) 489 | ref_image_latents = ref_image_latents.to(image_embeddings.dtype) 490 | 491 | # cast back to fp16 if needed 492 | if needs_upcasting: 493 | self.vae.to(dtype=vae_dtype) 494 | 495 | # Repeat the image latents for each frame so we can concatenate them with the noise 496 | # image_latents [batch, channels, height, width] ->[batch, num_frames, channels, height, width] 497 | image_latents = image_latents.unsqueeze(1).repeat(1, num_frames + frames_per_batch, 1, 1, 1) 498 | 499 | 500 | # 5. Get Added Time IDs 501 | added_time_ids = self._get_add_time_ids( 502 | fps, 503 | motion_bucket_id, 504 | motion_bucket_id_exp, 505 | image_embeddings.dtype, 506 | batch_size, 507 | num_videos_per_prompt, 508 | do_classifier_free_guidance, 509 | ) 510 | added_time_ids = added_time_ids.to(device, dtype=self.unet.dtype) 511 | # import pdb;pdb.set_trace() 512 | 513 | # 4. Prepare timesteps 514 | self.scheduler.set_timesteps(num_inference_steps, device=device) 515 | timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, i2i_noise_strength, device) 516 | latent_timestep = timesteps[:1].repeat(batch_size * num_videos_per_prompt) 517 | 518 | 519 | # 5. Prepare latent variables 520 | num_channels_latents = self.unet.config.in_channels 521 | latents = self.prepare_latents( 522 | batch_size * num_videos_per_prompt, 523 | num_frames + frames_per_batch, 524 | num_channels_latents, 525 | height, 526 | width, 527 | image_embeddings.dtype, 528 | device, 529 | generator, 530 | latents, 531 | ref_image_latents, 532 | timestep=latent_timestep 533 | ) 534 | 535 | # Prepare a list of pose condition images 536 | pose_cond_tensor_list = [] 537 | for pose_image in pose_images: 538 | pose_cond_tensor = pose_image.unsqueeze(0) 539 | pose_cond_tensor = pose_cond_tensor.unsqueeze(2) # (bs, c, 1, h, w) 540 | pose_cond_tensor_list.append(pose_cond_tensor) 541 | 542 | for _ in range(frames_per_batch): 543 | pose_cond_tensor_list.append(pose_cond_tensor) 544 | 545 | pose_cond_tensor = torch.cat(pose_cond_tensor_list, dim=2) # (bs, c, t, h, w) 546 | pose_cond_tensor = pose_cond_tensor.to( 547 | device=device, dtype=self.pose_guider.dtype 548 | ) 549 | face_mask = pose_cond_tensor[0, :1, :1] 550 | # print(pose_cond_tensor.shape) 551 | 552 | pose_fea = self.pose_guider(pose_cond_tensor).transpose( 553 | 1, 2 554 | ) # (bs, f, c, H, W) 555 | 556 | # 7. Prepare guidance scale 557 | guidance_scale = torch.linspace( 558 | min_guidance_scale1, 559 | max_guidance_scale1, 560 | num_inference_steps) 561 | guidance_scale1 = guidance_scale.to(device, latents.dtype) 562 | 563 | guidance_scale = torch.linspace( 564 | min_guidance_scale2, 565 | max_guidance_scale2, 566 | num_inference_steps) 567 | guidance_scale2 = guidance_scale.to(device, latents.dtype) 568 | 569 | # print(guidance_scale) 570 | 571 | self._guidance_scale1 = guidance_scale1 572 | self._guidance_scale2 = guidance_scale2 573 | 574 | # 8. Denoising loop 575 | latents_all = latents # for any-frame generation 576 | 577 | num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order 578 | self._num_timesteps = len(timesteps) 579 | shift = 0 580 | with self.progress_bar(total=num_inference_steps) as progress_bar: 581 | for i, t in enumerate(timesteps): 582 | 583 | # init 584 | pred_latents = torch.zeros_like( 585 | latents_all, 586 | dtype=self.unet.dtype, 587 | ) 588 | counter = torch.zeros( 589 | (latents_all.shape[0], num_frames+frames_per_batch, 1, 1, 1), 590 | dtype=self.unet.dtype, 591 | ).to(device=latents_all.device) 592 | # print(t) 593 | 594 | for batch, index_start in enumerate(range(0, num_frames+frames_per_batch, frames_per_batch - overlap)): 595 | self.scheduler._step_index = None 596 | index_start -= shift 597 | # print(index_start) 598 | def indice_slice(tensor, idx_list): 599 | tensor_list = [] 600 | for idx in idx_list: 601 | idx = idx % tensor.shape[1] 602 | tensor_list.append(tensor[:,idx]) 603 | return torch.stack(tensor_list, 1) 604 | idx_list = list(range(index_start, index_start+frames_per_batch)) 605 | latents = indice_slice(latents_all, idx_list) 606 | pose_cond_fea = indice_slice(pose_fea, idx_list) 607 | image_latents_input = indice_slice(image_latents, idx_list) 608 | batch_image_embeddings = indice_slice(image_embeddings, idx_list) 609 | batch_audio_prompts = indice_slice(audio_prompts, idx_list) 610 | # import pdb;pdb.set_trace() 611 | 612 | batch_emo_prompts = indice_slice(emo_prompts, idx_list) 613 | # import pdb;pdb.set_trace() 614 | 615 | cross_attention_kwargs = {'ip_adapter_masks': [face_mask]*2} 616 | latent_model_input = torch.cat([latents] * 3) if do_classifier_free_guidance else latents 617 | latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) 618 | pose_cond_fea = pose_cond_fea.repeat(3 if do_classifier_free_guidance else 1, 1, 1, 1, 1) 619 | # latent_model_input = torch.cat([latents] * 4) if do_classifier_free_guidance else latents 620 | # latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) 621 | # pose_cond_fea = pose_cond_fea.repeat(4 if do_classifier_free_guidance else 1, 1, 1, 1, 1) 622 | # import ipdb;ipdb.set_trace() 623 | # Concatenate image_latents over channels dimention 624 | latent_model_input = torch.cat([ 625 | latent_model_input, 626 | image_latents_input], dim=2) 627 | # predict the noise residual 628 | noise_pred = self.unet( 629 | latent_model_input, 630 | t, 631 | encoder_hidden_states=(batch_image_embeddings.flatten(0,1), [batch_audio_prompts.flatten(0,1)] + [batch_emo_prompts.flatten(0,1)]), 632 | spatial_condition=pose_cond_fea, 633 | cross_attention_kwargs=cross_attention_kwargs, 634 | added_time_ids=added_time_ids, 635 | return_dict=False, 636 | )[0] 637 | # perform guidance 638 | # import ipdb;ipdb.set_trace() 639 | if do_classifier_free_guidance: 640 | noise_pred_uncond, noise_pred_drop_audio, noise_pred_cond = noise_pred.chunk(3) 641 | noise_pred = noise_pred_uncond + self.guidance_scale1[i] * (noise_pred_drop_audio - noise_pred_uncond) \ 642 | + self.guidance_scale2[i] * (noise_pred_cond - noise_pred_drop_audio) 643 | 644 | # compute the previous noisy sample x_t -> x_t-1 645 | latents = self.scheduler.step(noise_pred, t.to(self.unet.dtype), latents).prev_sample 646 | 647 | if callback_on_step_end is not None: 648 | callback_kwargs = {} 649 | for k in callback_on_step_end_tensor_inputs: 650 | callback_kwargs[k] = locals()[k] 651 | callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) 652 | 653 | latents = callback_outputs.pop("latents", latents) 654 | 655 | # if batch == 0: 656 | for iii in range(frames_per_batch): 657 | p = (index_start + iii) % pred_latents.shape[1] 658 | pred_latents[:, p] += latents[:, iii] 659 | counter[:, p] += 1 660 | shift += shift_offset 661 | shift = shift % frames_per_batch 662 | 663 | pred_latents = pred_latents / counter 664 | latents_all = pred_latents 665 | 666 | if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): 667 | progress_bar.update() 668 | 669 | latents = latents_all 670 | if not output_type == "latent": 671 | # cast back to fp16 if needed 672 | if needs_upcasting: 673 | self.vae.to(dtype=vae_dtype) 674 | frames = self.decode_latents(latents, num_frames + frames_per_batch, decode_chunk_size)[:,:,:num_frames] 675 | else: 676 | frames = latents 677 | 678 | self.maybe_free_model_hooks() 679 | 680 | if not return_dict: 681 | return frames 682 | return Pose2VideoSVDPipelineOutput(frames=frames) 683 | 684 | 685 | -------------------------------------------------------------------------------- /src/utils/RIFE/IFNet_HDv3.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from .warplayer import warp 5 | 6 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 7 | 8 | def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): 9 | return nn.Sequential( 10 | nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, 11 | padding=padding, dilation=dilation, bias=True), 12 | nn.PReLU(out_planes) 13 | ) 14 | 15 | def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): 16 | return nn.Sequential( 17 | nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, 18 | padding=padding, dilation=dilation, bias=False), 19 | nn.BatchNorm2d(out_planes), 20 | nn.PReLU(out_planes) 21 | ) 22 | 23 | class IFBlock(nn.Module): 24 | def __init__(self, in_planes, c=64): 25 | super(IFBlock, self).__init__() 26 | self.conv0 = nn.Sequential( 27 | conv(in_planes, c//2, 3, 2, 1), 28 | conv(c//2, c, 3, 2, 1), 29 | ) 30 | self.convblock0 = nn.Sequential( 31 | conv(c, c), 32 | conv(c, c) 33 | ) 34 | self.convblock1 = nn.Sequential( 35 | conv(c, c), 36 | conv(c, c) 37 | ) 38 | self.convblock2 = nn.Sequential( 39 | conv(c, c), 40 | conv(c, c) 41 | ) 42 | self.convblock3 = nn.Sequential( 43 | conv(c, c), 44 | conv(c, c) 45 | ) 46 | self.conv1 = nn.Sequential( 47 | nn.ConvTranspose2d(c, c//2, 4, 2, 1), 48 | nn.PReLU(c//2), 49 | nn.ConvTranspose2d(c//2, 4, 4, 2, 1), 50 | ) 51 | self.conv2 = nn.Sequential( 52 | nn.ConvTranspose2d(c, c//2, 4, 2, 1), 53 | nn.PReLU(c//2), 54 | nn.ConvTranspose2d(c//2, 1, 4, 2, 1), 55 | ) 56 | 57 | def forward(self, x, flow, scale=1): 58 | x = F.interpolate(x, scale_factor= 1. / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) 59 | flow = F.interpolate(flow, scale_factor= 1. / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 1. / scale 60 | feat = self.conv0(torch.cat((x, flow), 1)) 61 | feat = self.convblock0(feat) + feat 62 | feat = self.convblock1(feat) + feat 63 | feat = self.convblock2(feat) + feat 64 | feat = self.convblock3(feat) + feat 65 | flow = self.conv1(feat) 66 | mask = self.conv2(feat) 67 | flow = F.interpolate(flow, scale_factor=scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) * scale 68 | mask = F.interpolate(mask, scale_factor=scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) 69 | return flow, mask 70 | 71 | class IFNet(nn.Module): 72 | def __init__(self): 73 | super(IFNet, self).__init__() 74 | self.block0 = IFBlock(7+4, c=90) 75 | self.block1 = IFBlock(7+4, c=90) 76 | self.block2 = IFBlock(7+4, c=90) 77 | self.block_tea = IFBlock(10+4, c=90) 78 | # self.contextnet = Contextnet() 79 | # self.unet = Unet() 80 | 81 | def forward(self, x, scale_list=[4, 2, 1], training=False): 82 | if training == False: 83 | channel = x.shape[1] // 2 84 | img0 = x[:, :channel] 85 | img1 = x[:, channel:] 86 | flow_list = [] 87 | merged = [] 88 | mask_list = [] 89 | warped_img0 = img0 90 | warped_img1 = img1 91 | flow = (x[:, :4]).detach() * 0 92 | mask = (x[:, :1]).detach() * 0 93 | loss_cons = 0 94 | block = [self.block0, self.block1, self.block2] 95 | for i in range(3): 96 | f0, m0 = block[i](torch.cat((warped_img0[:, :3], warped_img1[:, :3], mask), 1), flow, scale=scale_list[i]) 97 | f1, m1 = block[i](torch.cat((warped_img1[:, :3], warped_img0[:, :3], -mask), 1), torch.cat((flow[:, 2:4], flow[:, :2]), 1), scale=scale_list[i]) 98 | flow = flow + (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2 99 | mask = mask + (m0 + (-m1)) / 2 100 | mask_list.append(mask) 101 | flow_list.append(flow) 102 | warped_img0 = warp(img0, flow[:, :2]) 103 | warped_img1 = warp(img1, flow[:, 2:4]) 104 | merged.append((warped_img0, warped_img1)) 105 | ''' 106 | c0 = self.contextnet(img0, flow[:, :2]) 107 | c1 = self.contextnet(img1, flow[:, 2:4]) 108 | tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1) 109 | res = tmp[:, 1:4] * 2 - 1 110 | ''' 111 | for i in range(3): 112 | mask_list[i] = torch.sigmoid(mask_list[i]) 113 | merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i]) 114 | # merged[i] = torch.clamp(merged[i] + res, 0, 1) 115 | return flow_list, mask_list[2], merged 116 | -------------------------------------------------------------------------------- /src/utils/RIFE/RIFE_HDv3.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from .IFNet_HDv3 import * 3 | import torch.nn.functional as F 4 | 5 | class RIFEModel: 6 | def __init__(self, device=None): 7 | if device is None: 8 | self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 9 | else: 10 | self.device = device 11 | self.flownet = IFNet().to(self.device).eval() 12 | 13 | def train(self): 14 | self.flownet.train() 15 | 16 | def eval(self): 17 | self.flownet.eval() 18 | 19 | 20 | def load_model(self, path, rank=-1): 21 | def convert(param): 22 | if rank == -1: 23 | return { 24 | k.replace("module.", ""): v 25 | for k, v in param.items() 26 | if "module." in k 27 | } 28 | else: 29 | return param 30 | self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path), map_location ='cpu'))) 31 | 32 | 33 | def inference(self, img0, img1, scale=1.0): 34 | imgs = torch.cat((img0, img1), 1) 35 | scale_list = [4/scale, 2/scale, 1/scale] 36 | flow, mask, merged = self.flownet(imgs, scale_list) 37 | return merged[2] -------------------------------------------------------------------------------- /src/utils/RIFE/warplayer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | backwarp_tenGrid = {} 5 | 6 | 7 | def warp(tenInput, tenFlow): 8 | device = tenFlow.device 9 | k = (str(tenFlow.device), str(tenFlow.size())) 10 | if k not in backwarp_tenGrid: 11 | tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device).view( 12 | 1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1) 13 | tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device).view( 14 | 1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3]) 15 | backwarp_tenGrid[k] = torch.cat( 16 | [tenHorizontal, tenVertical], 1).to(device) 17 | 18 | tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), 19 | tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1) 20 | 21 | g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1) 22 | return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True) 23 | -------------------------------------------------------------------------------- /src/utils/face_align/align.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 4 | sys.path.append(BASE_DIR) 5 | import torch 6 | from src.utils.face_align.yoloface import YoloFace 7 | 8 | class AlignImage(object): 9 | def __init__(self, device='cuda', det_path='checkpoints/yoloface_v5m.pt'): 10 | self.facedet = YoloFace(pt_path=det_path, confThreshold=0.5, nmsThreshold=0.45, device=device) 11 | 12 | @torch.no_grad() 13 | def __call__(self, im, maxface=False): 14 | bboxes, kpss, scores = self.facedet.detect(im) 15 | face_num = bboxes.shape[0] 16 | 17 | five_pts_list = [] 18 | scores_list = [] 19 | bboxes_list = [] 20 | for i in range(face_num): 21 | five_pts_list.append(kpss[i].reshape(5,2)) 22 | scores_list.append(scores[i]) 23 | bboxes_list.append(bboxes[i]) 24 | 25 | if maxface and face_num>1: 26 | max_idx = 0 27 | max_area = (bboxes[0, 2])*(bboxes[0, 3]) 28 | for i in range(1, face_num): 29 | area = (bboxes[i,2])*(bboxes[i,3]) 30 | if area>max_area: 31 | max_idx = i 32 | five_pts_list = [five_pts_list[max_idx]] 33 | scores_list = [scores_list[max_idx]] 34 | bboxes_list = [bboxes_list[max_idx]] 35 | 36 | return five_pts_list, scores_list, bboxes_list -------------------------------------------------------------------------------- /src/utils/face_align/yoloface.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | import os 3 | import cv2 4 | import numpy as np 5 | import torch 6 | import torchvision 7 | 8 | 9 | def xyxy2xywh(x): 10 | # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right 11 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) 12 | y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center 13 | y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center 14 | y[:, 2] = x[:, 2] - x[:, 0] # width 15 | y[:, 3] = x[:, 3] - x[:, 1] # height 16 | return y 17 | 18 | 19 | def xywh2xyxy(x): 20 | # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right 21 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) 22 | y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x 23 | y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y 24 | y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x 25 | y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y 26 | return y 27 | 28 | 29 | def box_iou(box1, box2): 30 | # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py 31 | """ 32 | Return intersection-over-union (Jaccard index) of boxes. 33 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 34 | Arguments: 35 | box1 (Tensor[N, 4]) 36 | box2 (Tensor[M, 4]) 37 | Returns: 38 | iou (Tensor[N, M]): the NxM matrix containing the pairwise 39 | IoU values for every element in boxes1 and boxes2 40 | """ 41 | 42 | def box_area(box): 43 | # box = 4xn 44 | return (box[2] - box[0]) * (box[3] - box[1]) 45 | 46 | area1 = box_area(box1.T) 47 | area2 = box_area(box2.T) 48 | 49 | # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) 50 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - 51 | torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 52 | # iou = inter / (area1 + area2 - inter) 53 | return inter / (area1[:, None] + area2 - inter) 54 | 55 | 56 | def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): 57 | # Rescale coords (xyxy) from img1_shape to img0_shape 58 | if ratio_pad is None: # calculate from img0_shape 59 | gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new 60 | pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding 61 | else: 62 | gain = ratio_pad[0][0] 63 | pad = ratio_pad[1] 64 | 65 | coords[:, [0, 2]] -= pad[0] # x padding 66 | coords[:, [1, 3]] -= pad[1] # y padding 67 | coords[:, :4] /= gain 68 | clip_coords(coords, img0_shape) 69 | return coords 70 | 71 | 72 | def clip_coords(boxes, img_shape): 73 | # Clip bounding xyxy bounding boxes to image shape (height, width) 74 | boxes[:, 0].clamp_(0, img_shape[1]) # x1 75 | boxes[:, 1].clamp_(0, img_shape[0]) # y1 76 | boxes[:, 2].clamp_(0, img_shape[1]) # x2 77 | boxes[:, 3].clamp_(0, img_shape[0]) # y2 78 | 79 | 80 | def scale_coords_landmarks(img1_shape, coords, img0_shape, ratio_pad=None): 81 | # Rescale coords (xyxy) from img1_shape to img0_shape 82 | if ratio_pad is None: # calculate from img0_shape 83 | gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new 84 | pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding 85 | else: 86 | gain = ratio_pad[0][0] 87 | pad = ratio_pad[1] 88 | 89 | coords[:, [0, 2, 4, 6, 8]] -= pad[0] # x padding 90 | coords[:, [1, 3, 5, 7, 9]] -= pad[1] # y padding 91 | coords[:, :10] /= gain 92 | #clip_coords(coords, img0_shape) 93 | coords[:, 0].clamp_(0, img0_shape[1]) # x1 94 | coords[:, 1].clamp_(0, img0_shape[0]) # y1 95 | coords[:, 2].clamp_(0, img0_shape[1]) # x2 96 | coords[:, 3].clamp_(0, img0_shape[0]) # y2 97 | coords[:, 4].clamp_(0, img0_shape[1]) # x3 98 | coords[:, 5].clamp_(0, img0_shape[0]) # y3 99 | coords[:, 6].clamp_(0, img0_shape[1]) # x4 100 | coords[:, 7].clamp_(0, img0_shape[0]) # y4 101 | coords[:, 8].clamp_(0, img0_shape[1]) # x5 102 | coords[:, 9].clamp_(0, img0_shape[0]) # y5 103 | return coords 104 | 105 | 106 | def show_results(img, xywh, conf, landmarks, class_num): 107 | h,w,c = img.shape 108 | tl = 1 or round(0.002 * (h + w) / 2) + 1 # line/font thickness 109 | x1 = int(xywh[0] * w - 0.5 * xywh[2] * w) 110 | y1 = int(xywh[1] * h - 0.5 * xywh[3] * h) 111 | x2 = int(xywh[0] * w + 0.5 * xywh[2] * w) 112 | y2 = int(xywh[1] * h + 0.5 * xywh[3] * h) 113 | cv2.rectangle(img, (x1,y1), (x2, y2), (0,255,0), thickness=tl, lineType=cv2.LINE_AA) 114 | 115 | clors = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(0,255,255)] 116 | 117 | for i in range(5): 118 | point_x = int(landmarks[2 * i] * w) 119 | point_y = int(landmarks[2 * i + 1] * h) 120 | cv2.circle(img, (point_x, point_y), tl+1, clors[i], -1) 121 | 122 | tf = max(tl - 1, 1) # font thickness 123 | label = str(conf)[:5] 124 | cv2.putText(img, label, (x1, y1 - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) 125 | return img 126 | 127 | 128 | def make_divisible(x, divisor): 129 | # Returns x evenly divisible by divisor 130 | return (x // divisor) * divisor 131 | 132 | 133 | def non_max_suppression_face(prediction, conf_thres=0.5, iou_thres=0.45, classes=None, agnostic=False, labels=()): 134 | """Performs Non-Maximum Suppression (NMS) on inference results 135 | Returns: 136 | detections with shape: nx6 (x1, y1, x2, y2, conf, cls) 137 | """ 138 | 139 | nc = prediction.shape[2] - 15 # number of classes 140 | xc = prediction[..., 4] > conf_thres # candidates 141 | 142 | # Settings 143 | min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height 144 | # time_limit = 10.0 # seconds to quit after 145 | redundant = True # require redundant detections 146 | multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img) 147 | merge = False # use merge-NMS 148 | 149 | # t = time.time() 150 | output = [torch.zeros((0, 16), device=prediction.device)] * prediction.shape[0] 151 | for xi, x in enumerate(prediction): # image index, image inference 152 | # Apply constraints 153 | # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height 154 | x = x[xc[xi]] # confidence 155 | 156 | # Cat apriori labels if autolabelling 157 | if labels and len(labels[xi]): 158 | l = labels[xi] 159 | v = torch.zeros((len(l), nc + 15), device=x.device) 160 | v[:, :4] = l[:, 1:5] # box 161 | v[:, 4] = 1.0 # conf 162 | v[range(len(l)), l[:, 0].long() + 15] = 1.0 # cls 163 | x = torch.cat((x, v), 0) 164 | 165 | # If none remain process next image 166 | if not x.shape[0]: 167 | continue 168 | 169 | # Compute conf 170 | x[:, 15:] *= x[:, 4:5] # conf = obj_conf * cls_conf 171 | 172 | # Box (center x, center y, width, height) to (x1, y1, x2, y2) 173 | box = xywh2xyxy(x[:, :4]) 174 | 175 | # Detections matrix nx6 (xyxy, conf, landmarks, cls) 176 | if multi_label: 177 | i, j = (x[:, 15:] > conf_thres).nonzero(as_tuple=False).T 178 | x = torch.cat((box[i], x[i, j + 15, None], x[i, 5:15] ,j[:, None].float()), 1) 179 | else: # best class only 180 | conf, j = x[:, 15:].max(1, keepdim=True) 181 | x = torch.cat((box, conf, x[:, 5:15], j.float()), 1)[conf.view(-1) > conf_thres] 182 | 183 | # Filter by class 184 | if classes is not None: 185 | x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] 186 | 187 | # If none remain process next image 188 | n = x.shape[0] # number of boxes 189 | if not n: 190 | continue 191 | 192 | # Batched NMS 193 | c = x[:, 15:16] * (0 if agnostic else max_wh) # classes 194 | boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores 195 | i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS 196 | #if i.shape[0] > max_det: # limit detections 197 | # i = i[:max_det] 198 | if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) 199 | # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) 200 | iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix 201 | weights = iou * scores[None] # box weights 202 | x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes 203 | if redundant: 204 | i = i[iou.sum(1) > 1] # require redundancy 205 | 206 | output[xi] = x[i] 207 | # if (time.time() - t) > time_limit: 208 | # break # time limit exceeded 209 | 210 | return output 211 | 212 | 213 | class YoloFace(): 214 | def __init__(self, pt_path='checkpoints/yolov5m-face.pt', confThreshold=0.5, nmsThreshold=0.45, device='cuda'): 215 | assert os.path.exists(pt_path) 216 | 217 | self.inpSize = 416 218 | self.conf_thres = confThreshold 219 | self.iou_thres = nmsThreshold 220 | self.test_device = torch.device(device if torch.cuda.is_available() else "cpu") 221 | self.model = torch.jit.load(pt_path).to(self.test_device) 222 | self.last_w = 416 223 | self.last_h = 416 224 | self.grids = None 225 | 226 | @torch.no_grad() 227 | def detect(self, srcimg): 228 | # t0=time.time() 229 | 230 | h0, w0 = srcimg.shape[:2] # orig hw 231 | r = self.inpSize / min(h0, w0) # resize image to img_size 232 | h1 = int(h0*r+31)//32*32 233 | w1 = int(w0*r+31)//32*32 234 | 235 | img = cv2.resize(srcimg, (w1,h1), interpolation=cv2.INTER_LINEAR) 236 | 237 | # Convert 238 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # BGR to RGB 239 | 240 | # Run inference 241 | img = torch.from_numpy(img).to(self.test_device).permute(2,0,1) 242 | img = img.float()/255 # uint8 to fp16/32 0-1 243 | if img.ndimension() == 3: 244 | img = img.unsqueeze(0) 245 | 246 | # Inference 247 | if h1 != self.last_h or w1 != self.last_w or self.grids is None: 248 | grids = [] 249 | for scale in [8,16,32]: 250 | ny = h1//scale 251 | nx = w1//scale 252 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) 253 | grid = torch.stack((xv, yv), 2).view((1,1,ny, nx, 2)).float() 254 | grids.append(grid.to(self.test_device)) 255 | self.grids = grids 256 | self.last_w = w1 257 | self.last_h = h1 258 | 259 | pred = self.model(img, self.grids).cpu() 260 | 261 | # Apply NMS 262 | det = non_max_suppression_face(pred, self.conf_thres, self.iou_thres)[0] 263 | # Process detections 264 | # det = pred[0] 265 | bboxes = np.zeros((det.shape[0], 4)) 266 | kpss = np.zeros((det.shape[0], 5, 2)) 267 | scores = np.zeros((det.shape[0])) 268 | # gn = torch.tensor([w0, h0, w0, h0]).to(pred) # normalization gain whwh 269 | # gn_lks = torch.tensor([w0, h0, w0, h0, w0, h0, w0, h0, w0, h0]).to(pred) # normalization gain landmarks 270 | det = det.cpu().numpy() 271 | 272 | for j in range(det.shape[0]): 273 | # xywh = (xyxy2xywh(det[j, :4].view(1, 4)) / gn).view(4).cpu().numpy() 274 | bboxes[j, 0] = det[j, 0] * w0/w1 275 | bboxes[j, 1] = det[j, 1] * h0/h1 276 | bboxes[j, 2] = det[j, 2] * w0/w1 - bboxes[j, 0] 277 | bboxes[j, 3] = det[j, 3] * h0/h1 - bboxes[j, 1] 278 | scores[j] = det[j, 4] 279 | # landmarks = (det[j, 5:15].view(1, 10) / gn_lks).view(5,2).cpu().numpy() 280 | kpss[j, :, :] = det[j, 5:15].reshape(5, 2) * np.array([[w0/w1,h0/h1]]) 281 | # class_num = det[j, 15].cpu().numpy() 282 | # orgimg = show_results(orgimg, xywh, conf, landmarks, class_num) 283 | return bboxes, kpss, scores 284 | 285 | 286 | 287 | if __name__ == '__main__': 288 | import time 289 | 290 | imgpath = 'test.png' 291 | 292 | yoloface = YoloFace(pt_path='../checkpoints/yoloface_v5m.pt') 293 | srcimg = cv2.imread(imgpath) 294 | 295 | #warpup 296 | bboxes, kpss, scores = yoloface.detect(srcimg) 297 | bboxes, kpss, scores = yoloface.detect(srcimg) 298 | bboxes, kpss, scores = yoloface.detect(srcimg) 299 | 300 | t1 = time.time() 301 | for _ in range(10): 302 | bboxes, kpss, scores = yoloface.detect(srcimg) 303 | t2 = time.time() 304 | print('total time: {} ms'.format((t2 - t1) * 1000)) 305 | for i in range(bboxes.shape[0]): 306 | xmin, ymin, xamx, ymax = int(bboxes[i, 0]), int(bboxes[i, 1]), int(bboxes[i, 0] + bboxes[i, 2]), int(bboxes[i, 1] + bboxes[i, 3]) 307 | cv2.rectangle(srcimg, (xmin, ymin), (xamx, ymax), (0, 0, 255), thickness=2) 308 | for j in range(5): 309 | cv2.circle(srcimg, (int(kpss[i, j, 0]), int(kpss[i, j, 1])), 1, (0, 255, 0), thickness=5) 310 | cv2.imwrite('test_yoloface.jpg', srcimg) -------------------------------------------------------------------------------- /src/utils/util.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | import os.path as osp 4 | import shutil 5 | import sys 6 | from pathlib import Path 7 | 8 | import av 9 | import numpy as np 10 | import torch 11 | import torchvision 12 | from einops import rearrange 13 | from PIL import Image 14 | import skvideo 15 | import skvideo.io 16 | import cv2 17 | 18 | 19 | class VideoUtils(object): 20 | def __init__(self, video_path=None, output_video_path=None, bit_rate='origin', fps=25): 21 | if video_path is not None: 22 | meta_data = skvideo.io.ffprobe(video_path) 23 | # avg_frame_rate = meta_data['video']['@r_frame_rate'] 24 | # a, b = avg_frame_rate.split('/') 25 | # fps = float(a) / float(b) 26 | # fps = 25 27 | codec_name = 'libx264' 28 | # codec_name = meta_data['video'].get('@codec_name') 29 | # if codec_name=='hevc': 30 | # codec_name='h264' 31 | # profile = meta_data['video'].get('@profile') 32 | color_space = meta_data['video'].get('@color_space') 33 | color_transfer = meta_data['video'].get('@color_transfer') 34 | color_primaries = meta_data['video'].get('@color_primaries') 35 | color_range = meta_data['video'].get('@color_range') 36 | pix_fmt = meta_data['video'].get('@pix_fmt') 37 | if bit_rate=='origin': 38 | bit_rate = meta_data['video'].get('@bit_rate') 39 | else: 40 | bit_rate=None 41 | if pix_fmt is None: 42 | pix_fmt = 'yuv420p' 43 | 44 | reader_output_dict = {'-r': str(fps)} 45 | writer_input_dict = {'-r': str(fps)} 46 | writer_output_dict = {'-pix_fmt': pix_fmt, '-r': str(fps), '-vcodec':str(codec_name)} 47 | # if bit_rate is not None: 48 | # writer_output_dict['-b:v'] = bit_rate 49 | writer_output_dict['-crf'] = '17' 50 | 51 | # if video has alpha channel, convert to bgra, uint16 to process 52 | if pix_fmt.startswith('yuva'): 53 | writer_input_dict['-pix_fmt'] = 'bgra64le' 54 | reader_output_dict['-pix_fmt'] = 'bgra64le' 55 | elif pix_fmt.endswith('le'): 56 | writer_input_dict['-pix_fmt'] = 'bgr48le' 57 | reader_output_dict['-pix_fmt'] = 'bgr48le' 58 | else: 59 | writer_input_dict['-pix_fmt'] = 'bgr24' 60 | reader_output_dict['-pix_fmt'] = 'bgr24' 61 | 62 | if color_range is not None: 63 | writer_output_dict['-color_range'] = color_range 64 | writer_input_dict['-color_range'] = color_range 65 | if color_space is not None: 66 | writer_output_dict['-colorspace'] = color_space 67 | writer_input_dict['-colorspace'] = color_space 68 | if color_primaries is not None: 69 | writer_output_dict['-color_primaries'] = color_primaries 70 | writer_input_dict['-color_primaries'] = color_primaries 71 | if color_transfer is not None: 72 | writer_output_dict['-color_trc'] = color_transfer 73 | writer_input_dict['-color_trc'] = color_transfer 74 | 75 | writer_output_dict['-sws_flags'] = 'full_chroma_int+bitexact+accurate_rnd' 76 | reader_output_dict['-sws_flags'] = 'full_chroma_int+bitexact+accurate_rnd' 77 | # writer_input_dict['-pix_fmt'] = 'bgr48le' 78 | # reader_output_dict = {'-pix_fmt': 'bgr48le'} 79 | 80 | # -s 1920x1080 81 | # writer_input_dict['-s'] = '1920x1080' 82 | # writer_output_dict['-s'] = '1920x1080' 83 | # writer_input_dict['-s'] = '1080x1920' 84 | # writer_output_dict['-s'] = '1080x1920' 85 | 86 | print(writer_input_dict) 87 | print(writer_output_dict) 88 | 89 | self.reader = skvideo.io.FFmpegReader(video_path, outputdict=reader_output_dict) 90 | else: 91 | 92 | # fps = 25 93 | codec_name = 'libx264' 94 | bit_rate=None 95 | pix_fmt = 'yuv420p' 96 | 97 | reader_output_dict = {'-r': str(fps)} 98 | writer_input_dict = {'-r': str(fps)} 99 | writer_output_dict = {'-pix_fmt': pix_fmt, '-r': str(fps), '-vcodec':str(codec_name)} 100 | # if bit_rate is not None: 101 | # writer_output_dict['-b:v'] = bit_rate 102 | writer_output_dict['-crf'] = '17' 103 | 104 | # if video has alpha channel, convert to bgra, uint16 to process 105 | if pix_fmt.startswith('yuva'): 106 | writer_input_dict['-pix_fmt'] = 'bgra64le' 107 | reader_output_dict['-pix_fmt'] = 'bgra64le' 108 | elif pix_fmt.endswith('le'): 109 | writer_input_dict['-pix_fmt'] = 'bgr48le' 110 | reader_output_dict['-pix_fmt'] = 'bgr48le' 111 | else: 112 | writer_input_dict['-pix_fmt'] = 'bgr24' 113 | reader_output_dict['-pix_fmt'] = 'bgr24' 114 | 115 | writer_output_dict['-sws_flags'] = 'full_chroma_int+bitexact+accurate_rnd' 116 | print(writer_input_dict) 117 | print(writer_output_dict) 118 | 119 | if output_video_path is not None: 120 | self.writer = skvideo.io.FFmpegWriter(output_video_path, inputdict=writer_input_dict, outputdict=writer_output_dict, verbosity=1) 121 | 122 | def getframes(self): 123 | return self.reader.nextFrame() 124 | 125 | def writeframe(self, frame): 126 | if frame is None: 127 | self.writer.close() 128 | else: 129 | self.writer.writeFrame(frame) 130 | 131 | def seed_everything(seed): 132 | import random 133 | 134 | import numpy as np 135 | 136 | torch.manual_seed(seed) 137 | torch.cuda.manual_seed_all(seed) 138 | np.random.seed(seed % (2**32)) 139 | random.seed(seed) 140 | 141 | 142 | def import_filename(filename): 143 | spec = importlib.util.spec_from_file_location("mymodule", filename) 144 | module = importlib.util.module_from_spec(spec) 145 | sys.modules[spec.name] = module 146 | spec.loader.exec_module(module) 147 | return module 148 | 149 | 150 | def delete_additional_ckpt(base_path, num_keep): 151 | dirs = [] 152 | for d in os.listdir(base_path): 153 | if d.startswith("checkpoint-"): 154 | dirs.append(d) 155 | num_tot = len(dirs) 156 | if num_tot <= num_keep: 157 | return 158 | # ensure ckpt is sorted and delete the ealier! 159 | del_dirs = sorted(dirs, key=lambda x: int(x.split("-")[-1]))[: num_tot - num_keep] 160 | for d in del_dirs: 161 | path_to_dir = osp.join(base_path, d) 162 | if osp.exists(path_to_dir): 163 | shutil.rmtree(path_to_dir) 164 | 165 | 166 | def save_videos_from_pil(pil_images, path, fps=8): 167 | save_fmt = Path(path).suffix 168 | os.makedirs(os.path.dirname(path), exist_ok=True) 169 | width, height = pil_images[0].size 170 | 171 | if save_fmt == ".mp4": 172 | video_cap = VideoUtils(output_video_path=path, fps=fps) 173 | for pil_image in pil_images: 174 | image_cv2 = np.array(pil_image)[:,:,[2,1,0]] 175 | video_cap.writeframe(image_cv2) 176 | video_cap.writeframe(None) 177 | 178 | elif save_fmt == ".gif": 179 | pil_images[0].save( 180 | fp=path, 181 | format="GIF", 182 | append_images=pil_images[1:], 183 | save_all=True, 184 | duration=(1 / fps * 1000), 185 | loop=0, 186 | optimize=False, 187 | lossless=True 188 | ) 189 | else: 190 | raise ValueError("Unsupported file type. Use .mp4 or .gif.") 191 | 192 | 193 | def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8): 194 | videos = rearrange(videos, "b c t h w -> t b c h w") 195 | height, width = videos.shape[-2:] 196 | outputs = [] 197 | 198 | for x in videos: 199 | x = torchvision.utils.make_grid(x, nrow=n_rows) # (c h w) 200 | x = x.transpose(0, 1).transpose(1, 2).squeeze(-1) # (h w c) 201 | if rescale: 202 | x = (x + 1.0) / 2.0 # -1,1 -> 0,1 203 | x = (x * 255).numpy().astype(np.uint8) 204 | x = Image.fromarray(x) 205 | 206 | outputs.append(x) 207 | 208 | os.makedirs(os.path.dirname(path), exist_ok=True) 209 | 210 | save_videos_from_pil(outputs, path, fps) 211 | 212 | 213 | def read_frames(video_path): 214 | container = av.open(video_path) 215 | 216 | video_stream = next(s for s in container.streams if s.type == "video") 217 | frames = [] 218 | for packet in container.demux(video_stream): 219 | for frame in packet.decode(): 220 | image = Image.frombytes( 221 | "RGB", 222 | (frame.width, frame.height), 223 | frame.to_rgb().to_ndarray(), 224 | ) 225 | frames.append(image) 226 | 227 | return frames 228 | 229 | 230 | def get_fps(video_path): 231 | container = av.open(video_path) 232 | video_stream = next(s for s in container.streams if s.type == "video") 233 | fps = video_stream.average_rate 234 | container.close() 235 | return fps 236 | --------------------------------------------------------------------------------