Skip to content

Commit ba574bb

Browse files
committed
chore: fix all linting issues
1 parent 8a3a7cb commit ba574bb

14 files changed

Lines changed: 623 additions & 366 deletions

File tree

demucs/api.py

Lines changed: 32 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
import subprocess
2424

25-
from . import audio_legacy
25+
from . import audio_legacy # noqa: F401
2626
import torch as th
2727
import torchaudio as ta
2828

@@ -118,9 +118,17 @@ def __init__(
118118
self._name = model
119119
self._repo = repo
120120
self._load_model()
121-
self.update_parameter(device=device, shifts=shifts, overlap=overlap, split=split,
122-
segment=segment, jobs=jobs, progress=progress, callback=callback,
123-
callback_arg=callback_arg)
121+
self.update_parameter(
122+
device=device,
123+
shifts=shifts,
124+
overlap=overlap,
125+
split=split,
126+
segment=segment,
127+
jobs=jobs,
128+
progress=progress,
129+
callback=callback,
130+
callback_arg=callback_arg,
131+
)
124132

125133
def update_parameter(
126134
self,
@@ -131,9 +139,7 @@ def update_parameter(
131139
segment: Optional[Union[int, _NotProvided]] = NotProvided,
132140
jobs: Union[int, _NotProvided] = NotProvided,
133141
progress: Union[bool, _NotProvided] = NotProvided,
134-
callback: Optional[
135-
Union[Callable[[dict], None], _NotProvided]
136-
] = NotProvided,
142+
callback: Optional[Union[Callable[[dict], None], _NotProvided]] = NotProvided,
137143
callback_arg: Optional[Union[dict, _NotProvided]] = NotProvided,
138144
):
139145
"""
@@ -213,8 +219,9 @@ def _load_audio(self, track: Path):
213219
wav = None
214220

215221
try:
216-
wav = AudioFile(track).read(streams=0, samplerate=self._samplerate,
217-
channels=self._audio_channels)
222+
wav = AudioFile(track).read(
223+
streams=0, samplerate=self._samplerate, channels=self._audio_channels
224+
)
218225
except FileNotFoundError:
219226
errors["ffmpeg"] = "FFmpeg is not installed."
220227
except subprocess.CalledProcessError:
@@ -269,20 +276,20 @@ def separate_tensor(
269276
wav -= ref.mean()
270277
wav /= ref.std() + 1e-8
271278
out = apply_model(
272-
self._model,
273-
wav[None],
274-
segment=self._segment,
275-
shifts=self._shifts,
276-
split=self._split,
277-
overlap=self._overlap,
278-
device=self._device,
279-
num_workers=self._jobs,
280-
callback=self._callback,
281-
callback_arg=_replace_dict(
282-
self._callback_arg, ("audio_length", wav.shape[1])
283-
),
284-
progress=self._progress,
285-
)
279+
self._model,
280+
wav[None],
281+
segment=self._segment,
282+
shifts=self._shifts,
283+
split=self._split,
284+
overlap=self._overlap,
285+
device=self._device,
286+
num_workers=self._jobs,
287+
callback=self._callback,
288+
callback_arg=_replace_dict(
289+
self._callback_arg, ("audio_length", wav.shape[1])
290+
),
291+
progress=self._progress,
292+
)
286293
if out is None:
287294
raise KeyboardInterrupt
288295
out *= ref.std() + 1e-8
@@ -336,7 +343,7 @@ def list_models(repo: Optional[Path] = None) -> Dict[str, Dict[str, Union[str, P
336343
"""
337344
model_repo: ModelOnlyRepo
338345
if repo is None:
339-
models = _parse_remote_files(REMOTE_ROOT / 'files.txt')
346+
models = _parse_remote_files(REMOTE_ROOT / "files.txt")
340347
model_repo = RemoteRepo(models)
341348
bag_repo = BagOnlyRepo(REMOTE_ROOT, model_repo)
342349
else:
@@ -363,7 +370,7 @@ def list_models(repo: Optional[Path] = None) -> Dict[str, Dict[str, Union[str, P
363370
split=args.split,
364371
segment=args.segment,
365372
jobs=args.jobs,
366-
callback=print
373+
callback=print,
367374
)
368375
out = args.out / args.name
369376
out.mkdir(parents=True, exist_ok=True)

demucs/apply.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def __init__(self, models: tp.List[Model],
5757
self.audio_channels = first.audio_channels
5858
self.samplerate = first.samplerate
5959
self.sources = first.sources
60-
self.models = nn.ModuleList(models)
60+
self.models = tp.cast(tp.List[Model], nn.ModuleList(models))
6161

6262
if weights is None:
6363
weights = [[1. for _ in first.sources] for _ in models]
@@ -142,7 +142,7 @@ def _replace_dict(_dict: tp.Optional[dict], *subs: tp.Tuple[tp.Hashable, tp.Any]
142142
return _dict
143143

144144

145-
def apply_model(model: tp.Union[BagOfModels, Model],
145+
def apply_model(model: tp.Union[BagOfModels, Demucs, HDemucs, HTDemucs],
146146
mix: tp.Union[th.Tensor, TensorChunk],
147147
shifts: int = 1, split: bool = True,
148148
overlap: float = 0.25, transition_power: float = 1.,

demucs/audio.py

Lines changed: 68 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import lameenc
1111
import julius
1212
import numpy as np
13-
from . import audio_legacy
13+
from . import audio_legacy # noqa: F401
1414
import torch
1515
import torchaudio as ta
1616
import typing as tp
@@ -19,18 +19,27 @@
1919

2020

2121
def _read_info(path):
22-
stdout_data = sp.check_output([
23-
'ffprobe', "-loglevel", "panic",
24-
str(path), '-print_format', 'json', '-show_format', '-show_streams'
25-
])
26-
return json.loads(stdout_data.decode('utf-8'))
22+
stdout_data = sp.check_output(
23+
[
24+
"ffprobe",
25+
"-loglevel",
26+
"panic",
27+
str(path),
28+
"-print_format",
29+
"json",
30+
"-show_format",
31+
"-show_streams",
32+
]
33+
)
34+
return json.loads(stdout_data.decode("utf-8"))
2735

2836

2937
class AudioFile:
3038
"""
3139
Allows to read audio from any format supported by ffmpeg, as well as resampling or
3240
converting to mono on the fly. See :method:`read` for more details.
3341
"""
42+
3443
def __init__(self, path: Path):
3544
self.path = Path(path)
3645
self._info = None
@@ -51,30 +60,33 @@ def info(self):
5160

5261
@property
5362
def duration(self):
54-
return float(self.info['format']['duration'])
63+
return float(self.info["format"]["duration"])
5564

5665
@property
5766
def _audio_streams(self):
5867
return [
59-
index for index, stream in enumerate(self.info["streams"])
68+
index
69+
for index, stream in enumerate(self.info["streams"])
6070
if stream["codec_type"] == "audio"
6171
]
6272

6373
def __len__(self):
6474
return len(self._audio_streams)
6575

6676
def channels(self, stream=0):
67-
return int(self.info['streams'][self._audio_streams[stream]]['channels'])
77+
return int(self.info["streams"][self._audio_streams[stream]]["channels"])
6878

6979
def samplerate(self, stream=0):
70-
return int(self.info['streams'][self._audio_streams[stream]]['sample_rate'])
71-
72-
def read(self,
73-
seek_time=None,
74-
duration=None,
75-
streams=slice(None),
76-
samplerate=None,
77-
channels=None):
80+
return int(self.info["streams"][self._audio_streams[stream]]["sample_rate"])
81+
82+
def read(
83+
self,
84+
seek_time=None,
85+
duration=None,
86+
streams=slice(None),
87+
samplerate=None,
88+
channels=None,
89+
):
7890
"""
7991
Slightly more efficient implementation than stempeg,
8092
in particular, this will extract all stems at once
@@ -106,22 +118,24 @@ def read(self,
106118
query_duration = None
107119
else:
108120
target_size = int((samplerate or self.samplerate()) * duration)
109-
query_duration = float((target_size + 1) / (samplerate or self.samplerate()))
121+
query_duration = float(
122+
(target_size + 1) / (samplerate or self.samplerate())
123+
)
110124

111125
with temp_filenames(len(streams)) as filenames:
112-
command = ['ffmpeg', '-y']
113-
command += ['-loglevel', 'panic']
126+
command = ["ffmpeg", "-y"]
127+
command += ["-loglevel", "panic"]
114128
if seek_time:
115-
command += ['-ss', str(seek_time)]
116-
command += ['-i', str(self.path)]
129+
command += ["-ss", str(seek_time)]
130+
command += ["-i", str(self.path)]
117131
for stream, filename in zip(streams, filenames):
118-
command += ['-map', f'0:{self._audio_streams[stream]}']
132+
command += ["-map", f"0:{self._audio_streams[stream]}"]
119133
if query_duration is not None:
120-
command += ['-t', str(query_duration)]
121-
command += ['-threads', '1']
122-
command += ['-f', 'f32le']
134+
command += ["-t", str(query_duration)]
135+
command += ["-threads", "1"]
136+
command += ["-f", "f32le"]
123137
if samplerate is not None:
124-
command += ['-ar', str(samplerate)]
138+
command += ["-ar", str(samplerate)]
125139
command += [filename]
126140

127141
sp.run(command, check=True)
@@ -163,7 +177,9 @@ def convert_audio_channels(wav, channels=2):
163177
wav = wav[..., :channels, :]
164178
else:
165179
# Case 4: What is a reasonable choice here?
166-
raise ValueError('The audio file has less channels than requested but is not mono.')
180+
raise ValueError(
181+
"The audio file has less channels than requested but is not mono."
182+
)
167183
return wav
168184

169185

@@ -216,32 +232,34 @@ def encode_mp3(wav, path, samplerate=44100, bitrate=320, quality=2, verbose=Fals
216232
f.write(mp3_data)
217233

218234

219-
def prevent_clip(wav, mode='rescale'):
235+
def prevent_clip(wav, mode="rescale"):
220236
"""
221237
different strategies for avoiding raw clipping.
222238
"""
223-
if mode is None or mode == 'none':
239+
if mode is None or mode == "none":
224240
return wav
225241
assert wav.dtype.is_floating_point, "too late for clipping"
226-
if mode == 'rescale':
242+
if mode == "rescale":
227243
wav = wav / max(1.01 * wav.abs().max(), 1)
228-
elif mode == 'clamp':
244+
elif mode == "clamp":
229245
wav = wav.clamp(-0.99, 0.99)
230-
elif mode == 'tanh':
246+
elif mode == "tanh":
231247
wav = torch.tanh(wav)
232248
else:
233249
raise ValueError(f"Invalid mode {mode}")
234250
return wav
235251

236252

237-
def save_audio(wav: torch.Tensor,
238-
path: tp.Union[str, Path],
239-
samplerate: int,
240-
bitrate: int = 320,
241-
clip: tp.Literal["rescale", "clamp", "tanh", "none"] = 'rescale',
242-
bits_per_sample: tp.Literal[16, 24, 32] = 16,
243-
as_float: bool = False,
244-
preset: tp.Literal[2, 3, 4, 5, 6, 7] = 2):
253+
def save_audio(
254+
wav: torch.Tensor,
255+
path: tp.Union[str, Path],
256+
samplerate: int,
257+
bitrate: int = 320,
258+
clip: tp.Literal["rescale", "clamp", "tanh", "none"] = "rescale",
259+
bits_per_sample: tp.Literal[16, 24, 32] = 16,
260+
as_float: bool = False,
261+
preset: tp.Literal[2, 3, 4, 5, 6, 7] = 2,
262+
):
245263
"""Save audio file, automatically preventing clipping if necessary
246264
based on the given `clip` strategy. If the path ends in `.mp3`, this
247265
will save as mp3 with the given `bitrate`. Use `preset` to set mp3 quality:
@@ -255,11 +273,16 @@ def save_audio(wav: torch.Tensor,
255273
elif suffix == ".wav":
256274
if as_float:
257275
bits_per_sample = 32
258-
encoding = 'PCM_F'
276+
encoding = "PCM_F"
259277
else:
260-
encoding = 'PCM_S'
261-
ta.save(str(path), wav, sample_rate=samplerate,
262-
encoding=encoding, bits_per_sample=bits_per_sample)
278+
encoding = "PCM_S"
279+
ta.save(
280+
str(path),
281+
wav,
282+
sample_rate=samplerate,
283+
encoding=encoding,
284+
bits_per_sample=bits_per_sample,
285+
)
263286
elif suffix == ".flac":
264287
ta.save(str(path), wav, sample_rate=samplerate, bits_per_sample=bits_per_sample)
265288
else:

demucs/audio_legacy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import sys
66
import warnings
77

8-
if not "torchaudio" in sys.modules:
8+
if "torchaudio" not in sys.modules:
99
os.environ["TORCHAUDIO_USE_BACKEND_DISPATCHER"] = "0"
1010
elif os.getenv("TORCHAUDIO_USE_BACKEND_DISPATCHER", default="1") == "1":
1111
if sys.modules["torchaudio"].__version__ >= "2.1":

demucs/demucs.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,17 @@ def __init__(self, channels: int, compress: float = 4, depth: int = 2, init: flo
134134
for d in range(self.depth):
135135
dilation = 2 ** d if dilate else 1
136136
padding = dilation * (kernel // 2)
137-
mods = [
137+
mods: tp.List[
138+
nn.Conv1d |
139+
nn.GroupNorm |
140+
nn.Identity |
141+
nn.GELU |
142+
nn.ReLU |
143+
nn.GLU |
144+
LayerScale |
145+
BLSTM |
146+
LocalState
147+
] = [
138148
nn.Conv1d(channels, hidden, kernel, dilation=dilation, padding=padding),
139149
norm_fn(hidden), act(),
140150
nn.Conv1d(hidden, 2 * channels, 1),

0 commit comments

Comments
 (0)