-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.py
161 lines (139 loc) · 5.82 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Command-line for audio compression."""
import argparse
import sys
from pathlib import Path
import torchaudio
from compress import MODELS, compress, decompress
from utils import convert_audio, save_audio
SUFFIX = '.ecdc'
def get_parser():
parser = argparse.ArgumentParser(
'encodec',
description='High fidelity neural audio codec. '
'If input is a .ecdc, decompresses it. '
'If input is .wav, compresses it. If output is also wav, '
'do a compression/decompression cycle.')
parser.add_argument(
'input', type=Path,
help='Input file, whatever is supported by torchaudio on your system.')
parser.add_argument(
'output', type=Path, nargs='?',
help='Output file, otherwise inferred from input file.')
parser.add_argument(
'-b', '--bandwidth', type=float, default=6, choices=[1.5, 3., 6., 12., 24.],
help='Target bandwidth (1.5, 3, 6, 12 or 24). 1.5 is not supported with --hq.')
parser.add_argument(
'-q', '--hq', action='store_true',
help='Use HQ stereo model operating on 48 kHz sampled audio.')
parser.add_argument(
'-l', '--lm', action='store_true',
help='Use a language model to reduce the model size (5x slower though).')
parser.add_argument(
'-f', '--force', action='store_true',
help='Overwrite output file if it exists.')
parser.add_argument(
'-s', '--decompress_suffix', type=str, default='_decompressed',
help='Suffix for the decompressed output file (if no output path specified)')
parser.add_argument(
'-r', '--rescale', action='store_true',
help='Automatically rescale the output to avoid clipping.')
parser.add_argument(
'-m','--model_name', type=str, default='encodec_24khz',
help='support encodec_24khz,encodec_48khz,my_encodec')
parser.add_argument(
'-c','--checkpoint', type=str,
help='if use my_encodec, please input checkpoint')
parser.add_argument(
"-d","--device",type=str,
default="cuda"
)
return parser
def fatal(*args):
print(*args, file=sys.stderr)
sys.exit(1)
def check_output_exists(args):
if not args.output.parent.exists():
fatal(f"Output folder for {args.output} does not exist.")
if args.output.exists() and not args.force:
fatal(f"Output file {args.output} exist. Use -f / --force to overwrite.")
def check_clipping(wav, args):
if args.rescale:
return
mx = wav.abs().max()
limit = 0.99
if mx > limit:
print(
f"Clipping!! max scale {mx}, limit is {limit}. "
"To avoid clipping, use the `-r` option to rescale the output.",
file=sys.stderr)
def main(args,model):
if args.input.suffix.lower() == SUFFIX:
# Decompression
if args.output is None:
args.output = args.input.with_name(args.input.stem + args.decompress_suffix).with_suffix('.wav')
elif args.output.suffix.lower() != '.wav':
fatal("Output extension must be .wav")
check_output_exists(args)
out, out_sample_rate = decompress(args.input.read_bytes(),device=args.device())
check_clipping(out, args)
save_audio(out, args.output, out_sample_rate, rescale=args.rescale)
else:
# Compression
if args.output is None:
args.output = args.input.with_suffix(SUFFIX)
elif args.output.suffix.lower() not in [SUFFIX, '.wav']:
fatal(f"Output extension must be .wav or {SUFFIX}")
check_output_exists(args)
wav, sr = torchaudio.load(args.input)
wav = convert_audio(wav, sr, model.sample_rate, model.channels)
wav = wav.to(args.device)
compressed = compress(model, wav, use_lm=args.lm)
if args.output.suffix.lower() == SUFFIX:
args.output.write_bytes(compressed)
else:
# Directly run decompression stage
assert args.output.suffix.lower() == '.wav'
out, out_sample_rate = decompress(model,compressed,device=args.device)
check_clipping(out, args)
save_audio(out, args.output, out_sample_rate, rescale=args.rescale)
def cli_main(args):
if args.hq:
model_name = 'encodec_48khz'
else:
model_name = args.model_name
if model_name == 'my_encodec':
model = MODELS[model_name](args.checkpoint)
elif model_name == 'encodec_bw':
model = MODELS[model_name](args.checkpoint,[args.bandwidth])
else:
model = MODELS[model_name]()
model = model.to(args.device)
print(f"-------------USE {model_name} MODEL-------------")
if args.bandwidth not in model.target_bandwidths:
fatal(f"Bandwidth {args.bandwidth} is not supported by the model {model_name}")
model.set_target_bandwidth(args.bandwidth)
if args.input.is_dir():
output_root = args.output
input_root = args.input
if not output_root.exists():
output_root.mkdir(parents=True)
for wav in args.input.glob('**/*.wav'):
print(f"Processing {wav}")
relative_path = wav.relative_to(input_root)
args.input = wav
output_path = output_root.joinpath(relative_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
args.output = output_path.with_name(output_path.stem + f"_bw{int(args.bandwidth)}.wav")
main(args,model)
elif args.input.is_file():
main(args,model)
if __name__ == '__main__':
args = get_parser().parse_args()
if not args.input.exists():
fatal(f"Input file {args.input} does not exist.")
cli_main(args)