Francke commited on
Commit
089bec4
·
1 Parent(s): 93ac05b
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/demo1_video.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ assets/demo2_video.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ assets/demo3_video.mp4 filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LatentSync.code-workspace ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "folders": [
3
+ {
4
+ "path": "."
5
+ }
6
+ ]
7
+ }
ORIGINAL_README.md ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LatentSync: Audio Conditioned Latent Diffusion Models for Lip Sync
2
+
3
+ <div align="center">
4
+
5
+ [![arXiv](https://img.shields.io/badge/arXiv_paper-2412.09262-b31b1b)](https://arxiv.org/abs/2412.09262)
6
+
7
+ </div>
8
+
9
+ ## 📖 Abstract
10
+
11
+ We present *LatentSync*, an end-to-end lip sync framework based on audio conditioned latent diffusion models without any intermediate motion representation, diverging from previous diffusion-based lip sync methods based on pixel space diffusion or two-stage generation. Our framework can leverage the powerful capabilities of Stable Diffusion to directly model complex audio-visual correlations. Additionally, we found that the diffusion-based lip sync methods exhibit inferior temporal consistency due to the inconsistency in the diffusion process across different frames. We propose *Temporal REPresentation Alignment (TREPA)* to enhance temporal consistency while preserving lip-sync accuracy. TREPA uses temporal representations extracted by large-scale self-supervised video models to align the generated frames with the ground truth frames.
12
+
13
+ ## 🏗️ Framework
14
+
15
+ <p align="center">
16
+ <img src="assets/framework.png" width=100%>
17
+ <p>
18
+
19
+ LatentSync uses the Whisper to convert melspectrogram into audio embeddings, which are then integrated into the U-Net via cross-attention layers. The reference and masked frames are channel-wise concatenated with noised latents as the input of U-Net. In the training process, we use one-step method to get estimated clean latents from predicted noises, which are then decoded to obtain the estimated clean frames. The TREPA, LPIPS and SyncNet loss are added in the pixel space.
20
+
21
+ ## 🎬 Demo
22
+
23
+ <table class="center">
24
+ <tr style="font-weight: bolder;text-align:center;">
25
+ <td width="50%"><b>Original video</b></td>
26
+ <td width="50%"><b>Lip-synced video</b></td>
27
+ </tr>
28
+ <tr>
29
+ <td>
30
+ <video src=https://github.com/user-attachments/assets/ff3a84da-dc9b-498a-950f-5c54f58dd5c5 controls preload></video>
31
+ </td>
32
+ <td>
33
+ <video src=https://github.com/user-attachments/assets/150e00fd-381e-4421-a478-a9ea3d1212a8 controls preload></video>
34
+ </td>
35
+ </tr>
36
+ <tr>
37
+ <td>
38
+ <video src=https://github.com/user-attachments/assets/32c830a9-4d7d-4044-9b33-b184d8e11010 controls preload></video>
39
+ </td>
40
+ <td>
41
+ <video src=https://github.com/user-attachments/assets/84e4fe9d-b108-44a4-8712-13a012348145 controls preload></video>
42
+ </td>
43
+ </tr>
44
+ <tr>
45
+ <td>
46
+ <video src=https://github.com/user-attachments/assets/7510a448-255a-44ee-b093-a1b98bd3961d controls preload></video>
47
+ </td>
48
+ <td>
49
+ <video src=https://github.com/user-attachments/assets/6150c453-c559-4ae0-bb00-c565f135ff41 controls preload></video>
50
+ </td>
51
+ </tr>
52
+ <tr>
53
+ <td width=300px>
54
+ <video src=https://github.com/user-attachments/assets/0f7f9845-68b2-4165-bd08-c7bbe01a0e52 controls preload></video>
55
+ </td>
56
+ <td width=300px>
57
+ <video src=https://github.com/user-attachments/assets/c34fe89d-0c09-4de3-8601-3d01229a69e3 controls preload></video>
58
+ </td>
59
+ </tr>
60
+ <tr>
61
+ <td>
62
+ <video src=https://github.com/user-attachments/assets/7ce04d50-d39f-4154-932a-ec3a590a8f64 controls preload></video>
63
+ </td>
64
+ <td>
65
+ <video src=https://github.com/user-attachments/assets/70bde520-42fa-4a0e-b66c-d3040ae5e065 controls preload></video>
66
+ </td>
67
+ </tr>
68
+ </table>
69
+
70
+ (Photorealistic videos are filmed by contracted models, and anime videos are from [VASA-1](https://www.microsoft.com/en-us/research/project/vasa-1/) and [EMO](https://humanaigc.github.io/emote-portrait-alive/))
71
+
72
+ ## 📑 Open-source Plan
73
+
74
+ - [x] Inference code and checkpoints
75
+ - [x] Data processing pipeline
76
+ - [x] Training code
77
+
78
+ ## 🔧 Setting up the Environment
79
+
80
+ Install the required packages and download the checkpoints via:
81
+
82
+ ```bash
83
+ source setup_env.sh
84
+ ```
85
+
86
+ If the download is successful, the checkpoints should appear as follows:
87
+
88
+ ```
89
+ ./checkpoints/
90
+ |-- latentsync_unet.pt
91
+ |-- latentsync_syncnet.pt
92
+ |-- whisper
93
+ | `-- tiny.pt
94
+ |-- auxiliary
95
+ | |-- 2DFAN4-cd938726ad.zip
96
+ | |-- i3d_torchscript.pt
97
+ | |-- koniq_pretrained.pkl
98
+ | |-- s3fd-619a316812.pth
99
+ | |-- sfd_face.pth
100
+ | |-- syncnet_v2.model
101
+ | |-- vgg16-397923af.pth
102
+ | `-- vit_g_hybrid_pt_1200e_ssv2_ft.pth
103
+ ```
104
+
105
+ These already include all the checkpoints required for latentsync training and inference. If you just want to try inference, you only need to download `latentsync_unet.pt` and `tiny.pt` from our [HuggingFace repo](https://huggingface.co/chunyu-li/LatentSync)
106
+
107
+ ## 🚀 Inference
108
+
109
+ Run the script for inference, which requires about 6.5 GB GPU memory.
110
+
111
+ ```bash
112
+ ./inference.sh
113
+ ```
114
+
115
+ You can change the parameter `guidance_scale` to 1.5 to improve the lip-sync accuracy.
116
+
117
+ ## 🔄 Data Processing Pipeline
118
+
119
+ The complete data processing pipeline includes the following steps:
120
+
121
+ 1. Remove the broken video files.
122
+ 2. Resample the video FPS to 25, and resample the audio to 16000 Hz.
123
+ 3. Scene detect via [PySceneDetect](https://github.com/Breakthrough/PySceneDetect).
124
+ 4. Split each video into 5-10 second segments.
125
+ 5. Remove videos where the face is smaller than 256 $\times$ 256, as well as videos with more than one face.
126
+ 6. Affine transform the faces according to the landmarks detected by [face-alignment](https://github.com/1adrianb/face-alignment), then resize to 256 $\times$ 256.
127
+ 7. Remove videos with [sync confidence score](https://www.robots.ox.ac.uk/~vgg/publications/2016/Chung16a/chung16a.pdf) lower than 3, and adjust the audio-visual offset to 0.
128
+ 8. Calculate [hyperIQA](https://openaccess.thecvf.com/content_CVPR_2020/papers/Su_Blindly_Assess_Image_Quality_in_the_Wild_Guided_by_a_CVPR_2020_paper.pdf) score, and remove videos with scores lower than 40.
129
+
130
+ Run the script to execute the data processing pipeline:
131
+
132
+ ```bash
133
+ ./data_processing_pipeline.sh
134
+ ```
135
+
136
+ You can change the parameter `input_dir` in the script to specify the data directory to be processed. The processed data will be saved in the same directory. Each step will generate a new directory to prevent the need to redo the entire pipeline in case the process is interrupted by an unexpected error.
137
+
138
+ ## 🏋️‍♂️ Training U-Net
139
+
140
+ Before training, you must process the data as described above and download all the checkpoints. We released a pretrained SyncNet with 94% accuracy on the VoxCeleb2 dataset for the supervision of U-Net training. Note that this SyncNet is trained on affine transformed videos, so when using or evaluating this SyncNet, you need to perform affine transformation on the video first (the code of affine transformation is included in the data processing pipeline).
141
+
142
+ If all the preparations are complete, you can train the U-Net with the following script:
143
+
144
+ ```bash
145
+ ./train_unet.sh
146
+ ```
147
+
148
+ You should change the parameters in U-Net config file to specify the data directory, checkpoint save path, and other training hyperparameters.
149
+
150
+ ## 🏋️‍♂️ Training SyncNet
151
+
152
+ In case you want to train SyncNet on your own datasets, you can run the following script. The data processing pipeline for SyncNet is the same as U-Net.
153
+
154
+ ```bash
155
+ ./train_syncnet.sh
156
+ ```
157
+
158
+ After `validations_steps` training, the loss charts will be saved in `train_output_dir`. They contain both the training and validation loss.
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
  title: LatentSync
3
- emoji: 😻
4
- colorFrom: red
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 5.10.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: LatentSync
3
+ emoji: 👄
4
+ colorFrom: blue
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 5.9.1
8
  app_file: app.py
9
  pinned: false
10
+ short_description: Audio Conditioned LipSync with Latent Diffusion Models
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import sys
4
+ import shutil
5
+ import uuid
6
+ import subprocess
7
+ from glob import glob
8
+ from huggingface_hub import snapshot_download
9
+
10
+ # Download models
11
+ os.makedirs("checkpoints", exist_ok=True)
12
+
13
+ snapshot_download(
14
+ repo_id = "chunyu-li/LatentSync",
15
+ local_dir = "./checkpoints"
16
+ )
17
+
18
+ import tempfile
19
+ from moviepy.editor import VideoFileClip
20
+ from pydub import AudioSegment
21
+
22
+ def process_video(input_video_path, temp_dir="temp_dir"):
23
+ """
24
+ Crop a given MP4 video to a maximum duration of 10 seconds if it is longer than 10 seconds.
25
+ Save the new video in the specified folder (default is temp_dir).
26
+
27
+ Args:
28
+ input_video_path (str): Path to the input video file.
29
+ temp_dir (str): Directory where the processed video will be saved.
30
+
31
+ Returns:
32
+ str: Path to the cropped video file.
33
+ """
34
+ # Ensure the temp_dir exists
35
+ os.makedirs(temp_dir, exist_ok=True)
36
+
37
+ # Load the video
38
+ video = VideoFileClip(input_video_path)
39
+
40
+ # Determine the output path
41
+ input_file_name = os.path.basename(input_video_path)
42
+ output_video_path = os.path.join(temp_dir, f"cropped_{input_file_name}")
43
+
44
+ # Crop the video to 10 seconds if necessary
45
+ # if video.duration > 10:
46
+ # video = video.subclip(0, 10)
47
+
48
+ # Write the cropped video to the output path
49
+ video.write_videofile(output_video_path, codec="libx264", audio_codec="aac")
50
+
51
+ # Return the path to the cropped video
52
+ return output_video_path
53
+
54
+ def process_audio(file_path, temp_dir):
55
+ # Load the audio file
56
+ audio = AudioSegment.from_file(file_path)
57
+
58
+ # Check and cut the audio if longer than 4 seconds
59
+ max_duration = 8 * 1000 # 4 seconds in milliseconds
60
+ if len(audio) > max_duration:
61
+ audio = audio[:max_duration]
62
+
63
+ # Save the processed audio in the temporary directory
64
+ output_path = os.path.join(temp_dir, "trimmed_audio.wav")
65
+ audio.export(output_path, format="wav")
66
+
67
+ # Return the path to the trimmed file
68
+ print(f"Processed audio saved at: {output_path}")
69
+ return output_path
70
+
71
+ import argparse
72
+ from omegaconf import OmegaConf
73
+ import torch
74
+ from diffusers import AutoencoderKL, DDIMScheduler
75
+ from latentsync.models.unet import UNet3DConditionModel
76
+ from latentsync.pipelines.lipsync_pipeline import LipsyncPipeline
77
+ from diffusers.utils.import_utils import is_xformers_available
78
+ from accelerate.utils import set_seed
79
+ from latentsync.whisper.audio2feature import Audio2Feature
80
+
81
+
82
+ def main(video_path, audio_path, progress=gr.Progress(track_tqdm=True)):
83
+ inference_ckpt_path = "checkpoints/latentsync_unet.pt"
84
+ unet_config_path = "configs/unet/second_stage.yaml"
85
+ config = OmegaConf.load(unet_config_path)
86
+
87
+ print(f"Input video path: {video_path}")
88
+ print(f"Input audio path: {audio_path}")
89
+ print(f"Loaded checkpoint path: {inference_ckpt_path}")
90
+
91
+ is_shared_ui = True if "fffiloni/LatentSync" in os.environ['SPACE_ID'] else False
92
+ temp_dir = None
93
+ if is_shared_ui:
94
+ temp_dir = tempfile.mkdtemp()
95
+ cropped_video_path = process_video(video_path)
96
+ print(f"Cropped video saved to: {cropped_video_path}")
97
+ video_path=cropped_video_path
98
+
99
+ trimmed_audio_path = process_audio(audio_path, temp_dir)
100
+ print(f"Processed file was stored temporarily at: {trimmed_audio_path}")
101
+ audio_path=trimmed_audio_path
102
+
103
+ scheduler = DDIMScheduler.from_pretrained("configs")
104
+
105
+ if config.model.cross_attention_dim == 768:
106
+ whisper_model_path = "checkpoints/whisper/small.pt"
107
+ elif config.model.cross_attention_dim == 384:
108
+ whisper_model_path = "checkpoints/whisper/tiny.pt"
109
+ else:
110
+ raise NotImplementedError("cross_attention_dim must be 768 or 384")
111
+
112
+ audio_encoder = Audio2Feature(model_path=whisper_model_path, device="cuda", num_frames=config.data.num_frames)
113
+
114
+ vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
115
+ vae.config.scaling_factor = 0.18215
116
+ vae.config.shift_factor = 0
117
+
118
+ unet, _ = UNet3DConditionModel.from_pretrained(
119
+ OmegaConf.to_container(config.model),
120
+ inference_ckpt_path, # load checkpoint
121
+ device="cpu",
122
+ )
123
+
124
+ unet = unet.to(dtype=torch.float16)
125
+
126
+ # set xformers
127
+ if is_xformers_available():
128
+ unet.enable_xformers_memory_efficient_attention()
129
+
130
+ pipeline = LipsyncPipeline(
131
+ vae=vae,
132
+ audio_encoder=audio_encoder,
133
+ unet=unet,
134
+ scheduler=scheduler,
135
+ ).to("cuda")
136
+
137
+ seed = -1
138
+ if seed != -1:
139
+ set_seed(seed)
140
+ else:
141
+ torch.seed()
142
+
143
+ print(f"Initial seed: {torch.initial_seed()}")
144
+
145
+ unique_id = str(uuid.uuid4())
146
+ video_out_path = f"video_out{unique_id}.mp4"
147
+
148
+ pipeline(
149
+ video_path=video_path,
150
+ audio_path=audio_path,
151
+ video_out_path=video_out_path,
152
+ video_mask_path=video_out_path.replace(".mp4", "_mask.mp4"),
153
+ num_frames=config.data.num_frames,
154
+ num_inference_steps=config.run.inference_steps,
155
+ guidance_scale=1.0,
156
+ weight_dtype=torch.float16,
157
+ width=config.data.resolution,
158
+ height=config.data.resolution,
159
+ )
160
+
161
+ if is_shared_ui:
162
+ # Clean up the temporary directory
163
+ if os.path.exists(temp_dir):
164
+ shutil.rmtree(temp_dir)
165
+ print(f"Temporary directory {temp_dir} deleted.")
166
+
167
+ return video_out_path
168
+
169
+
170
+ css="""
171
+ div#col-container{
172
+ margin: 0 auto;
173
+ max-width: 982px;
174
+ }
175
+ """
176
+ with gr.Blocks(css=css) as demo:
177
+ with gr.Column(elem_id="col-container"):
178
+ gr.Markdown("# LatentSync: Audio Conditioned Latent Diffusion Models for Lip Sync")
179
+ gr.Markdown("LatentSync, an end-to-end lip sync framework based on audio conditioned latent diffusion models without any intermediate motion representation, diverging from previous diffusion-based lip sync methods based on pixel space diffusion or two-stage generation.")
180
+ gr.HTML("""
181
+ <div style="display:flex;column-gap:4px;">
182
+ <a href="https://github.com/bytedance/LatentSync">
183
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue'>
184
+ </a>
185
+ <a href="https://arxiv.org/abs/2412.09262">
186
+ <img src='https://img.shields.io/badge/ArXiv-Paper-red'>
187
+ </a>
188
+ <a href="https://huggingface.co/spaces/fffiloni/LatentSync?duplicate=true">
189
+ <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-sm.svg" alt="Duplicate this Space">
190
+ </a>
191
+ <a href="https://huggingface.co/fffiloni">
192
+ <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/follow-me-on-HF-sm-dark.svg" alt="Follow me on HF">
193
+ </a>
194
+ </div>
195
+ """)
196
+ with gr.Row():
197
+ with gr.Column():
198
+ video_input = gr.Video(label="Video Control", format="mp4")
199
+ audio_input = gr.Audio(label="Audio Input", type="filepath")
200
+ submit_btn = gr.Button("Submit")
201
+ with gr.Column():
202
+ video_result = gr.Video(label="Result")
203
+
204
+ gr.Examples(
205
+ examples = [
206
+ ["assets/demo1_video.mp4", "assets/demo1_audio.wav"],
207
+ ["assets/demo2_video.mp4", "assets/demo2_audio.wav"],
208
+ ["assets/demo3_video.mp4", "assets/demo3_audio.wav"],
209
+ ],
210
+ inputs = [video_input, audio_input]
211
+ )
212
+
213
+ submit_btn.click(
214
+ fn = main,
215
+ inputs = [video_input, audio_input],
216
+ outputs = [video_result]
217
+ )
218
+
219
+ demo.queue().launch(show_api=False, show_error=True)
data_processing_pipeline.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ python -m preprocess.data_processing_pipeline \
4
+ --total_num_workers 20 \
5
+ --per_gpu_num_workers 20 \
6
+ --resolution 256 \
7
+ --sync_conf_threshold 3 \
8
+ --temp_dir temp \
9
+ --input_dir /mnt/bn/maliva-gen-ai-v2/chunyu.li/VoxCeleb2/raw
inference.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ python -m scripts.inference \
4
+ --unet_config_path "configs/unet/second_stage.yaml" \
5
+ --inference_ckpt_path "checkpoints/latentsync_unet.pt" \
6
+ --guidance_scale 1.0 \
7
+ --video_path "assets/demo1_video.mp4" \
8
+ --audio_path "assets/demo1_audio.wav" \
9
+ --video_out_path "video_out.mp4"
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ libgl1
requirements.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.2.2
2
+ torchvision==0.17.2
3
+ --extra-index-url https://download.pytorch.org/whl/cu121
4
+ xformers==0.0.26
5
+ triton==2.2.0
6
+
7
+ diffusers==0.11.1
8
+ transformers==4.38.0
9
+ huggingface-hub==0.25.2
10
+ imageio==2.27.0
11
+ decord==0.6.0
12
+ accelerate==0.26.1
13
+ einops==0.7.0
14
+ omegaconf==2.3.0
15
+ safetensors==0.4.2
16
+ opencv-python==4.9.0.80
17
+ mediapipe==0.10.11
18
+ av==11.0.0
19
+ torch-fidelity==0.3.0
20
+ torchmetrics==1.3.1
21
+ python_speech_features==0.6
22
+ librosa==0.10.1
23
+ scenedetect==0.6.1
24
+ ffmpeg-python==0.2.0
25
+ lpips==0.1.4
26
+ face-alignment==1.4.1
27
+ ninja==1.11.1.1
28
+ pandas==2.0.3
29
+ numpy==1.24.4
30
+ pydub
31
+ moviepy==1.0.3
setup_env.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Create a new conda environment
4
+ conda create -y -n latentsync python=3.10.13
5
+ conda activate latentsync
6
+
7
+ # Install ffmpeg
8
+ conda install -y -c conda-forge ffmpeg
9
+
10
+ # Python dependencies
11
+ pip install -r requirements.txt
12
+
13
+ # OpenCV dependencies
14
+ sudo apt -y install libgl1
15
+
16
+ # Download all the checkpoints from HuggingFace
17
+ huggingface-cli download chunyu-li/LatentSync --local-dir checkpoints --exclude "*.git*" "README.md"
18
+
19
+ # Soft links for the auxiliary models
20
+ mkdir -p ~/.cache/torch/hub/checkpoints
21
+ ln -s $(pwd)/checkpoints/auxiliary/2DFAN4-cd938726ad.zip ~/.cache/torch/hub/checkpoints/2DFAN4-cd938726ad.zip
22
+ ln -s $(pwd)/checkpoints/auxiliary/s3fd-619a316812.pth ~/.cache/torch/hub/checkpoints/s3fd-619a316812.pth
23
+ ln -s $(pwd)/checkpoints/auxiliary/vgg16-397923af.pth ~/.cache/torch/hub/checkpoints/vgg16-397923af.pth
train_syncnet.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ torchrun --nnodes=1 --nproc_per_node=1 --master_port=25678 -m scripts.train_syncnet \
4
+ --config_path "configs/syncnet/syncnet_16_pixel.yaml"
train_unet.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ torchrun --nnodes=1 --nproc_per_node=1 --master_port=25678 -m scripts.train_unet \
4
+ --unet_config_path "configs/unet/first_stage.yaml"