First push
This commit is contained in:
seclusionenthusiast committed 2026-03-03 14:52:19 +09:00
commit c4a020c191
146 files changed
+40796

No files matched your search

View File
Whitespace-only changes.
+129
View File
@@ -0,0 +1,129 @@
from music21 import environment, converter, metadata, stream
from pathlib import Path
import subprocess
import os
import traceback
def _post_process_abc_content(abc_text: str, title: str) -> str:
"""Cleans midi2abc output, sets title, removes comments."""
lines = abc_text.splitlines()
cleaned_lines = []
seen_midi_program_in_voice = False
for line in lines:
# The midi2abc tool generates a default title from the filename.
if line.startswith('T:'):
cleaned_lines.append(f'T: {title}')
continue
if line.strip().startswith('% Last note suggests'):
continue
if line.strip().startswith('V:'):
seen_midi_program_in_voice = False
if line.strip().startswith('%%MIDI program'):
if not seen_midi_program_in_voice:
seen_midi_program_in_voice = True
cleaned_lines.append(line)
continue
cleaned_lines.append(line)
return '\n'.join(cleaned_lines)
def convert_midi_to_abc(
midi_paths: list, song_title: str
) -> dict[str, str] | None:
"""Converts MIDI files to a dictionary of ABC strings."""
us = environment.UserSettings()
us['directoryScratch'] = '/tmp'
temp_dir = Path(us['directoryScratch'])
abc_results = {}
for midi_path in midi_paths:
part_name = Path(midi_path).stem
part_title = f"{song_title} ({part_name})"
print(f" -> Processing part: {part_name}.mid")
temp_midi_path = temp_dir / f"{part_title}.mid"
temp_abc_path = temp_dir / f"{part_title}.abc"
try:
score_part = converter.parse(midi_path, forceSource=True)
if not score_part or not score_part.flatten().notesAndRests:
print(f" -> Skipping empty MIDI: {Path(midi_path).name}") # noqa
continue
single_part_score = stream.Score()
single_part_score.insert(0, metadata.Metadata())
single_part_score.metadata.title = part_title
score_part.parts[0].id = part_name
single_part_score.insert(0, score_part.parts[0])
single_part_score.write('midi', fp=str(temp_midi_path))
cmd = ['midi2abc', str(temp_midi_path),
'-o', str(temp_abc_path)]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
print(f" -> ERROR: midi2abc failed for {part_name}: "
f"{result.stderr}")
continue
if not temp_abc_path.exists() or temp_abc_path.stat().st_size == 0:
print(f" -> ERROR: midi2abc created an empty file for {part_name}.")
continue
with open(temp_abc_path, 'r', encoding='utf-8') as f:
abc_text_content = f.read()
abc_results[part_name] = _post_process_abc_content(
abc_text_content, part_title)
print(f" -> Successfully converted {part_name} to ABC.")
except Exception as e:
print(
f" -> ERROR during ABC conversion for {part_name}: {e}")
traceback.print_exc()
finally:
if temp_midi_path.exists():
os.remove(temp_midi_path)
if temp_abc_path.exists():
os.remove(temp_abc_path)
return abc_results if abc_results else None
def generate_mix_abc(mix_midi_path: str, song_title: str) -> str | None:
"""Generates ABC notation for a single 'mix' MIDI file."""
us = environment.UserSettings()
us['directoryScratch'] = '/tmp'
temp_dir = Path(us['directoryScratch'])
mix_title = f"{song_title} (Mix)"
temp_abc_path = temp_dir / f"{mix_title}.abc"
try:
print("\n -> Creating combined 'Mix' ABC score...")
cmd = ['midi2abc', mix_midi_path, '-o', str(temp_abc_path)]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode == 0 and temp_abc_path.exists():
raw_mix_abc = temp_abc_path.read_text(encoding='utf-8')
cleaned_mix_abc = _post_process_abc_content(raw_mix_abc, mix_title)
print(" -> Successfully created 'Mix' ABC.")
return cleaned_mix_abc
else:
print(
f" -> ERROR: midi2abc failed for Mix: {result.stderr}")
return None
except Exception as e:
print(f" -> ERROR during Mix ABC conversion: {e}")
return None
finally:
if temp_abc_path.exists():
os.remove(temp_abc_path)
+70
View File
@@ -0,0 +1,70 @@
"""
ABC notation conversion via abc_generator (backend/services/abc_generator.py).
"""
from .. import job_manager as jm
from ..config import JOBS_DIR
from . import abc_generator
def run_abc_conversion(job_id: str, midi_paths: list[str], song_title: str):
"""
Background task: convert MIDI file(s) to ABC notation.
midi_paths: list of MIDI file paths
song_title: title to use in ABC headers
"""
output_dir = JOBS_DIR / job_id
output_dir.mkdir(parents=True, exist_ok=True)
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Converting MIDI to ABC...")
try:
abc_results = abc_generator.convert_midi_to_abc(midi_paths, song_title)
if not abc_results:
raise RuntimeError("No ABC output produced — MIDI may be empty or unreadable.")
files = []
for part_name, abc_text in abc_results.items():
safe_name = part_name.replace("/", "_").replace("\\", "_")
filename = f"{safe_name}.abc"
dest = output_dir / filename
dest.write_text(abc_text, encoding="utf-8")
files.append({"name": filename, "path": str(dest)})
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="ABC conversion complete.",
files=files,
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")
def run_mix_abc_conversion(job_id: str, mix_midi_path: str, song_title: str):
"""Convert a single mix MIDI to ABC notation."""
output_dir = JOBS_DIR / job_id
output_dir.mkdir(parents=True, exist_ok=True)
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Converting mix MIDI to ABC...")
try:
abc_text = abc_generator.generate_mix_abc(mix_midi_path, song_title)
if not abc_text:
raise RuntimeError("No ABC output produced.")
dest = output_dir / "mix.abc"
dest.write_text(abc_text, encoding="utf-8")
files = [{"name": "mix.abc", "path": str(dest)}]
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="ABC conversion complete.",
files=files,
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")
+155
View File
@@ -0,0 +1,155 @@
"""
Apollo separator - Vocal enhancement and reverb removal
Models from MVSEP-Central-Backup: https://huggingface.co/miercolesv/MVSEP-Central-Backup
"""
import os
import torch
from pathlib import Path
from typing import Dict
from ..config import APOLLO_MODEL_DIR, CPU_SEPARATION
# Model configurations
APOLLO_MODELS = {
"apollo_vocals": {
"model_path": "epoch=54-val_loss=-17.6221.ckpt",
"config_path": "config_apollo_vocals_ep_54.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Apollo-Vocal-MSST",
"stems": ["dry_vocals", "reverb"],
"description": "Apollo vocal enhancement/reverb removal",
},
"apollo_edm": {
"model_path": "apollo_edm_by_essid.ckpt",
"config_path": "apollo_edm_by_essid.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Politrees/UVR_resources/models/Apollo",
"stems": ["enhanced", "residual"],
"description": "Apollo EDM enhancement",
},
"apollo_edm_big": {
"model_path": "apollo_edm_big_by_essid.ckpt",
"config_path": "apollo_edm_big_by_essid.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Politrees/UVR_resources/models/Apollo",
"stems": ["enhanced", "residual"],
"description": "Apollo EDM Big enhancement",
},
}
class ApolloSeparator:
"""
Apollo separator for vocal enhancement and reverb removal.
Apollo models separate vocals into dry vocals and reverb,
useful for cleaning up vocal recordings.
"""
def __init__(
self,
model_id: str = "apollo_vocals",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in APOLLO_MODELS:
raise ValueError(f"Unknown Apollo model: {model_id}")
self.model_id = model_id
self.model_config = APOLLO_MODELS[model_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self._model = None
def _ensure_model(self):
"""Download model from HuggingFace if not present."""
model_dir = APOLLO_MODEL_DIR / self.model_id
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / self.model_config["model_path"]
config_path = model_dir / self.model_config["config_path"]
if not model_path.exists() or not config_path.exists():
try:
from huggingface_hub import hf_hub_download
print(f"Downloading Apollo model: {self.model_id}")
if not model_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['model_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['config_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Apollo model: {e}")
return str(model_path), str(config_path)
def _load_model(self):
"""Lazy-load the model."""
if self._model is None:
model_path, config_path = self._ensure_model()
self._model = None # Placeholder for actual model loading
return self._model
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate vocals into dry vocals and reverb.
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# For now, use audio-separator as fallback
# Full implementation would load the actual Apollo model
try:
from audio_separator.separator import Separator
sep = Separator(
model_file_dir=str(APOLLO_MODEL_DIR),
output_dir=str(output_path),
output_format=self.output_format.upper(),
output_bitrate=self.mp3_bitrate if self.output_format == "mp3" else None,
)
# Use dereverb model as approximation
sep.load_model()
result = sep.separate(input_path)
stems = self.model_config.get("stems", ["dry_vocals", "reverb"])
output_paths = {}
if isinstance(result, list):
for i, path in enumerate(result):
if i < len(stems):
stem_name = stems[i]
final_path = output_path / f"{stem_name}.{self.output_format}"
Path(path).rename(final_path)
output_paths[stem_name] = str(final_path)
else:
final_path = output_path / f"dry_vocals.{self.output_format}"
Path(result).rename(final_path)
output_paths["dry_vocals"] = str(final_path)
return output_paths
except ImportError:
raise ImportError(
"audio-separator is required for Apollo separation. "
"Install with: pip install audio-separator"
)
+144
View File
@@ -0,0 +1,144 @@
"""
Aspiration separator - Breath/aspiration removal from vocals
Models from MVSEP-Central-Backup: https://huggingface.co/miercolesv/MVSEP-Central-Backup
"""
import os
import torch
from pathlib import Path
from typing import Dict
from ..config import ASPIRATION_MODEL_DIR, CPU_SEPARATION
# Model configurations
ASPIRATION_MODELS = {
"aspiration_full": {
"model_path": "aspiration_mel_band_roformer_sdr_18.9845.ckpt",
"config_path": "config_aspiration_mel_band_roformer.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Aspiration-MelBand-Sucial",
"stems": ["clean_vocals", "aspiration"],
"aggression": "full",
},
"aspiration_light": {
"model_path": "aspiration_mel_band_roformer_less_aggr_sdr_18.1201.ckpt",
"config_path": "config_aspiration_mel_band_roformer.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Aspiration-MelBand-Sucial",
"stems": ["clean_vocals", "aspiration"],
"aggression": "light",
},
}
class AspirationSeparator:
"""
Aspiration separator for breath/aspiration removal from vocals.
Useful for cleaning vocal recordings by separating breath sounds
from the main vocal performance.
"""
def __init__(
self,
model_id: str = "aspiration_full",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in ASPIRATION_MODELS:
raise ValueError(f"Unknown Aspiration model: {model_id}")
self.model_id = model_id
self.model_config = ASPIRATION_MODELS[model_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self._model = None
def _ensure_model(self):
"""Download model from HuggingFace if not present."""
model_dir = ASPIRATION_MODEL_DIR / self.model_id
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / self.model_config["model_path"]
config_path = model_dir / self.model_config["config_path"]
if not model_path.exists() or not config_path.exists():
try:
from huggingface_hub import hf_hub_download
print(f"Downloading Aspiration model: {self.model_id}")
if not model_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['model_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['config_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Aspiration model: {e}")
return str(model_path), str(config_path)
def _load_model(self):
"""Lazy-load the model."""
if self._model is None:
model_path, config_path = self._ensure_model()
self._model = None # Placeholder for actual model loading
return self._model
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate vocals into clean vocals and aspiration (breath).
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
try:
from audio_separator.separator import Separator
sep = Separator(
model_file_dir=str(ASPIRATION_MODEL_DIR),
output_dir=str(output_path),
output_format=self.output_format.upper(),
output_bitrate=self.mp3_bitrate if self.output_format == "mp3" else None,
)
sep.load_model()
result = sep.separate(input_path)
stems = self.model_config.get("stems", ["clean_vocals", "aspiration"])
output_paths = {}
if isinstance(result, list):
for i, path in enumerate(result):
if i < len(stems):
stem_name = stems[i]
final_path = output_path / f"{stem_name}.{self.output_format}"
Path(path).rename(final_path)
output_paths[stem_name] = str(final_path)
else:
final_path = output_path / f"clean_vocals.{self.output_format}"
Path(result).rename(final_path)
output_paths["clean_vocals"] = str(final_path)
return output_paths
except ImportError:
raise ImportError(
"audio-separator is required for Aspiration separation. "
"Install with: pip install audio-separator"
)
+150
View File
@@ -0,0 +1,150 @@
"""
Bandit-v2 separator - Multi-language/multi-stem separation
Models from MVSEP-Central-Backup: https://huggingface.co/miercolesv/MVSEP-Central-Backup
"""
import os
import torch
from pathlib import Path
from typing import Dict
from ..config import BANDIT_MODEL_DIR, CPU_SEPARATION
# Model configurations
BANDIT_MODELS = {
"bandit_v2_multi": {
"model_path": "checkpoint-multi_state_dict.ckpt",
"config_path": "config_dnr_bandit_v2_mus64.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Bandit-v2",
"stems": ["vocals", "drums", "bass", "other"],
"language": "multi",
},
"bandit_v2_eng": {
"model_path": "checkpoint-eng_state_dict.ckpt",
"config_path": "config_dnr_bandit_v2_mus64.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Bandit-v2",
"stems": ["vocals", "drums", "bass", "other"],
"language": "english",
},
# Additional language models available:
# - checkpoint-cmn_state_dict.ckpt (Chinese)
# - checkpoint-deu_state_dict.ckpt (German)
# - checkpoint-fao_state_dict.ckpt (Faroese)
# - checkpoint-fra_state_dict.ckpt (French)
# - checkpoint-spa_state_dict.ckpt (Spanish)
}
class BanditSeparator:
"""
Bandit-v2 separator for multi-language/multi-stem separation.
Bandit models are trained on different languages and provide
high-quality separation optimized for specific language characteristics.
"""
def __init__(
self,
model_id: str = "bandit_v2_multi",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in BANDIT_MODELS:
raise ValueError(f"Unknown Bandit model: {model_id}")
self.model_id = model_id
self.model_config = BANDIT_MODELS[model_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self._model = None
def _ensure_model(self):
"""Download model from HuggingFace if not present."""
model_dir = BANDIT_MODEL_DIR / self.model_id
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / self.model_config["model_path"]
config_path = model_dir / self.model_config["config_path"]
if not model_path.exists() or not config_path.exists():
try:
from huggingface_hub import hf_hub_download
print(f"Downloading Bandit model: {self.model_id}")
if not model_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['model_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['config_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Bandit model: {e}")
return str(model_path), str(config_path)
def _load_model(self):
"""Lazy-load the model."""
if self._model is None:
model_path, config_path = self._ensure_model()
self._model = None # Placeholder for actual model loading
return self._model
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate audio into stems using Bandit-v2.
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
try:
from audio_separator.separator import Separator
sep = Separator(
model_file_dir=str(BANDIT_MODEL_DIR),
output_dir=str(output_path),
output_format=self.output_format.upper(),
output_bitrate=self.mp3_bitrate if self.output_format == "mp3" else None,
)
sep.load_model()
result = sep.separate(input_path)
stems = self.model_config.get("stems", ["vocals", "drums", "bass", "other"])
output_paths = {}
if isinstance(result, list):
for i, path in enumerate(result):
if i < len(stems):
stem_name = stems[i]
final_path = output_path / f"{stem_name}.{self.output_format}"
Path(path).rename(final_path)
output_paths[stem_name] = str(final_path)
else:
final_path = output_path / f"vocals.{self.output_format}"
Path(result).rename(final_path)
output_paths["vocals"] = str(final_path)
return output_paths
except ImportError:
raise ImportError(
"audio-separator is required for Bandit separation. "
"Install with: pip install audio-separator"
)
+3
View File
@@ -0,0 +1,3 @@
from .bs_roformer import BSRoformer
__all__ = ['BSRoformer']
+116
View File
@@ -0,0 +1,116 @@
from functools import wraps
from packaging import version
from collections import namedtuple
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange, reduce
"""
Code adapted from https://github.com/Anjok07/ultimatevocalremovergui/blob/v5.6.0_roformer_add%2Bdirectml/lib_v5/bs_roformer.py and https://github.com/lucidrains/BS-RoFormer which are copyrighted under the terms of the MIT license.
"""
# constants
FlashAttentionConfig = namedtuple('FlashAttentionConfig', ['enable_flash', 'enable_math', 'enable_mem_efficient'])
# helpers
def exists(val):
return val is not None
def once(fn):
called = False
@wraps(fn)
def inner(x):
nonlocal called
if called:
return
called = True
return fn(x)
return inner
print_once = once(print)
# main class
class Attend(nn.Module):
def __init__(
self,
dropout = 0.,
flash = False,
scale = None
):
super().__init__()
self.dropout = dropout
self.attn_dropout = nn.Dropout(dropout)
self.scale = scale
self.flash = flash
assert not (flash and version.parse(torch.__version__) < version.parse('2.0.0')), 'in order to use flash attention, you must be using pytorch 2.0 or above'
# determine efficient attention configs for cuda and cpu
self.cpu_config = FlashAttentionConfig(True, True, True)
self.cuda_config = None
if not torch.cuda.is_available() or not flash:
return
device_properties = torch.cuda.get_device_properties(torch.device('cuda'))
if device_properties.major == 8 and device_properties.minor == 0:
print_once('A100 GPU detected, using flash attention if input tensor is on cuda')
self.cuda_config = FlashAttentionConfig(True, False, False)
else:
self.cuda_config = FlashAttentionConfig(False, True, True)
def flash_attn(self, q, k, v):
_, heads, q_len, _, k_len, is_cuda, device = *q.shape, k.shape[-2], q.is_cuda, q.device
# Check if there is a compatible device for flash attention
config = self.cuda_config if is_cuda else self.cpu_config
# pytorch 2.0 flash attn: q, k, v, mask, dropout, softmax_scale
with torch.backends.cuda.sdp_kernel(**config._asdict()):
out = F.scaled_dot_product_attention(
q, k, v,
dropout_p = self.dropout if self.training else 0.
)
return out
def forward(self, q, k, v):
"""
einstein notation
b - batch
h - heads
n, i, j - sequence length (base sequence length, source, target)
d - feature dimension
"""
q_len, k_len, device = q.shape[-2], k.shape[-2], q.device
scale = self.scale if self.scale is not None else q.shape[-1] ** -0.5
if self.flash:
return self.flash_attn(q, k, v)
# similarity
sim = einsum(f"b h i d, b h j d -> b h i j", q, k) * scale
# attention
attn = sim.softmax(dim=-1)
attn = self.attn_dropout(attn)
# aggregate values
out = einsum(f"b h i j, b h j d -> b h i d", attn, v)
return out
+604
View File
@@ -0,0 +1,604 @@
from functools import partial
import torch
from torch import nn, einsum, Tensor
from torch.nn import Module, ModuleList
import torch.nn.functional as F
from .attend import Attend
from beartype.typing import Tuple, Optional, List, Callable
from beartype import beartype
from rotary_embedding_torch import RotaryEmbedding
from einops import rearrange, pack, unpack
from einops.layers.torch import Rearrange
"""
Code adapted from https://github.com/Anjok07/ultimatevocalremovergui/blob/v5.6.0_roformer_add%2Bdirectml/lib_v5/bs_roformer.py and https://github.com/lucidrains/BS-RoFormer which are copyrighted under the terms of the MIT license.
"""
# helper functions
def exists(val):
return val is not None
def default(v, d):
return v if exists(v) else d
def pack_one(t, pattern):
return pack([t], pattern)
def unpack_one(t, ps, pattern):
return unpack(t, ps, pattern)[0]
# norm
def l2norm(t):
return F.normalize(t, dim = -1, p = 2)
class RMSNorm(Module):
def __init__(self, dim):
super().__init__()
self.scale = dim ** 0.5
self.gamma = nn.Parameter(torch.ones(dim))
def forward(self, x):
x = x.to(self.gamma.device)
return F.normalize(x, dim=-1) * self.scale * self.gamma
# attention
class FeedForward(Module):
def __init__(
self,
dim,
mult=4,
dropout=0.
):
super().__init__()
dim_inner = int(dim * mult)
self.net = nn.Sequential(
RMSNorm(dim),
nn.Linear(dim, dim_inner),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(dim_inner, dim),
nn.Dropout(dropout)
)
def forward(self, x):
return self.net(x)
class Attention(Module):
def __init__(
self,
dim,
heads=8,
dim_head=64,
dropout=0.,
rotary_embed=None,
flash=True
):
super().__init__()
self.heads = heads
self.scale = dim_head ** -0.5
dim_inner = heads * dim_head
self.rotary_embed = rotary_embed
self.attend = Attend(flash=flash, dropout=dropout)
self.norm = RMSNorm(dim)
self.to_qkv = nn.Linear(dim, dim_inner * 3, bias=False)
self.to_gates = nn.Linear(dim, heads)
self.to_out = nn.Sequential(
nn.Linear(dim_inner, dim, bias=False),
nn.Dropout(dropout)
)
def forward(self, x):
x = self.norm(x)
q, k, v = rearrange(self.to_qkv(x), 'b n (qkv h d) -> qkv b h n d', qkv=3, h=self.heads)
if exists(self.rotary_embed):
q = self.rotary_embed.rotate_queries_or_keys(q)
k = self.rotary_embed.rotate_queries_or_keys(k)
out = self.attend(q, k, v)
gates = self.to_gates(x)
out = out * rearrange(gates, 'b n h -> b h n 1').sigmoid()
out = rearrange(out, 'b h n d -> b n (h d)')
return self.to_out(out)
class LinearAttention(Module):
"""
this flavor of linear attention proposed in https://arxiv.org/abs/2106.09681 by El-Nouby et al.
"""
@beartype
def __init__(
self,
*,
dim,
dim_head=32,
heads=8,
scale=8,
flash=False,
dropout=0.
):
super().__init__()
dim_inner = dim_head * heads
self.norm = RMSNorm(dim)
self.to_qkv = nn.Sequential(
nn.Linear(dim, dim_inner * 3, bias=False),
Rearrange('b n (qkv h d) -> qkv b h d n', qkv=3, h=heads)
)
self.temperature = nn.Parameter(torch.ones(heads, 1, 1))
self.attend = Attend(
scale=scale,
dropout=dropout,
flash=flash
)
self.to_out = nn.Sequential(
Rearrange('b h d n -> b n (h d)'),
nn.Linear(dim_inner, dim, bias=False)
)
def forward(
self,
x
):
x = self.norm(x)
q, k, v = self.to_qkv(x)
q, k = map(l2norm, (q, k))
q = q * self.temperature.exp()
out = self.attend(q, k, v)
return self.to_out(out)
class Transformer(Module):
def __init__(
self,
*,
dim,
depth,
dim_head=64,
heads=8,
attn_dropout=0.,
ff_dropout=0.,
ff_mult=4,
norm_output=True,
rotary_embed=None,
flash_attn=True,
linear_attn=False
):
super().__init__()
self.layers = ModuleList([])
for _ in range(depth):
if linear_attn:
attn = LinearAttention(dim=dim, dim_head=dim_head, heads=heads, dropout=attn_dropout, flash=flash_attn)
else:
attn = Attention(dim=dim, dim_head=dim_head, heads=heads, dropout=attn_dropout,
rotary_embed=rotary_embed, flash=flash_attn)
self.layers.append(ModuleList([
attn,
FeedForward(dim=dim, mult=ff_mult, dropout=ff_dropout)
]))
self.norm = RMSNorm(dim) if norm_output else nn.Identity()
def forward(self, x):
for attn, ff in self.layers:
x = attn(x) + x
x = ff(x) + x
return self.norm(x)
# bandsplit module
class BandSplit(Module):
@beartype
def __init__(
self,
dim,
dim_inputs: Tuple[int, ...]
):
super().__init__()
self.dim_inputs = dim_inputs
self.to_features = ModuleList([])
for dim_in in dim_inputs:
net = nn.Sequential(
RMSNorm(dim_in),
nn.Linear(dim_in, dim)
)
self.to_features.append(net)
def forward(self, x):
x = x.split(self.dim_inputs, dim=-1)
outs = []
for split_input, to_feature in zip(x, self.to_features):
split_output = to_feature(split_input)
outs.append(split_output)
return torch.stack(outs, dim=-2)
def MLP(
dim_in,
dim_out,
dim_hidden=None,
depth=1,
activation=nn.Tanh
):
dim_hidden = default(dim_hidden, dim_in)
net = []
dims = (dim_in, *((dim_hidden,) * (depth - 1)), dim_out)
for ind, (layer_dim_in, layer_dim_out) in enumerate(zip(dims[:-1], dims[1:])):
is_last = ind == (len(dims) - 2)
net.append(nn.Linear(layer_dim_in, layer_dim_out))
if is_last:
continue
net.append(activation())
return nn.Sequential(*net)
class MaskEstimator(Module):
@beartype
def __init__(
self,
dim,
dim_inputs: Tuple[int, ...],
depth,
mlp_expansion_factor=4
):
super().__init__()
self.dim_inputs = dim_inputs
self.to_freqs = ModuleList([])
dim_hidden = dim * mlp_expansion_factor
for dim_in in dim_inputs:
net = []
mlp = nn.Sequential(
MLP(dim, dim_in * 2, dim_hidden=dim_hidden, depth=depth),
nn.GLU(dim=-1)
)
self.to_freqs.append(mlp)
def forward(self, x):
x = x.unbind(dim=-2)
outs = []
for band_features, mlp in zip(x, self.to_freqs):
freq_out = mlp(band_features)
outs.append(freq_out)
return torch.cat(outs, dim=-1)
# main class
DEFAULT_FREQS_PER_BANDS = (
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
12, 12, 12, 12, 12, 12, 12, 12,
24, 24, 24, 24, 24, 24, 24, 24,
48, 48, 48, 48, 48, 48, 48, 48,
128, 129,
)
class BSRoformer(Module):
@beartype
def __init__(
self,
dim,
*,
depth,
stereo=False,
num_stems=1,
time_transformer_depth=2,
freq_transformer_depth=2,
linear_transformer_depth=0,
freqs_per_bands: Tuple[int, ...] = DEFAULT_FREQS_PER_BANDS,
# in the paper, they divide into ~60 bands, test with 1 for starters
dim_head=64,
heads=8,
attn_dropout=0.,
ff_dropout=0.,
flash_attn=True,
dim_freqs_in=1025,
stft_n_fft=2048,
stft_hop_length=512,
# 10ms at 44100Hz, from sections 4.1, 4.4 in the paper - @faroit recommends // 2 or // 4 for better reconstruction
stft_win_length=2048,
stft_normalized=False,
stft_window_fn: Optional[Callable] = None,
mask_estimator_depth=2,
multi_stft_resolution_loss_weight=1.,
multi_stft_resolutions_window_sizes: Tuple[int, ...] = (4096, 2048, 1024, 512, 256),
multi_stft_hop_size=147,
multi_stft_normalized=False,
multi_stft_window_fn: Callable = torch.hann_window,
# Extra kwargs to ignore from config
**kwargs
):
super().__init__()
self.stereo = stereo
self.audio_channels = 2 if stereo else 1
self.num_stems = num_stems
self.layers = ModuleList([])
transformer_kwargs = dict(
dim=dim,
heads=heads,
dim_head=dim_head,
attn_dropout=attn_dropout,
ff_dropout=ff_dropout,
flash_attn=flash_attn,
norm_output=False
)
time_rotary_embed = RotaryEmbedding(dim=dim_head)
freq_rotary_embed = RotaryEmbedding(dim=dim_head)
for _ in range(depth):
tran_modules = []
if linear_transformer_depth > 0:
tran_modules.append(Transformer(depth=linear_transformer_depth, linear_attn=True, **transformer_kwargs))
tran_modules.append(
Transformer(depth=time_transformer_depth, rotary_embed=time_rotary_embed, **transformer_kwargs)
)
tran_modules.append(
Transformer(depth=freq_transformer_depth, rotary_embed=freq_rotary_embed, **transformer_kwargs)
)
self.layers.append(nn.ModuleList(tran_modules))
self.final_norm = RMSNorm(dim)
self.stft_kwargs = dict(
n_fft=stft_n_fft,
hop_length=stft_hop_length,
win_length=stft_win_length,
normalized=stft_normalized
)
self.stft_window_fn = partial(default(stft_window_fn, torch.hann_window), stft_win_length)
freqs = torch.stft(torch.randn(1, 4096), **self.stft_kwargs, return_complex=True).shape[1]
assert len(freqs_per_bands) > 1
assert sum(
freqs_per_bands) == freqs, f'the number of freqs in the bands must equal {freqs} based on the STFT settings, but got {sum(freqs_per_bands)}'
freqs_per_bands_with_complex = tuple(2 * f * self.audio_channels for f in freqs_per_bands)
self.band_split = BandSplit(
dim=dim,
dim_inputs=freqs_per_bands_with_complex
)
self.mask_estimators = nn.ModuleList([])
for _ in range(num_stems):
mask_estimator = MaskEstimator(
dim=dim,
dim_inputs=freqs_per_bands_with_complex,
depth=mask_estimator_depth
)
self.mask_estimators.append(mask_estimator)
# for the multi-resolution stft loss
self.multi_stft_resolution_loss_weight = multi_stft_resolution_loss_weight
self.multi_stft_resolutions_window_sizes = multi_stft_resolutions_window_sizes
self.multi_stft_n_fft = stft_n_fft
self.multi_stft_window_fn = multi_stft_window_fn
self.multi_stft_kwargs = dict(
hop_length=multi_stft_hop_size,
normalized=multi_stft_normalized
)
def forward(
self,
raw_audio,
target=None,
return_loss_breakdown=False
):
"""
einops
b - batch
f - freq
t - time
s - audio channel (1 for mono, 2 for stereo)
n - number of 'stems'
c - complex (2)
d - feature dimension
"""
original_device = raw_audio.device
x_is_mps = True if original_device.type == 'mps' else False
if x_is_mps:
raw_audio = raw_audio.cpu()
device = raw_audio.device
if raw_audio.ndim == 2:
raw_audio = rearrange(raw_audio, 'b t -> b 1 t')
channels = raw_audio.shape[1]
assert (not self.stereo and channels == 1) or (
self.stereo and channels == 2), 'stereo needs to be set to True if passing in audio signal that is stereo (channel dimension of 2). also need to be False if mono (channel dimension of 1)'
# to stft
raw_audio, batch_audio_channel_packed_shape = pack_one(raw_audio, '* t')
stft_window = self.stft_window_fn(device=device)
stft_repr = torch.stft(raw_audio, **self.stft_kwargs, window=stft_window, return_complex=True)
stft_repr = torch.view_as_real(stft_repr)
stft_repr = unpack_one(stft_repr, batch_audio_channel_packed_shape, '* f t c')
stft_repr = rearrange(stft_repr,
'b s f t c -> b (f s) t c') # merge stereo / mono into the frequency, with frequency leading dimension, for band splitting
x = rearrange(stft_repr, 'b f t c -> b t (f c)')
x = self.band_split(x)
# axial / hierarchical attention
for transformer_block in self.layers:
if len(transformer_block) == 3:
linear_transformer, time_transformer, freq_transformer = transformer_block
x, ft_ps = pack([x], 'b * d')
x = linear_transformer(x)
x, = unpack(x, ft_ps, 'b * d')
else:
time_transformer, freq_transformer = transformer_block
x = rearrange(x, 'b t f d -> b f t d')
x, ps = pack([x], '* t d')
x = time_transformer(x)
x, = unpack(x, ps, '* t d')
x = rearrange(x, 'b f t d -> b t f d')
x, ps = pack([x], '* f d')
x = freq_transformer(x)
x, = unpack(x, ps, '* f d')
x = self.final_norm(x)
num_stems = len(self.mask_estimators)
mask = torch.stack([fn(x) for fn in self.mask_estimators], dim=1)
mask = rearrange(mask, 'b n t (f c) -> b n f t c', c=2)
if x_is_mps:
mask = mask.to('cpu')
# modulate frequency representation
stft_repr = rearrange(stft_repr, 'b f t c -> b 1 f t c')
# complex number multiplication
stft_repr = torch.view_as_complex(stft_repr)
mask = torch.view_as_complex(mask)
stft_repr = stft_repr * mask
# istft
stft_repr = rearrange(stft_repr, 'b n (f s) t -> (b n s) f t', s=self.audio_channels)
recon_audio = torch.istft(stft_repr, **self.stft_kwargs, window=stft_window, return_complex=False)
recon_audio = rearrange(recon_audio, '(b n s) t -> b n s t', s=self.audio_channels, n=num_stems)
if num_stems == 1:
recon_audio = rearrange(recon_audio, 'b 1 s t -> b s t')
# if a target is passed in, calculate loss for learning
if not exists(target):
return recon_audio
if self.num_stems > 1:
assert target.ndim == 4 and target.shape[1] == self.num_stems
if target.ndim == 2:
target = rearrange(target, '... t -> ... 1 t')
target = target[..., :recon_audio.shape[-1]]
loss = F.l1_loss(recon_audio, target)
multi_stft_resolution_loss = 0.
for window_size in self.multi_stft_resolutions_window_sizes:
res_stft_kwargs = dict(
n_fft=max(window_size, self.multi_stft_n_fft),
win_length=window_size,
return_complex=True,
window=self.multi_stft_window_fn(window_size, device=device),
**self.multi_stft_kwargs,
)
recon_Y = torch.stft(rearrange(recon_audio, '... s t -> (... s) t'), **res_stft_kwargs)
target_Y = torch.stft(rearrange(target, '... s t -> (... s) t'), **res_stft_kwargs)
multi_stft_resolution_loss = multi_stft_resolution_loss + F.l1_loss(recon_Y, target_Y)
weighted_multi_resolution_loss = multi_stft_resolution_loss * self.multi_stft_resolution_loss_weight
total_loss = loss + weighted_multi_resolution_loss
if not return_loss_breakdown:
# Move the result back to the original device if it was moved to CPU for MPS compatibility
if x_is_mps:
total_loss = total_loss.to(original_device)
return total_loss
# For detailed loss breakdown, ensure all components are moved back to the original device for MPS
if x_is_mps:
loss = loss.to(original_device)
multi_stft_resolution_loss = multi_stft_resolution_loss.to(original_device)
weighted_multi_resolution_loss = weighted_multi_resolution_loss.to(original_device)
return total_loss, (loss, multi_stft_resolution_loss)
@@ -0,0 +1,258 @@
"""
BS-RoFormer Chorus separator for male/female vocals separation.
Uses the Chorus_Male_Female_BS_Roformer model.
"""
import gc
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Dict, Optional
import numpy as np
import torch
import torch.nn as nn
import yaml
from omegaconf import OmegaConf
from tqdm import tqdm
from .bs_roformer import BSRoformer
SAMPLE_RATE = 44100
# HuggingFace model coordinates
HF_REPO_ID = 'Sucial/Chorus_Male_Female_BS_Roformer'
HF_REVISION = 'main'
def _try_download_model(model_dir: Path, model_path: Path, config_path: Path) -> None:
"""Download model from HuggingFace if not present."""
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=HF_REPO_ID,
revision=HF_REVISION,
local_dir=str(model_dir),
)
def _load_audio(path: str) -> np.ndarray:
"""Load audio as (channels, samples) float32 array."""
import soundfile as sf
try:
data, sr = sf.read(path, dtype='float32', always_2d=True)
data = data.T
except Exception:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
subprocess.run(
['ffmpeg', '-y', '-i', path, '-ar', str(SAMPLE_RATE),
'-ac', '2', '-f', 'wav', tmp_path],
check=True, capture_output=True,
)
data, sr = sf.read(tmp_path, dtype='float32', always_2d=True)
data = data.T
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
if sr != SAMPLE_RATE:
import librosa
data = np.array([
librosa.resample(ch, orig_sr=sr, target_sr=SAMPLE_RATE)
for ch in data
], dtype=np.float32)
if data.shape[0] == 1:
data = np.vstack([data, data])
return data
def _save_audio(path: str, data: np.ndarray, output_format: str, bitrate: str = '256k') -> None:
"""Save (samples, channels) array to audio file."""
import soundfile as sf
ext = output_format.lower()
if ext in ('wav', 'flac'):
sf.write(path, data, SAMPLE_RATE, format=ext.upper(),
subtype='PCM_24' if ext == 'wav' else 'PCM_16')
else:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
sf.write(tmp_path, data, SAMPLE_RATE, format='WAV', subtype='PCM_16')
subprocess.run(
['ffmpeg', '-y', '-i', tmp_path, '-b:a', bitrate, path],
check=True, capture_output=True,
)
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
class BSRoformerChorusSeparator:
"""
BS-RoFormer separator for male/female chorus separation.
Separates male and female voices in choir singing.
Note: This is an experimental model trained primarily on Chinese songs.
Works best when male and female sing simultaneously (not alternately).
"""
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
self.model_dir = Path(model_dir) if model_dir else Path('/opt/bs_roformer_models/chorus')
self.model_path = self.model_dir / 'model_chorus_bs_roformer_ep_267_sdr_24.1275.ckpt'
self.config_path = self.model_dir / 'config.yaml'
self.device = 'cpu' if cpu_separation else 'cuda'
self.output_format = output_format.lower()
self.mp3_bitrate = mp3_bitrate
self._config = None
def _ensure_model(self):
_try_download_model(self.model_dir, self.model_path, self.config_path)
def _load_config(self):
if self._config is None:
with open(self.config_path, 'r') as f:
config = yaml.load(f, Loader=yaml.UnsafeLoader)
self._config = OmegaConf.create(config)
return self._config
def get_model(self) -> BSRoformer:
self._ensure_model()
config = self._load_config()
model_cfg = OmegaConf.to_container(config.model, resolve=True)
# Convert lists to tuples where needed
for key in ('freqs_per_bands', 'multi_stft_resolutions_window_sizes'):
if key in model_cfg and isinstance(model_cfg[key], list):
model_cfg[key] = tuple(model_cfg[key])
model = BSRoformer(**model_cfg)
checkpoint = torch.load(str(self.model_path), map_location='cpu', weights_only=False)
if 'state_dict' in checkpoint:
state_dict = checkpoint['state_dict']
elif 'model' in checkpoint:
state_dict = checkpoint['model']
else:
state_dict = checkpoint
model.load_state_dict(state_dict)
model.to(self.device).eval()
return model
def _demix(self, mix: np.ndarray, model: BSRoformer,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, np.ndarray]:
"""Separate into male and female vocals."""
config = self._load_config()
hop_length = config.model.stft_hop_length
segment_size = getattr(config.inference, 'dim_t', 2000)
C = hop_length * (segment_size - 1)
N = num_overlap_override if num_overlap_override is not None else getattr(config.inference, 'num_overlap', 4)
step = int(C // N)
fade_size = C // 10
batch_size = batch_size_override if batch_size_override is not None else getattr(config.inference, 'batch_size', 1)
device = self.device
mix_t = torch.tensor(mix, dtype=torch.float32)
length_init = mix_t.shape[-1]
if length_init > 2 * (C - step) and (C - step > 0):
mix_t = nn.functional.pad(mix_t, (C - step, C - step), mode='reflect')
fadein = torch.linspace(0, 1, fade_size).to(device)
fadeout = torch.linspace(1, 0, fade_size).to(device)
window_start = torch.ones(C).to(device)
window_start[-fade_size:] *= fadeout
window_finish = torch.ones(C).to(device)
window_finish[:fade_size] *= fadein
window_middle = torch.ones(C).to(device)
window_middle[:fade_size] *= fadein
window_middle[-fade_size:] *= fadeout
# This model outputs: instrumental, male, female (3 stems)
stems = ['instrumental', 'male', 'female']
num_stems = len(stems)
req_shape = (num_stems,) + tuple(mix_t.shape)
with torch.inference_mode():
result = torch.zeros(req_shape, dtype=torch.float32, device=device)
counter = torch.zeros(req_shape, dtype=torch.float32, device=device)
batch_data, batch_locs = [], []
i = 0
total_seg = sum(1 for _ in range(0, mix_t.shape[1], step))
with tqdm(total=total_seg, desc='Separating', unit='segment', ncols=100) as pbar:
while i < mix_t.shape[1]:
part = mix_t[:, i:i + C].to(device)
l = part.shape[-1]
if l < C:
part = nn.functional.pad(
part,
(0, C - l) if l > C // 2 + 1 else (0, C - l, 0, 0),
mode='reflect' if l > C // 2 + 1 else 'constant',
)
batch_data.append(part)
batch_locs.append((i, l))
i += step
if len(batch_data) >= batch_size or i >= mix_t.shape[1]:
arr = torch.stack(batch_data, dim=0)
x = model(arr)
for j, (start, ln) in enumerate(batch_locs):
window = (window_start if start == 0
else window_finish if i >= mix_t.shape[1]
else window_middle)
result[..., start:start + ln] += x[j][..., :ln] * window[..., :ln]
counter[..., start:start + ln] += window[..., :ln]
pbar.update(len(batch_data))
batch_data, batch_locs = [], []
estimated = result / counter.clamp(min=1e-10)
if length_init > 2 * (C - step) and (C - step > 0):
estimated = estimated[..., (C - step):-(C - step)]
sources = {}
for idx, name in enumerate(stems):
sources[name] = estimated[idx].cpu().numpy()
return sources
def separate_into_parts(self, input_path: str, output_dir: str,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, str]:
"""Separate audio and write stems."""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
audio = _load_audio(input_path)
model = self.get_model()
sources = self._demix(audio, model,
batch_size_override=batch_size_override,
num_overlap_override=num_overlap_override)
del model
torch.cuda.empty_cache()
gc.collect()
ext = self.output_format
result = {}
for name, data in sources.items():
dest = str(output_dir / f'{name}.{ext}')
_save_audio(dest, data.T, ext, self.mp3_bitrate)
result[name] = dest
return result
+322
View File
@@ -0,0 +1,322 @@
"""
Standalone BS-RoFormer separator — no Django, no Spleeter/TensorFlow dependency.
Audio I/O uses soundfile (WAV/FLAC) + subprocess ffmpeg (MP3 encoding).
Model architecture is unchanged from the original spleeter-web implementation.
"""
import gc
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Dict, Optional
import numpy as np
import torch
import torch.nn as nn
import yaml
from omegaconf import OmegaConf
from tqdm import tqdm
from .bs_roformer import BSRoformer
# ---------------------------------------------------------------------------
# HuggingFace model coordinates
# ---------------------------------------------------------------------------
HF_REPO_ID = 'jarredou/BS-ROFO-SW-Fixed'
HF_REVISION = 'f99fc5c2e4bc201413cfc1ca5767cf62ddb1a9a4'
# ---------------------------------------------------------------------------
# Default model paths (overridable via env var BS_ROFORMER_MODEL_DIR)
# ---------------------------------------------------------------------------
_MODEL_DIR_ENV = os.environ.get('BS_ROFORMER_MODEL_DIR', '/opt/bs_roformer_models')
DEFAULT_MODEL_DIR = Path(_MODEL_DIR_ENV)
DEFAULT_MODEL_PATH = DEFAULT_MODEL_DIR / 'BS-Rofo-SW-Fixed.ckpt'
DEFAULT_CONFIG_PATH = DEFAULT_MODEL_DIR / 'BS-Rofo-SW-Fixed.yaml'
SAMPLE_RATE = 44100
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _try_download_model(
model_dir: Path = DEFAULT_MODEL_DIR,
model_path: Path = DEFAULT_MODEL_PATH,
config_path: Path = DEFAULT_CONFIG_PATH,
) -> None:
"""Download BS-RoFormer model from HuggingFace if not already present."""
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=HF_REPO_ID,
revision=HF_REVISION,
local_dir=str(model_dir),
)
def _load_config(config_path: Path):
"""Load YAML config, supporting !!python/tuple tags."""
with open(config_path, 'r') as f:
config = yaml.load(f, Loader=yaml.UnsafeLoader)
return OmegaConf.create(config)
def _load_audio(path: str) -> np.ndarray:
"""
Load audio file and return as float32 numpy array of shape (channels, samples).
Uses soundfile for WAV/FLAC; falls back to ffmpeg decode for MP3 and other formats.
"""
import soundfile as sf
try:
data, sr = sf.read(path, dtype='float32', always_2d=True)
# soundfile returns (samples, channels); transpose to (channels, samples)
data = data.T
except Exception:
# Fallback: decode via ffmpeg to a temporary WAV
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
subprocess.run(
['ffmpeg', '-y', '-i', path, '-ar', str(SAMPLE_RATE),
'-ac', '2', '-f', 'wav', tmp_path],
check=True, capture_output=True,
)
data, sr = sf.read(tmp_path, dtype='float32', always_2d=True)
data = data.T
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
# Resample if needed
if sr != SAMPLE_RATE:
import librosa
data = np.array([
librosa.resample(ch, orig_sr=sr, target_sr=SAMPLE_RATE)
for ch in data
], dtype=np.float32)
# Ensure stereo
if data.shape[0] == 1:
data = np.vstack([data, data])
return data # (channels, samples)
def _save_audio(path: str, data: np.ndarray, output_format: str, bitrate: str = '256k') -> None:
"""
Save (samples, channels) float32 array as audio file.
WAV and FLAC use soundfile directly; MP3 encodes via ffmpeg.
"""
import soundfile as sf
ext = output_format.lower()
if ext in ('wav', 'flac'):
sf.write(path, data, SAMPLE_RATE, format=ext.upper(),
subtype='PCM_24' if ext == 'wav' else 'PCM_16')
else:
# Encode to MP3 via ffmpeg
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
sf.write(tmp_path, data, SAMPLE_RATE, format='WAV', subtype='PCM_16')
subprocess.run(
['ffmpeg', '-y', '-i', tmp_path,
'-b:a', bitrate, path],
check=True, capture_output=True,
)
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
# ---------------------------------------------------------------------------
# Separator class
# ---------------------------------------------------------------------------
class BSRoformerSeparator:
"""
Performs source separation using the BS-RoFormer model.
Pure PyTorch — no TensorFlow / Spleeter dependency.
"""
STEM_MODE_4 = '4stem'
STEM_MODE_5_GUITAR = '5stem_guitar'
STEM_MODE_5_PIANO = '5stem_piano'
STEM_MODE_6 = '6stem'
def __init__(
self,
model_path: Optional[str] = None,
config_path: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3', # 'mp3' | 'flac' | 'wav'
mp3_bitrate: str = '256k',
stem_mode: str = '4stem',
):
self.model_path = Path(model_path) if model_path else DEFAULT_MODEL_PATH
self.config_path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH
self.device = 'cpu' if cpu_separation else 'cuda'
self.output_format = output_format.lower()
self.mp3_bitrate = mp3_bitrate
self.stem_mode = stem_mode
self._config = None
# ------------------------------------------------------------------
# Model loading
# ------------------------------------------------------------------
def _ensure_model(self):
_try_download_model(DEFAULT_MODEL_DIR, self.model_path, self.config_path)
def _load_config(self):
if self._config is None:
self._config = _load_config(self.config_path)
return self._config
def get_model(self) -> BSRoformer:
self._ensure_model()
config = self._load_config()
model_cfg = OmegaConf.to_container(config.model, resolve=True)
# OmegaConf loads tuples as lists; the model requires tuples
for key in ('freqs_per_bands', 'multi_stft_resolutions_window_sizes'):
if key in model_cfg and isinstance(model_cfg[key], list):
model_cfg[key] = tuple(model_cfg[key])
model = BSRoformer(**model_cfg)
checkpoint = torch.load(str(self.model_path), map_location='cpu', weights_only=False)
model.load_state_dict(checkpoint)
model.to(self.device).eval()
return model
# ------------------------------------------------------------------
# Inference
# ------------------------------------------------------------------
def _demix(self, mix: np.ndarray, model: BSRoformer,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, np.ndarray]:
"""Separate (channels, samples) array into a dict of stem arrays."""
config = self._load_config()
hop_length = config.model.stft_hop_length
segment_size = config.inference.dim_t
C = hop_length * (segment_size - 1)
N = num_overlap_override if num_overlap_override is not None else config.inference.num_overlap
step = int(C // N)
fade_size = C // 10
batch_size = batch_size_override if batch_size_override is not None else config.inference.batch_size
device = self.device
mix_t = torch.tensor(mix, dtype=torch.float32)
length_init = mix_t.shape[-1]
if length_init > 2 * (C - step) and (C - step > 0):
mix_t = nn.functional.pad(mix_t, (C - step, C - step), mode='reflect')
fadein = torch.linspace(0, 1, fade_size).to(device)
fadeout = torch.linspace(1, 0, fade_size).to(device)
window_start = torch.ones(C).to(device); window_start[-fade_size:] *= fadeout
window_finish = torch.ones(C).to(device); window_finish[:fade_size] *= fadein
window_middle = torch.ones(C).to(device)
window_middle[:fade_size] *= fadein; window_middle[-fade_size:] *= fadeout
S = len(config.training.instruments)
req_shape = (S,) + tuple(mix_t.shape)
with torch.inference_mode():
result = torch.zeros(req_shape, dtype=torch.float32, device=device)
counter = torch.zeros(req_shape, dtype=torch.float32, device=device)
batch_data, batch_locs = [], []
i = 0
# count total segments for tqdm
total_seg = sum(1 for _ in range(0, mix_t.shape[1], step))
with tqdm(total=total_seg, desc='Separating', unit='segment', ncols=100) as pbar:
while i < mix_t.shape[1]:
part = mix_t[:, i:i + C].to(device)
l = part.shape[-1]
if l < C:
part = nn.functional.pad(
part,
(0, C - l) if l > C // 2 + 1 else (0, C - l, 0, 0),
mode='reflect' if l > C // 2 + 1 else 'constant',
)
batch_data.append(part)
batch_locs.append((i, l))
i += step
if len(batch_data) >= batch_size or i >= mix_t.shape[1]:
arr = torch.stack(batch_data, dim=0)
x = model(arr)
for j, (start, ln) in enumerate(batch_locs):
window = (window_start if start == 0
else window_finish if i >= mix_t.shape[1]
else window_middle)
result[..., start:start + ln] += x[j][..., :ln] * window[..., :ln]
counter[..., start:start + ln] += window[..., :ln]
pbar.update(len(batch_data))
batch_data, batch_locs = [], []
estimated = result / counter.clamp(min=1e-10)
if length_init > 2 * (C - step) and (C - step > 0):
estimated = estimated[..., (C - step):-(C - step)]
sources = {}
for idx, name in enumerate(config.training.instruments):
sources[name] = estimated[idx].cpu().numpy()
return sources
def _merge_stems(self, sources_6: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
"""Map 6-stem model output to the requested stem_mode output."""
v, d, b, o, g, p = (
sources_6['vocals'], sources_6['drums'], sources_6['bass'],
sources_6['other'], sources_6['guitar'], sources_6['piano'],
)
if self.stem_mode == self.STEM_MODE_4:
return {'vocals': v, 'drums': d, 'bass': b, 'other': o + g + p}
if self.stem_mode == self.STEM_MODE_5_GUITAR:
return {'vocals': v, 'drums': d, 'bass': b, 'guitar': g, 'other': o + p}
if self.stem_mode == self.STEM_MODE_5_PIANO:
return {'vocals': v, 'drums': d, 'bass': b, 'piano': p, 'other': o + g}
# 6stem — return all
return sources_6
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def separate_into_parts(self, input_path: str, output_dir: str,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, str]:
"""
Separate audio at input_path and write one file per stem into output_dir.
Returns {stem_name: output_file_path}.
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
audio = _load_audio(input_path) # (channels, samples)
model = self.get_model()
sources_6 = self._demix(audio, model,
batch_size_override=batch_size_override,
num_overlap_override=num_overlap_override)
del model
torch.cuda.empty_cache()
gc.collect()
stems = self._merge_stems(sources_6)
ext = self.output_format
result = {}
for name, data in stems.items():
dest = str(output_dir / f'{name}.{ext}')
_save_audio(dest, data.T, ext, self.mp3_bitrate) # T: (channels,samples)→(samples,channels)
result[name] = dest
return result
+106
View File
@@ -0,0 +1,106 @@
"""
BS-RoFormer SW separator - Swin Transformer variant for 6-stem separation
Models from mvsep.com / audio-separator
"""
import os
from pathlib import Path
from typing import Dict
try:
from audio_separator.separator import Separator
AUDIO_SEPARATOR_AVAILABLE = True
except ImportError:
AUDIO_SEPARATOR_AVAILABLE = False
from ..config import BS_ROFORMER_MODEL_DIR, CPU_SEPARATION
class BSRoformerSWSeparator:
"""
BS-RoFormer SW (Swin Transformer) separator.
This variant uses Swin Transformer architecture and provides
6-stem separation: vocals, drums, bass, guitar, piano, other.
"""
def __init__(
self,
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if not AUDIO_SEPARATOR_AVAILABLE:
raise ImportError(
"audio-separator is required for BS-RoFormer SW separation. "
"Install with: pip install audio-separator"
)
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self._separator = None
def _get_separator(self):
"""Lazy-load the separator with SW model."""
if self._separator is None:
# BS-RoFormer SW model is typically available in audio-separator
# as a pre-configured model
self._separator = Separator(
model_file_dir=str(BS_ROFORMER_MODEL_DIR),
output_dir=None,
output_format=self.output_format,
output_bitrate=self.mp3_bitrate if self.output_format == "mp3" else None,
normalization_threshold=0.9,
enable_denoise=False,
cpu_separation=self.cpu_separation,
)
# Load the SW model - this may need specific model name
# audio-separator typically provides this as "model_bs_roformer_sw"
try:
self._separator.load_model()
except Exception as e:
# Fallback: try to load specific model file
sw_model_path = BS_ROFORMER_MODEL_DIR / "bs_roformer_sw.ckpt"
if sw_model_path.exists():
self._separator.load_model(str(sw_model_path))
else:
raise RuntimeError(
f"BS-RoFormer SW model not found. Please download it first. Error: {e}"
)
return self._separator
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate audio into 6 stems.
Returns:
Dict mapping stem names to output file paths
Stems: vocals, drums, bass, guitar, piano, other
"""
sep = self._get_separator()
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Run separation
result = sep.separate(input_path)
# Map outputs to 6 stems
stems = ["vocals", "drums", "bass", "guitar", "piano", "other"]
output_paths = {}
if isinstance(result, list):
for i, path in enumerate(result):
if i < len(stems):
stem_name = stems[i]
final_path = output_path / f"{stem_name}.{self.output_format}"
Path(path).rename(final_path)
output_paths[stem_name] = str(final_path)
else:
# Fallback - single output
final_path = output_path / f"vocals.{self.output_format}"
Path(result).rename(final_path)
output_paths["vocals"] = str(final_path)
return output_paths
+263
View File
@@ -0,0 +1,263 @@
"""
Ensemble separator - Combines multiple models for best quality separation
Uses model averaging/ensembling from multiple high-quality models.
"""
import os
import torch
import torchaudio
import numpy as np
from pathlib import Path
from typing import Dict, List, Optional
import tempfile
import shutil
from ..config import ENSEMBLE_CACHE_DIR, CPU_SEPARATION
# Ensemble configurations
ENSEMBLE_CONFIGS = {
"ensemble_vocal_best": {
"description": "Best vocal separation using BS-RoFormer x2 + MelBand RoFormer ft + SCNet XL IHF",
"models": [
{"type": "bs_roformer", "weight": 0.30, "stem_mode": "4stem"},
{"type": "mel_band", "weight": 0.25, "variant": "vocals"},
{"type": "scnet_xl_ihf", "weight": 0.45},
],
"stems": ["vocals", "instrumental"],
},
"ensemble_4stem": {
"description": "Best 4-stem separation using multiple models averaged",
"models": [
{"type": "demucs", "weight": 0.20, "model": "htdemucs_ft"},
{"type": "bs_roformer", "weight": 0.30, "stem_mode": "4stem"},
{"type": "mel_band", "weight": 0.25, "variant": "4stem"},
{"type": "scnet_large", "weight": 0.25},
],
"stems": ["vocals", "drums", "bass", "other"],
},
"ensemble_6stem": {
"description": "Best 6-stem separation using multiple models averaged",
"models": [
{"type": "bs_roformer", "weight": 0.35, "stem_mode": "6stem"},
{"type": "bs_roformer_sw", "weight": 0.35},
{"type": "demucs", "weight": 0.30, "model": "htdemucs_6s"},
],
"stems": ["vocals", "drums", "bass", "guitar", "piano", "other"],
},
}
class EnsembleSeparator:
"""
Ensemble separator that combines multiple models for best quality.
Uses weighted averaging of outputs from multiple separation models
to produce higher quality results than any single model alone.
"""
def __init__(
self,
ensemble_id: str = "ensemble_vocal_best",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if ensemble_id not in ENSEMBLE_CONFIGS:
raise ValueError(f"Unknown ensemble config: {ensemble_id}")
self.ensemble_id = ensemble_id
self.config = ENSEMBLE_CONFIGS[ensemble_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self.cache_dir = Path(ENSEMBLE_CACHE_DIR)
self.cache_dir.mkdir(parents=True, exist_ok=True)
def _load_audio(self, path: str) -> tuple:
"""Load audio file and return waveform and sample rate."""
waveform, sr = torchaudio.load(path)
return waveform, sr
def _save_audio(self, waveform: torch.Tensor, sr: int, path: str):
"""Save audio waveform to file."""
torchaudio.save(path, waveform, sr)
def _weighted_average(self, audio_tensors: List[torch.Tensor], weights: List[float]) -> torch.Tensor:
"""Compute weighted average of audio tensors."""
if len(audio_tensors) != len(weights):
raise ValueError("Number of tensors must match number of weights")
# Normalize weights
total_weight = sum(weights)
normalized_weights = [w / total_weight for w in weights]
# Compute weighted sum
result = torch.zeros_like(audio_tensors[0])
for tensor, weight in zip(audio_tensors, normalized_weights):
result += tensor * weight
return result
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Run ensemble separation combining multiple models.
This runs multiple models and averages their outputs for best quality.
Note: This takes significantly longer than single-model separation.
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Create temporary directory for intermediate results
temp_dir = Path(tempfile.mkdtemp(dir=self.cache_dir))
try:
stems = self.config["stems"]
stem_audio_data = {stem: [] for stem in stems}
stem_weights = {stem: [] for stem in stems}
# Run each model in the ensemble
for model_config in self.config["models"]:
model_type = model_config["type"]
weight = model_config["weight"]
print(f"Running ensemble component: {model_type} (weight: {weight})")
# Run individual model and get stems
model_stems = self._run_model_component(
model_config, input_path, temp_dir
)
# Add to collection for averaging
for stem_name, stem_path in model_stems.items():
if stem_name in stem_audio_data:
waveform, sr = self._load_audio(stem_path)
stem_audio_data[stem_name].append(waveform)
stem_weights[stem_name].append(weight)
# Compute weighted averages and save final outputs
output_paths = {}
sample_rate = 44100 # Default, will be updated from actual audio
for stem_name in stems:
if stem_name in stem_audio_data and stem_audio_data[stem_name]:
# Compute weighted average
averaged = self._weighted_average(
stem_audio_data[stem_name],
stem_weights[stem_name]
)
# Save result
output_file = output_path / f"{stem_name}.{self.output_format}"
# Convert to desired format
if self.output_format == "mp3":
# Save as WAV first, then convert
temp_wav = temp_dir / f"{stem_name}_temp.wav"
self._save_audio(averaged, sample_rate, str(temp_wav))
# Convert to MP3
import subprocess
bitrate = self.mp3_bitrate.replace("k", "")
subprocess.run([
"ffmpeg", "-y", "-i", str(temp_wav),
"-b:a", f"{bitrate}k",
"-f", "mp3", str(output_file)
], check=True, capture_output=True)
else:
self._save_audio(averaged, sample_rate, str(output_file))
output_paths[stem_name] = str(output_file)
return output_paths
finally:
# Cleanup temp directory
try:
shutil.rmtree(temp_dir, ignore_errors=True)
except:
pass
def _run_model_component(
self,
model_config: Dict,
input_path: str,
output_dir: Path
) -> Dict[str, str]:
"""
Run a single model component and return its output stems.
Returns:
Dict mapping stem names to file paths
"""
model_type = model_config["type"]
if model_type == "bs_roformer":
from .bs_roformer_separator import BSRoformerSeparator
sep = BSRoformerSeparator(
cpu_separation=self.cpu_separation,
output_format="wav", # Use WAV for lossless intermediate
mp3_bitrate="320k",
stem_mode=model_config.get("stem_mode", "4stem"),
)
return sep.separate_into_parts(input_path, str(output_dir / "bsr"))
elif model_type == "bs_roformer_sw":
from .bs_roformer_sw_separator import BSRoformerSWSeparator
sep = BSRoformerSWSeparator(
cpu_separation=self.cpu_separation,
output_format="wav",
mp3_bitrate="320k",
)
return sep.separate_into_parts(input_path, str(output_dir / "bsr_sw"))
elif model_type == "mel_band":
from .mel_band_specialized_separator import MelBandVocalsSeparator
variant = model_config.get("variant", "vocals")
if variant == "vocals":
sep = MelBandVocalsSeparator(
cpu_separation=self.cpu_separation,
output_format="wav",
mp3_bitrate="320k",
)
else:
from .mel_band_roformer_separator import MelBandRoformerSeparator
sep = MelBandRoformerSeparator(
cpu_separation=self.cpu_separation,
output_format="wav",
mp3_bitrate="320k",
)
return sep.separate_into_parts(input_path, str(output_dir / "mbr"))
elif model_type == "scnet_xl_ihf":
from .scnet_separator import SCNetSeparator
sep = SCNetSeparator(
model_id="scnet_xl_ihf",
cpu_separation=self.cpu_separation,
output_format="wav",
mp3_bitrate="320k",
)
return sep.separate_into_parts(input_path, str(output_dir / "scnet"))
elif model_type == "scnet_large":
from .scnet_separator import SCNetSeparator
sep = SCNetSeparator(
model_id="scnet_large",
cpu_separation=self.cpu_separation,
output_format="wav",
mp3_bitrate="320k",
)
return sep.separate_into_parts(input_path, str(output_dir / "scnet"))
elif model_type == "demucs":
# For Demucs, we'd need to run via CLI subprocess
# This is a placeholder
model_name = model_config.get("model", "htdemucs_ft")
# Return empty dict for now - would need actual implementation
return {}
else:
raise ValueError(f"Unknown model type in ensemble: {model_type}")
+847
View File
@@ -0,0 +1,847 @@
"""
LRC alignment service for creating enhanced ELRC files with word-level timestamps.
Uses the lyrics-sync module for vocal extraction and forced alignment.
"""
import os
import re
import sys
import time
import tempfile
from pathlib import Path
from typing import Optional, List, Tuple
from .. import job_manager as jm
from ..config import JOBS_DIR, LRC_SYNC_DIR
from .metadata_util import (
extract_lyrics_from_file,
lyrics_to_plaintext,
format_elrc,
is_lrc_synced
)
# Add lyrics-sync to path
_LRC_SYNC_PATH = Path(__file__).parent.parent.parent / "lyrics-sync"
if str(_LRC_SYNC_PATH) not in sys.path:
sys.path.insert(0, str(_LRC_SYNC_PATH))
class _LyricsSyncNoExtract:
"""
Drop-in replacement for LyricsSync that skips Demucs vocal extraction.
Use this when the input audio is already a separated vocals stem (e.g. from
a project's Stems folder), so we avoid loading and running htdemucs again.
The alignment pipeline is otherwise identical to the standard LyricsSync.
"""
def __init__(self, lang: str = "en-US", blank_id: int = 0, device: str = None) -> None:
from lsync.phoneme_recognizer import PhonemeRecognizer
from lsync.lyrics_processor import LyricsProcessor
self.phone_rec = PhonemeRecognizer(lang=lang, device=device)
self.lp = LyricsProcessor(lang=lang)
self.blank_id = blank_id
def sync(self, audio_fn: str, text_fn: str, save: bool = True, timing_precision: str = 'word'):
import os
import librosa
from lsync.config import TARGET_SR
from lsync.alignment import Aligner
from lsync.util import read_text, save_lrc, save_words
from lsync.lrc_formatter import LrcFormatter
audio_name = os.path.splitext(os.path.basename(audio_fn))[0]
# Load vocals directly (skip Demucs), resample to TARGET_SR
vocals, sr = librosa.load(audio_fn, sr=None, mono=True)
if sr != TARGET_SR:
vocals = librosa.resample(vocals, orig_sr=sr, target_sr=TARGET_SR)
# Rest of alignment pipeline is unchanged
emission, _, _, frame_duration = self.phone_rec.recognize(vocals)
tokens = self.phone_rec.tokenize(text_fn)
path = Aligner.align(emission, tokens, blank_id=self.blank_id)
processed_lyrics = self.lp.process(text_fn)
# Always compute word-level for the basic LRC output
words = self.lp.get_words_from_path(processed_lyrics, path, frame_duration)
original_lyrics = read_text(text_fn)
lrc = LrcFormatter.words2lrc(words, original_lyrics)
if save:
save_words(words, audio_name)
save_lrc(lrc, audio_name)
# Return syllable tokens for ELRC when requested
if timing_precision == 'syllable':
return_words = self.lp.get_syllables_from_path(processed_lyrics, path, frame_duration)
else:
return_words = words
return return_words, lrc
# ── Lyrics cleaning helpers ───────────────────────────────────────────────────
_SECTION_MARKER_RE = re.compile(r'^\[(?!\d{1,2}:\d{2})[^\]]*\]\s*$')
def clean_lyrics_text(text: str) -> str:
"""Remove section markers (e.g. [Chorus], [Verse 1]) and blank lines from plain lyrics."""
cleaned = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
continue
if _SECTION_MARKER_RE.match(stripped):
continue
cleaned.append(stripped)
return '\n'.join(cleaned)
_LRC_SECTION_LINE_RE = re.compile(
r'^\[\d{1,2}:\d{2}[.\d]*\]\s*\[(?!\d)[^\]]*\]\s*$'
)
def clean_lrc_content(content: str) -> tuple:
"""Remove section-marker lines from LRC/ELRC content.
A section-marker line looks like ``[01:30.00][Chorus]`` — a timestamp
followed by a non-timestamp bracket label and nothing else.
Returns ``(cleaned_str, lines_removed_count)``.
"""
lines = content.splitlines()
cleaned, removed = [], 0
for line in lines:
if _LRC_SECTION_LINE_RE.match(line):
removed += 1
else:
cleaned.append(line)
return '\n'.join(cleaned), removed
def run_lrc_alignment(
job_id: str,
audio_path: str,
lyrics_source: str = "auto", # 'auto', 'tag', 'file', 'text'
lyrics_content: Optional[str] = None,
lyrics_file_path: Optional[str] = None,
output_filename: Optional[str] = None,
style_options: Optional[dict] = None,
is_vocals: bool = False,
output_dir: Optional[str] = None,
timing_precision: str = 'word', # 'word' | 'syllable'
lrc_power_preset: str = 'standard', # 'eco' | 'standard' | 'performance'
):
"""
Background task: align lyrics with vocals to create ELRC file.
Args:
job_id: Job identifier
audio_path: Path to the audio file (with vocals)
lyrics_source: Where to get lyrics from
- 'auto': Try metadata tags, then external LRC, then fail
- 'tag': Only use metadata tags
- 'file': Use provided lyrics_file_path
- 'text': Use provided lyrics_content
lyrics_content: Raw lyrics text (when lyrics_source='text')
lyrics_file_path: Path to LRC/txt file (when lyrics_source='file')
output_filename: Optional custom filename for output ELRC
is_vocals: When True, the audio_path is already a separated vocals stem —
skip the internal Demucs extraction step for faster processing.
output_dir: Optional custom output directory (defaults to LRC_SYNC_DIR / job_id)
"""
if output_dir:
out_path = Path(output_dir)
else:
out_path = LRC_SYNC_DIR / job_id
out_path.mkdir(parents=True, exist_ok=True)
try:
# Import lyrics-sync here to handle any import issues gracefully
try:
from lsync import LyricsSync
except ImportError as e:
jm.update_job(
job_id,
status=jm.JobStatus.ERROR,
error=f"Lyrics sync module not available: {e}",
progress="Error."
)
return
# Step 1: Get lyrics
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Reading lyrics...")
lyrics_text = ""
lyrics_synced = False
if lyrics_source == "text" and lyrics_content:
lyrics_text = lyrics_content
lyrics_synced = is_lrc_synced(lyrics_content)
elif lyrics_source == "file" and lyrics_file_path:
lyrics_data = extract_lyrics_from_file(lyrics_file_path)
lyrics_text = lyrics_data["plain"]
lyrics_synced = lyrics_data["synced"]
elif lyrics_source in ("auto", "tag"):
lyrics_data = extract_lyrics_from_file(audio_path)
lyrics_text = lyrics_data["plain"]
lyrics_synced = lyrics_data["synced"]
# If no lyrics in tags, try external LRC file
if not lyrics_text and lyrics_source == "auto":
audio_dir = Path(audio_path).parent
audio_stem = Path(audio_path).stem
for ext in ['.lrc', '.LRC', '.txt', '.TXT']:
lrc_file = audio_dir / f"{audio_stem}{ext}"
if lrc_file.exists():
lyrics_data = extract_lyrics_from_file(str(lrc_file))
lyrics_text = lyrics_data["plain"]
lyrics_synced = lyrics_data["synced"]
break
if not lyrics_text:
jm.update_job(
job_id,
status=jm.JobStatus.ERROR,
error="No lyrics found. Please provide lyrics text or ensure audio file has lyrics tags.",
progress="Error."
)
return
# Strip section markers ([Chorus], [Verse 1], etc.) and blank lines
if not lyrics_synced:
lyrics_text = clean_lyrics_text(lyrics_text)
# Choose sync class: skip Demucs when audio is already vocals.
# In eco mode, force CPU for the phoneme recogniser to avoid GPU contention
# that causes display glitches on shared-GPU (WSL2) setups.
_align_device = "cpu" if lrc_power_preset == "eco" else None
SyncClass = _LyricsSyncNoExtract if is_vocals else LyricsSync
# If lyrics are already synced (LRC format), convert to ELRC with word-level timestamps
if lyrics_synced:
jm.update_job(job_id, progress="Lyrics already synced. Enhancing to word-level...")
_enhance_existing_lrc(
job_id, audio_path, lyrics_text, out_path,
output_filename, SyncClass, style_options, timing_precision,
align_device=_align_device,
)
else:
# Run full alignment pipeline
jm.update_job(job_id, progress="Starting lyrics alignment...")
_run_full_alignment(
job_id, audio_path, lyrics_text, out_path,
output_filename, SyncClass, style_options, timing_precision,
align_device=_align_device,
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")
def _run_full_alignment(
job_id: str,
audio_path: str,
lyrics_text: str,
output_dir: Path,
output_filename: Optional[str],
LyricsSyncClass,
style_options: Optional[dict] = None,
timing_precision: str = 'word',
align_device: Optional[str] = None,
):
"""Run full alignment using lyrics-sync."""
# Write lyrics to temp file
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
f.write(lyrics_text)
lyrics_temp_path = f.name
try:
# Initialize lyrics sync
is_no_extract = LyricsSyncClass is _LyricsSyncNoExtract
device_note = f" [{align_device.upper()}]" if align_device else ""
jm.update_job(job_id, progress=f"Initializing alignment model{device_note}...")
if is_no_extract:
lsync = LyricsSyncClass(lang="en-US", device=align_device)
else:
lsync = LyricsSyncClass(lang="en-US")
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Run alignment
prec_label = "syllable-level" if timing_precision == 'syllable' else "word-level"
if LyricsSyncClass is _LyricsSyncNoExtract:
prog_msg = f"Aligning lyrics ({prec_label})..."
else:
prog_msg = f"Extracting vocals and aligning lyrics ({prec_label})... (this may take a while)"
jm.update_job(job_id, progress=prog_msg)
words, lrc = lsync.sync(audio_path, lyrics_temp_path, save=False, timing_precision=timing_precision)
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Convert to ELRC format
elrc_content = _convert_to_elrc(words, lyrics_text, timing_precision)
# Save ELRC file
if not output_filename:
output_filename = f"{Path(audio_path).stem}.elrc"
elif not output_filename.endswith('.elrc'):
output_filename += '.elrc'
output_path = output_dir / output_filename
output_path.write_text(elrc_content, encoding='utf-8')
# Also save plain LRC version
lrc_filename = output_filename.replace('.elrc', '.lrc')
lrc_path = output_dir / lrc_filename
lrc_path.write_text(lrc, encoding='utf-8')
files = [
{"name": output_path.name, "path": str(output_path), "type": "elrc"},
{"name": lrc_path.name, "path": str(lrc_path), "type": "lrc"},
]
# Generate styled HTML preview if style options provided
if style_options:
jm.update_job(job_id, progress="Generating styled preview...")
html_content = _generate_styled_html(elrc_content, style_options, Path(audio_path).stem)
html_filename = output_filename.replace('.elrc', '.html')
html_path = output_dir / html_filename
html_path.write_text(html_content, encoding='utf-8')
files.append({"name": html_path.name, "path": str(html_path), "type": "html"})
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="ELRC alignment complete.",
files=files
)
finally:
# Cleanup temp file
try:
os.unlink(lyrics_temp_path)
except:
pass
def _enhance_existing_lrc(
job_id: str,
audio_path: str,
lrc_content: str,
output_dir: Path,
output_filename: Optional[str],
LyricsSyncClass,
style_options: Optional[dict] = None,
timing_precision: str = 'word',
align_device: Optional[str] = None,
):
"""Enhance existing LRC with word-level timestamps."""
from .metadata_util import parse_lrc
# Parse existing LRC
lines = parse_lrc(lrc_content)
# Get plain lyrics text
plain_lyrics = lyrics_to_plaintext(lrc_content)
# Run alignment
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
f.write(plain_lyrics)
lyrics_temp_path = f.name
try:
if LyricsSyncClass is _LyricsSyncNoExtract:
lsync = LyricsSyncClass(lang="en-US", device=align_device)
else:
lsync = LyricsSyncClass(lang="en-US")
prec_label = "syllable-level" if timing_precision == 'syllable' else "word-level"
if LyricsSyncClass is _LyricsSyncNoExtract:
prog_msg = f"Aligning words ({prec_label})..."
else:
prog_msg = f"Extracting vocals and aligning words ({prec_label})..."
jm.update_job(job_id, progress=prog_msg)
words, lrc = lsync.sync(audio_path, lyrics_temp_path, save=False, timing_precision=timing_precision)
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Convert to ELRC
elrc_content = _convert_to_elrc(words, plain_lyrics, timing_precision)
# Save files
if not output_filename:
output_filename = f"{Path(audio_path).stem}.elrc"
elif not output_filename.endswith('.elrc'):
output_filename += '.elrc'
output_path = output_dir / output_filename
output_path.write_text(elrc_content, encoding='utf-8')
lrc_filename = output_filename.replace('.elrc', '.lrc')
lrc_path = output_dir / lrc_filename
lrc_path.write_text(lrc, encoding='utf-8')
files = [
{"name": output_path.name, "path": str(output_path), "type": "elrc"},
{"name": lrc_path.name, "path": str(lrc_path), "type": "lrc"},
]
# Generate styled HTML preview if style options provided
if style_options:
jm.update_job(job_id, progress="Generating styled preview...")
html_content = _generate_styled_html(elrc_content, style_options, Path(audio_path).stem)
html_filename = output_filename.replace('.elrc', '.html')
html_path = output_dir / html_filename
html_path.write_text(html_content, encoding='utf-8')
files.append({"name": html_path.name, "path": str(html_path), "type": "html"})
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="ELRC enhancement complete.",
files=files
)
finally:
try:
os.unlink(lyrics_temp_path)
except:
pass
def _fmt_ts(seconds: float) -> str:
"""Format a time value as an ELRC inline timestamp <mm:ss.xx>."""
m = int(seconds // 60)
s = int(seconds % 60)
cs = int((seconds % 1) * 100)
return f"<{m:02d}:{s:02d}.{cs:02d}>"
def _line_ts(seconds: float) -> str:
"""Format a time value as an ELRC line timestamp [mm:ss.xx]."""
m = int(seconds // 60)
s = int(seconds % 60)
cs = int((seconds % 1) * 100)
return f"[{m:02d}:{s:02d}.{cs:02d}]"
def _convert_to_elrc(words, original_lyrics: str, timing_precision: str = 'word') -> str:
"""
Convert aligned words/syllables to ELRC format.
Word mode → ``[line_ts]<ts>Hello <ts>world``
Syllable mode → ``[line_ts]<ts>Hel<ts>lo <ts>world``
(no space between intra-word syllables; space between words)
Args:
words: List of Word objects (label, start, end, is_word_end)
original_lyrics: Original lyrics text for line structure
timing_precision: 'word' or 'syllable'
Returns:
ELRC formatted string
"""
original_lines = [line.strip() for line in original_lyrics.split('\n') if line.strip()]
elrc_lines = []
word_idx = 0
for line_text in original_lines:
if word_idx >= len(words):
break
orig_words = line_text.split()
if not orig_words:
continue
if timing_precision == 'syllable':
# Collect all syllables for this line by consuming until is_word_end
# for each original word
line_syls = []
for _ in orig_words:
while word_idx < len(words):
syl = words[word_idx]
line_syls.append(syl)
word_idx += 1
if getattr(syl, 'is_word_end', False):
break
if not line_syls:
continue
line_start = line_syls[0].start
line_content = ""
for i, syl in enumerate(line_syls):
# Space before a syllable only when the previous one ended a word
prefix = " " if i > 0 and getattr(line_syls[i - 1], 'is_word_end', True) else ""
line_content += f"{prefix}{_fmt_ts(syl.start)}{syl.label}"
else:
# Word mode: consume one Word per original word
line_aligned = []
for i in range(len(orig_words)):
if word_idx + i < len(words):
w = words[word_idx + i]
line_aligned.append(w)
if not line_aligned:
continue
line_start = line_aligned[0].start
line_content = " ".join(f"{_fmt_ts(w.start)}{w.label}" for w in line_aligned)
word_idx += len(orig_words)
elrc_lines.append(f"{_line_ts(line_start)}{line_content}")
return '\n'.join(elrc_lines)
def _generate_styled_html(elrc_content: str, style_options: dict, title: str) -> str:
"""
Generate an HTML file with styled lyrics preview.
Args:
elrc_content: ELRC formatted lyrics content
style_options: Dictionary with style configuration
title: Song title for the HTML page
Returns:
HTML content as string
"""
from .metadata_util import parse_elrc
# Extract style options with defaults
font_family = style_options.get('fontFamily', 'system-ui')
font_size = style_options.get('fontSize', 24)
text_color = style_options.get('textColor', '#e2e8f0')
highlight_color = style_options.get('highlightColor', '#3b82f6')
background_color = style_options.get('backgroundColor', '#0f172a')
word_highlight_color = style_options.get('wordHighlightColor', '#60a5fa')
line_spacing = style_options.get('lineSpacing', 1.5)
text_align = style_options.get('textAlign', 'center')
# Parse ELRC content
lines = parse_elrc(elrc_content)
# Build HTML lines
html_lines = []
for line_ts, line_text, words in lines:
if words:
# Build line with word spans for animation
word_spans = []
for word_ts, word in words:
minutes = int(word_ts // 60)
seconds = int(word_ts % 60)
millis = int((word_ts % 1) * 1000)
time_attr = f"{minutes:02d}:{seconds:02d}.{millis:03d}"
word_spans.append(
f'<span class="word" data-time="{time_attr}">{word}</span>'
)
line_html = ' '.join(word_spans)
else:
line_html = line_text
minutes = int(line_ts // 60)
seconds = int(line_ts % 60)
millis = int((line_ts % 1) * 1000)
line_time = f"{minutes:02d}:{seconds:02d}.{millis:03d}"
html_lines.append(
f'<div class="lyric-line" data-time="{line_time}">{line_html}</div>'
)
lyrics_html = '\n'.join(html_lines)
html_template = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title} - Lyrics</title>
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: {font_family};
background-color: {background_color};
color: {text_color};
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem 1rem;
}}
.container {{
max-width: 800px;
width: 100%;
}}
h1 {{
font-size: {font_size * 1.5}px;
margin-bottom: 2rem;
text-align: {text_align};
color: {text_color};
}}
.lyrics-container {{
display: flex;
flex-direction: column;
gap: {font_size * line_spacing * 0.5}px;
}}
.lyric-line {{
font-size: {font_size}px;
line-height: {line_spacing};
text-align: {text_align};
color: {text_color};
opacity: 0.6;
transition: all 0.3s ease;
padding: 0.5rem;
border-radius: 0.5rem;
}}
.lyric-line.active {{
color: {highlight_color};
opacity: 1;
transform: scale(1.02);
}}
.word {{
display: inline-block;
transition: color 0.2s ease;
padding: 0 0.1em;
}}
.word.active {{
color: {word_highlight_color};
text-shadow: 0 0 10px {word_highlight_color}40;
}}
.controls {{
position: fixed;
bottom: 2rem;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.8);
padding: 1rem 2rem;
border-radius: 2rem;
display: flex;
gap: 1rem;
align-items: center;
backdrop-filter: blur(10px);
}}
button {{
background: {highlight_color};
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 0.5rem;
cursor: pointer;
font-size: 14px;
transition: opacity 0.2s;
}}
button:hover {{
opacity: 0.8;
}}
input[type="range"] {{
width: 200px;
}}
.time-display {{
font-family: monospace;
font-size: 14px;
color: {text_color};
}}
</style>
</head>
<body>
<div class="container">
<h1>{title}</h1>
<div class="lyrics-container">
{lyrics_html}
</div>
</div>
<div class="controls">
<button id="playBtn">▶ Play</button>
<input type="range" id="progress" min="0" max="100" value="0">
<span class="time-display" id="timeDisplay">00:00</span>
</div>
<script>
const lines = document.querySelectorAll('.lyric-line');
const words = document.querySelectorAll('.word');
const playBtn = document.getElementById('playBtn');
const progress = document.getElementById('progress');
const timeDisplay = document.getElementById('timeDisplay');
let isPlaying = false;
let currentTime = 0;
// Derive duration from the last timestamp in the ELRC content
const allTimestamps = Array.from(document.querySelectorAll('[data-start]'))
.map(el => parseFloat(el.getAttribute('data-start')))
.filter(t => !isNaN(t));
let duration = allTimestamps.length > 0 ? Math.ceil(Math.max(...allTimestamps) + 10) : 300;
let animationId = null;
// Parse time string to seconds
function parseTime(timeStr) {{
const [mins, secs] = timeStr.split(':');
return parseInt(mins) * 60 + parseFloat(secs);
}}
// Format seconds to time string
function formatTime(seconds) {{
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${{mins.toString().padStart(2, '0')}}:${{secs.toString().padStart(2, '0')}}`;
}}
// Track last-active elements to avoid redundant DOM updates
let _activeLine = null;
let _activeWord = null;
// Update active line/word based on current time; scroll active line into view
function updateActiveElements() {{
// Find the last line whose timestamp <= currentTime
let newLine = null;
lines.forEach(line => {{
if (currentTime >= parseTime(line.dataset.time)) newLine = line;
}});
if (newLine !== _activeLine) {{
if (_activeLine) _activeLine.classList.remove('active');
if (newLine) {{
newLine.classList.add('active');
const ctrl = document.querySelector('.controls');
const ctrlH = ctrl ? ctrl.offsetHeight + 32 : 80;
const rect = newLine.getBoundingClientRect();
const lineMid = rect.top + rect.height / 2;
const availH = window.innerHeight - ctrlH;
const target = window.scrollY + lineMid - availH / 2;
window.scrollTo({{ top: Math.max(0, target), behavior: 'smooth' }});
}}
_activeLine = newLine;
}}
// Find the last word whose timestamp <= currentTime
let newWord = null;
words.forEach(word => {{
if (currentTime >= parseTime(word.dataset.time)) newWord = word;
}});
if (newWord !== _activeWord) {{
if (_activeWord) _activeWord.classList.remove('active');
if (newWord) newWord.classList.add('active');
_activeWord = newWord;
}}
}}
// Animation loop — use performance.now() delta for accurate wall-clock timing
let _lastTs = null;
function animate(ts) {{
if (isPlaying) {{
if (_lastTs !== null) currentTime += (ts - _lastTs) / 1000;
_lastTs = ts;
if (currentTime > duration) {{
currentTime = 0;
isPlaying = false;
playBtn.textContent = '▶ Play';
_lastTs = null;
}}
progress.value = (currentTime / duration) * 100;
timeDisplay.textContent = formatTime(currentTime);
updateActiveElements();
}} else {{
_lastTs = null;
}}
animationId = requestAnimationFrame(animate);
}}
// Play/Pause toggle
playBtn.addEventListener('click', () => {{
isPlaying = !isPlaying;
playBtn.textContent = isPlaying ? '⏸ Pause' : '▶ Play';
}});
// Progress bar interaction
progress.addEventListener('input', (e) => {{
currentTime = (e.target.value / 100) * duration;
timeDisplay.textContent = formatTime(currentTime);
updateActiveElements();
}});
// Start animation loop
animate();
</script>
</body>
</html>'''
return html_template
def extract_vocals_for_alignment(
job_id: str,
audio_path: str,
output_dir: Path
) -> str:
"""
Extract vocals from audio file for alignment purposes.
Returns path to extracted vocal file.
"""
jm.update_job(job_id, progress="Extracting vocals...")
try:
import torch
from demucs.pretrained import get_model
from demucs.apply import apply_model
from demucs.separate import load_track
device = "cuda" if torch.cuda.is_available() else "cpu"
model = get_model(name="htdemucs", repo=None)
model.to(device)
model.eval()
vocals_idx = model.sources.index("vocals")
# Load audio
wav = load_track(audio_path, 2, model.samplerate)
# Separate
ref = wav.mean(0)
wav = (wav - ref.mean()) / ref.std()
with torch.no_grad():
sources = apply_model(
model, wav[None], device=device, shifts=1,
split=True, overlap=0.25, progress=False
)
vocals = sources[0][vocals_idx]
vocals_np = vocals.cpu().numpy()[0, ...]
# Save vocals
import soundfile as sf
vocals_path = output_dir / f"{Path(audio_path).stem}_vocals.wav"
sf.write(vocals_path, vocals_np, model.samplerate)
return str(vocals_path)
except Exception as e:
# If vocal extraction fails, return original audio
jm.update_job(job_id, progress=f"Vocal extraction failed, using original audio: {e}")
return audio_path
+920
View File
@@ -0,0 +1,920 @@
"""
Lyric transcription service using OpenAI Whisper.
Based on Scriberr's transcription approach - provides word-level timestamps
and speaker diarization support for lyrics.
This service transcribes vocals to text with precise timing information,
suitable for generating LRC and ELRC files.
"""
import contextlib
import threading
import io
import json
import os
import tempfile
import warnings
from pathlib import Path
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
from dataclasses import dataclass
# Whisper's timing.py tries to JIT-compile Triton CUDA kernels for DTW alignment.
# This requires the full CUDA toolkit (nvcc), which is not present in the runtime
# image. The fallback (NumPy median kernel) is correct and only marginally slower,
# so suppress the noisy UserWarning.
warnings.filterwarnings(
"ignore",
message="Failed to launch Triton kernels",
category=UserWarning,
)
# PyTorch 2.6 changed torch.load's default from weights_only=False to True.
# WhisperX / wav2vec2 / pyannote checkpoints contain arbitrary omegaconf and
# other custom types that are not in the default allowlist, and chasing each
# class individually is fragile. Restore the pre-2.6 default (weights_only
# not set by caller → False) by monkey-patching torch.load at startup.
# All checkpoint sources used here (HuggingFace, faster-whisper, pyannote)
# are trusted, so the security trade-off is acceptable.
try:
import torch as _torch
_orig_torch_load = _torch.load
def _patched_torch_load(*args, **kwargs):
# Force weights_only=False regardless of what the caller passed.
# transformers explicitly passes weights_only=True (not just as a
# default), so setdefault is insufficient — we must overwrite it.
# All checkpoint sources used here (HuggingFace, faster-whisper,
# pyannote) are trusted, so the security trade-off is acceptable.
kwargs['weights_only'] = False
return _orig_torch_load(*args, **kwargs)
_torch.load = _patched_torch_load
except Exception:
pass
from .. import job_manager as jm
from ..config import JOBS_DIR, LRC_SYNC_DIR
@dataclass
class WordTimestamp:
"""Word-level timestamp information."""
word: str
start: float
end: float
confidence: Optional[float] = None
@dataclass
class Segment:
"""Segment (line/phrase) level timestamp information."""
text: str
start: float
end: float
words: List[WordTimestamp]
speaker: Optional[str] = None
@dataclass
class LyricTranscriptionResult:
"""Complete transcription result."""
text: str
segments: List[Segment]
language: str
duration: float
model: str
# Available Whisper models with their characteristics
WHISPER_MODELS = {
"tiny": {
"id": "tiny",
"label": "Tiny (fastest, least accurate)",
"size": "39 MB",
"relative_speed": "~32x",
"english_only": False,
},
"base": {
"id": "base",
"label": "Base (fast, good accuracy)",
"size": "74 MB",
"relative_speed": "~16x",
"english_only": False,
},
"small": {
"id": "small",
"label": "Small (balanced)",
"size": "244 MB",
"relative_speed": "~6x",
"english_only": False,
},
"medium": {
"id": "medium",
"label": "Medium (slower, better accuracy)",
"size": "769 MB",
"relative_speed": "~2x",
"english_only": False,
},
"large": {
"id": "large",
"label": "Large (slowest, best accuracy)",
"size": "1550 MB",
"relative_speed": "1x",
"english_only": False,
},
"large-v2": {
"id": "large-v2",
"label": "Large v2 (recommended)",
"size": "1550 MB",
"relative_speed": "1x",
"english_only": False,
},
"large-v3": {
"id": "large-v3",
"label": "Large v3 (latest)",
"size": "1550 MB",
"relative_speed": "1x",
"english_only": False,
},
}
DEFAULT_WHISPER_MODEL = "large-v2"
_whisper_cache: Dict[str, Any] = {}
# Set to False when a CUDA OOM or "unknown error" corrupts the GPU context.
# Once False, all subsequent Whisper loads are forced to CPU so the server
# keeps working without requiring a restart.
_cuda_ok: bool = True
def _mark_cuda_failed() -> None:
"""Record that the CUDA context is bad and purge any GPU-resident models."""
global _cuda_ok
_cuda_ok = False
_whisper_cache.clear()
try:
import torch
torch.cuda.empty_cache()
except Exception:
pass
def reset_cuda() -> dict:
"""
Re-enable GPU acceleration after a CUDA error recovery.
The transcriber falls back to CPU when a CUDA OOM or 'unknown error'
occurs. Call this once the GPU is confirmed free to restore GPU usage
without restarting the container.
"""
global _cuda_ok
_cuda_ok = True
_whisper_cache.clear()
cuda_available = False
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
cuda_available = True
except Exception:
pass
return {"ok": True, "cuda_available": cuda_available, "cuda_ok": _cuda_ok}
def get_whisper_model(model_name: str = DEFAULT_WHISPER_MODEL, device: Optional[str] = None):
"""
Load and in-process-cache a Whisper model.
Reuses an already-loaded model of the same name to avoid reloading ~1.5 GB
weights on every transcription call. If a *different* model is requested,
the cached one is evicted and the CUDA allocator cache is flushed first so
that the new model can fit alongside any other resident GPU allocations.
When `device` is explicitly passed (e.g. "cpu") it overrides the auto-detect
logic. This is used by the CUDA-error recovery path in `transcribe_lyrics`.
"""
import whisper
cache_key = f"{model_name}:{device or 'auto'}"
if cache_key in _whisper_cache:
return _whisper_cache[cache_key]
# Evict any previously cached model and release its GPU memory before
# loading the new one.
if _whisper_cache:
_whisper_cache.clear()
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception:
pass
load_kwargs: dict = {}
if device is not None:
load_kwargs["device"] = device
model = whisper.load_model(model_name, **load_kwargs)
_whisper_cache[cache_key] = model
return model
class _LineCapture(io.RawIOBase):
"""
File-like object that buffers writes and calls `callback` once per complete line.
Used to intercept Whisper's verbose stdout output for live progress reporting.
"""
def __init__(self, callback: Callable[[str], None]) -> None:
self._cb = callback
self._buf = ''
def write(self, text) -> int: # type: ignore[override]
if isinstance(text, (bytes, bytearray)):
text = text.decode('utf-8', errors='replace')
self._buf += text
while '\n' in self._buf:
line, self._buf = self._buf.split('\n', 1)
cleaned = line.strip()
if cleaned:
self._cb(cleaned)
return len(text)
def flush(self) -> None:
pass
# Some libraries call fileno(); raise so they fall back gracefully.
def fileno(self): # type: ignore[override]
raise io.UnsupportedOperation('fileno')
def transcribe_lyrics(
audio_path: str,
model_name: str = DEFAULT_WHISPER_MODEL,
language: Optional[str] = None,
task: Literal["transcribe", "translate"] = "transcribe",
include_word_timestamps: bool = True,
initial_prompt: Optional[str] = None,
temperature: float = 0.0,
condition_on_previous_text: bool = False,
compression_ratio_threshold: float = 1.35,
beam_size: Optional[int] = None,
line_callback: Optional[Callable[[str], None]] = None,
) -> LyricTranscriptionResult:
"""
Transcribe vocals to lyrics with word-level timestamps.
Anti-hallucination defaults (differ from stock Whisper):
- condition_on_previous_text=False — prevents the model from feeding
a repeated phrase back as context, breaking the repetition loop.
- temperature fallback tuple — when temperature=0.0, Whisper is
automatically given (0.0, 0.2, 0.4, 0.6, 0.8, 1.0) so it can retry
a stuck segment with increasing randomness.
- compression_ratio_threshold=1.35 — flags repetitive segments sooner
(stock default is 2.4) and triggers the temperature fallback.
- _deduplicate_segments post-pass — removes any repeated segments or
internally-looped phrases that still slip through.
Args:
audio_path: Path to audio file (should be vocals stem for best results)
model_name: Whisper model to use
language: ISO-639-1 language code (auto-detected if None)
task: 'transcribe' for original language, 'translate' for English
include_word_timestamps: Whether to include word-level timestamps
initial_prompt: Optional text to guide the model's style
temperature: Base sampling temperature; 0.0 enables the fallback tuple
condition_on_previous_text: Feed previous segment as context (False prevents loops)
compression_ratio_threshold: Retry segment above this gzip ratio (lower = stricter)
Returns:
LyricTranscriptionResult with text, segments, and timestamps
"""
import whisper
# Free any reserved-but-unallocated GPU memory from prior jobs (e.g. Demucs,
# BS-RoFormer) before the Whisper model is loaded / used.
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception:
pass
# If a previous job corrupted the CUDA context (OOM → "unknown error"),
# force CPU so this job still completes rather than failing immediately.
forced_device: Optional[str] = None if _cuda_ok else "cpu"
model = get_whisper_model(model_name, device=forced_device)
# When temperature is 0 (greedy), pass a fallback sequence so Whisper can
# recover from stuck segments by retrying with increasing randomness.
effective_temperature: Any = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0) if temperature == 0.0 else temperature
decode_options: dict = {
"task": task,
"temperature": effective_temperature,
"condition_on_previous_text": condition_on_previous_text,
"compression_ratio_threshold": compression_ratio_threshold,
}
if language:
decode_options["language"] = language
if initial_prompt:
decode_options["initial_prompt"] = initial_prompt
if beam_size is not None:
decode_options["beam_size"] = beam_size
def _run_transcribe(mdl: Any) -> Any:
"""Run model.transcribe(), capturing verbose output when a callback is set."""
if line_callback is not None:
_cap = _LineCapture(line_callback)
with contextlib.redirect_stdout(_cap), contextlib.redirect_stderr(_cap):
return mdl.transcribe(
audio_path,
word_timestamps=include_word_timestamps,
verbose=True,
**decode_options,
)
return mdl.transcribe(
audio_path,
word_timestamps=include_word_timestamps,
**decode_options,
)
# Run transcription with word timestamps.
# On any CUDA error (OOM already happened, or the context was already
# corrupted), mark the GPU as failed, reload the model on CPU, and retry.
# This keeps the server usable without a restart.
try:
result = _run_transcribe(model)
except RuntimeError as exc:
err_str = str(exc)
if "CUDA" in err_str or "cuda" in err_str:
_mark_cuda_failed()
if line_callback:
line_callback("⚠️ CUDA error — retrying on CPU (server restart not required)")
cpu_model = get_whisper_model(model_name, device="cpu")
result = _run_transcribe(cpu_model)
else:
raise
# Parse results into structured format
raw_segments: List[Segment] = []
for seg in result["segments"]:
words = []
if include_word_timestamps and "words" in seg:
for word_info in seg["words"]:
words.append(WordTimestamp(
word=word_info["word"].strip(),
start=word_info["start"],
end=word_info["end"],
confidence=word_info.get("probability")
))
raw_segments.append(Segment(
text=seg["text"].strip(),
start=seg["start"],
end=seg["end"],
words=words
))
# Calculate total duration
duration = max(seg.end for seg in raw_segments) if raw_segments else 0.0
return LyricTranscriptionResult(
text=result["text"].strip(),
segments=raw_segments,
language=result.get("language", "unknown"),
duration=duration,
model=f"whisper-{model_name}"
)
def result_to_lrc(result: LyricTranscriptionResult) -> str:
"""Convert transcription result to LRC format (line-level timestamps)."""
lines = []
for seg in result.segments:
minutes = int(seg.start // 60)
seconds = int(seg.start % 60)
centis = int((seg.start % 1) * 100)
lines.append(f"[{minutes:02d}:{seconds:02d}.{centis:02d}]{seg.text}")
return "\n".join(lines)
def result_to_elrc(result: LyricTranscriptionResult) -> str:
"""Convert transcription result to ELRC format (word-level timestamps)."""
lines = []
for seg in result.segments:
if not seg.words:
# Fallback to segment-level if no word timestamps
minutes = int(seg.start // 60)
seconds = int(seg.start % 60)
centis = int((seg.start % 1) * 100)
lines.append(f"[{minutes:02d}:{seconds:02d}.{centis:02d}]{seg.text}")
continue
# Line timestamp is start of first word
line_start = seg.words[0].start
line_min = int(line_start // 60)
line_sec = int(line_start % 60)
line_centi = int((line_start % 1) * 100)
# Build word-level timestamps
word_parts = []
for word in seg.words:
w_min = int(word.start // 60)
w_sec = int(word.start % 60)
w_centi = int((word.start % 1) * 100)
word_parts.append(f"<{w_min:02d}:{w_sec:02d}.{w_centi:02d}>{word.word}")
lines.append(f"[{line_min:02d}:{line_sec:02d}.{line_centi:02d}]{' '.join(word_parts)}")
return "\n".join(lines)
def result_to_json(result: LyricTranscriptionResult) -> Dict[str, Any]:
"""Convert transcription result to JSON-serializable dict."""
return {
"text": result.text,
"language": result.language,
"duration": result.duration,
"model": result.model,
"segments": [
{
"text": seg.text,
"start": seg.start,
"end": seg.end,
"speaker": seg.speaker,
"words": [
{
"word": w.word,
"start": w.start,
"end": w.end,
"confidence": w.confidence
}
for w in seg.words
]
}
for seg in result.segments
]
}
def result_to_txt(result: LyricTranscriptionResult) -> str:
"""Convert transcription result to plain text.
One Whisper segment per line so the output can be fed directly into the
ctc-forced-aligner (lrc_service) which splits on newlines to identify
individual lyric lines. Falls back to the joined text if no segments.
"""
if result.segments:
return '\n'.join(seg.text.strip() for seg in result.segments if seg.text.strip())
return result.text
def result_to_srt(result: LyricTranscriptionResult) -> str:
"""Convert transcription result to SRT subtitle format."""
lines = []
for i, seg in enumerate(result.segments, 1):
# Format: HH:MM:SS,mmm
def fmt_srt_time(t: float) -> str:
hours = int(t // 3600)
mins = int((t % 3600) // 60)
secs = int(t % 60)
millis = int((t % 1) * 1000)
return f"{hours:02d}:{mins:02d}:{secs:02d},{millis:03d}"
lines.append(str(i))
lines.append(f"{fmt_srt_time(seg.start)} --> {fmt_srt_time(seg.end)}")
lines.append(seg.text)
lines.append("") # Empty line between entries
return "\n".join(lines)
def result_to_vtt(result: LyricTranscriptionResult) -> str:
"""Convert transcription result to WebVTT subtitle format."""
lines = ["WEBVTT", ""]
for seg in result.segments:
def fmt_vtt_time(t: float) -> str:
hours = int(t // 3600)
mins = int((t % 3600) // 60)
secs = int(t % 60)
millis = int((t % 1) * 1000)
return f"{hours:02d}:{mins:02d}:{secs:02d}.{millis:03d}"
lines.append(f"{fmt_vtt_time(seg.start)} --> {fmt_vtt_time(seg.end)}")
lines.append(seg.text)
lines.append("")
return "\n".join(lines)
def run_lyric_transcription(
job_id: str,
audio_path: str,
model: str = DEFAULT_WHISPER_MODEL,
language: Optional[str] = None,
task: str = "transcribe",
output_formats: Optional[List[str]] = None,
initial_prompt: Optional[str] = None,
temperature: float = 0.0,
condition_on_previous_text: bool = False,
word_timestamps: bool = True,
beam_size: Optional[int] = None,
output_dir: Optional[str] = None,
engine: str = "whisperx",
diarize: bool = False,
):
"""
Background task: transcribe vocals/lyrics from audio.
Args:
job_id: Job identifier
audio_path: Path to audio file
model: Whisper model name
language: Language code (auto-detect if None)
task: 'transcribe' or 'translate'
output_formats: List of output formats ('lrc', 'elrc', 'json', 'txt', 'srt', 'vtt')
initial_prompt: Optional prompt text
temperature: Sampling temperature
output_dir: Custom output directory
engine: 'whisperx' (faster-whisper + phoneme alignment)
diarize: Run speaker diarization after alignment (WhisperX only)
"""
if output_formats is None:
output_formats = ["elrc", "json", "txt"]
if output_dir:
out_path = Path(output_dir)
else:
out_path = LRC_SYNC_DIR / job_id
out_path.mkdir(parents=True, exist_ok=True)
try:
if engine == "whisperx":
# ── WhisperX path: faster-whisper backend + phoneme-level alignment ──
try:
import torch
import whisperx
except ImportError as _imp_err:
jm.update_job(
job_id,
status=jm.JobStatus.ERROR,
error=f"WhisperX is not installed ({_imp_err}). "
"Install with: pip install whisperx",
progress="Error.",
)
return
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress=f"Loading WhisperX model ({model})...")
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
device = "cuda" if torch.cuda.is_available() else "cpu"
compute_type = "float16" if device == "cuda" else "int8"
wx_model = whisperx.load_model(model, device, compute_type=compute_type, language=language or None)
audio_arr = whisperx.load_audio(audio_path)
duration = float(len(audio_arr)) / 16000.0
jm.update_job(job_id, progress=f"Transcribing with WhisperX ({model})...")
wx_result = wx_model.transcribe(audio_arr, batch_size=16)
detected_lang = wx_result.get("language") or language or "unknown"
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
jm.update_job(job_id, progress="Aligning word timestamps (WhisperX)...")
model_a, metadata = whisperx.load_align_model(language_code=detected_lang, device=device)
wx_result = whisperx.align(
wx_result["segments"], model_a, metadata, audio_arr, device,
return_char_alignments=False,
)
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
if diarize:
jm.update_job(job_id, progress="Running speaker diarization...")
try:
import os
hf_token = os.environ.get("HF_TOKEN") or None
diarize_model = whisperx.DiarizationPipeline(use_auth_token=hf_token, device=device)
diarize_segments = diarize_model(audio_arr)
wx_result = whisperx.assign_word_speakers(diarize_segments, wx_result)
except Exception as _diar_err:
jm.update_job(job_id, progress=f"Diarization failed ({_diar_err}), continuing without speaker labels...")
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Convert WhisperX output → LyricTranscriptionResult
segments: List[Segment] = []
for seg in wx_result["segments"]:
words = []
for w in seg.get("words", []):
words.append(WordTimestamp(
word=w.get("word", ""),
start=float(w.get("start") or seg["start"]),
end=float(w.get("end") or seg["end"]),
confidence=w.get("score"),
))
segments.append(Segment(
text=seg["text"].strip(),
start=float(seg["start"]),
end=float(seg["end"]),
words=words,
speaker=seg.get("speaker"),
))
result = LyricTranscriptionResult(
text=" ".join(seg.text for seg in segments),
segments=segments,
language=detected_lang,
duration=duration,
model=f"whisperx-{model}",
)
else:
# ── Standard Whisper path ─────────────────────────────────────────────
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress=f"Loading Whisper model ({model})...")
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
jm.update_job(job_id, progress=f"Transcribing lyrics with Whisper ({model})...")
# Accumulate Whisper's verbose segment output for live progress display.
# Noisy lines (tqdm bars, empty lines) are filtered out.
_log: List[str] = []
_NOISE_TOKENS = ('%|', 'it/s', 'B/s', '100%')
def _on_line(line: str) -> None:
if any(tok in line for tok in _NOISE_TOKENS):
return
_log.append(line)
if len(_log) > 30:
_log.pop(0)
jm.update_job(job_id, progress='\n'.join(_log))
_TRANSCRIBE_TIMEOUT = 7200 # 2-hour hard cap
_result_box: list = [None]
_exc_box: list = [None]
def _do_transcribe():
try:
_result_box[0] = transcribe_lyrics(
audio_path=audio_path,
model_name=model,
language=language,
task=task, # type: ignore
include_word_timestamps=word_timestamps,
initial_prompt=initial_prompt,
temperature=temperature,
condition_on_previous_text=condition_on_previous_text,
beam_size=beam_size,
line_callback=_on_line,
)
except Exception as _e:
_exc_box[0] = _e
_t = threading.Thread(target=_do_transcribe, daemon=True)
_t.start()
_t.join(timeout=_TRANSCRIBE_TIMEOUT)
if _t.is_alive():
jm.update_job(
job_id,
status=jm.JobStatus.ERROR,
error=f"Transcription timed out after {_TRANSCRIBE_TIMEOUT // 3600}h. "
"The model is still running in the background and will release "
"the GPU when it finishes.",
progress="Timed out.",
)
return
if _exc_box[0] is not None:
raise _exc_box[0]
result = _result_box[0]
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Generate output files
jm.update_job(job_id, progress="Generating output files...")
base_name = Path(audio_path).stem
output_files = []
# JSON (full data)
if "json" in output_formats:
json_path = out_path / f"{base_name}_transcription.json"
json_data = result_to_json(result)
json_path.write_text(json.dumps(json_data, indent=2, ensure_ascii=False), encoding="utf-8")
output_files.append({"name": json_path.name, "path": str(json_path), "type": "json"})
# LRC (line-level)
if "lrc" in output_formats:
lrc_path = out_path / f"{base_name}.lrc"
lrc_content = result_to_lrc(result)
lrc_path.write_text(lrc_content, encoding="utf-8")
output_files.append({"name": lrc_path.name, "path": str(lrc_path), "type": "lrc"})
# ELRC (word-level)
if "elrc" in output_formats:
elrc_path = out_path / f"{base_name}.elrc"
elrc_content = result_to_elrc(result)
elrc_path.write_text(elrc_content, encoding="utf-8")
output_files.append({"name": elrc_path.name, "path": str(elrc_path), "type": "elrc"})
# Plain text
if "txt" in output_formats:
txt_path = out_path / f"{base_name}_lyrics.txt"
txt_content = result_to_txt(result)
txt_path.write_text(txt_content, encoding="utf-8")
output_files.append({"name": txt_path.name, "path": str(txt_path), "type": "txt"})
# SRT subtitles
if "srt" in output_formats:
srt_path = out_path / f"{base_name}.srt"
srt_content = result_to_srt(result)
srt_path.write_text(srt_content, encoding="utf-8")
output_files.append({"name": srt_path.name, "path": str(srt_path), "type": "srt"})
# VTT subtitles
if "vtt" in output_formats:
vtt_path = out_path / f"{base_name}.vtt"
vtt_content = result_to_vtt(result)
vtt_path.write_text(vtt_content, encoding="utf-8")
output_files.append({"name": vtt_path.name, "path": str(vtt_path), "type": "vtt"})
# Update job with results
result_summary = {
"model": result.model,
"language": result.language,
"duration": result.duration,
"segment_count": len(result.segments),
"word_count": sum(len(seg.words) for seg in result.segments),
}
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="Lyric transcription complete.",
files=output_files,
result=result_summary
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")
def run_lyric_transcription_with_diarization(
job_id: str,
audio_path: str,
model: str = DEFAULT_WHISPER_MODEL,
language: Optional[str] = None,
num_speakers: Optional[int] = None,
min_speakers: Optional[int] = None,
max_speakers: Optional[int] = None,
output_formats: Optional[List[str]] = None,
output_dir: Optional[str] = None,
):
"""
Background task: transcribe vocals with speaker diarization.
This uses WhisperX for diarization which requires additional setup:
- pip install whisperx
- HuggingFace token for pyannote models
Args:
job_id: Job identifier
audio_path: Path to audio file
model: Whisper model name
language: Language code
num_speakers: Exact number of speakers (optional)
min_speakers: Minimum number of speakers
max_speakers: Maximum number of speakers
output_formats: List of output formats
output_dir: Custom output directory
"""
if output_formats is None:
output_formats = ["json", "txt"]
if output_dir:
out_path = Path(output_dir)
else:
out_path = LRC_SYNC_DIR / job_id
out_path.mkdir(parents=True, exist_ok=True)
try:
import whisperx
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Loading WhisperX model...")
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Load WhisperX model
device = "cuda" if jm.import_module("torch").cuda.is_available() else "cpu"
compute_type = "float16" if device == "cuda" else "int8"
model_obj = whisperx.load_model(model, device, compute_type=compute_type)
# Load audio
audio = whisperx.load_audio(audio_path)
jm.update_job(job_id, progress="Transcribing with WhisperX...")
# Transcribe
result = model_obj.transcribe(audio, batch_size=16)
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Align timestamps
jm.update_job(job_id, progress="Aligning word timestamps...")
model_a, metadata = whisperx.load_align_model(language_code=result["language"], device=device)
result = whisperx.align(result["segments"], model_a, metadata, audio, device)
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
# Diarization
jm.update_job(job_id, progress="Running speaker diarization...")
diarize_model = whisperx.DiarizationPipeline(device=device)
diarize_segments = diarize_model(audio, num_speakers=num_speakers,
min_speakers=min_speakers,
max_speakers=max_speakers)
result = whisperx.assign_word_speakers(diarize_segments, result)
# Generate outputs
jm.update_job(job_id, progress="Generating output files...")
base_name = Path(audio_path).stem
output_files = []
if "json" in output_formats:
json_path = out_path / f"{base_name}_diarized.json"
json_path.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
output_files.append({"name": json_path.name, "path": str(json_path), "type": "json"})
if "txt" in output_formats:
txt_path = out_path / f"{base_name}_diarized.txt"
lines = [f"[{seg.get('speaker', 'UNKNOWN')}] {seg['text']}" for seg in result["segments"]]
txt_path.write_text("\n".join(lines), encoding="utf-8")
output_files.append({"name": txt_path.name, "path": str(txt_path), "type": "txt"})
result_summary = {
"model": f"whisperx-{model}",
"language": result.get("language", "unknown"),
"segment_count": len(result["segments"]),
"diarization": True,
}
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="Lyric transcription with diarization complete.",
files=output_files,
result=result_summary
)
except ImportError:
jm.update_job(
job_id,
status=jm.JobStatus.ERROR,
error="WhisperX not installed. Install with: pip install whisperx",
progress="Error."
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")
def is_whisper_available() -> bool:
"""Check if Whisper is available."""
try:
import whisper
return True
except ImportError:
return False
def is_whisperx_available() -> bool:
"""Check if WhisperX is available."""
try:
import whisperx
return True
except ImportError:
return False
+355
View File
@@ -0,0 +1,355 @@
"""
MDX-Net separator using ONNX models from Ultimate Vocal Remover (UVR).
Supports various MDX-Net models for vocals/instrumental separation.
"""
import gc
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Dict, Optional, Tuple
from collections import namedtuple
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import tqdm
# Try to import ONNX runtime
try:
import onnxruntime as ort
ONNX_AVAILABLE = True
except ImportError:
ONNX_AVAILABLE = False
SAMPLE_RATE = 44100
# Model configurations
MDXNET_MODELS = {
'mdxnet_voc_ft': {
'repo_id': 'Politrees/UVR_resources',
'path': 'models/MDXNet/UVR-MDX-NET-Voc_FT.onnx',
'stems': ['vocals', 'instrumental'],
'target_stem': 'vocals',
},
'mdxnet_inst_hq_1': {
'repo_id': 'Politrees/UVR_resources',
'path': 'models/MDXNet/UVR-MDX-NET-Inst_HQ_1.onnx',
'stems': ['instrumental', 'vocals'],
'target_stem': 'instrumental',
},
'mdxnet_inst_hq_2': {
'repo_id': 'Politrees/UVR_resources',
'path': 'models/MDXNet/UVR-MDX-NET-Inst_HQ_2.onnx',
'stems': ['instrumental', 'vocals'],
'target_stem': 'instrumental',
},
'mdxnet_inst_hq_3': {
'repo_id': 'Politrees/UVR_resources',
'path': 'models/MDXNet/UVR-MDX-NET-Inst_HQ_3.onnx',
'stems': ['instrumental', 'vocals'],
'target_stem': 'instrumental',
},
'mdxnet_karaoke': {
'repo_id': 'Politrees/UVR_resources',
'path': 'models/MDXNet/UVR_MDXNET_KARA.onnx',
'stems': ['lead', 'backing_instrumental'],
'target_stem': 'lead',
},
# New models from MVSEP-Central-Backup
'mdxnet_dereverb': {
'repo_id': 'miercolesv/MVSEP-Central-Backup',
'path': 'Dereverb-MelBand-Anvuew/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt',
'stems': ['dry_vocals', 'reverb'],
'target_stem': 'dry_vocals',
'use_melband': True, # Uses MelBand architecture, not pure ONNX
},
'mdxnet_drumsep': {
'repo_id': 'miercolesv/MVSEP-Central-Backup',
'path': 'Politrees/UVR_resources/models/MDX23C/MDX23C-DrumSep-aufr33-jarredou.ckpt',
'stems': ['drums', 'no_drums'],
'target_stem': 'drums',
'use_melband': True,
},
}
# MDX-Net specific constants
HOP_LENGTH = 1024
N_FFT = 2048
DIM_F = 3072
DIM_T = 8
def _load_audio(path: str, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
"""Load audio as (channels, samples) float32 array."""
import soundfile as sf
try:
data, sr = sf.read(path, dtype='float32', always_2d=True)
data = data.T
except Exception:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
subprocess.run(
['ffmpeg', '-y', '-i', path, '-ar', str(sample_rate),
'-ac', '2', '-f', 'wav', tmp_path],
check=True, capture_output=True,
)
data, sr = sf.read(tmp_path, dtype='float32', always_2d=True)
data = data.T
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
if sr != sample_rate:
import librosa
data = np.array([
librosa.resample(ch, orig_sr=sr, target_sr=sample_rate)
for ch in data
], dtype=np.float32)
# Ensure stereo
if data.shape[0] == 1:
data = np.vstack([data, data])
return data
def _save_audio(path: str, data: np.ndarray, output_format: str, bitrate: str = '256k') -> None:
"""Save (samples, channels) array to audio file."""
import soundfile as sf
ext = output_format.lower()
if ext in ('wav', 'flac'):
sf.write(path, data, SAMPLE_RATE, format=ext.upper(),
subtype='PCM_24' if ext == 'wav' else 'PCM_16')
else:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
sf.write(tmp_path, data, SAMPLE_RATE, format='WAV', subtype='PCM_16')
subprocess.run(
['ffmpeg', '-y', '-i', tmp_path, '-b:a', bitrate, path],
check=True, capture_output=True,
)
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
def _stft(wave: np.ndarray, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH) -> np.ndarray:
"""Compute STFT of audio."""
# wave shape: (channels, samples)
channels = wave.shape[0]
specs = []
for ch in range(channels):
spec = np.stft(wave[ch], n_fft=n_fft, hop_length=hop_length, window='hann')
specs.append(spec)
return np.array(specs) # (channels, freq, time, 2) where last dim is real/imag
def _istft(spec: np.ndarray, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH) -> np.ndarray:
"""Compute inverse STFT."""
channels = spec.shape[0]
waves = []
for ch in range(channels):
wave = np.istft(spec[ch], n_fft=n_fft, hop_length=hop_length, window='hann')
waves.append(wave)
return np.array(waves)
def _spec_to_batch(spec: np.ndarray, dim_f: int = DIM_F, dim_t: int = DIM_T) -> Tuple[np.ndarray, dict]:
"""Convert spectrogram to batch format for MDX-Net."""
# spec shape: (channels, freq, time, 2)
b, f, t, c = spec.shape
# Pad if necessary
pad_f = dim_f - f if f < dim_f else 0
pad_t = dim_t - (t % dim_t) if t % dim_t != 0 else 0
if pad_f > 0 or pad_t > 0:
spec = np.pad(spec, ((0, 0), (0, pad_f), (0, pad_t), (0, 0)))
# Reshape to batches
spec = spec.transpose(0, 3, 1, 2) # (channels, 2, freq, time)
# Split into time chunks
t_chunks = spec.shape[-1] // dim_t
spec = spec.reshape(b, c, dim_f, t_chunks, dim_t)
spec = spec.transpose(0, 3, 1, 2, 4) # (b, t_chunks, c, f, t)
spec = spec.reshape(-1, c, dim_f, dim_t)
metadata = {
'original_shape': (b, f, t, c),
'pad_f': pad_f,
'pad_t': pad_t,
't_chunks': t_chunks,
}
return spec, metadata
def _batch_to_spec(batch: np.ndarray, metadata: dict) -> np.ndarray:
"""Convert batch format back to spectrogram."""
b, f, t, c = metadata['original_shape']
pad_f = metadata['pad_f']
pad_t = metadata['pad_t']
t_chunks = metadata['t_chunks']
# Reshape back
batch = batch.reshape(b, t_chunks, c, DIM_F, DIM_T)
batch = batch.transpose(0, 2, 3, 1, 4) # (b, c, f, t_chunks, t)
batch = batch.reshape(b, c, DIM_F, t_chunks * DIM_T)
# Remove padding
spec = batch.transpose(0, 2, 3, 1) # (b, f, t, c)
if pad_f > 0:
spec = spec[:, :f, :, :]
if pad_t > 0:
spec = spec[:, :, :t, :]
return spec
class MDXNetSeparator:
"""
MDX-Net separator using ONNX models from Ultimate Vocal Remover.
Supports various models for vocals/instrumental/karaoke separation.
"""
def __init__(
self,
model_id: str,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
if not ONNX_AVAILABLE:
raise ImportError("onnxruntime is required for MDX-Net models. Install with: pip install onnxruntime")
if model_id not in MDXNET_MODELS:
raise ValueError(f"Unknown MDX-Net model: {model_id}. Available: {list(MDXNET_MODELS.keys())}")
self.model_id = model_id
self.model_config = MDXNET_MODELS[model_id]
self.model_dir = Path(model_dir) if model_dir else Path('/opt/mdxnet_models')
self.model_path = self.model_dir / self.model_config['path'].split('/')[-1]
self.device = 'cpu' if cpu_separation else 'cuda'
self.output_format = output_format.lower()
self.mp3_bitrate = mp3_bitrate
self.stems = self.model_config['stems']
self.target_stem = self.model_config['target_stem']
self._session = None
def _ensure_model(self):
"""Download model if not present."""
if self.model_path.exists():
return
self.model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import hf_hub_download
import shutil
# Download to HF cache then copy flat into model_dir so model_path is correct
cached = hf_hub_download(
repo_id=self.model_config['repo_id'],
filename=self.model_config['path'],
)
shutil.copy2(cached, str(self.model_path))
def _get_session(self):
"""Get or create ONNX runtime session."""
if self._session is None:
self._ensure_model()
providers = ['CPUExecutionProvider']
if not self.device == 'cpu' and 'CUDAExecutionProvider' in ort.get_available_providers():
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
self._session = ort.InferenceSession(
str(self.model_path),
providers=providers
)
return self._session
def _demix(self, mix: np.ndarray) -> Dict[str, np.ndarray]:
"""Separate audio into stems using MDX-Net."""
session = self._get_session()
input_name = session.get_inputs()[0].name
# Compute STFT
mix_spec = _stft(mix) # (channels, freq, time, 2)
# Convert to batch format
mix_batch, metadata = _spec_to_batch(mix_spec)
# Run inference in chunks
output_batches = []
batch_size = 1 # Process one chunk at a time for memory efficiency
with tqdm(total=len(mix_batch), desc='Separating', unit='chunk', ncols=100) as pbar:
for i in range(0, len(mix_batch), batch_size):
batch = mix_batch[i:i + batch_size]
# ONNX expects (batch, channels, freq, time)
outputs = session.run(None, {input_name: batch.astype(np.float32)})
output_batches.append(outputs[0])
pbar.update(len(batch))
# Concatenate outputs
target_spec = np.concatenate(output_batches, axis=0)
# Convert back to spectrogram format
target_spec = _batch_to_spec(target_spec, metadata)
# Inverse STFT to get audio
target_audio = _istft(target_spec)
# Calculate the other stem (residual)
other_audio = mix - target_audio
# Create output dict based on stems configuration
sources = {}
if self.target_stem == 'vocals':
sources['vocals'] = target_audio
sources['instrumental'] = other_audio
elif self.target_stem == 'instrumental':
sources['instrumental'] = target_audio
sources['vocals'] = other_audio
elif self.target_stem == 'lead':
sources['lead'] = target_audio
sources['backing_instrumental'] = other_audio
else:
sources[self.target_stem] = target_audio
sources['other'] = other_audio
return sources
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""Separate audio and write stems."""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# Load audio
audio = _load_audio(input_path)
# Separate
sources = self._demix(audio)
# Cleanup
if self._session is not None:
del self._session
self._session = None
gc.collect()
# Save outputs
ext = self.output_format
result = {}
for name, data in sources.items():
dest = str(output_dir / f'{name}.{ext}')
_save_audio(dest, data.T, ext, self.mp3_bitrate)
result[name] = dest
return result
+167
View File
@@ -0,0 +1,167 @@
"""
MedleyVox separator - Multi-singer vocal separation
HuggingFace model: Cyru5/MedleyVox
Backup: miercolesv/MVSEP-Central-Backup
"""
import os
import torch
import torchaudio
from pathlib import Path
from typing import Dict, Optional
import numpy as np
from ..config import MEDLEYVOX_MODEL_DIR, CPU_SEPARATION
# Model configurations
MEDLEYVOX_MODELS = {
"medleyvox": {
"model_path": "vocals 100.pth",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "MedleyVox-MultiSinger",
"stems": ["vocals", "instrumental"],
},
"medleyvox_55ep": {
"model_path": "vocals 55 epochs.pth",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "MedleyVox-MultiSinger",
"stems": ["vocals", "instrumental"],
},
"medleyvox_66ep": {
"model_path": "vocals 66.pth",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "MedleyVox-MultiSinger",
"stems": ["vocals", "instrumental"],
},
"medleyvox_88ep": {
"model_path": "vocals 88.pth",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "MedleyVox-MultiSinger",
"stems": ["vocals", "instrumental"],
},
"medleyvox_100ep": {
"model_path": "vocals 100.pth",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "MedleyVox-MultiSinger",
"stems": ["vocals", "instrumental"],
},
}
class MedleyVoxSeparator:
"""
MedleyVox separator for multi-singer vocal separation.
Specialized for separating vocals when multiple singers are present.
"""
def __init__(
self,
model_id: str = "medleyvox",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in MEDLEYVOX_MODELS:
raise ValueError(f"Unknown MedleyVox model: {model_id}")
self.model_id = model_id
self.model_config = MEDLEYVOX_MODELS[model_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self._model = None
self._device = None
def _ensure_model(self):
"""Download model from HuggingFace if not present."""
model_dir = MEDLEYVOX_MODEL_DIR / self.model_id
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / self.model_config["model_path"]
if not model_path.exists():
try:
from huggingface_hub import hf_hub_download
print(f"Downloading MedleyVox model: {self.model_id}")
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['model_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download MedleyVox model: {e}")
return str(model_path)
def _load_model(self):
"""Lazy-load the model."""
if self._model is None:
model_path = self._ensure_model()
# Set device
self._device = "cpu" if self.cpu_separation else ("cuda" if torch.cuda.is_available() else "cpu")
# Load model checkpoint
checkpoint = torch.load(model_path, map_location=self._device)
# MedleyVox uses a custom architecture
# This is a placeholder - actual implementation would need the model class
# For now, we'll use audio-separator as a fallback
self._model = None # Will use audio-separator fallback
return self._model
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate audio into vocals and instrumental.
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# For now, use audio-separator with UVR as fallback
# Full implementation would load the actual MedleyVox model
try:
from audio_separator.separator import Separator
# Use a generic 2-stem model as fallback
sep = Separator(
model_file_dir=str(MEDLEYVOX_MODEL_DIR),
output_dir=str(output_path),
output_format=self.output_format,
output_bitrate=self.mp3_bitrate if self.output_format == "mp3" else None,
cpu_separation=self.cpu_separation,
)
# Use UVR-MDX-NET Inst HQ as fallback
sep.load_model()
result = sep.separate(input_path)
# Map outputs to stem names
stems = self.model_config.get("stems", ["vocals", "instrumental"])
output_paths = {}
if isinstance(result, list):
for i, path in enumerate(result):
if i < len(stems):
stem_name = stems[i]
final_path = output_path / f"{stem_name}.{self.output_format}"
Path(path).rename(final_path)
output_paths[stem_name] = str(final_path)
else:
final_path = output_path / f"vocals.{self.output_format}"
Path(result).rename(final_path)
output_paths["vocals"] = str(final_path)
return output_paths
except ImportError:
raise ImportError(
"audio-separator is required for MedleyVox separation. "
"Install with: pip install audio-separator"
)
+336
View File
@@ -0,0 +1,336 @@
"""
MelBand RoFormer separator — standalone, no Django/Spleeter/TensorFlow dependency.
Audio I/O uses soundfile (WAV/FLAC) + subprocess ffmpeg (MP3 encoding).
Model architecture is from https://github.com/lucidrains/BS-RoFormer
This module patches sys.modules to fix the import path for models.bs_roformer.attend
which the melband files expect but doesn't exist in this project structure.
"""
import gc
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Dict, Optional
import numpy as np
import torch
import torch.nn as nn
import yaml
from omegaconf import OmegaConf
from tqdm import tqdm
# ---------------------------------------------------------------------------
# Import path patching
# The melband files import from models.bs_roformer.attend which doesn't exist
# in this project structure. We patch sys.modules to redirect to our bs_roformer.
# ---------------------------------------------------------------------------
if 'models' not in sys.modules:
sys.modules['models'] = type(sys)('models')
if 'models.bs_roformer' not in sys.modules:
import backend.services.bs_roformer as _bs_roformer
sys.modules['models.bs_roformer'] = _bs_roformer
if 'models.bs_roformer.attend' not in sys.modules:
from backend.services.bs_roformer import attend as _attend
sys.modules['models.bs_roformer.attend'] = _attend
# Import MelBandRoformer from the bs_roformer pip package (lucidrains/BS-RoFormer)
from bs_roformer.mel_band_roformer import MelBandRoformer
# ---------------------------------------------------------------------------
# HuggingFace model coordinates
# ---------------------------------------------------------------------------
HF_REPO_ID = 'fabiankruger/mel-band-roformer-4-stem'
HF_REVISION = 'main'
# ---------------------------------------------------------------------------
# Default model paths (overridable via env var MEL_BAND_MODEL_DIR)
# ---------------------------------------------------------------------------
_MODEL_DIR_ENV = os.environ.get('MEL_BAND_MODEL_DIR', '/opt/mel_band_models')
DEFAULT_MODEL_DIR = Path(_MODEL_DIR_ENV)
DEFAULT_MODEL_PATH = DEFAULT_MODEL_DIR / 'mel_band_roformer_4_stem.ckpt'
DEFAULT_CONFIG_PATH = DEFAULT_MODEL_DIR / 'config.yaml'
SAMPLE_RATE = 44100
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _try_download_model(
model_dir: Path = DEFAULT_MODEL_DIR,
model_path: Path = DEFAULT_MODEL_PATH,
config_path: Path = DEFAULT_CONFIG_PATH,
) -> None:
"""Download MelBand RoFormer model from HuggingFace if not already present."""
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=HF_REPO_ID,
revision=HF_REVISION,
local_dir=str(model_dir),
)
def _load_config(config_path: Path):
"""Load YAML config, supporting !!python/tuple tags."""
with open(config_path, 'r') as f:
config = yaml.load(f, Loader=yaml.UnsafeLoader)
return OmegaConf.create(config)
def _load_audio(path: str) -> np.ndarray:
"""
Load audio file and return as float32 numpy array of shape (channels, samples).
Uses soundfile for WAV/FLAC; falls back to ffmpeg decode for MP3 and other formats.
"""
import soundfile as sf
try:
data, sr = sf.read(path, dtype='float32', always_2d=True)
# soundfile returns (samples, channels); transpose to (channels, samples)
data = data.T
except Exception:
# Fallback: decode via ffmpeg to a temporary WAV
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
subprocess.run(
['ffmpeg', '-y', '-i', path, '-ar', str(SAMPLE_RATE),
'-ac', '2', '-f', 'wav', tmp_path],
check=True, capture_output=True,
)
data, sr = sf.read(tmp_path, dtype='float32', always_2d=True)
data = data.T
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
# Resample if needed
if sr != SAMPLE_RATE:
import librosa
data = np.array([
librosa.resample(ch, orig_sr=sr, target_sr=SAMPLE_RATE)
for ch in data
], dtype=np.float32)
# Ensure stereo
if data.shape[0] == 1:
data = np.vstack([data, data])
return data # (channels, samples)
def _save_audio(path: str, data: np.ndarray, output_format: str, bitrate: str = '256k') -> None:
"""
Save (samples, channels) float32 array as audio file.
WAV and FLAC use soundfile directly; MP3 encodes via ffmpeg.
"""
import soundfile as sf
ext = output_format.lower()
if ext in ('wav', 'flac'):
sf.write(path, data, SAMPLE_RATE, format=ext.upper(),
subtype='PCM_24' if ext == 'wav' else 'PCM_16')
else:
# Encode to MP3 via ffmpeg
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
sf.write(tmp_path, data, SAMPLE_RATE, format='WAV', subtype='PCM_16')
subprocess.run(
['ffmpeg', '-y', '-i', tmp_path,
'-b:a', bitrate, path],
check=True, capture_output=True,
)
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
# ---------------------------------------------------------------------------
# Separator class
# ---------------------------------------------------------------------------
class MelBandRoformerSeparator:
"""
Performs source separation using the MelBand RoFormer model.
Pure PyTorch — no TensorFlow / Spleeter dependency.
"""
# MelBand RoFormer outputs 4 stems by default
DEFAULT_STEMS = ['vocals', 'drums', 'bass', 'other']
def __init__(
self,
model_path: Optional[str] = None,
config_path: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3', # 'mp3' | 'flac' | 'wav'
mp3_bitrate: str = '256k',
):
self.model_path = Path(model_path) if model_path else DEFAULT_MODEL_PATH
self.config_path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH
self.device = 'cpu' if cpu_separation else 'cuda'
self.output_format = output_format.lower()
self.mp3_bitrate = mp3_bitrate
self._config = None
# ------------------------------------------------------------------
# Model loading
# ------------------------------------------------------------------
def _ensure_model(self):
_try_download_model(DEFAULT_MODEL_DIR, self.model_path, self.config_path)
def _load_config(self):
if self._config is None:
self._config = _load_config(self.config_path)
return self._config
def get_model(self) -> MelBandRoformer:
self._ensure_model()
config = self._load_config()
model_cfg = OmegaConf.to_container(config.model, resolve=True)
# OmegaConf loads tuples as lists; the model requires tuples for certain fields
if 'freqs_per_bands' in model_cfg and isinstance(model_cfg['freqs_per_bands'], list):
model_cfg['freqs_per_bands'] = tuple(model_cfg['freqs_per_bands'])
if 'multi_stft_resolutions_window_sizes' in model_cfg and isinstance(model_cfg['multi_stft_resolutions_window_sizes'], list):
model_cfg['multi_stft_resolutions_window_sizes'] = tuple(model_cfg['multi_stft_resolutions_window_sizes'])
model = MelBandRoformer(**model_cfg)
checkpoint = torch.load(str(self.model_path), map_location='cpu', weights_only=False)
# Handle different checkpoint formats
if 'state_dict' in checkpoint:
state_dict = checkpoint['state_dict']
elif 'model' in checkpoint:
state_dict = checkpoint['model']
else:
state_dict = checkpoint
model.load_state_dict(state_dict)
model.to(self.device).eval()
return model
# ------------------------------------------------------------------
# Inference
# ------------------------------------------------------------------
def _demix(self, mix: np.ndarray, model: MelBandRoformer,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, np.ndarray]:
"""Separate (channels, samples) array into a dict of stem arrays."""
config = self._load_config()
hop_length = config.model.stft_hop_length
segment_size = getattr(config.inference, 'dim_t', 2000)
C = hop_length * (segment_size - 1)
N = num_overlap_override if num_overlap_override is not None else getattr(config.inference, 'num_overlap', 4)
step = int(C // N)
fade_size = C // 10
batch_size = batch_size_override if batch_size_override is not None else getattr(config.inference, 'batch_size', 1)
device = self.device
mix_t = torch.tensor(mix, dtype=torch.float32)
length_init = mix_t.shape[-1]
if length_init > 2 * (C - step) and (C - step > 0):
mix_t = nn.functional.pad(mix_t, (C - step, C - step), mode='reflect')
fadein = torch.linspace(0, 1, fade_size).to(device)
fadeout = torch.linspace(1, 0, fade_size).to(device)
window_start = torch.ones(C).to(device)
window_start[-fade_size:] *= fadeout
window_finish = torch.ones(C).to(device)
window_finish[:fade_size] *= fadein
window_middle = torch.ones(C).to(device)
window_middle[:fade_size] *= fadein
window_middle[-fade_size:] *= fadeout
# Get stems from config or use default
stems = getattr(config.training, 'instruments', self.DEFAULT_STEMS)
num_stems = len(stems)
req_shape = (num_stems,) + tuple(mix_t.shape)
with torch.inference_mode():
result = torch.zeros(req_shape, dtype=torch.float32, device=device)
counter = torch.zeros(req_shape, dtype=torch.float32, device=device)
batch_data, batch_locs = [], []
i = 0
# Count total segments for tqdm
total_seg = sum(1 for _ in range(0, mix_t.shape[1], step))
with tqdm(total=total_seg, desc='Separating', unit='segment', ncols=100) as pbar:
while i < mix_t.shape[1]:
part = mix_t[:, i:i + C].to(device)
l = part.shape[-1]
if l < C:
part = nn.functional.pad(
part,
(0, C - l) if l > C // 2 + 1 else (0, C - l, 0, 0),
mode='reflect' if l > C // 2 + 1 else 'constant',
)
batch_data.append(part)
batch_locs.append((i, l))
i += step
if len(batch_data) >= batch_size or i >= mix_t.shape[1]:
arr = torch.stack(batch_data, dim=0)
x = model(arr)
for j, (start, ln) in enumerate(batch_locs):
window = (window_start if start == 0
else window_finish if i >= mix_t.shape[1]
else window_middle)
result[..., start:start + ln] += x[j][..., :ln] * window[..., :ln]
counter[..., start:start + ln] += window[..., :ln]
pbar.update(len(batch_data))
batch_data, batch_locs = [], []
estimated = result / counter.clamp(min=1e-10)
if length_init > 2 * (C - step) and (C - step > 0):
estimated = estimated[..., (C - step):-(C - step)]
sources = {}
for idx, name in enumerate(stems):
sources[name] = estimated[idx].cpu().numpy()
return sources
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def separate_into_parts(self, input_path: str, output_dir: str,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, str]:
"""
Separate audio at input_path and write one file per stem into output_dir.
Returns {stem_name: output_file_path}.
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
audio = _load_audio(input_path) # (channels, samples)
model = self.get_model()
sources = self._demix(audio, model,
batch_size_override=batch_size_override,
num_overlap_override=num_overlap_override)
del model
torch.cuda.empty_cache()
gc.collect()
ext = self.output_format
result = {}
for name, data in sources.items():
dest = str(output_dir / f'{name}.{ext}')
_save_audio(dest, data.T, ext, self.mp3_bitrate) # T: (channels,samples)→(samples,channels)
result[name] = dest
return result
@@ -0,0 +1,669 @@
"""
Specialized MelBand RoFormer separators for specific use cases:
- Vocals/Instrumental separation (2-stem)
- Dereverb (dry vocals vs reverb)
- Karaoke (lead vocals vs backing+instrumental)
Uses sys.modules patching for import path fixes.
"""
import gc
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Dict, Optional, List
import numpy as np
import torch
import torch.nn as nn
import yaml
from omegaconf import OmegaConf
from tqdm import tqdm
# ---------------------------------------------------------------------------
# Import path patching
# ---------------------------------------------------------------------------
if 'models' not in sys.modules:
sys.modules['models'] = type(sys)('models')
if 'models.bs_roformer' not in sys.modules:
import backend.services.bs_roformer as _bs_roformer
sys.modules['models.bs_roformer'] = _bs_roformer
if 'models.bs_roformer.attend' not in sys.modules:
from backend.services.bs_roformer import attend as _attend
sys.modules['models.bs_roformer.attend'] = _attend
from bs_roformer.mel_band_roformer import MelBandRoformer
SAMPLE_RATE = 44100
def _load_audio(path: str) -> np.ndarray:
"""Load audio as (channels, samples) float32 array."""
import soundfile as sf
try:
data, sr = sf.read(path, dtype='float32', always_2d=True)
data = data.T
except Exception:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
subprocess.run(
['ffmpeg', '-y', '-i', path, '-ar', str(SAMPLE_RATE),
'-ac', '2', '-f', 'wav', tmp_path],
check=True, capture_output=True,
)
data, sr = sf.read(tmp_path, dtype='float32', always_2d=True)
data = data.T
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
if sr != SAMPLE_RATE:
import librosa
data = np.array([
librosa.resample(ch, orig_sr=sr, target_sr=SAMPLE_RATE)
for ch in data
], dtype=np.float32)
if data.shape[0] == 1:
data = np.vstack([data, data])
return data
def _save_audio(path: str, data: np.ndarray, output_format: str, bitrate: str = '256k') -> None:
"""Save (samples, channels) array to audio file."""
import soundfile as sf
ext = output_format.lower()
if ext in ('wav', 'flac'):
sf.write(path, data, SAMPLE_RATE, format=ext.upper(),
subtype='PCM_24' if ext == 'wav' else 'PCM_16')
else:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
try:
sf.write(tmp_path, data, SAMPLE_RATE, format='WAV', subtype='PCM_16')
subprocess.run(
['ffmpeg', '-y', '-i', tmp_path, '-b:a', bitrate, path],
check=True, capture_output=True,
)
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
class MelBandSeparatorBase:
"""Base class for MelBand RoFormer separators."""
def __init__(
self,
model_path: Path,
config_path: Path,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
stems: List[str] = None,
):
self.model_path = model_path
self.config_path = config_path
self.device = 'cpu' if cpu_separation else 'cuda'
self.output_format = output_format.lower()
self.mp3_bitrate = mp3_bitrate
self.stems = stems or ['vocals', 'instrumental']
self._config = None
def _load_config(self):
if self._config is None:
with open(self.config_path, 'r') as f:
config = yaml.load(f, Loader=yaml.UnsafeLoader)
self._config = OmegaConf.create(config)
return self._config
def get_model(self) -> MelBandRoformer:
config = self._load_config()
model_cfg = OmegaConf.to_container(config.model, resolve=True)
# Convert lists to tuples where needed
if 'freqs_per_bands' in model_cfg and isinstance(model_cfg['freqs_per_bands'], list):
model_cfg['freqs_per_bands'] = tuple(model_cfg['freqs_per_bands'])
if 'multi_stft_resolutions_window_sizes' in model_cfg and isinstance(model_cfg['multi_stft_resolutions_window_sizes'], list):
model_cfg['multi_stft_resolutions_window_sizes'] = tuple(model_cfg['multi_stft_resolutions_window_sizes'])
model = MelBandRoformer(**model_cfg)
checkpoint = torch.load(str(self.model_path), map_location='cpu', weights_only=False)
if 'state_dict' in checkpoint:
state_dict = checkpoint['state_dict']
elif 'model' in checkpoint:
state_dict = checkpoint['model']
else:
state_dict = checkpoint
model.load_state_dict(state_dict)
model.to(self.device).eval()
return model
def _demix(self, mix: np.ndarray, model: MelBandRoformer,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, np.ndarray]:
"""Separate audio into stems."""
config = self._load_config()
hop_length = config.model.stft_hop_length
segment_size = getattr(config.inference, 'dim_t', 2000)
C = hop_length * (segment_size - 1)
N = num_overlap_override if num_overlap_override is not None else getattr(config.inference, 'num_overlap', 4)
step = int(C // N)
fade_size = C // 10
batch_size = batch_size_override if batch_size_override is not None else getattr(config.inference, 'batch_size', 1)
device = self.device
mix_t = torch.tensor(mix, dtype=torch.float32)
length_init = mix_t.shape[-1]
if length_init > 2 * (C - step) and (C - step > 0):
mix_t = nn.functional.pad(mix_t, (C - step, C - step), mode='reflect')
fadein = torch.linspace(0, 1, fade_size).to(device)
fadeout = torch.linspace(1, 0, fade_size).to(device)
window_start = torch.ones(C).to(device)
window_start[-fade_size:] *= fadeout
window_finish = torch.ones(C).to(device)
window_finish[:fade_size] *= fadein
window_middle = torch.ones(C).to(device)
window_middle[:fade_size] *= fadein
window_middle[-fade_size:] *= fadeout
num_stems = len(self.stems)
req_shape = (num_stems,) + tuple(mix_t.shape)
with torch.inference_mode():
result = torch.zeros(req_shape, dtype=torch.float32, device=device)
counter = torch.zeros(req_shape, dtype=torch.float32, device=device)
batch_data, batch_locs = [], []
i = 0
total_seg = sum(1 for _ in range(0, mix_t.shape[1], step))
with tqdm(total=total_seg, desc='Separating', unit='segment', ncols=100) as pbar:
while i < mix_t.shape[1]:
part = mix_t[:, i:i + C].to(device)
l = part.shape[-1]
if l < C:
part = nn.functional.pad(
part,
(0, C - l) if l > C // 2 + 1 else (0, C - l, 0, 0),
mode='reflect' if l > C // 2 + 1 else 'constant',
)
batch_data.append(part)
batch_locs.append((i, l))
i += step
if len(batch_data) >= batch_size or i >= mix_t.shape[1]:
arr = torch.stack(batch_data, dim=0)
x = model(arr)
for j, (start, ln) in enumerate(batch_locs):
window = (window_start if start == 0
else window_finish if i >= mix_t.shape[1]
else window_middle)
result[..., start:start + ln] += x[j][..., :ln] * window[..., :ln]
counter[..., start:start + ln] += window[..., :ln]
pbar.update(len(batch_data))
batch_data, batch_locs = [], []
estimated = result / counter.clamp(min=1e-10)
if length_init > 2 * (C - step) and (C - step > 0):
estimated = estimated[..., (C - step):-(C - step)]
sources = {}
for idx, name in enumerate(self.stems):
sources[name] = estimated[idx].cpu().numpy()
return sources
def separate_into_parts(self, input_path: str, output_dir: str,
batch_size_override: Optional[int] = None,
num_overlap_override: Optional[int] = None) -> Dict[str, str]:
"""Separate audio and write stems to output_dir."""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
audio = _load_audio(input_path)
model = self.get_model()
sources = self._demix(audio, model,
batch_size_override=batch_size_override,
num_overlap_override=num_overlap_override)
del model
torch.cuda.empty_cache()
gc.collect()
ext = self.output_format
result = {}
for name, data in sources.items():
dest = str(output_dir / f'{name}.{ext}')
_save_audio(dest, data.T, ext, self.mp3_bitrate)
result[name] = dest
return result
class MelBandVocalsSeparator(MelBandSeparatorBase):
"""MelBand RoFormer optimized for vocals/instrumental separation."""
HF_REPO_ID = 'becruily/mel-band-roformer-vocals'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/vocals')
model_path = model_dir / 'model.ckpt'
config_path = model_dir / 'config.yaml'
# Ensure model is downloaded
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['vocals', 'instrumental'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=self.HF_REPO_ID,
revision=self.HF_REVISION,
local_dir=str(model_dir),
)
class MelBandDereverbSeparator(MelBandSeparatorBase):
"""MelBand RoFormer for dereverb - separates dry vocals from reverb."""
HF_REPO_ID = 'anvuew/dereverb_mel_band_roformer'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
use_less_aggressive: bool = False,
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/dereverb')
# The dereverb repo has multiple checkpoints
if use_less_aggressive:
model_path = model_dir / 'dereverb_mel_band_roformer_less_aggressive_anvuew_sdr_18.8050.ckpt'
else:
model_path = model_dir / 'dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt'
config_path = model_dir / 'config.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['dry_vocals', 'reverb'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=self.HF_REPO_ID,
revision=self.HF_REVISION,
local_dir=str(model_dir),
)
class MelBandKaraokeSeparator(MelBandSeparatorBase):
"""MelBand RoFormer for karaoke - separates lead vocals from backing+instrumental."""
HF_REPO_ID = 'becruily/mel-band-roformer-karaoke'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/karaoke')
model_path = model_dir / 'model.ckpt'
config_path = model_dir / 'config.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['lead', 'backing_instrumental'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=self.HF_REPO_ID,
revision=self.HF_REVISION,
local_dir=str(model_dir),
)
class MelBandDereverbRoomSeparator(MelBandSeparatorBase):
"""MelBand RoFormer for room dereverb from MVSEP-Central-Backup."""
HF_REPO_ID = 'miercolesv/MVSEP-Central-Backup'
HF_SUBFOLDER = 'Dereverb-Room-Anvuew'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/dereverb_room')
model_path = model_dir / 'dereverb_room_anvuew_sdr_13.7432.ckpt'
config_path = model_dir / 'dereverb_room_anvuew.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['dry_vocals', 'room_reverb'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
try:
from huggingface_hub import hf_hub_download
if not model_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/dereverb_room_anvuew_sdr_13.7432.ckpt",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/dereverb_room_anvuew.yaml",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Room Dereverb model: {e}")
class MelBandDereverbAnvuewSeparator(MelBandSeparatorBase):
"""MelBand RoFormer Anvuew dereverb from MVSEP-Central-Backup."""
HF_REPO_ID = 'miercolesv/MVSEP-Central-Backup'
HF_SUBFOLDER = 'Dereverb-MelBand-Anvuew'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
use_less_aggressive: bool = False,
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/dereverb_anvuew')
if use_less_aggressive:
model_path = model_dir / 'dereverb_mel_band_roformer_less_aggressive_anvuew_sdr_18.8050.ckpt'
else:
model_path = model_dir / 'dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt'
config_path = model_dir / 'dereverb_mel_band_roformer_anvuew.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['dry_vocals', 'reverb'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
try:
from huggingface_hub import hf_hub_download
# Download the specific model variant
model_filename = model_path.name
if not model_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/{model_filename}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
# Download config
if not config_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/dereverb_mel_band_roformer_anvuew.yaml",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Anvuew Dereverb model: {e}")
class MelBandVocalsAnvuewSeparator(MelBandSeparatorBase):
"""MelBand RoFormer Anvuew vocals from MVSEP-Central-Backup."""
HF_REPO_ID = 'miercolesv/MVSEP-Central-Backup'
HF_SUBFOLDER = 'BS-RoFormer-Anvuew'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/vocals_anvuew')
model_path = model_dir / 'bs_roformer_anvuew_sdr_12.45.ckpt'
config_path = model_dir / 'config.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['vocals', 'instrumental'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
try:
from huggingface_hub import hf_hub_download
if not model_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/bs_roformer_anvuew_sdr_12.45.ckpt",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/config.yaml",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Anvuew Vocals model: {e}")
class MelBandKaraokeGaboxSeparator(MelBandSeparatorBase):
"""MelBand RoFormer Karaoke Gabox from MVSEP-Central-Backup."""
HF_REPO_ID = 'miercolesv/MVSEP-Central-Backup'
HF_SUBFOLDER = 'MelBandRoformers/bsroformers'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/karaoke_gabox')
model_path = model_dir / 'bs_karaoke_gabox_IS.ckpt'
config_path = model_dir / 'karaoke_bs_roformer.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['vocals', 'karaoke'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
try:
from huggingface_hub import hf_hub_download
if not model_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/bs_karaoke_gabox_IS.ckpt",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/karaoke_bs_roformer.yaml",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Karaoke Gabox model: {e}")
class MelBandDeuxBecruilySeparator(MelBandSeparatorBase):
"""MelBand RoFormer Deux Becruily - specialized 2-stem vocals model."""
HF_REPO_ID = 'miercolesv/MVSEP-Central-Backup'
HF_SUBFOLDER = 'MelBand-Roformer-Deux-Becruily'
HF_REVISION = 'main'
def __init__(
self,
model_dir: Optional[str] = None,
cpu_separation: bool = True,
output_format: str = 'mp3',
mp3_bitrate: str = '256k',
):
model_dir = Path(model_dir) if model_dir else Path('/opt/mel_band_models/deux_becruily')
model_path = model_dir / 'becruily_deux.ckpt'
config_path = model_dir / 'config_deux_becruily.yaml'
self._ensure_model(model_dir, model_path, config_path)
super().__init__(
model_path=model_path,
config_path=config_path,
cpu_separation=cpu_separation,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stems=['vocals', 'instrumental'],
)
def _ensure_model(self, model_dir: Path, model_path: Path, config_path: Path):
if model_path.exists() and config_path.exists():
return
model_dir.mkdir(parents=True, exist_ok=True)
try:
from huggingface_hub import hf_hub_download
print(f"Downloading Deux Becruily model from {self.HF_REPO_ID}")
# Download model
if not model_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/becruily_deux.ckpt",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
# Download config
if not config_path.exists():
hf_hub_download(
repo_id=self.HF_REPO_ID,
filename=f"{self.HF_SUBFOLDER}/config_deux_becruily.yaml",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Deux Becruily model: {e}")
+557
View File
@@ -0,0 +1,557 @@
"""
Audio metadata (ID3 / Vorbis / EXIF) utilities for reading and writing tags.
Uses mutagen for format-agnostic read/write.
"""
from pathlib import Path
from typing import Optional, List, Dict, Tuple
import re
def _read_cover_art(source_path: str):
"""
Read cover art from an audio file.
Returns (data_bytes, mime_type) or (None, None) if not found.
"""
try:
ext = Path(source_path).suffix.lower()
if ext == '.mp3':
from mutagen.id3 import ID3, ID3NoHeaderError
try:
tags = ID3(source_path)
apic_keys = [k for k in tags.keys() if k.startswith('APIC')]
if apic_keys:
apic = tags[apic_keys[0]]
return apic.data, apic.mime
except ID3NoHeaderError:
pass
elif ext == '.flac':
from mutagen.flac import FLAC
audio = FLAC(source_path)
if audio.pictures:
pic = audio.pictures[0]
return pic.data, pic.mime
elif ext == '.wav':
from mutagen.wave import WAVE
try:
audio = WAVE(source_path)
if audio.tags:
apic_keys = [k for k in audio.tags.keys() if k.startswith('APIC')]
if apic_keys:
apic = audio.tags[apic_keys[0]]
return apic.data, apic.mime
except Exception:
pass
except Exception:
pass
return None, None
def copy_metadata(source_path: str, dest_path: str, stem_label: Optional[str] = None,
copy_lyrics: bool = True) -> None:
"""
Copy all common tags (title, artist, album, track, date, genre, cover art, lyrics)
from source_path to dest_path. Optionally appends stem_label to the title.
Silently ignores unsupported formats — metadata is cosmetic, never fatal.
"""
try:
import mutagen
src = mutagen.File(source_path, easy=True)
if src is None:
return
title = src.get("title", [""])[0] if src.get("title") else ""
artist = src.get("artist", [""])[0] if src.get("artist") else ""
album = src.get("album", [""])[0] if src.get("album") else ""
tracknumber = src.get("tracknumber", [""])[0] if src.get("tracknumber") else ""
date = src.get("date", [""])[0] if src.get("date") else ""
genre = src.get("genre", [""])[0] if src.get("genre") else ""
if stem_label and title:
title = f"{title} ({stem_label})"
elif stem_label:
title = stem_label
cover_data, cover_mime = _read_cover_art(source_path)
# Read lyrics from source
lyrics = ""
if copy_lyrics:
lyrics = _read_lyrics_from_file(source_path)
ext = Path(dest_path).suffix.lower()
if ext == ".mp3":
_write_mp3_tags(dest_path, title, artist, album, tracknumber, date, genre,
cover_data, cover_mime, lyrics)
elif ext == ".flac":
_write_flac_tags(dest_path, title, artist, album, tracknumber, date, genre,
cover_data, cover_mime, lyrics)
elif ext == ".wav":
_write_wav_tags(dest_path, title, artist, album, tracknumber, date, genre,
cover_data, cover_mime)
except Exception:
pass # Never fail over metadata — it's cosmetic
def _read_lyrics_from_file(path: str) -> str:
"""Read lyrics from a file using the same logic as read_metadata."""
try:
ext = Path(path).suffix.lower()
if ext == '.mp3':
return _read_mp3_lyrics(path)
elif ext in ('.flac', '.ogg', '.opus'):
return _read_vorbis_lyrics(path)
except Exception:
pass
return ''
def _write_mp3_tags(path, title, artist, album, tracknumber, date, genre,
cover_data=None, cover_mime=None, lyrics=None):
from mutagen.id3 import ID3, ID3NoHeaderError, TIT2, TPE1, TALB, TRCK, TDRC, TCON, APIC, USLT
try:
tags = ID3(path)
except ID3NoHeaderError:
tags = ID3()
if title: tags["TIT2"] = TIT2(encoding=3, text=title)
if artist: tags["TPE1"] = TPE1(encoding=3, text=artist)
if album: tags["TALB"] = TALB(encoding=3, text=album)
if tracknumber: tags["TRCK"] = TRCK(encoding=3, text=tracknumber)
if date: tags["TDRC"] = TDRC(encoding=3, text=date)
if genre: tags["TCON"] = TCON(encoding=3, text=genre)
if lyrics: tags["USLT::'eng'"] = USLT(encoding=3, lang='eng', desc='', text=lyrics)
if cover_data:
tags["APIC:"] = APIC(
encoding=3, mime=cover_mime or "image/jpeg",
type=3, desc="Cover", data=cover_data,
)
tags.save(path)
def _write_flac_tags(path, title, artist, album, tracknumber, date, genre,
cover_data=None, cover_mime=None, lyrics=None):
from mutagen.flac import FLAC, Picture
audio = FLAC(path)
if title: audio["title"] = title
if artist: audio["artist"] = artist
if album: audio["album"] = album
if tracknumber: audio["tracknumber"] = tracknumber
if date: audio["date"] = date
if genre: audio["genre"] = genre
if lyrics: audio["lyrics"] = lyrics
if cover_data:
pic = Picture()
pic.type = 3 # front cover
pic.mime = cover_mime or "image/jpeg"
pic.desc = "Cover"
pic.data = cover_data
audio.clear_pictures()
audio.add_picture(pic)
audio.save()
def _write_wav_tags(path, title, artist, album, tracknumber, date, genre,
cover_data=None, cover_mime=None):
from mutagen.wave import WAVE
from mutagen.id3 import TIT2, TPE1, TALB, TRCK, TDRC, TCON, APIC
try:
audio = WAVE(path)
if audio.tags is None:
audio.add_tags()
if title: audio.tags["TIT2"] = TIT2(encoding=3, text=title)
if artist: audio.tags["TPE1"] = TPE1(encoding=3, text=artist)
if album: audio.tags["TALB"] = TALB(encoding=3, text=album)
if tracknumber: audio.tags["TRCK"] = TRCK(encoding=3, text=tracknumber)
if date: audio.tags["TDRC"] = TDRC(encoding=3, text=date)
if genre: audio.tags["TCON"] = TCON(encoding=3, text=genre)
if cover_data:
audio.tags["APIC:"] = APIC(
encoding=3, mime=cover_mime or "image/jpeg",
type=3, desc="Cover", data=cover_data,
)
audio.save()
except Exception:
pass
# ---------------------------------------------------------------------------
# Metadata reading
# ---------------------------------------------------------------------------
def read_metadata(source_path: str) -> dict:
"""
Read basic metadata from an audio file.
Returns dict with 'artist', 'title', 'album', 'lyrics' keys (all str).
Lyrics are read in order of priority:
1. Synced lyrics tags (SYLT for MP3, syncedlyrics for FLAC/OGG)
2. Unsynced lyrics tags (USLT for MP3, lyrics/unsyncedlyrics for FLAC/OGG)
3. External .lrc file with same base name
Silently returns empty strings on failure or unsupported format.
"""
result = {'artist': '', 'title': '', 'album': '', 'lyrics': ''}
try:
import mutagen
src = mutagen.File(source_path, easy=True)
if src is None:
return result
result['artist'] = (src.get('artist') or [''])[0]
result['title'] = (src.get('title') or [''])[0]
result['album'] = (src.get('album') or [''])[0]
ext = Path(source_path).suffix.lower()
lyrics = ''
# Try to read lyrics from tags first
if ext == '.mp3':
lyrics = _read_mp3_lyrics(source_path)
elif ext in ('.flac', '.ogg', '.opus'):
lyrics = _read_vorbis_lyrics(source_path)
# If no lyrics in tags, try external LRC file
if not lyrics:
lyrics = read_lrc_file(source_path)
result['lyrics'] = lyrics
except Exception:
pass
return result
def _read_mp3_lyrics(path: str) -> str:
"""Read lyrics from ID3 tags: SYLT (synced) → USLT (unsynced) → TXXX:LYRICS.
Also checks $-prefixed variants used by some tagging software.
"""
try:
from mutagen.id3 import ID3, ID3NoHeaderError
try:
tags = ID3(path)
except ID3NoHeaderError:
return ''
# Synced lyrics: SYLT contains list of (text, time_ms) tuples
sylt_keys = [k for k in tags.keys() if k.startswith('SYLT')]
if sylt_keys:
return '\n'.join(t for t, _ in tags[sylt_keys[0]].text)
# Unsynced lyrics
uslt_keys = [k for k in tags.keys() if k.startswith('USLT')]
if uslt_keys:
return tags[uslt_keys[0]].text
# TXXX:LYRICS fallback (also check $-prefixed variants)
for txxx_key in ('TXXX:LYRICS', 'TXXX:$LYRICS',
'TXXX:SYNCEDLYRICS', 'TXXX:$SYNCEDLYRICS',
'TXXX:UNSYNCEDLYRICS', 'TXXX:$UNSYNCEDLYRICS'):
if txxx_key in tags:
text = tags[txxx_key].text
if text:
return text[0] if isinstance(text, list) else str(text)
except Exception:
pass
return ''
def _read_vorbis_lyrics(path: str) -> str:
"""Read lyrics from FLAC/OGG Vorbis comment tags.
Checks SYNCEDLYRICS, LYRICS, and UNSYNCEDLYRICS (case-insensitive).
Also checks variants with $ prefix (e.g., $LYRICS) used by some tagging software.
Returns the first non-empty value found, or empty string if all are empty.
"""
try:
import mutagen
f = mutagen.File(path)
if f is None:
return ''
# Build case-insensitive lookup: upper() -> original key
key_map = {k.upper(): k for k in f.keys()}
# Check in priority order: SYNCEDLYRICS -> LYRICS -> UNSYNCEDLYRICS
# Also check $-prefixed variants as fallback
for key in ('SYNCEDLYRICS', '$SYNCEDLYRICS',
'LYRICS', '$LYRICS',
'UNSYNCEDLYRICS', '$UNSYNCEDLYRICS'):
if key in key_map:
val = f.get(key_map[key])
if val:
return val[0]
except Exception:
pass
return ''
# ---------------------------------------------------------------------------
# LRC file utilities
# ---------------------------------------------------------------------------
LRC_LINE_REGEX = re.compile(
r'^(\[\s*(\d+):(\d{1,2})(?:\.(\d{1,3}))?\s*\])' # timestamp [mm:ss.xx]
r'\s*(.*?)$', # lyrics text
re.MULTILINE
)
ELRC_WORD_REGEX = re.compile(
r'(<\s*(\d+):(\d{1,2})(?:\.(\d{1,3}))?\s*>)' # word timestamp <mm:ss.xx>
r'\s*([^<\n]+)', # word text
re.MULTILINE
)
def read_lrc_file(audio_path: str) -> str:
"""
Read lyrics from an external .lrc file with the same base name as the audio file.
Returns the raw LRC content or empty string if not found.
"""
audio_path = Path(audio_path)
lrc_path = audio_path.with_suffix('.lrc')
if not lrc_path.exists():
# Try case-insensitive search (covers both .lrc and .LRC on Linux)
for pattern in ('*.lrc', '*.LRC'):
for f in audio_path.parent.glob(pattern):
if f.stem.lower() == audio_path.stem.lower():
lrc_path = f
break
if lrc_path.exists():
break
if lrc_path.exists():
try:
return lrc_path.read_text(encoding='utf-8', errors='ignore')
except Exception:
pass
return ''
def parse_lrc(lrc_content: str) -> List[Tuple[float, str]]:
"""
Parse LRC content into list of (timestamp_seconds, line_text) tuples.
Args:
lrc_content: Raw LRC file content
Returns:
List of (timestamp, line) tuples sorted by timestamp
"""
lines = []
for match in LRC_LINE_REGEX.finditer(lrc_content):
minutes = int(match.group(2))
seconds = int(match.group(3))
millis = match.group(4)
text = match.group(5).strip()
if millis:
# Handle different millisecond precisions
millis = int(millis.ljust(3, '0')[:3])
else:
millis = 0
timestamp = minutes * 60 + seconds + millis / 1000.0
if text:
lines.append((timestamp, text))
# Sort by timestamp and remove duplicates
lines.sort(key=lambda x: x[0])
# Remove duplicate timestamps (keep first occurrence)
seen = set()
unique_lines = []
for ts, text in lines:
if ts not in seen:
seen.add(ts)
unique_lines.append((ts, text))
return unique_lines
def parse_elrc(elrc_content: str) -> List[Tuple[float, str, List[Tuple[float, str]]]]:
"""
Parse Enhanced LRC (ELRC) content with word-level timestamps.
Args:
elrc_content: Raw ELRC file content
Returns:
List of (line_timestamp, line_text, [(word_timestamp, word), ...]) tuples
"""
lines = []
for match in LRC_LINE_REGEX.finditer(elrc_content):
minutes = int(match.group(2))
seconds = int(match.group(3))
millis = match.group(4)
full_line = match.group(5)
if millis:
millis = int(millis.ljust(3, '0')[:3])
else:
millis = 0
line_timestamp = minutes * 60 + seconds + millis / 1000.0
# Parse word-level timestamps within this line
words = []
for word_match in ELRC_WORD_REGEX.finditer(full_line):
w_minutes = int(word_match.group(2))
w_seconds = int(word_match.group(3))
w_millis = word_match.group(4)
w_text = word_match.group(5).strip()
if w_millis:
w_millis = int(w_millis.ljust(3, '0')[:3])
else:
w_millis = 0
word_timestamp = w_minutes * 60 + w_seconds + w_millis / 1000.0
if w_text:
words.append((word_timestamp, w_text))
# Clean line text (remove word timestamps)
line_text = ELRC_WORD_REGEX.sub(r'\5', full_line).strip()
if line_text or words:
lines.append((line_timestamp, line_text, words))
lines.sort(key=lambda x: x[0])
return lines
def format_lrc(lines: List[Tuple[float, str]], include_empty: bool = False) -> str:
"""
Format lines back into LRC format.
Args:
lines: List of (timestamp_seconds, line_text) tuples
include_empty: Whether to include empty lines
Returns:
LRC formatted string
"""
result = []
for timestamp, text in lines:
if not text and not include_empty:
continue
minutes = int(timestamp // 60)
seconds = int(timestamp % 60)
millis = int((timestamp % 1) * 100)
result.append(f"[{minutes:02d}:{seconds:02d}.{millis:02d}]{text}")
return '\n'.join(result)
def format_elrc(lines: List[Tuple[float, str, List[Tuple[float, str]]]]) -> str:
"""
Format lines with word-level timestamps into ELRC format.
Args:
lines: List of (line_timestamp, line_text, [(word_timestamp, word), ...]) tuples
Returns:
ELRC formatted string
"""
result = []
for line_ts, line_text, words in lines:
minutes = int(line_ts // 60)
seconds = int(line_ts % 60)
millis = int((line_ts % 1) * 100)
if words:
# Build line with word timestamps
word_parts = []
for word_ts, word in words:
w_min = int(word_ts // 60)
w_sec = int(word_ts % 60)
w_mil = int((word_ts % 1) * 100)
word_parts.append(f"<{w_min:02d}:{w_sec:02d}.{w_mil:02d}>{word}")
line_content = ' '.join(word_parts)
else:
line_content = line_text
result.append(f"[{minutes:02d}:{seconds:02d}.{millis:02d}]{line_content}")
return '\n'.join(result)
def lyrics_to_plaintext(lyrics: str) -> str:
"""
Convert LRC/ELRC content to plain text (remove all timestamps).
Args:
lyrics: LRC formatted content
Returns:
Plain text lyrics
"""
# Remove line timestamps [mm:ss.xx]
text = re.sub(r'\[\s*\d+:\d{2}(?:\.\d{1,3})?\s*\]', '', lyrics)
# Remove word timestamps <mm:ss.xx>
text = re.sub(r'<\s*\d+:\d{2}(?:\.\d{1,3})?\s*>', '', text)
# Clean up whitespace
lines = [line.strip() for line in text.split('\n') if line.strip()]
return '\n'.join(lines)
def is_lrc_synced(lyrics: str) -> bool:
"""
Check if lyrics content contains LRC timestamps (synced lyrics).
Args:
lyrics: Lyrics content to check
Returns:
True if content contains LRC timestamps
"""
return bool(LRC_LINE_REGEX.search(lyrics))
def extract_lyrics_from_file(file_path: str) -> Dict[str, str]:
"""
Extract lyrics from an audio file or LRC file.
Args:
file_path: Path to audio file or LRC file
Returns:
Dict with 'source', 'raw', 'synced', 'plain' keys
- source: 'tag', 'lrc_file', or 'none'
- raw: Original lyrics content with timestamps if present
- synced: True if lyrics are timestamped
- plain: Plain text version without timestamps
"""
path = Path(file_path)
result = {'source': 'none', 'raw': '', 'synced': False, 'plain': ''}
# If it's an LRC file, read it directly
if path.suffix.lower() == '.lrc':
try:
content = path.read_text(encoding='utf-8', errors='ignore')
result['source'] = 'lrc_file'
result['raw'] = content
result['synced'] = is_lrc_synced(content)
result['plain'] = lyrics_to_plaintext(content)
except Exception:
pass
return result
# Otherwise, try to read from audio file metadata
metadata = read_metadata(file_path)
lyrics = metadata.get('lyrics', '')
if lyrics:
result['source'] = 'tag'
result['raw'] = lyrics
result['synced'] = is_lrc_synced(lyrics)
result['plain'] = lyrics_to_plaintext(lyrics)
else:
# Try external LRC file as last resort
lrc_content = read_lrc_file(file_path)
if lrc_content:
result['source'] = 'lrc_file'
result['raw'] = lrc_content
result['synced'] = is_lrc_synced(lrc_content)
result['plain'] = lyrics_to_plaintext(lrc_content)
return result
+56
View File
@@ -0,0 +1,56 @@
"""
Mix service: create static or dynamic mixes from separated stems.
CPU-bound (pydub) — uses the general executor, not the GPU queue.
"""
from pathlib import Path
from typing import Dict, List, Optional
from .. import job_manager as jm
from .preset_service import make_static, make_dynamic
def run_mix(
job_id: str,
stem_files: Dict[str, str], # stem_name (lowercase) → abs file path
preset_type: str, # 'static' | 'dynamic'
output_path: str,
output_format: str,
static_option: Optional[str] = None,
dynamic_levels: Optional[Dict[str, float]] = None,
):
"""Background task: create a mix from separated stems."""
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Creating mix...")
try:
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
if preset_type == "static":
muted = _get_muted_stems(static_option)
result_path = make_static(stem_files, muted, out, output_format)
elif preset_type == "dynamic":
volumes = dynamic_levels or {}
result_path = make_dynamic(stem_files, volumes, out, output_format)
else:
raise ValueError(f"Unknown preset type: {preset_type}")
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="Mix complete.",
files=[{"name": out.name, "path": result_path, "type": preset_type}],
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")
def _get_muted_stems(static_option: Optional[str]) -> List[str]:
if not static_option:
return []
option_map = {
"no_vocals": ["vocals"],
"no_drums": ["drums"],
"no_bass": ["bass"],
"no_vocals_no_bass": ["vocals", "bass"],
"no_drums_no_bass": ["drums", "bass"],
}
return option_map.get(static_option, [])
+310
View File
@@ -0,0 +1,310 @@
"""
Full pipeline: separate → transcribe → abc-convert.
Supports both Demucs (CLI) and BS-RoFormer (Python API) for the separation stage.
Uses project-based folder structure for organized output.
"""
import sys
import subprocess
import time
import shutil
from pathlib import Path
from .. import job_manager as jm
from ..config import PROJECTS_DIR, JOBS_DIR, CPU_SEPARATION, TRANSCRIBE_PRESETS
from .metadata_util import copy_metadata, read_metadata
from .project_namer import project_name, make_project_dirs
from .separator_service import BSR_PREFIX, BSR_STEM_MODE
from . import abc_generator
def run_pipeline(
job_id: str,
input_path: str,
sep_model: str,
sep_format: str,
transcribe_mode: str,
song_title: str,
project_name_override: str = None,
):
"""
Full pipeline:
1. Stem separation (Demucs CLI or BS-RoFormer Python API)
2. MIDI transcription (basic-pitch) for each non-drum stem
3. ABC notation conversion
Creates organized project folder structure under MEDIA_DIR.
"""
# Read metadata for project naming
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Reading metadata...")
metadata = read_metadata(input_path)
# Determine project name
if project_name_override:
proj_name = project_name_override
else:
filename_stem = Path(input_path).stem
proj_name = project_name(metadata.get('artist', ''), metadata.get('title', ''), filename_stem)
# Create project directories
jm.update_job(job_id, progress=f"Creating project: {proj_name}...")
dirs = make_project_dirs(
proj_name, PROJECTS_DIR,
{'instrumental': False, 'static': False, 'dynamic': False}
)
project_dir = dirs['project']
stems_dir = dirs['stems']
transcriptions_dir = project_dir / "Transcriptions"
transcriptions_dir.mkdir(exist_ok=True)
all_files = []
# Normalise mp3_320 → mp3 with explicit bitrate
mp3_bitrate = '320k' if sep_format == 'mp3_320' else '256k'
normalised_format = 'mp3' if sep_format == 'mp3_320' else sep_format
# ------------------------------------------------------------------
# Stage 1: Separation
# ------------------------------------------------------------------
jm.update_job(job_id, progress="[1/3] Separating stems...")
try:
if sep_model.startswith(BSR_PREFIX):
stem_files = _separate_bsroformer(
job_id, input_path, sep_model, normalised_format, stems_dir, mp3_bitrate
)
else:
stem_files = _separate_demucs(
job_id, input_path, sep_model, sep_format, stems_dir
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Separation failed.")
return
if stem_files is None:
return # cancelled inside sub-function
# Record stems with proper metadata
for stem_name, path in sorted(stem_files.items()):
copy_metadata(input_path, path, stem_label=stem_name.capitalize())
all_files.append({
"name": Path(path).name,
"path": path,
"stage": "separation",
"stem": stem_name
})
# ------------------------------------------------------------------
# Stage 2: Transcription (skip drum stems)
# ------------------------------------------------------------------
from basic_pitch.inference import predict
from basic_pitch import ICASSP_2022_MODEL_PATH
jm.update_job(job_id, progress="[2/3] Transcribing stems to MIDI...")
midi_files = []
transcribe_paths = [
(name, path) for name, path in stem_files.items()
if 'drums' not in name.lower()
]
params = TRANSCRIBE_PRESETS.get(transcribe_mode, TRANSCRIBE_PRESETS["polyphonic"])
for stem_name, stem_path in transcribe_paths:
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
jm.update_job(job_id, progress=f"[2/3] Transcribing: {stem_name}...")
try:
_, midi_data, _ = predict(stem_path, ICASSP_2022_MODEL_PATH, **params)
output_name = f"{proj_name} - {stem_name.capitalize()} ({transcribe_mode}).mid"
dest = transcriptions_dir / output_name
midi_data.write(str(dest))
all_files.append({
"name": dest.name,
"path": str(dest),
"stage": "transcription"
})
midi_files.append(str(dest))
except Exception as exc:
jm.update_job(job_id, progress=f"[2/3] Error on {stem_name}: {exc}")
# ------------------------------------------------------------------
# Stage 3: ABC conversion
# ------------------------------------------------------------------
if midi_files:
jm.update_job(job_id, progress="[3/3] Converting MIDI to ABC notation...")
try:
abc_results = abc_generator.convert_midi_to_abc(midi_files, song_title or proj_name)
if abc_results:
for part_name, abc_text in abc_results.items():
safe = part_name.replace("/", "_").replace("\\", "_")
dest = transcriptions_dir / f"{safe}.abc"
dest.write_text(abc_text, encoding="utf-8")
all_files.append({
"name": dest.name,
"path": str(dest),
"stage": "abc"
})
except Exception as exc:
jm.update_job(job_id, progress=f"[3/3] ABC conversion error: {exc}")
jm.update_job(
job_id, status=jm.JobStatus.DONE,
progress="Pipeline complete.",
files=all_files,
result={
"project_name": proj_name,
"project_path": str(project_dir),
"stems_dir": str(stems_dir),
"transcriptions_dir": str(transcriptions_dir),
}
)
jm.find_or_create_project(proj_name, job_id)
# ---------------------------------------------------------------------------
# Separation helpers
# ---------------------------------------------------------------------------
def _separate_demucs(
job_id: str, input_path: str, model: str, output_format: str, stems_dir: Path
) -> dict | None:
"""
Run Demucs CLI; returns dict mapping stem names to file paths, or None if cancelled.
"""
ext = output_format.lower()
fmt_flag = []
if ext == "mp3_320":
fmt_flag = ["--mp3", "--mp3-bitrate", "320"]
ext = "mp3"
elif ext == "mp3":
fmt_flag = ["--mp3", "--mp3-bitrate", "256"]
elif ext == "flac":
fmt_flag = ["--flac"]
# Use temp directory for demucs output
temp_out = JOBS_DIR / job_id / "demucs_out"
temp_out.mkdir(parents=True, exist_ok=True)
cmd = [
sys.executable, "-m", "demucs",
"--name", model,
"--out", str(temp_out),
*fmt_flag,
input_path,
]
try:
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
)
while True:
if jm.should_cancel(job_id):
process.terminate()
process.wait()
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return None
line = process.stdout.readline()
if line:
jm.update_job(job_id, progress=f"[1/3] {line.rstrip()}")
elif process.poll() is not None:
break
else:
time.sleep(0.1)
if process.returncode != 0:
raise RuntimeError(f"Demucs failed with code {process.returncode}")
input_stem = Path(input_path).stem
stem_src_dir = temp_out / model / input_stem
stem_files = {}
if stem_src_dir.exists():
for f in sorted(stem_src_dir.iterdir()):
if f.is_file():
stem_name = f.stem.lower()
for prefix in [input_stem.lower(), 'htdemucs', 'mdx']:
stem_name = stem_name.replace(prefix, '').strip('_- ')
if not stem_name:
stem_name = f.stem
dest = stems_dir / f"{input_stem} - {stem_name.capitalize()}{f.suffix}"
shutil.move(str(f), str(dest))
stem_files[stem_name] = str(dest)
try:
shutil.rmtree(temp_out, ignore_errors=True)
except:
pass
return stem_files
except Exception:
try:
shutil.rmtree(temp_out, ignore_errors=True)
except:
pass
raise
def _separate_bsroformer(
job_id: str, input_path: str, model: str, output_format: str, stems_dir: Path,
mp3_bitrate: str = '256k'
) -> dict | None:
"""
Run BS-RoFormer in-process; returns dict mapping stem names to file paths, or None if cancelled.
"""
from .bs_roformer_separator import BSRoformerSeparator
stem_mode = BSR_STEM_MODE.get(model, "4stem")
jm.update_job(job_id, progress=f"[1/3] Loading BS-RoFormer ({stem_mode})...")
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return None
sep = BSRoformerSeparator(
cpu_separation=CPU_SEPARATION,
output_format=output_format,
mp3_bitrate=mp3_bitrate,
stem_mode=stem_mode,
)
jm.update_job(job_id, progress="[1/3] Separating with BS-RoFormer...")
temp_out = JOBS_DIR / job_id / "bsr_out"
temp_out.mkdir(parents=True, exist_ok=True)
try:
stem_paths = sep.separate_into_parts(input_path, str(temp_out))
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return None
input_stem = Path(input_path).stem
stem_files = {}
for stem_name, path in sorted(stem_paths.items()):
src = Path(path)
dest = stems_dir / f"{input_stem} - {stem_name.capitalize()}{src.suffix}"
shutil.move(str(src), str(dest))
stem_files[stem_name.lower()] = str(dest)
try:
shutil.rmtree(temp_out, ignore_errors=True)
except:
pass
return stem_files
except Exception:
try:
shutil.rmtree(temp_out, ignore_errors=True)
except:
pass
raise
+96
View File
@@ -0,0 +1,96 @@
"""
Preset mixing: combine separated stems into a single output file.
- Instrumental: all non-vocal stems mixed
- Static: all stems except user-selected ones mixed
- Dynamic: all stems mixed with per-stem volume multipliers (0.0–2.0)
"""
import math
from pathlib import Path
from typing import Dict, List
from pydub import AudioSegment
def _load(path: str) -> AudioSegment:
return AudioSegment.from_file(path)
def _apply_gain(audio: AudioSegment, multiplier: float) -> AudioSegment:
"""Convert a linear multiplier to dB and apply as gain."""
if multiplier <= 0.0:
return AudioSegment.silent(duration=len(audio), frame_rate=audio.frame_rate)
gain_db = 20 * math.log10(multiplier)
return audio + gain_db
def _export(audio: AudioSegment, dest: Path, output_format: str) -> None:
if output_format == 'mp3_320':
audio.export(str(dest), format='mp3', bitrate='320k')
elif output_format == 'mp3':
audio.export(str(dest), format='mp3', bitrate='256k')
elif output_format == 'flac':
audio.export(str(dest), format='flac')
else:
audio.export(str(dest), format='wav')
def _mix(paths: List[str]) -> AudioSegment:
"""Overlay all audio files into one mix."""
if not paths:
raise ValueError("No stems to mix")
result = _load(paths[0])
for p in paths[1:]:
result = result.overlay(_load(p))
return result
def make_instrumental(
stem_files: Dict[str, str],
output_path: Path,
output_format: str,
) -> str:
"""Mix all stems except those with 'vocal' in the stem name."""
keep = [p for name, p in stem_files.items() if 'vocal' not in name.lower()]
if not keep:
raise RuntimeError("No non-vocal stems available for Instrumental preset")
_export(_mix(keep), output_path, output_format)
return str(output_path)
def make_static(
stem_files: Dict[str, str],
muted_stems: List[str],
output_path: Path,
output_format: str,
) -> str:
"""Mix all stems except those listed in muted_stems."""
muted_lower = {s.lower() for s in muted_stems}
keep = [p for name, p in stem_files.items() if name.lower() not in muted_lower]
if not keep:
raise RuntimeError("All stems are muted — nothing to mix for Static preset")
_export(_mix(keep), output_path, output_format)
return str(output_path)
def make_dynamic(
stem_files: Dict[str, str],
volumes: Dict[str, float],
output_path: Path,
output_format: str,
) -> str:
"""
Mix stems with per-stem linear volume multipliers.
volumes keys are stem names (lowercase); missing stems default to 1.0.
"""
adjusted: List[AudioSegment] = []
for name, path in stem_files.items():
vol = volumes.get(name.lower(), 1.0)
adjusted.append(_apply_gain(_load(path), vol))
if not adjusted:
raise RuntimeError("No stems available for Dynamic preset")
result = adjusted[0]
for a in adjusted[1:]:
result = result.overlay(a)
_export(result, output_path, output_format)
return str(output_path)
+93
View File
@@ -0,0 +1,93 @@
"""
Project metadata file service.
Writes/reads a project.json snapshot in each project root folder.
This file mirrors the DB state and can be used for browsing, repair,
and offline project identification without a database query.
"""
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
_METADATA_FILENAME = "project.json"
def write_project_metadata(
project_dir: Path,
*,
project_id: str,
name: str,
artist: str = "",
title: str = "",
model: str = "",
model_label: str = "",
format: str = "",
format_label: str = "",
source_file: str = "",
stems: dict,
sep_job_id: str = "",
trans_jobs: Optional[dict] = None,
abc_jobs: Optional[dict] = None,
lrc_jobs: Optional[dict] = None,
mix_job_id: Optional[str] = None,
created_at: Optional[str] = None,
) -> None:
"""
Write (or overwrite) project.json in *project_dir*.
If the file already exists its contents are merged so that keys not
supplied by the caller (e.g. trans_jobs added later) are preserved.
"""
meta_path = project_dir / _METADATA_FILENAME
# Load existing data so we can merge incremental updates
existing: dict = {}
if meta_path.exists():
try:
existing = json.loads(meta_path.read_text(encoding="utf-8"))
except Exception:
existing = {}
now = datetime.now(timezone.utc).isoformat()
updated = {
**existing,
"project_id": project_id,
"name": name,
"artist": artist,
"title": title,
"model": model,
"model_label": model_label,
"format": format,
"format_label": format_label,
"created_at": created_at or existing.get("created_at", now),
"updated_at": now,
"source_file": source_file or existing.get("source_file", ""),
"stems": stems if stems is not None else existing.get("stems", {}),
"sep_job_id": sep_job_id or existing.get("sep_job_id", ""),
"trans_jobs": trans_jobs if trans_jobs is not None else existing.get("trans_jobs", {}),
"abc_jobs": abc_jobs if abc_jobs is not None else existing.get("abc_jobs", {}),
"lrc_jobs": lrc_jobs if lrc_jobs is not None else existing.get("lrc_jobs", {}),
"mix_job_id": mix_job_id if mix_job_id is not None else existing.get("mix_job_id"),
}
meta_path.write_text(
json.dumps(updated, indent=2, ensure_ascii=False),
encoding="utf-8",
)
def read_project_metadata(project_dir: Path) -> Optional[dict]:
"""
Read project.json from *project_dir*.
Returns None if the file does not exist or cannot be parsed.
"""
meta_path = project_dir / _METADATA_FILENAME
if not meta_path.exists():
return None
try:
return json.loads(meta_path.read_text(encoding="utf-8"))
except Exception:
return None
+72
View File
@@ -0,0 +1,72 @@
"""
Project folder naming and structure creation.
Derives a human-readable project name from audio metadata and creates the
subdirectory layout under MEDIA_DIR.
"""
import re
from pathlib import Path
from typing import Dict
_ILLEGAL = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
def _sanitize(s: str) -> str:
"""Remove filesystem-illegal characters and trim trailing dots/spaces."""
s = _ILLEGAL.sub('', s).strip().rstrip('. ')
return s or ''
def project_name(artist: str, title: str, filename_stem: str = '') -> str:
"""
Return a human-readable project folder name.
Format: "Artist - Title". Falls back to filename_stem if both are missing.
"""
a = _sanitize(artist)
t = _sanitize(title)
if a and t:
return f"{a} - {t}"
if t:
return t
if a:
return a
fs = _sanitize(filename_stem)
return fs if fs else 'Unknown Project'
def make_project_dirs(
name: str,
media_dir: Path,
presets: Dict[str, bool],
) -> Dict[str, Path]:
"""
Create project subdirectories under media_dir/name/.
Always creates Stems/. Creates Instrumental/, Static/, Dynamic/ only when
the corresponding preset flag is True.
Returns a dict mapping role names ('project', 'stems', 'instrumental',
'static', 'dynamic') to their Path objects.
"""
project_dir = media_dir / name
stems_dir = project_dir / 'Stems'
stems_dir.mkdir(parents=True, exist_ok=True)
dirs: Dict[str, Path] = {'project': project_dir, 'stems': stems_dir}
if presets.get('instrumental'):
d = project_dir / 'Instrumental'
d.mkdir(exist_ok=True)
dirs['instrumental'] = d
if presets.get('static'):
d = project_dir / 'Static'
d.mkdir(exist_ok=True)
dirs['static'] = d
if presets.get('dynamic'):
d = project_dir / 'Dynamic'
d.mkdir(exist_ok=True)
dirs['dynamic'] = d
return dirs
+321
View File
@@ -0,0 +1,321 @@
"""
SCNet model architecture — vendored from:
https://github.com/ZFTurbo/Music-Source-Separation-Training (MIT license)
Paper: https://arxiv.org/abs/2401.13276
Contains SeparationNet and SCNet classes only; no training or I/O code.
"""
import math
from collections import deque
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.rnn import LSTM
# ---------------------------------------------------------------------------
# SeparationNet (dual-path RNN + FFT feature conversion)
# ---------------------------------------------------------------------------
class FeatureConversion(nn.Module):
def __init__(self, channels, inverse):
super().__init__()
self.inverse = inverse
self.channels = channels
def forward(self, x):
if self.inverse:
x = x.float()
x_r = x[:, :self.channels // 2, :, :]
x_i = x[:, self.channels // 2:, :, :]
x = torch.complex(x_r, x_i)
x = torch.fft.irfft(x, dim=3, norm="ortho")
else:
x = x.float()
x = torch.fft.rfft(x, dim=3, norm="ortho")
x = torch.cat([x.real, x.imag], dim=1)
return x
class DualPathRNN(nn.Module):
def __init__(self, d_model, expand, bidirectional=True):
super().__init__()
self.d_model = d_model
self.hidden_size = d_model * expand
self.lstm_layers = nn.ModuleList([
LSTM(d_model, self.hidden_size, num_layers=1, bidirectional=bidirectional, batch_first=True)
for _ in range(2)
])
self.linear_layers = nn.ModuleList([nn.Linear(self.hidden_size * 2, d_model) for _ in range(2)])
self.norm_layers = nn.ModuleList([nn.GroupNorm(1, d_model) for _ in range(2)])
def forward(self, x):
B, C, F, T = x.shape
original_x = x
x = self.norm_layers[0](x)
x = x.transpose(1, 3).contiguous().view(B * T, F, C)
x, _ = self.lstm_layers[0](x)
x = self.linear_layers[0](x)
x = x.view(B, T, F, C).transpose(1, 3) + original_x
original_x = x
x = self.norm_layers[1](x)
x = x.transpose(1, 2).contiguous().view(B * F, C, T).transpose(1, 2)
x, _ = self.lstm_layers[1](x)
x = self.linear_layers[1](x)
x = x.transpose(1, 2).contiguous().view(B, F, C, T).transpose(1, 2) + original_x
return x
class SeparationNet(nn.Module):
def __init__(self, channels, expand=1, num_layers=6):
super().__init__()
self.num_layers = num_layers
self.dp_modules = nn.ModuleList([
DualPathRNN(channels * (2 if i % 2 == 1 else 1), expand)
for i in range(num_layers)
])
self.feature_conversion = nn.ModuleList([
FeatureConversion(channels * 2, inverse=(i % 2 == 1))
for i in range(num_layers)
])
def forward(self, x):
for dp, fc in zip(self.dp_modules, self.feature_conversion):
x = dp(x)
x = fc(x)
return x
# ---------------------------------------------------------------------------
# SCNet building blocks
# ---------------------------------------------------------------------------
class Swish(nn.Module):
def forward(self, x):
return x * x.sigmoid()
class ConvolutionModule(nn.Module):
def __init__(self, channels, depth=2, compress=4, kernel=3):
super().__init__()
assert kernel % 2 == 1
hidden = int(channels / compress)
norm = lambda d: nn.GroupNorm(1, d)
self.layers = nn.ModuleList()
for _ in range(abs(depth)):
p = kernel // 2
self.layers.append(nn.Sequential(
norm(channels),
nn.Conv1d(channels, hidden * 2, kernel, padding=p),
nn.GLU(1),
nn.Conv1d(hidden, hidden, kernel, padding=p, groups=hidden),
norm(hidden),
Swish(),
nn.Conv1d(hidden, channels, 1),
))
def forward(self, x):
for layer in self.layers:
x = x + layer(x)
return x
class FusionLayer(nn.Module):
def __init__(self, channels, kernel_size=3, stride=1, padding=1):
super().__init__()
self.conv = nn.Conv2d(channels * 2, channels * 2, kernel_size, stride=stride, padding=padding)
def forward(self, x, skip=None):
if skip is not None:
x = x + skip
x = self.conv(x.repeat(1, 2, 1, 1))
return F.glu(x, dim=1)
class SDlayer(nn.Module):
def __init__(self, channels_in, channels_out, band_configs):
super().__init__()
self.convs = nn.ModuleList()
self.strides, self.kernels = [], []
for cfg in band_configs.values():
self.convs.append(
nn.Conv2d(channels_in, channels_out, (cfg['kernel'], 1), (cfg['stride'], 1))
)
self.strides.append(cfg['stride'])
self.kernels.append(cfg['kernel'])
self.SR_low = band_configs['low']['SR']
self.SR_mid = band_configs['mid']['SR']
def forward(self, x):
B, C, Fr, T = x.shape
splits = [
(0, math.ceil(Fr * self.SR_low)),
(math.ceil(Fr * self.SR_low), math.ceil(Fr * (self.SR_low + self.SR_mid))),
(math.ceil(Fr * (self.SR_low + self.SR_mid)), Fr),
]
outputs, original_lengths = [], []
for conv, stride, kernel, (start, end) in zip(self.convs, self.strides, self.kernels, splits):
extracted = x[:, :, start:end, :]
original_lengths.append(end - start)
L = extracted.shape[2]
total_pad = (kernel - stride) if stride == 1 else (stride - L % stride) % stride
pad_l = total_pad // 2
outputs.append(conv(F.pad(extracted, (0, 0, pad_l, total_pad - pad_l))))
return outputs, original_lengths
class SUlayer(nn.Module):
def __init__(self, channels_in, channels_out, band_configs):
super().__init__()
self.convtrs = nn.ModuleList([
nn.ConvTranspose2d(channels_in, channels_out, [cfg['kernel'], 1], [cfg['stride'], 1])
for cfg in band_configs.values()
])
def forward(self, x, lengths, origin_lengths):
splits = [
(0, lengths[0]),
(lengths[0], lengths[0] + lengths[1]),
(lengths[0] + lengths[1], None),
]
outputs = []
for convtr, (start, end), orig_len in zip(self.convtrs, splits, origin_lengths):
out = convtr(x[:, :, start:end, :])
dist = abs(orig_len - out.shape[2]) // 2
outputs.append(out[:, :, dist:dist + orig_len, :])
return torch.cat(outputs, dim=2)
class SDblock(nn.Module):
def __init__(self, channels_in, channels_out, band_configs={}, conv_config={}, depths=[3, 2, 1], kernel_size=3):
super().__init__()
self.SDlayer = SDlayer(channels_in, channels_out, band_configs)
self.conv_modules = nn.ModuleList([
ConvolutionModule(channels_out, depth, **conv_config) for depth in depths
])
self.globalconv = nn.Conv2d(channels_out, channels_out, kernel_size, 1, (kernel_size - 1) // 2)
def forward(self, x):
bands, original_lengths = self.SDlayer(x)
bands = [
F.gelu(
conv(band.permute(0, 2, 1, 3).reshape(-1, band.shape[1], band.shape[3]))
.view(band.shape[0], band.shape[2], band.shape[1], band.shape[3])
.permute(0, 2, 1, 3)
)
for conv, band in zip(self.conv_modules, bands)
]
lengths = [b.size(-2) for b in bands]
full_band = torch.cat(bands, dim=2)
return self.globalconv(full_band), full_band, lengths, original_lengths
# ---------------------------------------------------------------------------
# SCNet
# ---------------------------------------------------------------------------
class SCNet(nn.Module):
"""
Sparse Compression Network for music source separation.
Paper: https://arxiv.org/abs/2401.13276
"""
def __init__(
self,
sources=['drums', 'bass', 'other', 'vocals'],
audio_channels=2,
dims=[4, 32, 64, 128],
nfft=4096,
hop_size=1024,
win_size=4096,
normalized=True,
band_SR=[0.175, 0.392, 0.433],
band_stride=[1, 4, 16],
band_kernel=[3, 4, 16],
conv_depths=[3, 2, 1],
compress=4,
conv_kernel=3,
num_dplayer=6,
expand=1,
):
super().__init__()
self.sources = sources
self.audio_channels = audio_channels
self.dims = dims
band_keys = ['low', 'mid', 'high']
self.band_configs = {
band_keys[i]: {'SR': band_SR[i], 'stride': band_stride[i], 'kernel': band_kernel[i]}
for i in range(3)
}
self.hop_length = hop_size
self.conv_config = {'compress': compress, 'kernel': conv_kernel}
self.stft_config = {
'n_fft': nfft, 'hop_length': hop_size, 'win_length': win_size,
'center': True, 'normalized': normalized,
}
self.encoder = nn.ModuleList()
self.decoder = nn.ModuleList()
for i in range(len(dims) - 1):
self.encoder.append(SDblock(
channels_in=dims[i], channels_out=dims[i + 1],
band_configs=self.band_configs, conv_config=self.conv_config,
depths=conv_depths,
))
self.decoder.insert(0, nn.Sequential(
FusionLayer(channels=dims[i + 1]),
SUlayer(
channels_in=dims[i + 1],
channels_out=dims[i] if i != 0 else dims[i] * len(sources),
band_configs=self.band_configs,
),
))
self.separation_net = SeparationNet(
channels=dims[-1], expand=expand, num_layers=num_dplayer,
)
def forward(self, x):
B = x.shape[0]
padding = self.hop_length - x.shape[-1] % self.hop_length
if (x.shape[-1] + padding) // self.hop_length % 2 == 0:
padding += self.hop_length
x = F.pad(x, (0, padding))
L = x.shape[-1]
x = x.reshape(-1, L)
x = torch.stft(x, **self.stft_config, return_complex=True)
x = torch.view_as_real(x)
x = x.permute(0, 3, 1, 2).reshape(
x.shape[0] // self.audio_channels,
x.shape[3] * self.audio_channels,
x.shape[1], x.shape[2],
)
B, C, Fr, T = x.shape
save_skip = deque()
save_lengths = deque()
save_orig = deque()
for sd_layer in self.encoder:
x, skip, lengths, orig_len = sd_layer(x)
save_skip.append(skip)
save_lengths.append(lengths)
save_orig.append(orig_len)
x = self.separation_net(x)
for fusion_layer, su_layer in self.decoder:
x = fusion_layer(x, save_skip.pop())
x = su_layer(x, save_lengths.pop(), save_orig.pop())
n = self.dims[0]
x = x.view(B, n, -1, Fr, T)
x = x.reshape(-1, 2, Fr, T).permute(0, 2, 3, 1)
x = torch.view_as_complex(x.contiguous())
x = torch.istft(x, **self.stft_config)
x = x.reshape(B, len(self.sources), self.audio_channels, -1)
return x[:, :, :, :-padding]
+299
View File
@@ -0,0 +1,299 @@
"""
SCNet separator — native PyTorch inference.
Models from MVSEP-Central-Backup (HuggingFace).
Architecture vendored from MSST (MIT license):
https://github.com/ZFTurbo/Music-Source-Separation-Training
"""
import shutil
from pathlib import Path
from typing import Dict, Optional
import numpy as np
import torch
import torchaudio
import yaml
from .scnet_arch import SCNet
from ..config import SCNET_MODEL_DIR, CPU_SEPARATION
# ---------------------------------------------------------------------------
# Model registry
# ---------------------------------------------------------------------------
SCNET_MODELS = {
"scnet_xl": {
"model_file": "scnet_checkpoint_musdb18.ckpt",
"config_file": "config_musdb18_scnet_xl.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_model_path": "Politrees/UVR_resources/models/SCnet/scnet_checkpoint_musdb18.ckpt",
"hf_config_path": "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_xl.yaml",
},
"scnet_xl_ihf": {
"model_file": "scnet_checkpoint_musdb18.ckpt",
"config_file": "config_musdb18_scnet_xl.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_model_path": "Politrees/UVR_resources/models/SCnet/scnet_checkpoint_musdb18.ckpt",
"hf_config_path": "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_xl.yaml",
},
"scnet_large": {
"model_file": "SCNet-large_starrytong_fixed.ckpt",
"config_file": "config_musdb18_scnet_large_starrytong.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_model_path": "Politrees/UVR_resources/models/SCnet/SCNet-large_starrytong_fixed.ckpt",
"hf_config_path": "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_large_starrytong.yaml",
},
"scnet_large_starrytong": {
"model_file": "SCNet-large_starrytong_fixed.ckpt",
"config_file": "config_musdb18_scnet_large_starrytong.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_model_path": "Politrees/UVR_resources/models/SCnet/SCNet-large_starrytong_fixed.ckpt",
"hf_config_path": "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_large_starrytong.yaml",
},
}
# ---------------------------------------------------------------------------
# Audio I/O helpers
# ---------------------------------------------------------------------------
def _load_audio(path: str, sample_rate: int) -> np.ndarray:
"""Load audio and return (2, samples) float32 array at target sample rate."""
waveform, sr = torchaudio.load(path)
if sr != sample_rate:
waveform = torchaudio.functional.resample(waveform, sr, sample_rate)
if waveform.shape[0] == 1:
waveform = waveform.repeat(2, 1)
elif waveform.shape[0] > 2:
waveform = waveform[:2]
return waveform.numpy().astype(np.float32)
def _save_audio(path: str, audio: np.ndarray, sample_rate: int, output_format: str):
"""Save (channels, samples) numpy array to file via torchaudio (ffmpeg backend)."""
tensor = torch.tensor(audio, dtype=torch.float32)
fmt = output_format.lower()
if fmt == "mp3":
torchaudio.save(path, tensor, sample_rate, format="mp3")
elif fmt == "flac":
torchaudio.save(path, tensor, sample_rate, format="flac")
else:
torchaudio.save(path, tensor, sample_rate)
# ---------------------------------------------------------------------------
# Overlapping-window inference (MSST style)
# ---------------------------------------------------------------------------
def _build_window(chunk_size: int, step: int) -> np.ndarray:
"""
Linear fade-in / flat / fade-out window of length chunk_size.
Consecutive windows (offset by step) partition of unity: they sum to a
constant, so the overlap-add correctly averages.
"""
fade = step
fade_in = np.linspace(0.0, 1.0, fade, endpoint=False, dtype=np.float32)
fade_out = np.linspace(1.0, 0.0, fade, endpoint=False, dtype=np.float32)
flat_len = chunk_size - 2 * fade
if flat_len > 0:
return np.concatenate([fade_in, np.ones(flat_len, dtype=np.float32), fade_out])
# num_overlap == 2: no flat region
return np.concatenate([fade_in, fade_out])
def _demix(
model: SCNet,
mix: np.ndarray,
chunk_size: int,
num_overlap: int,
device: torch.device,
) -> np.ndarray:
"""
MSST-style overlapping-window inference.
Args:
mix: (channels, samples) float32
Returns:
(num_sources, channels, samples) float32
"""
C, N = mix.shape
step = chunk_size // num_overlap
border = chunk_size - step # == (num_overlap-1)*step
# Reflect-pad both sides so edge frames get proper context.
mix_padded = np.pad(mix, ((0, 0), (border, border)), mode="reflect")
window = _build_window(chunk_size, step)
sources_sum: Optional[np.ndarray] = None
weight_sum = np.zeros(mix_padded.shape[-1], dtype=np.float32)
with torch.no_grad():
for start in range(0, N, step):
p_end = start + chunk_size
if p_end > mix_padded.shape[-1]:
break
chunk = mix_padded[:, start:p_end] # (C, chunk_size)
# Per-chunk loudness normalisation
mean = float(chunk.mean())
std = max(float(chunk.std()), 1e-8)
chunk_norm = (chunk - mean) / std
inp = torch.tensor(chunk_norm[np.newaxis], dtype=torch.float32, device=device)
out = model(inp) # (1, num_sources, C, chunk_size)
out_np = out.squeeze(0).cpu().numpy() # (num_sources, C, chunk_size)
out_np = out_np * std + mean # denormalise
if sources_sum is None:
num_sources = out_np.shape[0]
sources_sum = np.zeros(
(num_sources, C, mix_padded.shape[-1]), dtype=np.float32
)
sources_sum[:, :, start:p_end] += out_np * window[np.newaxis, np.newaxis, :]
weight_sum[start:p_end] += window
if sources_sum is None:
raise RuntimeError("Audio is too short for chunked SCNet inference.")
weight_sum = np.maximum(weight_sum, 1e-8)
sources = sources_sum / weight_sum[np.newaxis, np.newaxis, :]
return sources[:, :, border : border + N]
# ---------------------------------------------------------------------------
# Separator class
# ---------------------------------------------------------------------------
class SCNetSeparator:
"""Native PyTorch inference wrapper for MSST SCNet models."""
def __init__(
self,
model_id: str = "scnet_xl",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in SCNET_MODELS:
raise ValueError(
f"Unknown SCNet model: {model_id}. "
f"Available: {list(SCNET_MODELS)}"
)
self.model_id = model_id
self.model_cfg = SCNET_MODELS[model_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self.device = torch.device(
"cpu" if cpu_separation else ("cuda" if torch.cuda.is_available() else "cpu")
)
self._model: Optional[SCNet] = None
self._config: Optional[dict] = None
# ------------------------------------------------------------------
# Model management
# ------------------------------------------------------------------
def _ensure_model(self) -> tuple[Path, Path]:
"""Download model and config from HuggingFace if not already cached."""
from huggingface_hub import hf_hub_download
model_dir = SCNET_MODEL_DIR / self.model_id
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / self.model_cfg["model_file"]
config_path = model_dir / self.model_cfg["config_file"]
if not model_path.exists():
print(f"[SCNet] Downloading {self.model_cfg['model_file']} …")
cached = hf_hub_download(
repo_id=self.model_cfg["hf_repo"],
filename=self.model_cfg["hf_model_path"],
)
shutil.copy2(cached, model_path)
if not config_path.exists():
print(f"[SCNet] Downloading {self.model_cfg['config_file']} …")
cached = hf_hub_download(
repo_id=self.model_cfg["hf_repo"],
filename=self.model_cfg["hf_config_path"],
)
shutil.copy2(cached, config_path)
return model_path, config_path
def _load_model(self) -> None:
"""Load YAML config and PyTorch checkpoint; instantiate SCNet."""
model_path, config_path = self._ensure_model()
# Some config files use !!python/tuple (e.g. mixup_probs); add a
# constructor so safe_load can handle them without crashing.
loader = yaml.SafeLoader
loader.add_constructor(
"tag:yaml.org,2002:python/tuple",
lambda ldr, node: tuple(ldr.construct_sequence(node)),
)
with open(config_path) as f:
cfg = yaml.load(f, Loader=loader)
self._config = cfg
model_params = cfg.get("model", {})
model = SCNet(**model_params)
state = torch.load(str(model_path), map_location="cpu", weights_only=False)
if "state_dict" in state:
state = state["state_dict"]
model.load_state_dict(state)
model.eval()
self._model = model.to(self.device)
def _get_model(self) -> SCNet:
if self._model is None:
self._load_model()
return self._model
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate audio into stems.
Returns:
Dict mapping stem name → output file path.
"""
model = self._get_model()
cfg = self._config
sample_rate: int = cfg.get("audio", {}).get("sample_rate", 44100)
inf_cfg: dict = cfg.get("inference", {})
chunk_size: int = inf_cfg.get("chunk_size", 485100)
num_overlap: int = inf_cfg.get("num_overlap", 2)
# Stem order from training config; fall back to model attribute
instruments = cfg.get("training", {}).get("instruments") or list(model.sources)
mix = _load_audio(input_path, sample_rate) # (2, N)
print(f"[SCNet] Running {self.model_id} on {self.device} …")
sources_np = _demix(model, mix, chunk_size, num_overlap, self.device)
# sources_np: (num_sources, 2, N)
out_dir = Path(output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
output_paths: Dict[str, str] = {}
for i, stem in enumerate(instruments):
if i >= sources_np.shape[0]:
break
ext = self.output_format.lower()
out_path = str(out_dir / f"{stem}.{ext}")
_save_audio(out_path, sources_np[i], sample_rate, self.output_format)
output_paths[stem] = out_path
print(f"[SCNet] Saved {stem} → {out_path}")
return output_paths
File diff suppressed because it is too large. Load diff
+281
View File
@@ -0,0 +1,281 @@
"""
Subsonic REST API client and local import service.
Auth: token-based (md5(password+salt)), salt generated per request.
Config priority:
1. MEDIA_DIR/subsonic.json (written by the Settings UI or seed_from_env())
2. Environment variables SUBSONIC_URL / SUBSONIC_USERNAME / SUBSONIC_PASSWORD
— on first use these are written to subsonic.json so the UI reflects them.
Credential storage:
The password is never written to disk in plaintext. It is encrypted with
Fernet (AES-128-CBC + HMAC-SHA256) using a key derived from SECRET_KEY.
If SECRET_KEY is not set, credentials can still be supplied via environment
variables but cannot be persisted to disk (the Settings UI will save only
URL + username and prompt for the password on every restart).
"""
import base64
import hashlib
import json
import os
import secrets
from pathlib import Path
from typing import Optional
import requests as _requests
from cryptography.fernet import Fernet, InvalidToken
from ..config import SUBSONIC_CONFIG_PATH, IMPORTS_DIR
_AUDIO_EXTS = {'.mp3', '.flac', '.wav', '.m4a', '.ogg', '.opus', '.aac'}
_CLIENT_ID = 'StemEngine'
_API_VERSION = '1.16.1'
# ---------------------------------------------------------------------------
# Encryption helpers
# ---------------------------------------------------------------------------
_fernet: Optional[Fernet] = None
_fernet_init = False # sentinel: False = derivation not yet attempted
def _get_fernet() -> Optional[Fernet]:
"""
Return a Fernet instance keyed by SECRET_KEY, or None if SECRET_KEY is not set.
Key is derived once via PBKDF2-SHA256 (200k rounds) and cached for the
process lifetime.
"""
global _fernet, _fernet_init
if _fernet_init:
return _fernet
_fernet_init = True
raw_key = os.environ.get('SECRET_KEY', '').strip()
if not raw_key:
_fernet = None
return None
# Derive a 32-byte key from whatever the user provides
derived = hashlib.pbkdf2_hmac(
'sha256', raw_key.encode(), b'stemengine-subsonic', 200_000, dklen=32
)
_fernet = Fernet(base64.urlsafe_b64encode(derived))
return _fernet
def _encrypt(plaintext: str) -> str:
f = _get_fernet()
if f is None:
raise RuntimeError(
"SECRET_KEY is not set — cannot persist credentials to disk. "
"Add SECRET_KEY to docker-compose.yml to enable Settings UI credential storage."
)
return f.encrypt(plaintext.encode()).decode()
def _decrypt(ciphertext: str) -> str:
f = _get_fernet()
if f is None:
raise RuntimeError(
"SECRET_KEY is not set — cannot decrypt stored credentials. "
"Set SECRET_KEY or re-enter credentials via the Settings UI."
)
try:
return f.decrypt(ciphertext.encode()).decode()
except InvalidToken as exc:
raise RuntimeError(
"Credential decryption failed — SECRET_KEY may have changed. "
"Re-enter credentials via the Settings UI."
) from exc
# ---------------------------------------------------------------------------
# Config helpers
# ---------------------------------------------------------------------------
def _config_from_env() -> Optional[dict]:
"""Return config from environment variables, or None if not fully set."""
url = os.environ.get('SUBSONIC_URL', '').strip()
username = os.environ.get('SUBSONIC_USERNAME', '').strip()
password = os.environ.get('SUBSONIC_PASSWORD', '').strip()
if url and username and password:
return {'url': url, 'username': username, 'password': password}
return None
def load_config() -> Optional[dict]:
"""
Return the active Subsonic config dict (plaintext password ready for use),
or None if no credentials are available.
Handles encrypted-at-rest configs (_enc=True) and the legacy plaintext format.
"""
if SUBSONIC_CONFIG_PATH.exists():
try:
stored = json.loads(SUBSONIC_CONFIG_PATH.read_text())
if stored.get('_enc'):
pwd = _decrypt(stored['password'])
return {'url': stored['url'], 'username': stored['username'], 'password': pwd}
else:
# Legacy plaintext — serve as-is; the UI can re-save to upgrade
return {k: v for k, v in stored.items() if not k.startswith('_')}
except RuntimeError:
raise # Surface decryption / key errors to the caller
except Exception:
pass
env_cfg = _config_from_env()
if env_cfg:
try:
save_config(env_cfg) # Persist encrypted if SECRET_KEY is available
except RuntimeError:
pass # No key — serve from env, don't write to disk
return env_cfg
return None
def save_config(config: dict) -> None:
"""
Persist Subsonic config with the password encrypted at rest.
Raises RuntimeError if SECRET_KEY is not set.
"""
stored = {
'url': config['url'],
'username': config['username'],
'password': _encrypt(config['password']),
'_enc': True,
}
SUBSONIC_CONFIG_PATH.write_text(json.dumps(stored, indent=2))
def delete_config() -> None:
if SUBSONIC_CONFIG_PATH.exists():
SUBSONIC_CONFIG_PATH.unlink()
# ---------------------------------------------------------------------------
# Auth / URL helpers
# ---------------------------------------------------------------------------
def _make_token(password: str) -> tuple[str, str]:
"""Return (token, salt) for Subsonic token auth."""
salt = secrets.token_hex(8)
token = hashlib.md5((password + salt).encode()).hexdigest()
return token, salt
def _params(config: dict) -> dict:
token, salt = _make_token(config['password'])
return {
'u': config['username'],
't': token,
's': salt,
'v': _API_VERSION,
'c': _CLIENT_ID,
'f': 'json',
}
def _url(config: dict, endpoint: str) -> str:
return f"{config['url'].rstrip('/')}/rest/{endpoint}"
# ---------------------------------------------------------------------------
# API methods
# ---------------------------------------------------------------------------
def test_connection(config: dict) -> bool:
"""Ping the Subsonic server; return True if auth succeeds."""
try:
r = _requests.get(_url(config, 'ping.view'), params=_params(config), timeout=10)
data = r.json()
return data.get('subsonic-response', {}).get('status') == 'ok'
except Exception:
return False
def search_songs(query: str, count: int = 20) -> list[dict]:
"""Search for songs by keyword. Returns a list of song dicts."""
config = load_config()
if not config:
raise RuntimeError("Subsonic server not configured")
p = _params(config)
p.update({'query': query, 'songCount': count, 'artistCount': 0, 'albumCount': 0})
r = _requests.get(_url(config, 'search3.view'), params=p, timeout=15)
r.raise_for_status()
resp = r.json().get('subsonic-response', {})
if resp.get('status') != 'ok':
msg = resp.get('error', {}).get('message', 'Subsonic API error')
raise RuntimeError(msg)
return [
{
'id': s.get('id', ''),
'title': s.get('title', 'Unknown'),
'artist': s.get('artist', ''),
'album': s.get('album', ''),
'duration': s.get('duration', 0),
'suffix': s.get('suffix', 'mp3'),
'size': s.get('size', 0),
'bitRate': s.get('bitRate', 0),
}
for s in resp.get('searchResult3', {}).get('song', [])
]
def import_song(song_id: str, title: str, artist: str = '', suffix: str = 'mp3') -> dict:
"""Download a Subsonic song to IMPORTS_DIR."""
config = load_config()
if not config:
raise RuntimeError("Subsonic server not configured")
def _safe(s: str) -> str:
return "".join(c for c in s if c.isalnum() or c in ' -_().').strip()
safe_title = _safe(title) or 'Unknown'
safe_artist = _safe(artist)
base_name = f"{safe_artist} - {safe_title}" if safe_artist else safe_title
dest = IMPORTS_DIR / f"{base_name}.{suffix}"
counter = 1
while dest.exists():
dest = IMPORTS_DIR / f"{base_name} ({counter}).{suffix}"
counter += 1
p = _params(config)
p['id'] = song_id
r = _requests.get(_url(config, 'stream.view'), params=p, stream=True, timeout=120)
r.raise_for_status()
with open(dest, 'wb') as f:
for chunk in r.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
return {
'filename': dest.name,
'path': str(dest),
'size': dest.stat().st_size,
'title': title,
'artist': artist,
}
def list_imports() -> list[dict]:
"""Return metadata for all audio files in IMPORTS_DIR, newest first."""
if not IMPORTS_DIR.exists():
return []
results = []
for f in sorted(IMPORTS_DIR.iterdir(), key=lambda x: x.stat().st_mtime, reverse=True):
if f.is_file() and f.suffix.lower() in _AUDIO_EXTS:
results.append({
'filename': f.name,
'path': str(f),
'size': f.stat().st_size,
})
return results
+56
View File
@@ -0,0 +1,56 @@
"""
MIDI transcription via basic-pitch (in-process Python API).
Supports two modes mapped to inference parameter presets:
polyphonic — general multi-instrument transcription
melody — single-voice / vocal melody (melodia trick, min frequency)
"""
from pathlib import Path
from .. import job_manager as jm
from ..config import JOBS_DIR, TRANSCRIBE_PRESETS
def run_transcription(job_id: str, input_path: str, mode: str):
"""
Background task: transcribe audio to MIDI using basic-pitch.
mode: 'polyphonic' | 'melody'
"""
from basic_pitch.inference import predict
from basic_pitch import ICASSP_2022_MODEL_PATH
output_dir = JOBS_DIR / job_id
output_dir.mkdir(parents=True, exist_ok=True)
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Loading basic-pitch model...")
try:
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
params = TRANSCRIBE_PRESETS.get(mode, TRANSCRIBE_PRESETS["polyphonic"])
jm.update_job(job_id, progress=f"Transcribing with basic-pitch ({mode})...")
_, midi_data, _ = predict(
input_path,
ICASSP_2022_MODEL_PATH,
**params,
)
if jm.should_cancel(job_id):
jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.")
return
output_name = f"{Path(input_path).stem}-{mode}.mid"
dest = output_dir / output_name
midi_data.write(str(dest))
jm.update_job(
job_id,
status=jm.JobStatus.DONE,
progress="Transcription complete.",
files=[{"name": dest.name, "path": str(dest)}],
)
except Exception as exc:
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")