Spanicin commited on
Commit
cfc39a0
·
verified ·
1 Parent(s): d8431dd

Upload 9 files

Browse files
videoretalking/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.
videoretalking/README.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <h2>VideoReTalking <br/> <span style="font-size:12px">Audio-based Lip Synchronization for Talking Head Video Editing in the Wild</span> </h2>
4
+
5
+ <a href='https://arxiv.org/abs/2211.14758'><img src='https://img.shields.io/badge/ArXiv-2211.14758-red'></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='https://vinthony.github.io/video-retalking/'><img src='https://img.shields.io/badge/Project-Page-Green'></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vinthony/video-retalking/blob/main/quick_demo.ipynb)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
6
+ [![Replicate](https://replicate.com/cjwbw/video-retalking/badge)](https://replicate.com/cjwbw/video-retalking)
7
+
8
+ <div>
9
+ <a target='_blank'>Kun Cheng <sup>*,1,2</sup> </a>&emsp;
10
+ <a href='https://vinthony.github.io/' target='_blank'>Xiaodong Cun <sup>*,2</a>&emsp;
11
+ <a href='https://yzhang2016.github.io/yongnorriszhang.github.io/' target='_blank'>Yong Zhang <sup>2</sup></a>&emsp;
12
+ <a href='https://menghanxia.github.io/' target='_blank'>Menghan Xia <sup>2</sup></a>&emsp;
13
+ <a href='https://feiiyin.github.io/' target='_blank'>Fei Yin <sup>2,3</sup></a>&emsp;<br/>
14
+ <a href='https://web.xidian.edu.cn/mrzhu/en/index.html' target='_blank'>Mingrui Zhu <sup>1</sup></a>&emsp;
15
+ <a href='https://xuanwangvc.github.io/' target='_blank'>Xuan Wang <sup>2</sup></a>&emsp;
16
+ <a href='https://juewang725.github.io/' target='_blank'>Jue Wang <sup>2</sup></a>&emsp;
17
+ <a href='https://web.xidian.edu.cn/nnwang/en/index.html' target='_blank'>Nannan Wang <sup>1</sup></a>
18
+ </div>
19
+ <br>
20
+ <div>
21
+ <sup>1</sup> Xidian University &emsp; <sup>2</sup> Tencent AI Lab &emsp; <sup>3</sup> Tsinghua University
22
+ </div>
23
+ <br>
24
+ <i><strong><a href='https://sa2022.siggraph.org/' target='_blank'>SIGGRAPH Asia 2022 Conference Track</a></strong></i>
25
+ <br>
26
+ <br>
27
+ <img src="https://opentalker.github.io/video-retalking/static/images/teaser.png" width="768px">
28
+
29
+
30
+ <div align="justify"> <BR> We present VideoReTalking, a new system to edit the faces of a real-world talking head video according to input audio, producing a high-quality and lip-syncing output video even with a different emotion. Our system disentangles this objective into three sequential tasks:
31
+
32
+ <BR> (1) face video generation with a canonical expression
33
+ <BR> (2) audio-driven lip-sync and
34
+ <BR> (3) face enhancement for improving photo-realism.
35
+
36
+ <BR> Given a talking-head video, we first modify the expression of each frame according to the same expression template using the expression editing network, resulting in a video with the canonical expression. This video, together with the given audio, is then fed into the lip-sync network to generate a lip-syncing video. Finally, we improve the photo-realism of the synthesized faces through an identity-aware face enhancement network and post-processing. We use learning-based approaches for all three steps and all our modules can be tackled in a sequential pipeline without any user intervention.</div>
37
+ <BR>
38
+
39
+ <p>
40
+ <img alt='pipeline' src="./docs/static/images/pipeline.png?raw=true" width="768px"><br>
41
+ <em align='center'>Pipeline</em>
42
+ </p>
43
+
44
+ </div>
45
+
46
+ ## Results in the Wild (contains audio)
47
+ https://user-images.githubusercontent.com/4397546/224310754-665eb2dd-aadc-47dc-b1f9-2029a937b20a.mp4
48
+
49
+
50
+
51
+
52
+ ## Environment
53
+ ```
54
+ git clone https://github.com/vinthony/video-retalking.git
55
+ cd video-retalking
56
+ conda create -n video_retalking python=3.8
57
+ conda activate video_retalking
58
+
59
+ conda install ffmpeg
60
+
61
+ # Please follow the instructions from https://pytorch.org/get-started/previous-versions/
62
+ # This installation command only works on CUDA 11.1
63
+ pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html
64
+
65
+ pip install -r requirements.txt
66
+ ```
67
+
68
+ ## Quick Inference
69
+
70
+ #### Pretrained Models
71
+ Please download our [pre-trained models](https://drive.google.com/drive/folders/18rhjMpxK8LVVxf7PI6XwOidt8Vouv_H0?usp=share_link) and put them in `./checkpoints`.
72
+
73
+ <!-- We also provide some [example videos and audio](https://drive.google.com/drive/folders/14OwbNGDCAMPPdY-l_xO1axpUjkPxI9Dv?usp=share_link). Please put them in `./examples`. -->
74
+
75
+ #### Inference
76
+
77
+ ```
78
+ python3 inference.py \
79
+ --face examples/face/1.mp4 \
80
+ --audio examples/audio/1.wav \
81
+ --outfile results/1_1.mp4
82
+ ```
83
+ This script includes data preprocessing steps. You can test any talking face videos without manual alignment. But it is worth noting that DNet cannot handle extreme poses.
84
+
85
+ You can also control the expression by adding the following parameters:
86
+
87
+ ```--exp_img```: Pre-defined expression template. The default is "neutral". You can choose "smile" or an image path.
88
+
89
+ ```--up_face```: You can choose "surprise" or "angry" to modify the expression of upper face with [GANimation](https://github.com/donydchen/ganimation_replicate).
90
+
91
+
92
+
93
+ ## Citation
94
+
95
+ If you find our work useful in your research, please consider citing:
96
+
97
+ ```
98
+ @misc{cheng2022videoretalking,
99
+ title={VideoReTalking: Audio-based Lip Synchronization for Talking Head Video Editing In the Wild},
100
+ author={Kun Cheng and Xiaodong Cun and Yong Zhang and Menghan Xia and Fei Yin and Mingrui Zhu and Xuan Wang and Jue Wang and Nannan Wang},
101
+ year={2022},
102
+ eprint={2211.14758},
103
+ archivePrefix={arXiv},
104
+ primaryClass={cs.CV}
105
+ }
106
+ ```
107
+
108
+ ## Acknowledgement
109
+ Thanks to
110
+ [Wav2Lip](https://github.com/Rudrabha/Wav2Lip),
111
+ [PIRenderer](https://github.com/RenYurui/PIRender),
112
+ [GFP-GAN](https://github.com/TencentARC/GFPGAN),
113
+ [GPEN](https://github.com/yangxy/GPEN),
114
+ [ganimation_replicate](https://github.com/donydchen/ganimation_replicate),
115
+ [STIT](https://github.com/rotemtzaban/STIT)
116
+ for sharing their code.
117
+
118
+
119
+ ## Related Work
120
+ - [StyleHEAT: One-Shot High-Resolution Editable Talking Face Generation via Pre-trained StyleGAN (ECCV 2022)](https://github.com/FeiiYin/StyleHEAT)
121
+ - [CodeTalker: Speech-Driven 3D Facial Animation with Discrete Motion Prior (CVPR 2023)](https://github.com/Doubiiu/CodeTalker)
122
+ - [SadTalker: Learning Realistic 3D Motion Coefficients for Stylized Audio-Driven Single Image Talking Face Animation (CVPR 2023)](https://github.com/Winfredy/SadTalker)
123
+ - [DPE: Disentanglement of Pose and Expression for General Video Portrait Editing (CVPR 2023)](https://github.com/Carlyx/DPE)
124
+ - [3D GAN Inversion with Facial Symmetry Prior (CVPR 2023)](https://github.com/FeiiYin/SPI/)
125
+ - [T2M-GPT: Generating Human Motion from Textual Descriptions with Discrete Representations (CVPR 2023)](https://github.com/Mael-zys/T2M-GPT)
126
+
127
+ ## Disclaimer
128
+
129
+ This is not an official product of Tencent.
130
+
131
+ ```
132
+ 1. Please carefully read and comply with the open-source license applicable to this code before using it.
133
+ 2. Please carefully read and comply with the intellectual property declaration applicable to this code before using it.
134
+ 3. This open-source code runs completely offline and does not collect any personal information or other data. If you use this code to provide services to end-users and collect related data, please take necessary compliance measures according to applicable laws and regulations (such as publishing privacy policies, adopting necessary data security strategies, etc.). If the collected data involves personal information, user consent must be obtained (if applicable). Any legal liabilities arising from this are unrelated to Tencent.
135
+ 4. Without Tencent's written permission, you are not authorized to use the names or logos legally owned by Tencent, such as "Tencent." Otherwise, you may be liable for your legal responsibilities.
136
+ 5. This open-source code does not have the ability to directly provide services to end-users. If you need to use this code for further model training or demos, as part of your product to provide services to end-users, or for similar use, please comply with applicable laws and regulations for your product or service. Any legal liabilities arising from this are unrelated to Tencent.
137
+ 6. It is prohibited to use this open-source code for activities that harm the legitimate rights and interests of others (including but not limited to fraud, deception, infringement of others' portrait rights, reputation rights, etc.), or other behaviors that violate applicable laws and regulations or go against social ethics and good customs (including providing incorrect or false information, spreading pornographic, terrorist, and violent information, etc.). Otherwise, you may be liable for your legal responsibilities.
138
+
139
+ ```
140
+ ## All Thanks To Our Contributors
141
+
142
+ <a href="https://github.com/OpenTalker/video-retalking/graphs/contributors">
143
+ <img src="https://contrib.rocks/image?repo=OpenTalker/video-retalking" />
144
+ </a>
videoretalking/cog.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Cog ⚙️
2
+ # Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
3
+
4
+ build:
5
+ gpu: true
6
+ system_packages:
7
+ - "libgl1-mesa-glx"
8
+ - "libglib2.0-0"
9
+ - "ffmpeg"
10
+ python_version: "3.11"
11
+ python_packages:
12
+ - "torch==2.0.1"
13
+ - "torchvision==0.15.2"
14
+ - "basicsr==1.4.2"
15
+ - "kornia==0.5.1"
16
+ - "face-alignment==1.3.4"
17
+ - "ninja==1.10.2.3"
18
+ - "einops==0.4.1"
19
+ - "facexlib==0.2.5"
20
+ - "librosa==0.9.2"
21
+ - "cmake==3.27.7"
22
+ - "numpy==1.23.4"
23
+ run:
24
+ - pip install dlib
25
+ - mkdir -p /root/.pyenv/versions/3.11.6/lib/python3.11/site-packages/facexlib/weights/ && wget --output-document "/root/.pyenv/versions/3.11.6/lib/python3.11/site-packages/facexlib/weights/detection_Resnet50_Final.pth" "https://github.com/xinntao/facexlib/releases/download/v0.1.0/detection_Resnet50_Final.pth"
26
+ - mkdir -p /root/.pyenv/versions/3.11.6/lib/python3.11/site-packages/facexlib/weights/ && wget --output-document "/root/.pyenv/versions/3.11.6/lib/python3.11/site-packages/facexlib/weights/parsing_parsenet.pth" "https://github.com/xinntao/facexlib/releases/download/v0.2.2/parsing_parsenet.pth"
27
+ - mkdir -p /root/.cache/torch/hub/checkpoints/ && wget --output-document "/root/.cache/torch/hub/checkpoints/s3fd-619a316812.pth" "https://www.adrianbulat.com/downloads/python-fan/s3fd-619a316812.pth"
28
+ - mkdir -p /root/.cache/torch/hub/checkpoints/ && wget --output-document "/root/.cache/torch/hub/checkpoints/2DFAN4-cd938726ad.zip" "https://www.adrianbulat.com/downloads/python-fan/2DFAN4-cd938726ad.zip"
29
+ predict: "predict.py:Predictor"
videoretalking/inference.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2, os, sys, subprocess, platform, torch
3
+ from tqdm import tqdm
4
+ from PIL import Image
5
+ from scipy.io import loadmat
6
+
7
+ sys.path.insert(0, 'third_part')
8
+ sys.path.insert(0, 'third_part/GPEN')
9
+ # sys.path.insert(0, 'third_part/GFPGAN')
10
+
11
+ # 3dmm extraction
12
+ from third_part.face3d.util.preprocess import align_img
13
+ from third_part.face3d.util.load_mats import load_lm3d
14
+ from third_part.face3d.extract_kp_videos import KeypointExtractor
15
+ # face enhancement
16
+ from third_part.GPEN.gpen_face_enhancer import FaceEnhancement
17
+ # from third_part.GFPGAN.gfpgan import GFPGANer
18
+ # expression control
19
+ from third_part.ganimation_replicate.model.ganimation import GANimationModel
20
+
21
+ from utils import audio
22
+ from utils.ffhq_preprocess import Croper
23
+ from utils.alignment_stit import crop_faces, calc_alignment_coefficients, paste_image
24
+ from utils.inference_utils import Laplacian_Pyramid_Blending_with_mask, face_detect, load_model, options, split_coeff, \
25
+ trans_image, transform_semantic, find_crop_norm_ratio, load_face3d_net, exp_aus_dict
26
+ import warnings
27
+ warnings.filterwarnings("ignore")
28
+
29
+ args = options()
30
+
31
+ def main():
32
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
33
+ print('[Info] Using {} for inference.'.format(device))
34
+ os.makedirs(os.path.join('temp', args.tmp_dir), exist_ok=True)
35
+
36
+ enhancer = FaceEnhancement(base_dir='checkpoints', size=512, model='GPEN-BFR-512', use_sr=False, \
37
+ sr_model='rrdb_realesrnet_psnr', channel_multiplier=2, narrow=1, device=device)
38
+ # restorer = GFPGANer(model_path='checkpoints/GFPGANv1.3.pth', upscale=1, arch='clean', \
39
+ # channel_multiplier=2, bg_upsampler=None)
40
+
41
+ base_name = args.face.split('/')[-1]
42
+ if os.path.isfile(args.face) and args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
43
+ args.static = True
44
+ if not os.path.isfile(args.face):
45
+ raise ValueError('--face argument must be a valid path to video/image file')
46
+ elif args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
47
+ full_frames = [cv2.imread(args.face)]
48
+ fps = args.fps
49
+ else:
50
+ video_stream = cv2.VideoCapture(args.face)
51
+ fps = video_stream.get(cv2.CAP_PROP_FPS)
52
+
53
+ full_frames = []
54
+ while True:
55
+ still_reading, frame = video_stream.read()
56
+ if not still_reading:
57
+ video_stream.release()
58
+ break
59
+ y1, y2, x1, x2 = args.crop
60
+ if x2 == -1: x2 = frame.shape[1]
61
+ if y2 == -1: y2 = frame.shape[0]
62
+ frame = frame[y1:y2, x1:x2]
63
+ full_frames.append(frame)
64
+
65
+ print ("[Step 0] Number of frames available for inference: "+str(len(full_frames)))
66
+ # face detection & cropping, cropping the first frame as the style of FFHQ
67
+ croper = Croper('checkpoints/shape_predictor_68_face_landmarks.dat')
68
+ full_frames_RGB = [cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) for frame in full_frames]
69
+ full_frames_RGB, crop, quad = croper.crop(full_frames_RGB, xsize=512)
70
+
71
+ clx, cly, crx, cry = crop
72
+ lx, ly, rx, ry = quad
73
+ lx, ly, rx, ry = int(lx), int(ly), int(rx), int(ry)
74
+ oy1, oy2, ox1, ox2 = cly+ly, min(cly+ry, full_frames[0].shape[0]), clx+lx, min(clx+rx, full_frames[0].shape[1])
75
+ # original_size = (ox2 - ox1, oy2 - oy1)
76
+ frames_pil = [Image.fromarray(cv2.resize(frame,(256,256))) for frame in full_frames_RGB]
77
+
78
+ # get the landmark according to the detected face.
79
+ if not os.path.isfile('temp/'+base_name+'_landmarks.txt') or args.re_preprocess:
80
+ print('[Step 1] Landmarks Extraction in Video.')
81
+ kp_extractor = KeypointExtractor()
82
+ lm = kp_extractor.extract_keypoint(frames_pil, './temp/'+base_name+'_landmarks.txt')
83
+ else:
84
+ print('[Step 1] Using saved landmarks.')
85
+ lm = np.loadtxt('temp/'+base_name+'_landmarks.txt').astype(np.float32)
86
+ lm = lm.reshape([len(full_frames), -1, 2])
87
+
88
+ if not os.path.isfile('temp/'+base_name+'_coeffs.npy') or args.exp_img is not None or args.re_preprocess:
89
+ net_recon = load_face3d_net(args.face3d_net_path, device)
90
+ lm3d_std = load_lm3d('checkpoints/BFM')
91
+
92
+ video_coeffs = []
93
+ for idx in tqdm(range(len(frames_pil)), desc="[Step 2] 3DMM Extraction In Video:"):
94
+ frame = frames_pil[idx]
95
+ W, H = frame.size
96
+ lm_idx = lm[idx].reshape([-1, 2])
97
+ if np.mean(lm_idx) == -1:
98
+ lm_idx = (lm3d_std[:, :2]+1) / 2.
99
+ lm_idx = np.concatenate([lm_idx[:, :1] * W, lm_idx[:, 1:2] * H], 1)
100
+ else:
101
+ lm_idx[:, -1] = H - 1 - lm_idx[:, -1]
102
+
103
+ trans_params, im_idx, lm_idx, _ = align_img(frame, lm_idx, lm3d_std)
104
+ trans_params = np.array([float(item) for item in np.hsplit(trans_params, 5)]).astype(np.float32)
105
+ im_idx_tensor = torch.tensor(np.array(im_idx)/255., dtype=torch.float32).permute(2, 0, 1).to(device).unsqueeze(0)
106
+ with torch.no_grad():
107
+ coeffs = split_coeff(net_recon(im_idx_tensor))
108
+
109
+ pred_coeff = {key:coeffs[key].cpu().numpy() for key in coeffs}
110
+ pred_coeff = np.concatenate([pred_coeff['id'], pred_coeff['exp'], pred_coeff['tex'], pred_coeff['angle'],\
111
+ pred_coeff['gamma'], pred_coeff['trans'], trans_params[None]], 1)
112
+ video_coeffs.append(pred_coeff)
113
+ semantic_npy = np.array(video_coeffs)[:,0]
114
+ np.save('temp/'+base_name+'_coeffs.npy', semantic_npy)
115
+ else:
116
+ print('[Step 2] Using saved coeffs.')
117
+ semantic_npy = np.load('temp/'+base_name+'_coeffs.npy').astype(np.float32)
118
+
119
+ # generate the 3dmm coeff from a single image
120
+ if args.exp_img is not None and ('.png' in args.exp_img or '.jpg' in args.exp_img):
121
+ print('extract the exp from',args.exp_img)
122
+ exp_pil = Image.open(args.exp_img).convert('RGB')
123
+ lm3d_std = load_lm3d('third_part/face3d/BFM')
124
+
125
+ W, H = exp_pil.size
126
+ kp_extractor = KeypointExtractor()
127
+ lm_exp = kp_extractor.extract_keypoint([exp_pil], 'temp/'+base_name+'_temp.txt')[0]
128
+ if np.mean(lm_exp) == -1:
129
+ lm_exp = (lm3d_std[:, :2] + 1) / 2.
130
+ lm_exp = np.concatenate(
131
+ [lm_exp[:, :1] * W, lm_exp[:, 1:2] * H], 1)
132
+ else:
133
+ lm_exp[:, -1] = H - 1 - lm_exp[:, -1]
134
+
135
+ trans_params, im_exp, lm_exp, _ = align_img(exp_pil, lm_exp, lm3d_std)
136
+ trans_params = np.array([float(item) for item in np.hsplit(trans_params, 5)]).astype(np.float32)
137
+ im_exp_tensor = torch.tensor(np.array(im_exp)/255., dtype=torch.float32).permute(2, 0, 1).to(device).unsqueeze(0)
138
+ with torch.no_grad():
139
+ expression = split_coeff(net_recon(im_exp_tensor))['exp'][0]
140
+ del net_recon
141
+ elif args.exp_img == 'smile':
142
+ expression = torch.tensor(loadmat('checkpoints/expression.mat')['expression_mouth'])[0]
143
+ else:
144
+ print('using expression center')
145
+ expression = torch.tensor(loadmat('checkpoints/expression.mat')['expression_center'])[0]
146
+
147
+ # load DNet, model(LNet and ENet)
148
+ D_Net, model = load_model(args, device)
149
+
150
+ if not os.path.isfile('temp/'+base_name+'_stablized.npy') or args.re_preprocess:
151
+ imgs = []
152
+ for idx in tqdm(range(len(frames_pil)), desc="[Step 3] Stabilize the expression In Video:"):
153
+ if args.one_shot:
154
+ source_img = trans_image(frames_pil[0]).unsqueeze(0).to(device)
155
+ semantic_source_numpy = semantic_npy[0:1]
156
+ else:
157
+ source_img = trans_image(frames_pil[idx]).unsqueeze(0).to(device)
158
+ semantic_source_numpy = semantic_npy[idx:idx+1]
159
+ ratio = find_crop_norm_ratio(semantic_source_numpy, semantic_npy)
160
+ coeff = transform_semantic(semantic_npy, idx, ratio).unsqueeze(0).to(device)
161
+
162
+ # hacking the new expression
163
+ coeff[:, :64, :] = expression[None, :64, None].to(device)
164
+ with torch.no_grad():
165
+ output = D_Net(source_img, coeff)
166
+ img_stablized = np.uint8((output['fake_image'].squeeze(0).permute(1,2,0).cpu().clamp_(-1, 1).numpy() + 1 )/2. * 255)
167
+ imgs.append(cv2.cvtColor(img_stablized,cv2.COLOR_RGB2BGR))
168
+ np.save('temp/'+base_name+'_stablized.npy',imgs)
169
+ del D_Net
170
+ else:
171
+ print('[Step 3] Using saved stabilized video.')
172
+ imgs = np.load('temp/'+base_name+'_stablized.npy')
173
+ torch.cuda.empty_cache()
174
+
175
+ if not args.audio.endswith('.wav'):
176
+ command = 'ffmpeg -loglevel error -y -i {} -strict -2 {}'.format(args.audio, 'temp/{}/temp.wav'.format(args.tmp_dir))
177
+ subprocess.call(command, shell=True)
178
+ args.audio = 'temp/{}/temp.wav'.format(args.tmp_dir)
179
+ wav = audio.load_wav(args.audio, 16000)
180
+ mel = audio.melspectrogram(wav)
181
+ if np.isnan(mel.reshape(-1)).sum() > 0:
182
+ raise ValueError('Mel contains nan! Using a TTS voice? Add a small epsilon noise to the wav file and try again')
183
+
184
+ mel_step_size, mel_idx_multiplier, i, mel_chunks = 16, 80./fps, 0, []
185
+ while True:
186
+ start_idx = int(i * mel_idx_multiplier)
187
+ if start_idx + mel_step_size > len(mel[0]):
188
+ mel_chunks.append(mel[:, len(mel[0]) - mel_step_size:])
189
+ break
190
+ mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size])
191
+ i += 1
192
+
193
+ print("[Step 4] Load audio; Length of mel chunks: {}".format(len(mel_chunks)))
194
+ imgs = imgs[:len(mel_chunks)]
195
+ full_frames = full_frames[:len(mel_chunks)]
196
+ lm = lm[:len(mel_chunks)]
197
+
198
+ imgs_enhanced = []
199
+ for idx in tqdm(range(len(imgs)), desc='[Step 5] Reference Enhancement'):
200
+ img = imgs[idx]
201
+ pred, _, _ = enhancer.process(img, img, face_enhance=True, possion_blending=False)
202
+ imgs_enhanced.append(pred)
203
+ gen = datagen(imgs_enhanced.copy(), mel_chunks, full_frames, None, (oy1,oy2,ox1,ox2))
204
+
205
+ frame_h, frame_w = full_frames[0].shape[:-1]
206
+ out = cv2.VideoWriter('temp/{}/result.mp4'.format(args.tmp_dir), cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_w, frame_h))
207
+
208
+ if args.up_face != 'original':
209
+ instance = GANimationModel()
210
+ instance.initialize()
211
+ instance.setup()
212
+
213
+ kp_extractor = KeypointExtractor()
214
+ for i, (img_batch, mel_batch, frames, coords, img_original, f_frames) in enumerate(tqdm(gen, desc='[Step 6] Lip Synthesis:', total=int(np.ceil(float(len(mel_chunks)) / args.LNet_batch_size)))):
215
+ img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(device)
216
+ mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(device)
217
+ img_original = torch.FloatTensor(np.transpose(img_original, (0, 3, 1, 2))).to(device)/255. # BGR -> RGB
218
+
219
+ with torch.no_grad():
220
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
221
+ pred, low_res = model(mel_batch, img_batch, reference)
222
+ pred = torch.clamp(pred, 0, 1)
223
+
224
+ if args.up_face in ['sad', 'angry', 'surprise']:
225
+ tar_aus = exp_aus_dict[args.up_face]
226
+ else:
227
+ pass
228
+
229
+ if args.up_face == 'original':
230
+ cur_gen_faces = img_original
231
+ else:
232
+ test_batch = {'src_img': torch.nn.functional.interpolate((img_original * 2 - 1), size=(128, 128), mode='bilinear'),
233
+ 'tar_aus': tar_aus.repeat(len(incomplete), 1)}
234
+ instance.feed_batch(test_batch)
235
+ instance.forward()
236
+ cur_gen_faces = torch.nn.functional.interpolate(instance.fake_img / 2. + 0.5, size=(384, 384), mode='bilinear')
237
+
238
+ if args.without_rl1 is not False:
239
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
240
+ mask = torch.where(incomplete==0, torch.ones_like(incomplete), torch.zeros_like(incomplete))
241
+ pred = pred * mask + cur_gen_faces * (1 - mask)
242
+
243
+ pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.
244
+
245
+ torch.cuda.empty_cache()
246
+ for p, f, xf, c in zip(pred, frames, f_frames, coords):
247
+ y1, y2, x1, x2 = c
248
+ p = cv2.resize(p.astype(np.uint8), (x2 - x1, y2 - y1))
249
+
250
+ ff = xf.copy()
251
+ ff[y1:y2, x1:x2] = p
252
+
253
+ # month region enhancement by GFPGAN
254
+ # cropped_faces, restored_faces, restored_img = restorer.enhance(
255
+ # ff, has_aligned=False, only_center_face=True, paste_back=True)
256
+ restored_img = ff
257
+ mm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0]
258
+ mouse_mask = np.zeros_like(restored_img)
259
+ tmp_mask = enhancer.faceparser.process(restored_img[y1:y2, x1:x2], mm)[0]
260
+ mouse_mask[y1:y2, x1:x2]= cv2.resize(tmp_mask, (x2 - x1, y2 - y1))[:, :, np.newaxis] / 255.
261
+
262
+ height, width = ff.shape[:2]
263
+ restored_img, ff, full_mask = [cv2.resize(x, (512, 512)) for x in (restored_img, ff, np.float32(mouse_mask))]
264
+ img = Laplacian_Pyramid_Blending_with_mask(restored_img, ff, full_mask[:, :, 0], 10)
265
+ pp = np.uint8(cv2.resize(np.clip(img, 0 ,255), (width, height)))
266
+
267
+ pp, orig_faces, enhanced_faces = enhancer.process(pp, xf, bbox=c, face_enhance=False, possion_blending=True)
268
+ out.write(pp)
269
+ out.release()
270
+
271
+ if not os.path.isdir(os.path.dirname(args.outfile)):
272
+ os.makedirs(os.path.dirname(args.outfile), exist_ok=True)
273
+ command = 'ffmpeg -loglevel error -y -i {} -i {} -strict -2 -q:v 1 {}'.format(args.audio, 'temp/{}/result.mp4'.format(args.tmp_dir), args.outfile)
274
+ subprocess.call(command, shell=platform.system() != 'Windows')
275
+ print('outfile:', args.outfile)
276
+
277
+
278
+ # frames:256x256, full_frames: original size
279
+ def datagen(frames, mels, full_frames, frames_pil, cox):
280
+ img_batch, mel_batch, frame_batch, coords_batch, ref_batch, full_frame_batch = [], [], [], [], [], []
281
+ base_name = args.face.split('/')[-1]
282
+ refs = []
283
+ image_size = 256
284
+
285
+ # original frames
286
+ kp_extractor = KeypointExtractor()
287
+ fr_pil = [Image.fromarray(frame) for frame in frames]
288
+ lms = kp_extractor.extract_keypoint(fr_pil, 'temp/'+base_name+'x12_landmarks.txt')
289
+ frames_pil = [ (lm, frame) for frame,lm in zip(fr_pil, lms)] # frames is the croped version of modified face
290
+ crops, orig_images, quads = crop_faces(image_size, frames_pil, scale=1.0, use_fa=True)
291
+ inverse_transforms = [calc_alignment_coefficients(quad + 0.5, [[0, 0], [0, image_size], [image_size, image_size], [image_size, 0]]) for quad in quads]
292
+ del kp_extractor.detector
293
+
294
+ oy1,oy2,ox1,ox2 = cox
295
+ face_det_results = face_detect(full_frames, args, jaw_correction=True)
296
+
297
+ for inverse_transform, crop, full_frame, face_det in zip(inverse_transforms, crops, full_frames, face_det_results):
298
+ imc_pil = paste_image(inverse_transform, crop, Image.fromarray(
299
+ cv2.resize(full_frame[int(oy1):int(oy2), int(ox1):int(ox2)], (256, 256))))
300
+
301
+ ff = full_frame.copy()
302
+ ff[int(oy1):int(oy2), int(ox1):int(ox2)] = cv2.resize(np.array(imc_pil.convert('RGB')), (ox2 - ox1, oy2 - oy1))
303
+ oface, coords = face_det
304
+ y1, y2, x1, x2 = coords
305
+ refs.append(ff[y1: y2, x1:x2])
306
+
307
+ for i, m in enumerate(mels):
308
+ idx = 0 if args.static else i % len(frames)
309
+ frame_to_save = frames[idx].copy()
310
+ face = refs[idx]
311
+ oface, coords = face_det_results[idx].copy()
312
+
313
+ face = cv2.resize(face, (args.img_size, args.img_size))
314
+ oface = cv2.resize(oface, (args.img_size, args.img_size))
315
+
316
+ img_batch.append(oface)
317
+ ref_batch.append(face)
318
+ mel_batch.append(m)
319
+ coords_batch.append(coords)
320
+ frame_batch.append(frame_to_save)
321
+ full_frame_batch.append(full_frames[idx].copy())
322
+
323
+ if len(img_batch) >= args.LNet_batch_size:
324
+ img_batch, mel_batch, ref_batch = np.asarray(img_batch), np.asarray(mel_batch), np.asarray(ref_batch)
325
+ img_masked = img_batch.copy()
326
+ img_original = img_batch.copy()
327
+ img_masked[:, args.img_size//2:] = 0
328
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.
329
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
330
+
331
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
332
+ img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch, ref_batch = [], [], [], [], [], [], []
333
+
334
+ if len(img_batch) > 0:
335
+ img_batch, mel_batch, ref_batch = np.asarray(img_batch), np.asarray(mel_batch), np.asarray(ref_batch)
336
+ img_masked = img_batch.copy()
337
+ img_original = img_batch.copy()
338
+ img_masked[:, args.img_size//2:] = 0
339
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.
340
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
341
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
342
+
343
+
344
+ if __name__ == '__main__':
345
+ main()
videoretalking/inference1.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2, os, sys, subprocess, platform, torch
3
+ from tqdm import tqdm
4
+ from PIL import Image
5
+ from scipy.io import loadmat
6
+
7
+ sys.path.insert(0, 'third_part')
8
+ sys.path.insert(0, 'third_part/GPEN')
9
+ sys.path.insert(0, 'third_part/GFPGAN')
10
+
11
+ # 3dmm extraction
12
+ from third_part.face3d.util.preprocess import align_img
13
+ from third_part.face3d.util.load_mats import load_lm3d
14
+ from third_part.face3d.extract_kp_videos import KeypointExtractor
15
+ # face enhancement
16
+ from third_part.GPEN.gpen_face_enhancer import FaceEnhancement
17
+ from third_part.GFPGAN.gfpgan import GFPGANer
18
+ # expression control
19
+ from third_part.ganimation_replicate.model.ganimation import GANimationModel
20
+
21
+ from utils import audio
22
+ from utils.ffhq_preprocess import Croper
23
+ from utils.alignment_stit import crop_faces, calc_alignment_coefficients, paste_image
24
+ from utils.inference_utils import Laplacian_Pyramid_Blending_with_mask, face_detect, load_model, options, split_coeff, \
25
+ trans_image, transform_semantic, find_crop_norm_ratio, load_face3d_net, exp_aus_dict
26
+ import warnings
27
+ warnings.filterwarnings("ignore")
28
+
29
+ args = options()
30
+
31
+ def main():
32
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
33
+ print('[Info] Using {} for inference.'.format(device))
34
+ os.makedirs(os.path.join('temp', args.tmp_dir), exist_ok=True)
35
+
36
+ enhancer = FaceEnhancement(base_dir='checkpoints', size=1024, model='GPEN-BFR-1024', use_sr=False, \
37
+ sr_model='rrdb_realesrnet_psnr', channel_multiplier=2, narrow=1, device=device)
38
+ restorer = GFPGANer(model_path='checkpoints/GFPGANv1.3.pth', upscale=1, arch='clean', \
39
+ channel_multiplier=2, bg_upsampler=None)
40
+
41
+ base_name = args.face.split('/')[-1]
42
+ if os.path.isfile(args.face) and args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
43
+ args.static = True
44
+ if not os.path.isfile(args.face):
45
+ raise ValueError('--face argument must be a valid path to video/image file')
46
+ elif args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
47
+ full_frames = [cv2.imread(args.face)]
48
+ fps = args.fps
49
+ else:
50
+ video_stream = cv2.VideoCapture(args.face)
51
+ fps = video_stream.get(cv2.CAP_PROP_FPS)
52
+
53
+ full_frames = []
54
+ while True:
55
+ still_reading, frame = video_stream.read()
56
+ if not still_reading:
57
+ video_stream.release()
58
+ break
59
+ y1, y2, x1, x2 = args.crop
60
+ if x2 == -1: x2 = frame.shape[1]
61
+ if y2 == -1: y2 = frame.shape[0]
62
+ frame = frame[y1:y2, x1:x2]
63
+ full_frames.append(frame)
64
+
65
+ print ("[Step 0] Number of frames available for inference: "+str(len(full_frames)))
66
+ # face detection & cropping, cropping the first frame as the style of FFHQ
67
+ croper = Croper('checkpoints/shape_predictor_68_face_landmarks.dat')
68
+ full_frames_RGB = [cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) for frame in full_frames]
69
+ full_frames_RGB, crop, quad = croper.crop(full_frames_RGB, xsize=512)
70
+
71
+ clx, cly, crx, cry = crop
72
+ lx, ly, rx, ry = quad
73
+ lx, ly, rx, ry = int(lx), int(ly), int(rx), int(ry)
74
+ oy1, oy2, ox1, ox2 = cly+ly, min(cly+ry, full_frames[0].shape[0]), clx+lx, min(clx+rx, full_frames[0].shape[1])
75
+ # original_size = (ox2 - ox1, oy2 - oy1)
76
+ frames_pil = [Image.fromarray(cv2.resize(frame,(256,256))) for frame in full_frames_RGB]
77
+
78
+ # get the landmark according to the detected face.
79
+ if not os.path.isfile('temp/'+base_name+'_landmarks.txt') or args.re_preprocess:
80
+ print('[Step 1] Landmarks Extraction in Video.')
81
+ kp_extractor = KeypointExtractor()
82
+ lm = kp_extractor.extract_keypoint(frames_pil, './temp/'+base_name+'_landmarks.txt')
83
+ else:
84
+ print('[Step 1] Using saved landmarks.')
85
+ lm = np.loadtxt('temp/'+base_name+'_landmarks.txt').astype(np.float32)
86
+ lm = lm.reshape([len(full_frames), -1, 2])
87
+
88
+ if not os.path.isfile('temp/'+base_name+'_coeffs.npy') or args.exp_img is not None or args.re_preprocess:
89
+ net_recon = load_face3d_net(args.face3d_net_path, device)
90
+ lm3d_std = load_lm3d('checkpoints/BFM')
91
+
92
+ video_coeffs = []
93
+ for idx in tqdm(range(len(frames_pil)), desc="[Step 2] 3DMM Extraction In Video:"):
94
+ frame = frames_pil[idx]
95
+ W, H = frame.size
96
+ lm_idx = lm[idx].reshape([-1, 2])
97
+ if np.mean(lm_idx) == -1:
98
+ lm_idx = (lm3d_std[:, :2]+1) / 2.
99
+ lm_idx = np.concatenate([lm_idx[:, :1] * W, lm_idx[:, 1:2] * H], 1)
100
+ else:
101
+ lm_idx[:, -1] = H - 1 - lm_idx[:, -1]
102
+
103
+ trans_params, im_idx, lm_idx, _ = align_img(frame, lm_idx, lm3d_std)
104
+ trans_params = np.array([float(item) for item in np.hsplit(trans_params, 5)]).astype(np.float32)
105
+ im_idx_tensor = torch.tensor(np.array(im_idx)/255., dtype=torch.float32).permute(2, 0, 1).to(device).unsqueeze(0)
106
+ with torch.no_grad():
107
+ coeffs = split_coeff(net_recon(im_idx_tensor))
108
+
109
+ pred_coeff = {key:coeffs[key].cpu().numpy() for key in coeffs}
110
+ pred_coeff = np.concatenate([pred_coeff['id'], pred_coeff['exp'], pred_coeff['tex'], pred_coeff['angle'],\
111
+ pred_coeff['gamma'], pred_coeff['trans'], trans_params[None]], 1)
112
+ video_coeffs.append(pred_coeff)
113
+ semantic_npy = np.array(video_coeffs)[:,0]
114
+ np.save('temp/'+base_name+'_coeffs.npy', semantic_npy)
115
+ else:
116
+ print('[Step 2] Using saved coeffs.')
117
+ semantic_npy = np.load('temp/'+base_name+'_coeffs.npy').astype(np.float32)
118
+
119
+ # generate the 3dmm coeff from a single image
120
+ if args.exp_img is not None and ('.png' in args.exp_img or '.jpg' in args.exp_img):
121
+ print('extract the exp from',args.exp_img)
122
+ exp_pil = Image.open(args.exp_img).convert('RGB')
123
+ lm3d_std = load_lm3d('third_part/face3d/BFM')
124
+
125
+ W, H = exp_pil.size
126
+ kp_extractor = KeypointExtractor()
127
+ lm_exp = kp_extractor.extract_keypoint([exp_pil], 'temp/'+base_name+'_temp.txt')[0]
128
+ if np.mean(lm_exp) == -1:
129
+ lm_exp = (lm3d_std[:, :2] + 1) / 2.
130
+ lm_exp = np.concatenate(
131
+ [lm_exp[:, :1] * W, lm_exp[:, 1:2] * H], 1)
132
+ else:
133
+ lm_exp[:, -1] = H - 1 - lm_exp[:, -1]
134
+
135
+ trans_params, im_exp, lm_exp, _ = align_img(exp_pil, lm_exp, lm3d_std)
136
+ trans_params = np.array([float(item) for item in np.hsplit(trans_params, 5)]).astype(np.float32)
137
+ im_exp_tensor = torch.tensor(np.array(im_exp)/255., dtype=torch.float32).permute(2, 0, 1).to(device).unsqueeze(0)
138
+ with torch.no_grad():
139
+ expression = split_coeff(net_recon(im_exp_tensor))['exp'][0]
140
+ del net_recon
141
+ elif args.exp_img == 'smile':
142
+ expression = torch.tensor(loadmat('checkpoints/expression.mat')['expression_mouth'])[0]
143
+ else:
144
+ print('using expression center')
145
+ expression = torch.tensor(loadmat('checkpoints/expression.mat')['expression_center'])[0]
146
+
147
+ # load DNet, model(LNet and ENet)
148
+ D_Net, model = load_model(args, device)
149
+
150
+ if not os.path.isfile('temp/'+base_name+'_stablized.npy') or args.re_preprocess:
151
+ imgs = []
152
+ for idx in tqdm(range(len(frames_pil)), desc="[Step 3] Stabilize the expression In Video:"):
153
+ if args.one_shot:
154
+ source_img = trans_image(frames_pil[0]).unsqueeze(0).to(device)
155
+ semantic_source_numpy = semantic_npy[0:1]
156
+ else:
157
+ source_img = trans_image(frames_pil[idx]).unsqueeze(0).to(device)
158
+ semantic_source_numpy = semantic_npy[idx:idx+1]
159
+ ratio = find_crop_norm_ratio(semantic_source_numpy, semantic_npy)
160
+ coeff = transform_semantic(semantic_npy, idx, ratio).unsqueeze(0).to(device)
161
+
162
+ # hacking the new expression
163
+ coeff[:, :64, :] = expression[None, :64, None].to(device)
164
+ with torch.no_grad():
165
+ output = D_Net(source_img, coeff)
166
+ img_stablized = np.uint8((output['fake_image'].squeeze(0).permute(1,2,0).cpu().clamp_(-1, 1).numpy() + 1 )/2. * 255)
167
+ imgs.append(cv2.cvtColor(img_stablized,cv2.COLOR_RGB2BGR))
168
+ np.save('temp/'+base_name+'_stablized.npy',imgs)
169
+ del D_Net
170
+ else:
171
+ print('[Step 3] Using saved stabilized video.')
172
+ imgs = np.load('temp/'+base_name+'_stablized.npy')
173
+ torch.cuda.empty_cache()
174
+
175
+ if not args.audio.endswith('.wav'):
176
+ command = 'ffmpeg -loglevel error -y -i {} -strict -2 {}'.format(args.audio, 'temp/{}/temp.wav'.format(args.tmp_dir))
177
+ subprocess.call(command, shell=True)
178
+ args.audio = 'temp/{}/temp.wav'.format(args.tmp_dir)
179
+ wav = audio.load_wav(args.audio, 16000)
180
+ mel = audio.melspectrogram(wav)
181
+ if np.isnan(mel.reshape(-1)).sum() > 0:
182
+ raise ValueError('Mel contains nan! Using a TTS voice? Add a small epsilon noise to the wav file and try again')
183
+
184
+ mel_step_size, mel_idx_multiplier, i, mel_chunks = 16, 80./fps, 0, []
185
+ while True:
186
+ start_idx = int(i * mel_idx_multiplier)
187
+ if start_idx + mel_step_size > len(mel[0]):
188
+ mel_chunks.append(mel[:, len(mel[0]) - mel_step_size:])
189
+ break
190
+ mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size])
191
+ i += 1
192
+
193
+ print("[Step 4] Load audio; Length of mel chunks: {}".format(len(mel_chunks)))
194
+ imgs = imgs[:len(mel_chunks)]
195
+ full_frames = full_frames[:len(mel_chunks)]
196
+ lm = lm[:len(mel_chunks)]
197
+
198
+ imgs_enhanced = []
199
+ for idx in tqdm(range(len(imgs)), desc='[Step 5] Reference Enhancement'):
200
+ img = imgs[idx]
201
+ pred, _, _ = enhancer.process(img, img, face_enhance=True, possion_blending=False)
202
+ imgs_enhanced.append(pred)
203
+ gen = datagen(imgs_enhanced.copy(), mel_chunks, full_frames, None, (oy1,oy2,ox1,ox2))
204
+
205
+ frame_h, frame_w = full_frames[0].shape[:-1]
206
+ out = cv2.VideoWriter('temp/{}/result.mp4'.format(args.tmp_dir), cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_w, frame_h))
207
+
208
+ if args.up_face != 'original':
209
+ instance = GANimationModel()
210
+ instance.initialize()
211
+ instance.setup()
212
+
213
+ kp_extractor = KeypointExtractor()
214
+ for i, (img_batch, mel_batch, frames, coords, img_original, f_frames) in enumerate(tqdm(gen, desc='[Step 6] Lip Synthesis:', total=int(np.ceil(float(len(mel_chunks)) / args.LNet_batch_size)))):
215
+ img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(device)
216
+ mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(device)
217
+ img_original = torch.FloatTensor(np.transpose(img_original, (0, 3, 1, 2))).to(device)/255. # BGR -> RGB
218
+
219
+ with torch.no_grad():
220
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
221
+ pred, low_res = model(mel_batch, img_batch, reference)
222
+ pred = torch.clamp(pred, 0, 1)
223
+
224
+ if args.up_face in ['sad', 'angry', 'surprise']:
225
+ tar_aus = exp_aus_dict[args.up_face]
226
+ else:
227
+ pass
228
+
229
+ if args.up_face == 'original':
230
+ cur_gen_faces = img_original
231
+ else:
232
+ test_batch = {'src_img': torch.nn.functional.interpolate((img_original * 2 - 1), size=(128, 128), mode='bilinear'),
233
+ 'tar_aus': tar_aus.repeat(len(incomplete), 1)}
234
+ instance.feed_batch(test_batch)
235
+ instance.forward()
236
+ cur_gen_faces = torch.nn.functional.interpolate(instance.fake_img / 2. + 0.5, size=(384, 384), mode='bilinear')
237
+
238
+ if args.without_rl1 is not False:
239
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
240
+ mask = torch.where(incomplete==0, torch.ones_like(incomplete), torch.zeros_like(incomplete))
241
+ pred = pred * mask + cur_gen_faces * (1 - mask)
242
+
243
+ pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.
244
+
245
+ torch.cuda.empty_cache()
246
+ for p, f, xf, c in zip(pred, frames, f_frames, coords):
247
+ y1, y2, x1, x2 = c
248
+ p = cv2.resize(p.astype(np.uint8), (x2 - x1, y2 - y1))
249
+
250
+ ff = xf.copy()
251
+ ff[y1:y2, x1:x2] = p
252
+ height, width = ff.shape[:2]
253
+ pp = np.uint8(cv2.resize(np.clip(ff, 0 ,512), (width, height)))
254
+
255
+ pp, orig_faces, enhanced_faces = enhancer.process(pp, xf, bbox=c, face_enhance=True, possion_blending=False)
256
+ # month region enhancement by GFPGAN
257
+ cropped_faces, restored_faces, restored_img = restorer.enhance(
258
+ pp, has_aligned=False, only_center_face=True, paste_back=True)
259
+ # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
260
+ mm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0]
261
+ #mm = [0, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0]
262
+ mouse_mask = np.zeros_like(restored_img)
263
+ tmp_mask = enhancer.faceparser.process(restored_img[y1:y2, x1:x2], mm)[0]
264
+ mouse_mask[y1:y2, x1:x2]= cv2.resize(tmp_mask, (x2 - x1, y2 - y1))[:, :, np.newaxis] / 255.
265
+
266
+
267
+ restored_img, ff, full_mask = [cv2.resize(x, (1024, 1024)) for x in (restored_img, ff, np.float32(mouse_mask))]
268
+ img = Laplacian_Pyramid_Blending_with_mask(restored_img, ff, full_mask[:, :, 0], 10)
269
+ pp = np.uint8(cv2.resize(np.clip(img, 0 ,1024), (width, height)))
270
+ out.write(pp)
271
+ out.release()
272
+
273
+ if not os.path.isdir(os.path.dirname(args.outfile)):
274
+ os.makedirs(os.path.dirname(args.outfile), exist_ok=True)
275
+ command = 'ffmpeg -loglevel error -y -i {} -i {} -strict -2 -q:v 1 {}'.format(args.audio, 'temp/{}/result.mp4'.format(args.tmp_dir), args.outfile)
276
+ subprocess.call(command, shell=platform.system() != 'Windows')
277
+ print('outfile:', args.outfile)
278
+
279
+
280
+ # frames:256x256, full_frames: original size
281
+ def datagen(frames, mels, full_frames, frames_pil, cox):
282
+ img_batch, mel_batch, frame_batch, coords_batch, ref_batch, full_frame_batch = [], [], [], [], [], []
283
+ base_name = args.face.split('/')[-1]
284
+ refs = []
285
+ image_size = 256
286
+
287
+ # original frames
288
+ kp_extractor = KeypointExtractor()
289
+ fr_pil = [Image.fromarray(frame) for frame in frames]
290
+ lms = kp_extractor.extract_keypoint(fr_pil, 'temp/'+base_name+'x12_landmarks.txt')
291
+ frames_pil = [ (lm, frame) for frame,lm in zip(fr_pil, lms)] # frames is the croped version of modified face
292
+ crops, orig_images, quads = crop_faces(image_size, frames_pil, scale=1.0, use_fa=True)
293
+ inverse_transforms = [calc_alignment_coefficients(quad + 0.5, [[0, 0], [0, image_size], [image_size, image_size], [image_size, 0]]) for quad in quads]
294
+ del kp_extractor.detector
295
+
296
+ oy1,oy2,ox1,ox2 = cox
297
+ face_det_results = face_detect(full_frames, args, jaw_correction=True)
298
+
299
+ for inverse_transform, crop, full_frame, face_det in zip(inverse_transforms, crops, full_frames, face_det_results):
300
+ imc_pil = paste_image(inverse_transform, crop, Image.fromarray(
301
+ cv2.resize(full_frame[int(oy1):int(oy2), int(ox1):int(ox2)], (256, 256))))
302
+
303
+ ff = full_frame.copy()
304
+ ff[int(oy1):int(oy2), int(ox1):int(ox2)] = cv2.resize(np.array(imc_pil.convert('RGB')), (ox2 - ox1, oy2 - oy1))
305
+ oface, coords = face_det
306
+ y1, y2, x1, x2 = coords
307
+ refs.append(ff[y1: y2, x1:x2])
308
+
309
+ for i, m in enumerate(mels):
310
+ idx = 0 if args.static else i % len(frames)
311
+ frame_to_save = frames[idx].copy()
312
+ face = refs[idx]
313
+ oface, coords = face_det_results[idx].copy()
314
+
315
+ face = cv2.resize(face, (args.img_size, args.img_size))
316
+ oface = cv2.resize(oface, (args.img_size, args.img_size))
317
+
318
+ img_batch.append(oface)
319
+ ref_batch.append(face)
320
+ mel_batch.append(m)
321
+ coords_batch.append(coords)
322
+ frame_batch.append(frame_to_save)
323
+ full_frame_batch.append(full_frames[idx].copy())
324
+
325
+ if len(img_batch) >= args.LNet_batch_size:
326
+ img_batch, mel_batch, ref_batch = np.asarray(img_batch), np.asarray(mel_batch), np.asarray(ref_batch)
327
+ img_masked = img_batch.copy()
328
+ img_original = img_batch.copy()
329
+ img_masked[:, args.img_size//2:] = 0
330
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.
331
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
332
+
333
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
334
+ img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch, ref_batch = [], [], [], [], [], [], []
335
+
336
+ if len(img_batch) > 0:
337
+ img_batch, mel_batch, ref_batch = np.asarray(img_batch), np.asarray(mel_batch), np.asarray(ref_batch)
338
+ img_masked = img_batch.copy()
339
+ img_original = img_batch.copy()
340
+ img_masked[:, args.img_size//2:] = 0
341
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.
342
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
343
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
344
+
345
+
346
+ if __name__ == '__main__':
347
+ main()
videoretalking/inference_function.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2, os, sys, subprocess, platform, torch
3
+ from tqdm import tqdm
4
+ from PIL import Image
5
+ from scipy.io import loadmat
6
+ from moviepy.editor import AudioFileClip, VideoFileClip
7
+
8
+ sys.path.insert(0, 'third_part')
9
+ sys.path.insert(0, 'third_part/GPEN')
10
+
11
+ # 3dmm extraction
12
+ from third_part.face3d.util.preprocess import align_img
13
+ from third_part.face3d.util.load_mats import load_lm3d
14
+ from third_part.face3d.extract_kp_videos import KeypointExtractor
15
+ # face enhancement
16
+ from third_part.GPEN.gpen_face_enhancer import FaceEnhancement
17
+ # expression control
18
+ from third_part.ganimation_replicate.model.ganimation import GANimationModel
19
+
20
+ from utils import audio
21
+ from utils.ffhq_preprocess import Croper
22
+ from utils.alignment_stit import crop_faces, calc_alignment_coefficients, paste_image
23
+ from utils.inference_utils import Laplacian_Pyramid_Blending_with_mask, face_detect, load_model, options, split_coeff, \
24
+ trans_image, transform_semantic, find_crop_norm_ratio, load_face3d_net, exp_aus_dict
25
+ import warnings
26
+ warnings.filterwarnings("ignore")
27
+
28
+ def video_lipsync_correctness(face, audio_path, outfile=None, tmp_dir="temp", crop=[0, -1, 0, -1], re_preprocess=False, exp_img="neutral", face3d_net_path="checkpoints/face3d_pretrain_epoch_20.pth", one_shot=False, up_face="original", LNet_batch_size=16, without_rl1=False, static=False):
29
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
30
+ print('[Info] Using {} for inference.'.format(device))
31
+ os.makedirs(os.path.join('temp', tmp_dir), exist_ok=True)
32
+
33
+ enhancer = FaceEnhancement(base_dir='checkpoints', size=512, model='GPEN-BFR-512', use_sr=False, \
34
+ sr_model='rrdb_realesrnet_psnr', channel_multiplier=2, narrow=1, device=device)
35
+
36
+ base_name = face.split('/')[-1]
37
+ print('base_name',base_name)
38
+ if os.path.isfile(face) and face.split('.')[1] in ['jpg', 'png', 'jpeg']:
39
+ static = True
40
+ if not os.path.isfile(face):
41
+ raise ValueError('--face argument must be a valid path to video/image file')
42
+ elif face.split('.')[1] in ['jpg', 'png', 'jpeg']:
43
+ full_frames = [cv2.imread(face)]
44
+ fps = fps
45
+ else:
46
+ video_stream = cv2.VideoCapture(face)
47
+ fps = video_stream.get(cv2.CAP_PROP_FPS)
48
+
49
+ full_frames = []
50
+ while True:
51
+ still_reading, frame = video_stream.read()
52
+ if not still_reading:
53
+ video_stream.release()
54
+ break
55
+ y1, y2, x1, x2 = crop
56
+ if x2 == -1: x2 = frame.shape[1]
57
+ if y2 == -1: y2 = frame.shape[0]
58
+ frame = frame[y1:y2, x1:x2]
59
+ full_frames.append(frame)
60
+
61
+ print ("[Step 0] Number of frames available for inference: "+str(len(full_frames)))
62
+ # face detection & cropping, cropping the first frame as the style of FFHQ
63
+ croper = Croper('checkpoints/shape_predictor_68_face_landmarks.dat')
64
+ full_frames_RGB = [cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) for frame in full_frames]
65
+ full_frames_RGB, crop, quad = croper.crop(full_frames_RGB, xsize=512)
66
+
67
+ clx, cly, crx, cry = crop
68
+ lx, ly, rx, ry = quad
69
+ lx, ly, rx, ry = int(lx), int(ly), int(rx), int(ry)
70
+ oy1, oy2, ox1, ox2 = cly+ly, min(cly+ry, full_frames[0].shape[0]), clx+lx, min(clx+rx, full_frames[0].shape[1])
71
+ # original_size = (ox2 - ox1, oy2 - oy1)
72
+ frames_pil = [Image.fromarray(cv2.resize(frame,(256,256))) for frame in full_frames_RGB]
73
+
74
+ # get the landmark according to the detected face.
75
+ if not os.path.isfile('temp/'+base_name+'_landmarks.txt') or re_preprocess:
76
+ print('[Step 1] Landmarks Extraction in Video.')
77
+ kp_extractor = KeypointExtractor()
78
+ lm = kp_extractor.extract_keypoint(frames_pil, 'temp/'+base_name+'_landmarks.txt')
79
+ else:
80
+ print('[Step 1] Using saved landmarks.')
81
+ lm = np.loadtxt('temp/'+base_name+'_landmarks.txt').astype(np.float32)
82
+ lm = lm.reshape([len(full_frames), -1, 2])
83
+
84
+ if not os.path.isfile('temp/'+base_name+'_coeffs.npy') or exp_img is not None or re_preprocess:
85
+ net_recon = load_face3d_net(face3d_net_path, device)
86
+ lm3d_std = load_lm3d('checkpoints/BFM_Fitting')
87
+
88
+ video_coeffs = []
89
+ for idx in tqdm(range(len(frames_pil)), desc="[Step 2] 3DMM Extraction In Video:"):
90
+ frame = frames_pil[idx]
91
+ W, H = frame.size
92
+ lm_idx = lm[idx].reshape([-1, 2])
93
+ if np.mean(lm_idx) == -1:
94
+ lm_idx = (lm3d_std[:, :2]+1) / 2.
95
+ lm_idx = np.concatenate([lm_idx[:, :1] * W, lm_idx[:, 1:2] * H], 1)
96
+ else:
97
+ lm_idx[:, -1] = H - 1 - lm_idx[:, -1]
98
+
99
+ trans_params, im_idx, lm_idx, _ = align_img(frame, lm_idx, lm3d_std)
100
+ trans_params = np.array([float(item) for item in np.hsplit(trans_params, 5)]).astype(np.float32)
101
+ im_idx_tensor = torch.tensor(np.array(im_idx)/255., dtype=torch.float32).permute(2, 0, 1).to(device).unsqueeze(0)
102
+ with torch.no_grad():
103
+ coeffs = split_coeff(net_recon(im_idx_tensor))
104
+
105
+ pred_coeff = {key:coeffs[key].cpu().numpy() for key in coeffs}
106
+ pred_coeff = np.concatenate([pred_coeff['id'], pred_coeff['exp'], pred_coeff['tex'], pred_coeff['angle'],\
107
+ pred_coeff['gamma'], pred_coeff['trans'], trans_params[None]], 1)
108
+ video_coeffs.append(pred_coeff)
109
+ semantic_npy = np.array(video_coeffs)[:,0]
110
+ np.save('temp/'+base_name+'_coeffs.npy', semantic_npy)
111
+ else:
112
+ print('[Step 2] Using saved coeffs.')
113
+ semantic_npy = np.load('temp/'+base_name+'_coeffs.npy').astype(np.float32)
114
+
115
+ # generate the 3dmm coeff from a single image
116
+ if exp_img is not None and ('.png' in exp_img or '.jpg' in exp_img):
117
+ print('extract the exp from',exp_img)
118
+ exp_pil = Image.open(exp_img).convert('RGB')
119
+ lm3d_std = load_lm3d('third_part/face3d/BFM')
120
+
121
+ W, H = exp_pil.size
122
+ kp_extractor = KeypointExtractor()
123
+ lm_exp = kp_extractor.extract_keypoint([exp_pil], 'temp/'+base_name+'_temp.txt')[0]
124
+ if np.mean(lm_exp) == -1:
125
+ lm_exp = (lm3d_std[:, :2] + 1) / 2.
126
+ lm_exp = np.concatenate(
127
+ [lm_exp[:, :1] * W, lm_exp[:, 1:2] * H], 1)
128
+ else:
129
+ lm_exp[:, -1] = H - 1 - lm_exp[:, -1]
130
+
131
+ trans_params, im_exp, lm_exp, _ = align_img(exp_pil, lm_exp, lm3d_std)
132
+ trans_params = np.array([float(item) for item in np.hsplit(trans_params, 5)]).astype(np.float32)
133
+ im_exp_tensor = torch.tensor(np.array(im_exp)/255., dtype=torch.float32).permute(2, 0, 1).to(device).unsqueeze(0)
134
+ with torch.no_grad():
135
+ expression = split_coeff(net_recon(im_exp_tensor))['exp'][0]
136
+ del net_recon
137
+ elif exp_img == 'smile':
138
+ expression = torch.tensor(loadmat('checkpoints/expression.mat')['expression_mouth'])[0]
139
+ else:
140
+ print('using expression center')
141
+ expression = torch.tensor(loadmat('checkpoints/expression.mat')['expression_center'])[0]
142
+
143
+ # load DNet, model(LNet and ENet)
144
+ D_Net, model = load_model(device,DNet_path='checkpoints/DNet.pt',LNet_path='checkpoints/LNet.pth',ENet_path='checkpoints/ENet.pth')
145
+
146
+ if not os.path.isfile('temp/'+base_name+'_stablized.npy') or re_preprocess:
147
+ imgs = []
148
+ for idx in tqdm(range(len(frames_pil)), desc="[Step 3] Stabilize the expression In Video:"):
149
+ if one_shot:
150
+ source_img = trans_image(frames_pil[0]).unsqueeze(0).to(device)
151
+ semantic_source_numpy = semantic_npy[0:1]
152
+ else:
153
+ source_img = trans_image(frames_pil[idx]).unsqueeze(0).to(device)
154
+ semantic_source_numpy = semantic_npy[idx:idx+1]
155
+ ratio = find_crop_norm_ratio(semantic_source_numpy, semantic_npy)
156
+ coeff = transform_semantic(semantic_npy, idx, ratio).unsqueeze(0).to(device)
157
+
158
+ # hacking the new expression
159
+ coeff[:, :64, :] = expression[None, :64, None].to(device)
160
+ with torch.no_grad():
161
+ output = D_Net(source_img, coeff)
162
+ img_stablized = np.uint8((output['fake_image'].squeeze(0).permute(1,2,0).cpu().clamp_(-1, 1).numpy() + 1 )/2. * 255)
163
+ imgs.append(cv2.cvtColor(img_stablized,cv2.COLOR_RGB2BGR))
164
+ np.save('temp/'+base_name+'_stablized.npy',imgs)
165
+ del D_Net
166
+ else:
167
+ print('[Step 3] Using saved stabilized video.')
168
+ imgs = np.load('temp/'+base_name+'_stablized.npy')
169
+ torch.cuda.empty_cache()
170
+
171
+ if not audio_path.endswith('.wav'):
172
+ # command = 'ffmpeg -loglevel error -y -i {} -strict -2 {}'.format(audio_path, 'temp/{}/temp.wav'.format(tmp_dir))
173
+ # subprocess.call(command, shell=True)
174
+ converted_audio_path = os.path.join('temp', tmp_dir, 'temp.wav')
175
+ audio_clip = AudioFileClip(audio_path)
176
+ audio_clip.write_audiofile(converted_audio_path, codec='pcm_s16le')
177
+ audio_clip.close()
178
+ audio_path = converted_audio_path
179
+ # audio_path = 'temp/{}/temp.wav'.format(tmp_dir)
180
+ wav = audio.load_wav(audio_path, 16000)
181
+ mel = audio.melspectrogram(wav)
182
+ if np.isnan(mel.reshape(-1)).sum() > 0:
183
+ raise ValueError('Mel contains nan! Using a TTS voice? Add a small epsilon noise to the wav file and try again')
184
+
185
+ mel_step_size, mel_idx_multiplier, i, mel_chunks = 16, 80./fps, 0, []
186
+ while True:
187
+ start_idx = int(i * mel_idx_multiplier)
188
+ if start_idx + mel_step_size > len(mel[0]):
189
+ mel_chunks.append(mel[:, len(mel[0]) - mel_step_size:])
190
+ break
191
+ mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size])
192
+ i += 1
193
+
194
+ print("[Step 4] Load audio; Length of mel chunks: {}".format(len(mel_chunks)))
195
+ imgs = imgs[:len(mel_chunks)]
196
+ full_frames = full_frames[:len(mel_chunks)]
197
+ lm = lm[:len(mel_chunks)]
198
+
199
+ imgs_enhanced = []
200
+ for idx in tqdm(range(len(imgs)), desc='[Step 5] Reference Enhancement'):
201
+ img = imgs[idx]
202
+ pred, _, _ = enhancer.process(img, img, face_enhance=True, possion_blending=False)
203
+ imgs_enhanced.append(pred)
204
+ gen = datagen(imgs_enhanced.copy(), mel_chunks, full_frames, None, (oy1,oy2,ox1,ox2), face, static, LNet_batch_size, img_size=384)
205
+
206
+ frame_h, frame_w = full_frames[0].shape[:-1]
207
+ out = cv2.VideoWriter('temp/{}/result.mp4'.format(tmp_dir), cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_w, frame_h))
208
+
209
+ if up_face != 'original':
210
+ instance = GANimationModel()
211
+ instance.initialize()
212
+ instance.setup()
213
+
214
+ kp_extractor = KeypointExtractor()
215
+ for i, (img_batch, mel_batch, frames, coords, img_original, f_frames) in enumerate(tqdm(gen, desc='[Step 6] Lip Synthesis:', total=int(np.ceil(float(len(mel_chunks)) / LNet_batch_size)))):
216
+ img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(device)
217
+ mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(device)
218
+ img_original = torch.FloatTensor(np.transpose(img_original, (0, 3, 1, 2))).to(device)/255. # BGR -> RGB
219
+
220
+ with torch.no_grad():
221
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
222
+ pred, low_res = model(mel_batch, img_batch, reference)
223
+ pred = torch.clamp(pred, 0, 1)
224
+
225
+ if up_face in ['sad', 'angry', 'surprise']:
226
+ tar_aus = exp_aus_dict[up_face]
227
+ else:
228
+ pass
229
+
230
+ if up_face == 'original':
231
+ cur_gen_faces = img_original
232
+ else:
233
+ test_batch = {'src_img': torch.nn.functional.interpolate((img_original * 2 - 1), size=(128, 128), mode='bilinear'),
234
+ 'tar_aus': tar_aus.repeat(len(incomplete), 1)}
235
+ instance.feed_batch(test_batch)
236
+ instance.forward()
237
+ cur_gen_faces = torch.nn.functional.interpolate(instance.fake_img / 2. + 0.5, size=(384, 384), mode='bilinear')
238
+
239
+ if without_rl1 is not False:
240
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
241
+ mask = torch.where(incomplete==0, torch.ones_like(incomplete), torch.zeros_like(incomplete))
242
+ pred = pred * mask + cur_gen_faces * (1 - mask)
243
+
244
+ pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.
245
+
246
+ torch.cuda.empty_cache()
247
+ for p, f, xf, c in zip(pred, frames, f_frames, coords):
248
+ y1, y2, x1, x2 = c
249
+ p = cv2.resize(p.astype(np.uint8), (x2 - x1, y2 - y1))
250
+
251
+ ff = xf.copy()
252
+ ff[y1:y2, x1:x2] = p
253
+
254
+ restored_img = ff
255
+ mm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0]
256
+ mouse_mask = np.zeros_like(restored_img)
257
+ tmp_mask = enhancer.faceparser.process(restored_img[y1:y2, x1:x2], mm)[0]
258
+ mouse_mask[y1:y2, x1:x2]= cv2.resize(tmp_mask, (x2 - x1, y2 - y1))[:, :, np.newaxis] / 255.
259
+
260
+ height, width = ff.shape[:2]
261
+ restored_img, ff, full_mask = [cv2.resize(x, (512, 512)) for x in (restored_img, ff, np.float32(mouse_mask))]
262
+ img = Laplacian_Pyramid_Blending_with_mask(restored_img, ff, full_mask[:, :, 0], 10)
263
+ pp = np.uint8(cv2.resize(np.clip(img, 0 ,255), (width, height)))
264
+
265
+ pp, orig_faces, enhanced_faces = enhancer.process(pp, xf, bbox=c, face_enhance=False, possion_blending=True)
266
+ out.write(pp)
267
+ out.release()
268
+
269
+ if not os.path.isdir(os.path.dirname(outfile)):
270
+ os.makedirs(os.path.dirname(outfile), exist_ok=True)
271
+ # command = 'ffmpeg -loglevel error -y -i {} -i {} -strict -2 -q:v 1 {}'.format(audio_path, 'temp/{}/result.mp4'.format(tmp_dir), outfile)
272
+ # subprocess.call(command, shell=platform.system() != 'Windows')
273
+ video_path = 'temp/{}/result.mp4'.format(tmp_dir)
274
+ audio_clip = AudioFileClip(audio_path)
275
+ video_clip = VideoFileClip(video_path)
276
+ video_clip = video_clip.set_audio(audio_clip)
277
+
278
+ # Write the result to the output file
279
+ video_clip.write_videofile(outfile, codec='libx264', audio_codec='aac')
280
+ print('outfile:', outfile)
281
+
282
+ # frames:256x256, full_frames: original size
283
+ def datagen(frames, mels, full_frames, frames_pil, cox, face, static, LNet_batch_size, img_size):
284
+ img_batch, mel_batch, frame_batch, coords_batch, ref_batch, full_frame_batch = [], [], [], [], [], []
285
+ base_name = face.split('/')[-1]
286
+ refs = []
287
+ image_size = 256
288
+
289
+ # original frames
290
+ kp_extractor = KeypointExtractor()
291
+ fr_pil = [Image.fromarray(frame) for frame in frames]
292
+ lms = kp_extractor.extract_keypoint(fr_pil, 'temp/'+base_name+'x12_landmarks.txt')
293
+ frames_pil = [ (lm, frame) for frame,lm in zip(fr_pil, lms)] # frames is the croped version of modified face
294
+ crops, orig_images, quads = crop_faces(image_size, frames_pil, scale=1.0, use_fa=True)
295
+ inverse_transforms = [calc_alignment_coefficients(quad + 0.5, [[0, 0], [0, image_size], [image_size, image_size], [image_size, 0]]) for quad in quads]
296
+ del kp_extractor.detector
297
+
298
+ oy1,oy2,ox1,ox2 = cox
299
+ face_det_results = face_detect(full_frames, face_det_batch_size=4, nosmooth=False, pads=[0, 20, 0, 0], jaw_correction=True, detector=None)
300
+
301
+ for inverse_transform, crop, full_frame, face_det in zip(inverse_transforms, crops, full_frames, face_det_results):
302
+ imc_pil = paste_image(inverse_transform, crop, Image.fromarray(
303
+ cv2.resize(full_frame[int(oy1):int(oy2), int(ox1):int(ox2)], (256, 256))))
304
+
305
+ ff = full_frame.copy()
306
+ ff[int(oy1):int(oy2), int(ox1):int(ox2)] = cv2.resize(np.array(imc_pil.convert('RGB')), (ox2 - ox1, oy2 - oy1))
307
+ oface, coords = face_det
308
+ y1, y2, x1, x2 = coords
309
+ refs.append(ff[y1: y2, x1:x2])
310
+
311
+ for i, m in enumerate(mels):
312
+ idx = 0 if static else i % len(frames)
313
+ frame_to_save = frames[idx].copy()
314
+ face = refs[idx]
315
+ oface, coords = face_det_results[idx].copy()
316
+
317
+ face = cv2.resize(face, (img_size, img_size))
318
+ oface = cv2.resize(oface, (img_size, img_size))
319
+
320
+ img_batch.append(oface)
321
+ ref_batch.append(face)
322
+ mel_batch.append(m)
323
+ coords_batch.append(coords)
324
+ frame_batch.append(frame_to_save)
325
+ full_frame_batch.append(full_frames[idx].copy())
326
+
327
+ if len(img_batch) >= LNet_batch_size:
328
+ img_batch, mel_batch, ref_batch = np.asarray(img_batch), np.asarray(mel_batch), np.asarray(ref_batch)
329
+ img_masked = img_batch.copy()
330
+ img_original = img_batch.copy()
331
+ img_masked[:, img_size//2:] = 0
332
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.
333
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
334
+
335
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
336
+ img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch, ref_batch = [], [], [], [], [], [], []
337
+
338
+ if len(img_batch) > 0:
339
+ img_batch, mel_batch, ref_batch = np.asarray(img_batch), np.asarray(mel_batch), np.asarray(ref_batch)
340
+ img_masked = img_batch.copy()
341
+ img_original = img_batch.copy()
342
+ img_masked[:, img_size//2:] = 0
343
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.
344
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
345
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
346
+
347
+
348
+
349
+ if __name__ == "__main__":
350
+ face_path = "C:/Users/fd01076/Downloads/download_1.mp4" # Replace with the path to your face image or video
351
+ audio_path = "C:/Users/fd01076/Downloads/audio_1.mp3" # Replace with the path to your audio file
352
+ output_path = "C:/Users/fd01076/Downloads/result.mp4" # Replace with the path for the output video
353
+
354
+ # Call the function
355
+ video_lipsync_correctness(
356
+ face=face_path,
357
+ audio_path=audio_path,
358
+ outfile=output_path,
359
+ tmp_dir="temp",
360
+ crop=[0, -1, 0, -1],
361
+ re_preprocess=True, # Set to True if you want to reprocess; False otherwise
362
+ exp_img="neutral", # Can be 'smile', 'neutral', or path to an expression image
363
+ face3d_net_path="checkpoints/face3d_pretrain_epoch_20.pth",
364
+ one_shot=False,
365
+ up_face="original", # Options: 'original', 'sad', 'angry', 'surprise'
366
+ LNet_batch_size=16,
367
+ without_rl1=False
368
+ )
videoretalking/inference_videoretalking.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ python3 inference.py \
2
+ --face ./examples/face/1.mp4 \
3
+ --audio ./examples/audio/1.wav \
4
+ --outfile results/1_1.mp4
videoretalking/predict.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prediction interface for Cog ⚙️
2
+ # https://github.com/replicate/cog/blob/main/docs/python.md
3
+
4
+ import os
5
+ import sys
6
+ import argparse
7
+ import subprocess
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ from PIL import Image
11
+ from scipy.io import loadmat
12
+ import torch
13
+ import cv2
14
+ from cog import BasePredictor, Input, Path
15
+
16
+ sys.path.insert(0, "third_part")
17
+ sys.path.insert(0, "third_part/GPEN")
18
+ sys.path.insert(0, "third_part/GFPGAN")
19
+
20
+ # 3dmm extraction
21
+ from third_part.face3d.util.preprocess import align_img
22
+ from third_part.face3d.util.load_mats import load_lm3d
23
+ from third_part.face3d.extract_kp_videos import KeypointExtractor
24
+
25
+ # face enhancement
26
+ from third_part.GPEN.gpen_face_enhancer import FaceEnhancement
27
+ from third_part.GFPGAN.gfpgan import GFPGANer
28
+
29
+ # expression control
30
+ from third_part.ganimation_replicate.model.ganimation import GANimationModel
31
+
32
+ from utils import audio
33
+ from utils.ffhq_preprocess import Croper
34
+ from utils.alignment_stit import crop_faces, calc_alignment_coefficients, paste_image
35
+ from utils.inference_utils import (
36
+ Laplacian_Pyramid_Blending_with_mask,
37
+ face_detect,
38
+ load_model,
39
+ options,
40
+ split_coeff,
41
+ trans_image,
42
+ transform_semantic,
43
+ find_crop_norm_ratio,
44
+ load_face3d_net,
45
+ exp_aus_dict,
46
+ )
47
+
48
+
49
+ class Predictor(BasePredictor):
50
+ def setup(self) -> None:
51
+ """Load the model into memory to make running multiple predictions efficient"""
52
+ self.enhancer = FaceEnhancement(
53
+ base_dir="checkpoints",
54
+ size=512,
55
+ model="GPEN-BFR-512",
56
+ use_sr=False,
57
+ sr_model="rrdb_realesrnet_psnr",
58
+ channel_multiplier=2,
59
+ narrow=1,
60
+ device="cuda",
61
+ )
62
+ self.restorer = GFPGANer(
63
+ model_path="checkpoints/GFPGANv1.3.pth",
64
+ upscale=1,
65
+ arch="clean",
66
+ channel_multiplier=2,
67
+ bg_upsampler=None,
68
+ )
69
+ self.croper = Croper("checkpoints/shape_predictor_68_face_landmarks.dat")
70
+ self.kp_extractor = KeypointExtractor()
71
+
72
+ face3d_net_path = "checkpoints/face3d_pretrain_epoch_20.pth"
73
+
74
+ self.net_recon = load_face3d_net(face3d_net_path, "cuda")
75
+ self.lm3d_std = load_lm3d("checkpoints/BFM")
76
+
77
+ def predict(
78
+ self,
79
+ face: Path = Input(description="Input video file of a talking-head."),
80
+ input_audio: Path = Input(description="Input audio file."),
81
+ ) -> Path:
82
+ """Run a single prediction on the model"""
83
+ device = "cuda"
84
+ args = argparse.Namespace(
85
+ DNet_path="checkpoints/DNet.pt",
86
+ LNet_path="checkpoints/LNet.pth",
87
+ ENet_path="checkpoints/ENet.pth",
88
+ face3d_net_path="checkpoints/face3d_pretrain_epoch_20.pth",
89
+ face=str(face),
90
+ audio=str(input_audio),
91
+ exp_img="neutral",
92
+ outfile=None,
93
+ fps=25,
94
+ pads=[0, 20, 0, 0],
95
+ face_det_batch_size=4,
96
+ LNet_batch_size=16,
97
+ img_size=384,
98
+ crop=[0, -1, 0, -1],
99
+ box=[-1, -1, -1, -1],
100
+ nosmooth=False,
101
+ static=False,
102
+ up_face="original",
103
+ one_shot=False,
104
+ without_rl1=False,
105
+ tmp_dir="temp",
106
+ re_preprocess=False,
107
+ )
108
+
109
+ base_name = args.face.split("/")[-1]
110
+
111
+ if args.face.split(".")[1] in ["jpg", "png", "jpeg"]:
112
+ full_frames = [cv2.imread(args.face)]
113
+ args.static = True
114
+ fps = args.fps
115
+ else:
116
+ video_stream = cv2.VideoCapture(args.face)
117
+ fps = video_stream.get(cv2.CAP_PROP_FPS)
118
+ full_frames = []
119
+ while True:
120
+ still_reading, frame = video_stream.read()
121
+ if not still_reading:
122
+ video_stream.release()
123
+ break
124
+ y1, y2, x1, x2 = args.crop
125
+ if x2 == -1:
126
+ x2 = frame.shape[1]
127
+ if y2 == -1:
128
+ y2 = frame.shape[0]
129
+ frame = frame[y1:y2, x1:x2]
130
+ full_frames.append(frame)
131
+
132
+ full_frames_RGB = [
133
+ cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) for frame in full_frames
134
+ ]
135
+ full_frames_RGB, crop, quad = self.croper.crop(full_frames_RGB, xsize=512)
136
+
137
+ clx, cly, crx, cry = crop
138
+ lx, ly, rx, ry = quad
139
+ lx, ly, rx, ry = int(lx), int(ly), int(rx), int(ry)
140
+ oy1, oy2, ox1, ox2 = (
141
+ cly + ly,
142
+ min(cly + ry, full_frames[0].shape[0]),
143
+ clx + lx,
144
+ min(clx + rx, full_frames[0].shape[1]),
145
+ )
146
+ # original_size = (ox2 - ox1, oy2 - oy1)
147
+ frames_pil = [
148
+ Image.fromarray(cv2.resize(frame, (256, 256))) for frame in full_frames_RGB
149
+ ]
150
+
151
+ # get the landmark according to the detected face.
152
+ if (
153
+ not os.path.isfile("temp/" + base_name + "_landmarks.txt")
154
+ or args.re_preprocess
155
+ ):
156
+ print("[Step 1] Landmarks Extraction in Video.")
157
+ lm = self.kp_extractor.extract_keypoint(
158
+ frames_pil, "./temp/" + base_name + "_landmarks.txt"
159
+ )
160
+ else:
161
+ print("[Step 1] Using saved landmarks.")
162
+ lm = np.loadtxt("temp/" + base_name + "_landmarks.txt").astype(np.float32)
163
+ lm = lm.reshape([len(full_frames), -1, 2])
164
+
165
+ if (
166
+ not os.path.isfile("temp/" + base_name + "_coeffs.npy")
167
+ or args.exp_img is not None
168
+ or args.re_preprocess
169
+ ):
170
+ video_coeffs = []
171
+ for idx in tqdm(
172
+ range(len(frames_pil)), desc="[Step 2] 3DMM Extraction In Video:"
173
+ ):
174
+ frame = frames_pil[idx]
175
+ W, H = frame.size
176
+ lm_idx = lm[idx].reshape([-1, 2])
177
+ if np.mean(lm_idx) == -1:
178
+ lm_idx = (self.lm3d_std[:, :2] + 1) / 2.0
179
+ lm_idx = np.concatenate([lm_idx[:, :1] * W, lm_idx[:, 1:2] * H], 1)
180
+ else:
181
+ lm_idx[:, -1] = H - 1 - lm_idx[:, -1]
182
+
183
+ trans_params, im_idx, lm_idx, _ = align_img(
184
+ frame, lm_idx, self.lm3d_std
185
+ )
186
+ trans_params = np.array(
187
+ [float(item) for item in np.hsplit(trans_params, 5)]
188
+ ).astype(np.float32)
189
+ im_idx_tensor = (
190
+ torch.tensor(np.array(im_idx) / 255.0, dtype=torch.float32)
191
+ .permute(2, 0, 1)
192
+ .to(device)
193
+ .unsqueeze(0)
194
+ )
195
+ with torch.no_grad():
196
+ coeffs = split_coeff(self.net_recon(im_idx_tensor))
197
+
198
+ pred_coeff = {key: coeffs[key].cpu().numpy() for key in coeffs}
199
+ pred_coeff = np.concatenate(
200
+ [
201
+ pred_coeff["id"],
202
+ pred_coeff["exp"],
203
+ pred_coeff["tex"],
204
+ pred_coeff["angle"],
205
+ pred_coeff["gamma"],
206
+ pred_coeff["trans"],
207
+ trans_params[None],
208
+ ],
209
+ 1,
210
+ )
211
+ video_coeffs.append(pred_coeff)
212
+ semantic_npy = np.array(video_coeffs)[:, 0]
213
+ np.save("temp/" + base_name + "_coeffs.npy", semantic_npy)
214
+ else:
215
+ print("[Step 2] Using saved coeffs.")
216
+ semantic_npy = np.load("temp/" + base_name + "_coeffs.npy").astype(
217
+ np.float32
218
+ )
219
+
220
+ # generate the 3dmm coeff from a single image
221
+ if args.exp_img == "smile":
222
+ expression = torch.tensor(
223
+ loadmat("checkpoints/expression.mat")["expression_mouth"]
224
+ )[0]
225
+ else:
226
+ print("using expression center")
227
+ expression = torch.tensor(
228
+ loadmat("checkpoints/expression.mat")["expression_center"]
229
+ )[0]
230
+
231
+ # load DNet, model(LNet and ENet)
232
+ D_Net, model = load_model(args, device)
233
+
234
+ if (
235
+ not os.path.isfile("temp/" + base_name + "_stablized.npy")
236
+ or args.re_preprocess
237
+ ):
238
+ imgs = []
239
+ for idx in tqdm(
240
+ range(len(frames_pil)),
241
+ desc="[Step 3] Stabilize the expression In Video:",
242
+ ):
243
+ if args.one_shot:
244
+ source_img = trans_image(frames_pil[0]).unsqueeze(0).to(device)
245
+ semantic_source_numpy = semantic_npy[0:1]
246
+ else:
247
+ source_img = trans_image(frames_pil[idx]).unsqueeze(0).to(device)
248
+ semantic_source_numpy = semantic_npy[idx : idx + 1]
249
+ ratio = find_crop_norm_ratio(semantic_source_numpy, semantic_npy)
250
+ coeff = (
251
+ transform_semantic(semantic_npy, idx, ratio).unsqueeze(0).to(device)
252
+ )
253
+
254
+ # hacking the new expression
255
+ coeff[:, :64, :] = expression[None, :64, None].to(device)
256
+ with torch.no_grad():
257
+ output = D_Net(source_img, coeff)
258
+ img_stablized = np.uint8(
259
+ (
260
+ output["fake_image"]
261
+ .squeeze(0)
262
+ .permute(1, 2, 0)
263
+ .cpu()
264
+ .clamp_(-1, 1)
265
+ .numpy()
266
+ + 1
267
+ )
268
+ / 2.0
269
+ * 255
270
+ )
271
+ imgs.append(cv2.cvtColor(img_stablized, cv2.COLOR_RGB2BGR))
272
+ np.save("temp/" + base_name + "_stablized.npy", imgs)
273
+ del D_Net
274
+ else:
275
+ print("[Step 3] Using saved stabilized video.")
276
+ imgs = np.load("temp/" + base_name + "_stablized.npy")
277
+ torch.cuda.empty_cache()
278
+
279
+ if not args.audio.endswith(".wav"):
280
+ command = "ffmpeg -loglevel error -y -i {} -strict -2 {}".format(
281
+ args.audio, "temp/{}/temp.wav".format(args.tmp_dir)
282
+ )
283
+ subprocess.call(command, shell=True)
284
+ args.audio = "temp/{}/temp.wav".format(args.tmp_dir)
285
+ wav = audio.load_wav(args.audio, 16000)
286
+ mel = audio.melspectrogram(wav)
287
+ if np.isnan(mel.reshape(-1)).sum() > 0:
288
+ raise ValueError(
289
+ "Mel contains nan! Using a TTS voice? Add a small epsilon noise to the wav file and try again"
290
+ )
291
+
292
+ mel_step_size, mel_idx_multiplier, i, mel_chunks = 16, 80.0 / fps, 0, []
293
+ while True:
294
+ start_idx = int(i * mel_idx_multiplier)
295
+ if start_idx + mel_step_size > len(mel[0]):
296
+ mel_chunks.append(mel[:, len(mel[0]) - mel_step_size :])
297
+ break
298
+ mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size])
299
+ i += 1
300
+
301
+ print("[Step 4] Load audio; Length of mel chunks: {}".format(len(mel_chunks)))
302
+ imgs = imgs[: len(mel_chunks)]
303
+ full_frames = full_frames[: len(mel_chunks)]
304
+ lm = lm[: len(mel_chunks)]
305
+
306
+ imgs_enhanced = []
307
+ for idx in tqdm(range(len(imgs)), desc="[Step 5] Reference Enhancement"):
308
+ img = imgs[idx]
309
+ pred, _, _ = self.enhancer.process(
310
+ img, img, face_enhance=True, possion_blending=False
311
+ )
312
+ imgs_enhanced.append(pred)
313
+ gen = datagen(
314
+ imgs_enhanced.copy(), mel_chunks, full_frames, args, (oy1, oy2, ox1, ox2)
315
+ )
316
+
317
+ frame_h, frame_w = full_frames[0].shape[:-1]
318
+ out = cv2.VideoWriter(
319
+ "temp/{}/result.mp4".format(args.tmp_dir),
320
+ cv2.VideoWriter_fourcc(*"mp4v"),
321
+ fps,
322
+ (frame_w, frame_h),
323
+ )
324
+
325
+ if args.up_face != "original":
326
+ instance = GANimationModel()
327
+ instance.initialize()
328
+ instance.setup()
329
+
330
+ # kp_extractor = KeypointExtractor()
331
+ for i, (
332
+ img_batch,
333
+ mel_batch,
334
+ frames,
335
+ coords,
336
+ img_original,
337
+ f_frames,
338
+ ) in enumerate(
339
+ tqdm(
340
+ gen,
341
+ desc="[Step 6] Lip Synthesis:",
342
+ total=int(np.ceil(float(len(mel_chunks)) / args.LNet_batch_size)),
343
+ )
344
+ ):
345
+ img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(
346
+ device
347
+ )
348
+ mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(
349
+ device
350
+ )
351
+ img_original = (
352
+ torch.FloatTensor(np.transpose(img_original, (0, 3, 1, 2))).to(device)
353
+ / 255.0
354
+ ) # BGR -> RGB
355
+
356
+ with torch.no_grad():
357
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
358
+ pred, low_res = model(mel_batch, img_batch, reference)
359
+ pred = torch.clamp(pred, 0, 1)
360
+
361
+ if args.up_face in ["sad", "angry", "surprise"]:
362
+ tar_aus = exp_aus_dict[args.up_face]
363
+ else:
364
+ pass
365
+
366
+ if args.up_face == "original":
367
+ cur_gen_faces = img_original
368
+ else:
369
+ test_batch = {
370
+ "src_img": torch.nn.functional.interpolate(
371
+ (img_original * 2 - 1), size=(128, 128), mode="bilinear"
372
+ ),
373
+ "tar_aus": tar_aus.repeat(len(incomplete), 1),
374
+ }
375
+ instance.feed_batch(test_batch)
376
+ instance.forward()
377
+ cur_gen_faces = torch.nn.functional.interpolate(
378
+ instance.fake_img / 2.0 + 0.5, size=(384, 384), mode="bilinear"
379
+ )
380
+
381
+ if args.without_rl1 is not False:
382
+ incomplete, reference = torch.split(img_batch, 3, dim=1)
383
+ mask = torch.where(
384
+ incomplete == 0,
385
+ torch.ones_like(incomplete),
386
+ torch.zeros_like(incomplete),
387
+ )
388
+ pred = pred * mask + cur_gen_faces * (1 - mask)
389
+
390
+ pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.0
391
+
392
+ torch.cuda.empty_cache()
393
+ for p, f, xf, c in zip(pred, frames, f_frames, coords):
394
+ y1, y2, x1, x2 = c
395
+ p = cv2.resize(p.astype(np.uint8), (x2 - x1, y2 - y1))
396
+
397
+ ff = xf.copy()
398
+ ff[y1:y2, x1:x2] = p
399
+
400
+ # month region enhancement by GFPGAN
401
+ cropped_faces, restored_faces, restored_img = self.restorer.enhance(
402
+ ff, has_aligned=False, only_center_face=True, paste_back=True
403
+ )
404
+ # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
405
+ mm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0]
406
+ mouse_mask = np.zeros_like(restored_img)
407
+ tmp_mask = self.enhancer.faceparser.process(
408
+ restored_img[y1:y2, x1:x2], mm
409
+ )[0]
410
+ mouse_mask[y1:y2, x1:x2] = (
411
+ cv2.resize(tmp_mask, (x2 - x1, y2 - y1))[:, :, np.newaxis] / 255.0
412
+ )
413
+
414
+ height, width = ff.shape[:2]
415
+ restored_img, ff, full_mask = [
416
+ cv2.resize(x, (512, 512))
417
+ for x in (restored_img, ff, np.float32(mouse_mask))
418
+ ]
419
+ img = Laplacian_Pyramid_Blending_with_mask(
420
+ restored_img, ff, full_mask[:, :, 0], 10
421
+ )
422
+ pp = np.uint8(cv2.resize(np.clip(img, 0, 255), (width, height)))
423
+
424
+ pp, orig_faces, enhanced_faces = self.enhancer.process(
425
+ pp, xf, bbox=c, face_enhance=False, possion_blending=True
426
+ )
427
+ out.write(pp)
428
+ out.release()
429
+
430
+ output_file = "/tmp/output.mp4"
431
+ command = "ffmpeg -loglevel error -y -i {} -i {} -strict -2 -q:v 1 {}".format(
432
+ args.audio, "temp/{}/result.mp4".format(args.tmp_dir), output_file
433
+ )
434
+ subprocess.call(command, shell=True)
435
+
436
+ return Path(output_file)
437
+
438
+
439
+ # frames:256x256, full_frames: original size
440
+ def datagen(frames, mels, full_frames, args, cox):
441
+ img_batch, mel_batch, frame_batch, coords_batch, ref_batch, full_frame_batch = (
442
+ [],
443
+ [],
444
+ [],
445
+ [],
446
+ [],
447
+ [],
448
+ )
449
+ base_name = args.face.split("/")[-1]
450
+ refs = []
451
+ image_size = 256
452
+
453
+ # original frames
454
+ kp_extractor = KeypointExtractor()
455
+ fr_pil = [Image.fromarray(frame) for frame in frames]
456
+ lms = kp_extractor.extract_keypoint(
457
+ fr_pil, "temp/" + base_name + "x12_landmarks.txt"
458
+ )
459
+ frames_pil = [
460
+ (lm, frame) for frame, lm in zip(fr_pil, lms)
461
+ ] # frames is the croped version of modified face
462
+ crops, orig_images, quads = crop_faces(
463
+ image_size, frames_pil, scale=1.0, use_fa=True
464
+ )
465
+ inverse_transforms = [
466
+ calc_alignment_coefficients(
467
+ quad + 0.5,
468
+ [[0, 0], [0, image_size], [image_size, image_size], [image_size, 0]],
469
+ )
470
+ for quad in quads
471
+ ]
472
+ del kp_extractor.detector
473
+
474
+ oy1, oy2, ox1, ox2 = cox
475
+ face_det_results = face_detect(full_frames, args, jaw_correction=True)
476
+
477
+ for inverse_transform, crop, full_frame, face_det in zip(
478
+ inverse_transforms, crops, full_frames, face_det_results
479
+ ):
480
+ imc_pil = paste_image(
481
+ inverse_transform,
482
+ crop,
483
+ Image.fromarray(
484
+ cv2.resize(
485
+ full_frame[int(oy1) : int(oy2), int(ox1) : int(ox2)], (256, 256)
486
+ )
487
+ ),
488
+ )
489
+
490
+ ff = full_frame.copy()
491
+ ff[int(oy1) : int(oy2), int(ox1) : int(ox2)] = cv2.resize(
492
+ np.array(imc_pil.convert("RGB")), (ox2 - ox1, oy2 - oy1)
493
+ )
494
+ oface, coords = face_det
495
+ y1, y2, x1, x2 = coords
496
+ refs.append(ff[y1:y2, x1:x2])
497
+
498
+ for i, m in enumerate(mels):
499
+ idx = 0 if args.static else i % len(frames)
500
+ frame_to_save = frames[idx].copy()
501
+ face = refs[idx]
502
+ oface, coords = face_det_results[idx].copy()
503
+
504
+ face = cv2.resize(face, (args.img_size, args.img_size))
505
+ oface = cv2.resize(oface, (args.img_size, args.img_size))
506
+
507
+ img_batch.append(oface)
508
+ ref_batch.append(face)
509
+ mel_batch.append(m)
510
+ coords_batch.append(coords)
511
+ frame_batch.append(frame_to_save)
512
+ full_frame_batch.append(full_frames[idx].copy())
513
+
514
+ if len(img_batch) >= args.LNet_batch_size:
515
+ img_batch, mel_batch, ref_batch = (
516
+ np.asarray(img_batch),
517
+ np.asarray(mel_batch),
518
+ np.asarray(ref_batch),
519
+ )
520
+ img_masked = img_batch.copy()
521
+ img_original = img_batch.copy()
522
+ img_masked[:, args.img_size // 2 :] = 0
523
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.0
524
+ mel_batch = np.reshape(
525
+ mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1]
526
+ )
527
+
528
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
529
+ (
530
+ img_batch,
531
+ mel_batch,
532
+ frame_batch,
533
+ coords_batch,
534
+ img_original,
535
+ full_frame_batch,
536
+ ref_batch,
537
+ ) = ([], [], [], [], [], [], [])
538
+
539
+ if len(img_batch) > 0:
540
+ img_batch, mel_batch, ref_batch = (
541
+ np.asarray(img_batch),
542
+ np.asarray(mel_batch),
543
+ np.asarray(ref_batch),
544
+ )
545
+ img_masked = img_batch.copy()
546
+ img_original = img_batch.copy()
547
+ img_masked[:, args.img_size // 2 :] = 0
548
+ img_batch = np.concatenate((img_masked, ref_batch), axis=3) / 255.0
549
+ mel_batch = np.reshape(
550
+ mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1]
551
+ )
552
+ yield img_batch, mel_batch, frame_batch, coords_batch, img_original, full_frame_batch
videoretalking/requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ basicsr==1.4.2
2
+ kornia==0.5.1
3
+ face-alignment==1.3.4
4
+ ninja==1.10.2.3
5
+ einops==0.4.1
6
+ facexlib==0.2.5
7
+ librosa==0.9.2
8
+ dlib==19.24.0
9
+ gradio>=3.7.0
10
+ numpy==1.23.4