Wav2Lip README

The project's README from github.com/Rudrabha/Wav2Lip. As one markdown file: README.md.

Wav2Lip: Accurately Lip-syncing Videos In The Wild

Commercial Version

Create your first lipsync generation in minutes. Please note, the commercial version is of a much higher quality than the old open source model!

Create your API Key

Create your API key from the Dashboard. You will use this key to securely access the Sync API.

Make your first generation

The following example shows how to make a lipsync generation using the Sync API.

Python

Step 1: Install Sync SDK

pip install syncsdk

Step 2: Make your first generation

Copy the following code into a file quickstart.py and replace YOUR_API_KEY_HERE with your generated API key.

# quickstart.py
import time
from sync import Sync
from sync.common import Audio, GenerationOptions, Video
from sync.core.api_error import ApiError

# ---------- UPDATE API KEY ----------
# Replace with your Sync.so API key
api_key = "YOUR_API_KEY_HERE" 

# ----------[OPTIONAL] UPDATE INPUT VIDEO AND AUDIO URL ----------
# URL to your source video
video_url = "https://assets.sync.so/docs/example-video.mp4"
# URL to your audio file
audio_url = "https://assets.sync.so/docs/example-audio.wav"
# ----------------------------------------

client = Sync(
    base_url="https://api.sync.so", 
    api_key=api_key
).generations

print("Starting lip sync generation job...")

try:
    response = client.create(
        input=[Video(url=video_url),Audio(url=audio_url)],
        model="lipsync-2",
        options=GenerationOptions(sync_mode="cut_off"),
        outputFileName="quickstart"
    )
except ApiError as e:
    print(f'create generation request failed with status code {e.status_code} and error {e.body}')
    exit()

job_id = response.id
print(f"Generation submitted successfully, job id: {job_id}")

generation = client.get(job_id)
status = generation.status
while status not in ['COMPLETED', 'FAILED']:
    print('polling status for generation', job_id)
    time.sleep(10)
    generation = client.get(job_id)
    status = generation.status

if status == 'COMPLETED':
    print('generation', job_id, 'completed successfully, output url:', generation.output_url)
else:
    print('generation', job_id, 'failed')

Run the script:

python quickstart.py

Step 3: Done!

It may take a few minutes for the generation to complete. You should see the generated video URL in the terminal post completion.


TypeScript

Step 1: Install dependencies

npm i @sync.so/sdk

Step 2: Make your first generation

Copy the following code into a file quickstart.ts and replace YOUR_API_KEY_HERE with your generated API key.

// quickstart.ts
import { SyncClient, SyncError } from "@sync.so/sdk";

// ---------- UPDATE API KEY ----------
// Replace with your Sync.so API key
const apiKey = "YOUR_API_KEY_HERE";

// ----------[OPTIONAL] UPDATE INPUT VIDEO AND AUDIO URL ----------
// URL to your source video
const videoUrl = "https://assets.sync.so/docs/example-video.mp4";
// URL to your audio file
const audioUrl = "https://assets.sync.so/docs/example-audio.wav";
// ----------------------------------------

const client = new SyncClient({ apiKey });

async function main() {
    console.log("Starting lip sync generation job...");

    let jobId: string;
    try {
        const response = await client.generations.create({
            input: [
                {
                    type: "video",
                    url: videoUrl,
                },
                {
                    type: "audio",
                    url: audioUrl,
                },
            ],
            model: "lipsync-2",
            options: {
                sync_mode: "cut_off",
            },
            outputFileName: "quickstart"
        });
        jobId = response.id;
        console.log(`Generation submitted successfully, job id: ${jobId}`);
    } catch (err) {
        if (err instanceof SyncError) {
            console.error(`create generation request failed with status code ${err.statusCode} and error ${JSON.stringify(err.body)}`);
        } else {
            console.error('An unexpected error occurred:', err);
        }
        return;
    }

    let generation;
    let status;
    while (status !== 'COMPLETED' && status !== 'FAILED') {
        console.log(`polling status for generation ${jobId}...`);
        try {
            await new Promise(resolve => setTimeout(resolve, 10000));
            generation = await client.generations.get(jobId);
            status = generation.status;
        } catch (err) {
            if (err instanceof SyncError) {
                console.error(`polling failed with status code ${err.statusCode} and error ${JSON.stringify(err.body)}`);
            } else {
                console.error('An unexpected error occurred during polling:', err);
            }
            status = 'FAILED';
        }
    }

    if (status === 'COMPLETED') {
        console.log(`generation ${jobId} completed successfully, output url: ${generation?.outputUrl}`);
    } else {
        console.log(`generation ${jobId} failed`);
    }
}

main();

Run the script:

npx tsx quickstart.ts -y

Step 3: Done!

You should see the generated video URL in the terminal.


Next Steps

Well done! You've just made your first lipsync generation with sync.so!

Ready to unlock the full potential of lipsync? Dive into our interactive Studio to experiment with all available models, or explore our API Documentation to take your lip-sync generations to the next level!

Contact

Non Commercial Open-source Version

This code is part of the paper: A Lip Sync Expert Is All You Need for Speech to Lip Generation In the Wild published at ACM Multimedia 2020. PWC PWC PWC

📑 Original Paper 📰 Project Page 🌀 Demo ⚡ Live Testing 📔 Colab Notebook
Paper Project Page Demo Video Interactive Demo Colab Notebook /Updated Collab Notebook

Logo

Highlights


Disclaimer

All results from this open-source code or our demo website should only be used for research/academic/personal purposes only. As the models are trained on the LRS2 dataset, any form of commercial use is strictly prohibited. For commercial requests please contact us directly! Prerequisites


Model Description Link to the model
Wav2Lip Highly accurate lip-sync Link
Wav2Lip + GAN Slightly inferior lip-sync, but better visual quality Link

Lip-syncing videos using the pre-trained models (Inference)

You can lip-sync any video to any audio:

python inference.py --checkpoint_path <ckpt> --face <video.mp4> --audio <an-audio-source> 

The result is saved (by default) in results/result_voice.mp4. You can specify it as an argument, similar to several other available options. The audio source can be any file supported by FFMPEG containing audio data: *.wav, *.mp3 or even a video file, from which the code will automatically extract the audio.

Tips for better results:

Our models are trained on LRS2. See here for a few suggestions regarding training on other datasets.

LRS2 dataset folder structure
data_root (mvlrs_v1)
├── main, pretrain (we use only main folder in this work)
|	├── list of folders
|	│   ├── five-digit numbered video IDs ending with (.mp4)

Place the LRS2 filelists (train, val, test) .txt files in the filelists/ folder.

Preprocess the dataset for fast training
python preprocess.py --data_root data_root/main --preprocessed_root lrs2_preprocessed/

Additional options like batch_size and the number of GPUs to use in parallel to use can also be set.

Preprocessed LRS2 folder structure
preprocessed_root (lrs2_preprocessed)
├── list of folders
|	├── Folders with five-digit numbered video IDs
|	│   ├── *.jpg
|	│   ├── audio.wav

Train!

There are two major steps: (i) Train the expert lip-sync discriminator, (ii) Train the Wav2Lip model(s).

Training the expert discriminator

You can download the pre-trained weights if you want to skip this step. To train it:

python color_syncnet_train.py --data_root lrs2_preprocessed/ --checkpoint_dir <folder_to_save_checkpoints>
Training the Wav2Lip models

You can either train the model without the additional visual quality discriminator (< 1 day of training) or use the discriminator (~2 days). For the former, run:

python wav2lip_train.py --data_root lrs2_preprocessed/ --checkpoint_dir <folder_to_save_checkpoints> --syncnet_checkpoint_path <path_to_expert_disc_checkpoint>

To train with the visual quality discriminator, you should run hq_wav2lip_train.py instead. The arguments for both files are similar. In both cases, you can resume training as well. Look at python wav2lip_train.py --help for more details. You can also set additional less commonly-used hyper-parameters at the bottom of the hparams.py file. Training on datasets other than LRS2

Training on other datasets might require modifications to the code. Please read the following before you raise an issue:


Please check the evaluation/ folder for the instructions. License and Citation

This repository can only be used for personal/research/non-commercial purposes. However, for commercial requests, please contact us directly at [email protected] or [email protected]. We have a turn-key hosted API with new and improved lip-syncing models here: https://synclabs.so/ The size of the generated face will be 192 x 288 in our new models. Please cite the following paper if you use this repository:

@inproceedings{10.1145/3394171.3413532,
author = {Prajwal, K R and Mukhopadhyay, Rudrabha and Namboodiri, Vinay P. and Jawahar, C.V.},
title = {A Lip Sync Expert Is All You Need for Speech to Lip Generation In the Wild},
year = {2020},
isbn = {9781450379885},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/3394171.3413532},
doi = {10.1145/3394171.3413532},
booktitle = {Proceedings of the 28th ACM International Conference on Multimedia},
pages = {484–492},
numpages = {9},
keywords = {lip sync, talking face generation, video generation},
location = {Seattle, WA, USA},
series = {MM '20}
}

Acknowledgments

Parts of the code structure are inspired by this TTS repository. We thank the author for this wonderful code. The code for Face Detection has been taken from the face_alignment repository. We thank the authors for releasing their code and models. We thank zabique for the tutorial collab notebook.

Acknowledgements

Wav2Lip (Rudrabha/Wav2Lip)

Searching Database…

13.2K ·GitHub
Что это такое?Wav2Lip — это открытый код и предобученные модели из статьи на конференции ACM Multimedia 2020: они синхронизируют губы на любом видео с любым целевым звуковым файлом речи с высокой точностью — для исследований, учебных и личных целей.
Это онлайн-сервис или код, который я запускаю у себя?Этот репозиторий — код на Python, который вы запускаете сами, он охватывает и инференс, и обучение; авторы также предлагают гораздо более качественную коммерческую HD-модель через свой облачный API Sync Labs.
Как это запустить?Установите Python 3.6 и ffmpeg, выполните pip install -r requirements.txt, затем скачайте предобученные веса и положите модель детекции лиц по пути facedetection/detection/sfd/s3fd.pth. Ноутбук Google Colab позволяет вовсе обойтись без локальной настройки.
Мне нужно обучать свою модель, или веса уже готовы к использованию?Предобученные модели доступны для скачивания: базовая Wav2Lip с самой точной синхронизацией губ и Wav2Lip + GAN, которая синхронизирует чуть хуже, но выглядит визуально лучше. Полный код для обучения тоже включён.
Рот в моём результате выглядит странно — есть известные способы это исправить?В README предлагается настроить рамку лица с помощью --pads, отключить сглаживание флагом --nosmooth, если видны артефакты вроде двойного рта, и попробовать --resize_factor, так как модели обучались на лицах с низким разрешением.
Могу ли я использовать это в коммерческом продукте?Нет — открытая версия допускается только для личных, исследовательских и учебных целей, а коммерческое использование строго запрещено. Коммерческие запросы авторы направляют в свой платный сервис Sync Labs.
Можно ли дообучить его на нескольких минутах записи одного человека?Скорее всего нет — авторы предупреждают, что это часто даёт плохие результаты, и называют это открытой исследовательской проблемой, решения у которой у них пока нет. Обучение на своём датасете к тому же требует сначала обучить эксперт-дискриминатор и может понадобиться правка кода.
Какие аудио и видео можно ему подавать на вход?Любое видео плюс любой аудиофайл, который поддерживает FFMPEG, — .wav, .mp3 или даже другое видео, из которого звук извлекается автоматически. Результат с синхронизацией губ по умолчанию сохраняется в results/resultvoice.mp4.
Чем платная версия Sync Labs отличается от этой открытой модели?Это HD-модель с генерируемым лицом 192x288 и гораздо более высоким качеством, доступ к ней — по API-ключу через sync.so. Открытая модель — это более старый релиз с более низким качеством, строго некоммерческий.
Он работает с CGI-лицами и синтетическими голосами или только с реальными людьми?Он работает с любым лицом, голосом и языком — в README прямо сказано, что он справляется и с CGI-лицами, и с синтетическими голосами.
Creator
Rudrabha
Size
0.5 MB
Stars
13.2K
Updated
CommitJun 22
Age
6y
Commits · 90 Days