-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
210 lines (191 loc) · 6.77 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Imperial College London (Pingchuan Ma)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import os
import torch
import argparse
from metrics.measures import get_wer
from metrics.measures import get_cer
from lipreading.utils import save2npz
from lipreading.utils import save2avi
from lipreading.utils import AverageMeter
from lipreading.subroutines import LipreadingPipeline
def load_args(default_config=None):
parser = argparse.ArgumentParser(description='Lipreading Project')
parser.add_argument(
"--config-filename",
type=str,
default=None,
help="Model configuration with ini format",
)
# --
parser.add_argument("--data-filename",
default=None,
type=str,
help="The filename for sequence.",
)
parser.add_argument(
"--landmarks-filename",
default="",
type=str,
help="The filename for tracked landmarks.",
)
parser.add_argument(
"--dst-filename",
type=str,
default=None,
help="The filename of the saved mouth patches or embedding.",
)
# -- for benchmark evaluation
parser.add_argument("--data-dir",
default=None,
type=str,
help="The directory for sequence.",
)
parser.add_argument(
"--landmarks-dir",
default="",
type=str,
help="The directory for tracked landmarks.",
)
parser.add_argument("--labels-filename",
default=None,
type=str,
help="The filename for labels.",
)
parser.add_argument(
"--dst-dir",
type=str,
default=None,
help="The directory of saved mouth patches or embeddings.",
)
# -- feature extraction
parser.add_argument(
"--feats-position",
default="",
choices=["", "mouth", "resnet", "conformer"],
help="Specify the position for feature extraction.",
)
# -- utils
parser.add_argument(
"--video-ext",
default=".mp4",
type=str,
help="The extension for video files.",
)
parser.add_argument(
"--landmarks-ext",
default=".pkl",
type=str,
help="The extension for landmarks file.",
)
parser.add_argument(
"--gpu-idx",
default=-1,
type=int,
help="Inference in GPU when gpu_idx >= 0 or in CPU when gpu_idx < 0.",
)
args = parser.parse_args()
return args
args = load_args()
def benchmark_inference(lipreader, data_dir, landmarks_dir, lines, dst_dir=""):
"""benchmark_inference.
:param lipreader: LipreadingPipeline object, contains the function for \
facial tracking[option], facial pre-processing and lipreading inference.
:param data_dir: str, the directory for tracked landmarks.
:param landmarks_dir: str, the directory for tracked landmarks.
:param lines: List, the list of basename for each sequence.
:param dst_dir: str, The directory of the saved mouth patch or embeddings.
"""
wer = AverageMeter()
cer = AverageMeter()
for idx, line in enumerate(lines):
basename, groundtruth = line.split()[0], " ".join(line.split()[1:])
data_filename = os.path.join(data_dir, basename+args.video_ext)
landmarks_filename = os.path.join(landmarks_dir, basename+args.landmarks_ext)
output = lipreader(data_filename, landmarks_filename)
if isinstance(output, str):
print(f"hyp: {output}")
if groundtruth is not None:
print(f"ref: {groundtruth}")
wer.update( get_wer(output, groundtruth), len(groundtruth.split()))
cer.update( get_cer(output, groundtruth), len(groundtruth.replace(" ", "")))
print(
f"progress: {idx+1}/{len(lines)}\tcur WER: {wer.val*100:.1f}\t"
f"cur CER: {cer.val*100:.1f}\t"
f"avg WER: {wer.avg*100:.1f}\tavg CER: {cer.avg*100:.1f}"
)
elif isinstance(output, tuple):
print(
f"filename: {basename} has been saved to "
f"{os.path.join(dst_dir, basename+'.avi')}."
)
save2avi(
os.path.join(dst_dir, basename+".avi"),
data=output[0],
fps=output[1],
)
else:
print(
f"filename: {basename} has been saved to "
f"{os.path.join(dst_dir, basename+'.npz')}."
)
save2npz(
os.path.join(dst_dir, basename+".npz"),
data=output.cpu().detach().numpy()
)
return
def one_step_inference(lipreader, data_filename, landmarks_filename, dst_filename=""):
"""one_step_inference.
:param lipreader: LipreadingPipeline object, contains the function for \
facial tracking[option], facial pre-processing and lipreading inference.
:param data_filename: str, the filename for tracked landmarks.
:param landmarks_filename: str, the filename for tracked landmarks.
:param dst_filename: str, the filename of the saved mouth patch or embedding.
"""
output = lipreader(data_filename, landmarks_filename)
if isinstance(output, str):
print(f"hyp: {output}")
elif isinstance(output, tuple):
assert dst_filename[-4:] == ".avi", f"the ext of {dst_filename} should be .avi"
print(f"mouth patch is saved to {dst_filename}.")
save2avi(dst_filename, data=output[0], fps=output[1])
else:
assert dst_filename[-4:] == ".npz", f"the ext of {dst_filename} should be .npz"
print(f"embedding is saved to {dst_filename}.")
save2npz(dst_filename, data=output.cpu().detach().numpy())
return
def main():
# -- pick device for inference.
if torch.cuda.is_available() and args.gpu_idx >= 0:
device = torch.device(f"cuda:{args.gpu_idx}")
else:
device = "cpu"
lipreader = LipreadingPipeline(
config_filename=args.config_filename,
feats_position=args.feats_position,
device=device,
face_track=not args.landmarks_filename and not args.landmarks_dir,
)
if args.data_filename is not None:
one_step_inference(
lipreader,
args.data_filename,
args.landmarks_filename,
args.dst_filename,
)
else:
assert os.path.isdir(args.data_dir), \
f"{args.data_dir} is not a directory."
assert os.path.isfile(args.labels_filename), \
f"{args.labels_filename} does not exist."
benchmark_inference(
lipreader,
args.data_dir,
args.landmarks_dir,
open(args.labels_filename).read().splitlines(),
args.dst_dir,
)
if __name__ == '__main__':
main()