-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmdx_headless_runner.py
More file actions
1349 lines (1123 loc) · 52.8 KB
/
mdx_headless_runner.py
File metadata and controls
1349 lines (1123 loc) · 52.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MDX-Net Headless Runner
Run MDX-Net model separation without GUI
Usage:
python mdx_headless_runner.py --model model.ckpt --input input.wav --output output/
# Use model name (auto-download if not installed)
python mdx_headless_runner.py -m "UVR-MDX-NET Inst HQ 3" -i input.wav -o output/ --gpu
# Use JSON config file (for non-standard models)
python mdx_headless_runner.py --model model.ckpt --json config.json --input input.wav --output output/
# List available models
python mdx_headless_runner.py --list
# Download a model without inference
python mdx_headless_runner.py --download "UVR-MDX-NET Inst HQ 3"
"""
# Suppress deprecation warnings from librosa's pkg_resources usage
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="librosa")
warnings.filterwarnings("ignore", message=".*pkg_resources.*")
import os
import sys
import json
import math
import hashlib
import time
import torch
import argparse
import yaml
from pathlib import Path
from types import SimpleNamespace
# Import progress system
from progress import (
ProgressManager, ProgressStage,
create_progress_callbacks, create_download_progress_callback
)
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 导入必需的模块
from separate import SeperateMDX, SeperateMDXC, prepare_mix
from gui_data.constants import (
MDX_ARCH_TYPE,
VOCAL_STEM,
INST_STEM,
DEFAULT,
CUDA_DEVICE,
CPU,
secondary_stem,
ALL_STEMS,
DRUM_STEM,
BASS_STEM,
OTHER_STEM
)
# ml_collections 替代
try:
from ml_collections import ConfigDict
except ImportError:
# 如果没有 ml_collections,使用简单的 dict 包装
class ConfigDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key, value in self.items():
if isinstance(value, dict):
self[key] = ConfigDict(value)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
self[key] = value
# 设备检测
mps_available = torch.backends.mps.is_available() if hasattr(torch.backends, 'mps') else False
cuda_available = torch.cuda.is_available()
cpu = torch.device('cpu')
# 默认路径
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_MODEL_DATA_JSON = os.path.join(SCRIPT_DIR, 'models', 'MDX_Net_Models', 'model_data', 'model_data.json')
DEFAULT_MDX_C_CONFIG_PATH = os.path.join(SCRIPT_DIR, 'models', 'MDX_Net_Models', 'model_data', 'mdx_c_configs')
# 模型下载器 (lazy import to avoid circular imports)
_downloader = None
def _get_downloader():
"""Get or create model downloader instance."""
global _downloader
if _downloader is None:
from model_downloader import ModelDownloader
_downloader = ModelDownloader(base_path=SCRIPT_DIR, verbose=True)
return _downloader
# ============================================================================
# Model Registry Functions (Phase 2)
# ============================================================================
def list_models(show_installed_only: bool = False, show_uninstalled_only: bool = False) -> list:
"""
List available MDX-Net models from official UVR registry.
Args:
show_installed_only: If True, only show installed models
show_uninstalled_only: If True, only show uninstalled models
Returns:
List of model info dictionaries
"""
downloader = _get_downloader()
downloader.sync_registry()
models = downloader.list_models('mdx', show_installed=True)
if show_installed_only:
models = [m for m in models if m['installed']]
elif show_uninstalled_only:
models = [m for m in models if not m['installed']]
return models
def get_model_info(model_name: str) -> dict:
"""
Get detailed information about a specific MDX-Net model.
Args:
model_name: Model name or display name
Returns:
Model info dictionary or None if not found
"""
downloader = _get_downloader()
downloader.sync_registry()
return downloader.get_model_info(model_name, 'mdx')
def download_model(model_name: str) -> tuple:
"""
Download a specific MDX-Net model.
Args:
model_name: Model name or display name
Returns:
Tuple of (success: bool, message: str)
"""
downloader = _get_downloader()
downloader.sync_registry()
return downloader.download_model(model_name, 'mdx')
def _detect_host_path(path_str: str):
"""
Detect if a path string appears to be a host OS path not accessible inside this container.
This catches cases where users pass Windows/WSL paths directly to Docker
(e.g. docker run ... -m "C:\\Users\\...\\model.ckpt") without mounting them.
Returns:
'windows' if it looks like a Windows absolute path (C:\\...)
'wsl' if it looks like a WSL-mounted path (/mnt/c/...)
None if it's not a host-specific path pattern
"""
import re
# Windows absolute path: C:\ or C:/ or D:\
if re.match(r'^[A-Za-z]:[/\\]', path_str):
return 'windows'
# WSL-style mount path
if re.match(r'^/mnt/[a-z]/', path_str):
return 'wsl'
return None
def _try_find_model_by_basename(basename: str, search_dirs: list):
"""
Search for a model file by its basename in standard directories.
Checks the given directories and their immediate subdirectories.
Used as a fallback when a host path is detected but the file might
have been mounted under a different path.
"""
for search_dir in search_dirs:
if not os.path.isdir(search_dir):
continue
# Direct match
candidate = os.path.join(search_dir, basename)
if os.path.isfile(candidate):
return candidate
# One-level subdirectory search
try:
for subdir in os.listdir(search_dir):
subdir_path = os.path.join(search_dir, subdir)
if os.path.isdir(subdir_path):
candidate = os.path.join(subdir_path, basename)
if os.path.isfile(candidate):
return candidate
except OSError:
continue
return None
def resolve_model_path(model_identifier: str, verbose: bool = True, progress_callback=None) -> str:
"""
Resolve a model identifier to a local file path.
If the identifier is a path to an existing file, return it.
If it's a model name, look it up in the registry and download if needed.
Supports:
- Direct file paths (local or mounted)
- Registry model names (auto-download)
- Host OS paths (Windows/WSL) with auto-detection and helpful errors
Args:
model_identifier: File path or model name
verbose: Whether to print progress
progress_callback: Optional download progress callback (current, total, filename)
Returns:
Local file path to the model
Raises:
FileNotFoundError: If model cannot be found or downloaded
"""
# Check if it's already a valid file path
if os.path.isfile(model_identifier):
return model_identifier
# ── Detect host filesystem paths (e.g. Windows paths inside Docker) ──────
# When running inside Docker, a user may pass a host-side path like
# C:\Users\...\model.ckpt which doesn't exist in the Linux container.
# If the CLI wrapper auto-mounted it, the file will be found by os.path.isfile
# above. Otherwise, try to find by basename or provide clear guidance.
host_path_type = _detect_host_path(model_identifier)
if host_path_type:
# Extract basename (normalize backslashes for Windows paths)
model_basename = os.path.basename(model_identifier.replace('\\', '/'))
# Search in standard model directories
models_dir = os.environ.get('UVR_MODELS_DIR', '/models')
custom_models_dir = os.environ.get('UVR_CUSTOM_MODELS_DIR', '/uvr_models')
search_dirs = [
custom_models_dir, # custom model mount point
models_dir, # default model volume
os.path.join(models_dir, 'MDX_Net_Models'), # MDX subdirectory
]
found = _try_find_model_by_basename(model_basename, search_dirs)
if found:
if verbose:
print(f"[INFO] Detected local model path ({host_path_type}), "
f"found mounted model: {found}")
return found
# Not found — provide clear, actionable error
raise FileNotFoundError(
f"\n{'='*60}\n"
f"ERROR: Local model path not accessible in container\n"
f"{'='*60}\n"
f"\n"
f"Host path: {model_identifier}\n"
f"Path type: {host_path_type}\n"
f"\n"
f"The model file exists on your host machine but was not\n"
f"mounted into the Docker container.\n"
f"\n"
f"Solutions:\n"
f"\n"
f" 1. Use the CLI wrapper (auto-mounts model paths):\n"
f" uvr-mdx -m \"{model_identifier}\" -i input.wav -o output/\n"
f"\n"
f" 2. Manually mount the model directory:\n"
f" docker run \\\n"
f" -v \"/path/to/model/dir:/uvr_models:ro\" \\\n"
f" ... \\\n"
f" -m \"/uvr_models/{model_basename}\"\n"
f"\n"
f" 3. Use a registry model name (no mounting needed):\n"
f" uvr-mdx --list # see available models\n"
)
# Check if it's a path that might exist in standard locations
if os.path.sep in model_identifier or '/' in model_identifier or '\\' in model_identifier:
# It looks like a path - try some common bases
# Normalize path separators for cross-platform compatibility
normalized_basename = os.path.basename(model_identifier.replace('\\', '/'))
models_dir = os.environ.get('UVR_MODELS_DIR', '/models')
candidates = [
model_identifier,
os.path.join(SCRIPT_DIR, model_identifier),
os.path.join(SCRIPT_DIR, 'models', 'MDX_Net_Models', normalized_basename),
os.path.join(models_dir, 'MDX_Net_Models', normalized_basename),
os.path.join(os.environ.get('UVR_CUSTOM_MODELS_DIR', '/uvr_models'), normalized_basename),
]
for candidate in candidates:
if os.path.isfile(candidate):
return candidate
# Path not found
raise FileNotFoundError(f"Model file not found: {model_identifier}")
# Treat as model name - look up in registry
downloader = _get_downloader()
if verbose:
print(f"Looking up model: {model_identifier}")
success, result = downloader.ensure_model(model_identifier, 'mdx', progress_callback=progress_callback)
if success:
if verbose:
print(f"Model path: {result}")
return result
else:
raise FileNotFoundError(f"Model not found: {model_identifier}. Error: {result}")
def get_model_hash(model_path):
"""
计算模型文件的 MD5 哈希(与 UVR 完全一致)
UVR 读取文件的最后 10MB(10000 * 1024 字节)来计算哈希。
如果文件小于 10MB,则读取整个文件。
"""
try:
with open(model_path, 'rb') as f:
# 与 UVR.py get_model_hash() 完全一致:读取最后 10MB
try:
f.seek(-10000 * 1024, 2) # 从文件末尾向前 10MB
return hashlib.md5(f.read()).hexdigest()
except OSError:
# 文件小于 10MB,读取整个文件
f.seek(0)
return hashlib.md5(f.read()).hexdigest()
except Exception as e:
print(f"Warning: Cannot compute model hash: {e}")
return None
def load_model_data_json(json_path=None, model_path=None):
"""
加载 model_data.json
优先从模型文件所在目录的 model_data 子目录查找,
这与 UVR GUI 的行为一致。
"""
paths_to_try = [json_path] if json_path else []
# 如果提供了模型路径,从模型目录派生 model_data.json 路径
if model_path:
model_dir = os.path.dirname(model_path)
paths_to_try.append(os.path.join(model_dir, 'model_data', 'model_data.json'))
# 添加默认路径
paths_to_try.extend([
DEFAULT_MODEL_DATA_JSON,
os.path.join(os.path.dirname(sys.executable), 'models', 'MDX_Net_Models', 'model_data', 'model_data.json'),
# UVR 常见安装路径
os.path.join(os.path.expanduser('~'), 'AppData', 'Local', 'Programs',
'Ultimate Vocal Remover', 'models', 'MDX_Net_Models', 'model_data', 'model_data.json'),
])
for path in paths_to_try:
if path and os.path.isfile(path):
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f), path
except Exception as e:
print(f"Warning: Cannot load {path}: {e}")
return {}, None
def find_mdx_c_config_path(config_yaml, model_path=None):
"""
查找 MDX-C 配置文件
优先从模型文件所在目录的 model_data/mdx_c_configs 子目录查找,
这与 UVR GUI 的行为一致。
"""
paths_to_try = []
# 如果提供了模型路径,从模型目录派生配置路径
if model_path:
model_dir = os.path.dirname(model_path)
paths_to_try.append(os.path.join(model_dir, 'model_data', 'mdx_c_configs', config_yaml))
paths_to_try.extend([
os.path.join(DEFAULT_MDX_C_CONFIG_PATH, config_yaml),
os.path.join(os.path.dirname(sys.executable), 'models', 'MDX_Net_Models', 'model_data', 'mdx_c_configs', config_yaml),
# UVR 常见安装路径
os.path.join(os.path.expanduser('~'), 'AppData', 'Local', 'Programs',
'Ultimate Vocal Remover', 'models', 'MDX_Net_Models', 'model_data', 'mdx_c_configs', config_yaml),
])
for path in paths_to_try:
if os.path.isfile(path):
return path
return None
def create_model_data(model_path, **kwargs):
"""
创建完全兼容 UVR 的 ModelData 对象
Args:
model_path: 模型文件路径 (.ckpt 或 .onnx)
**kwargs: 可选参数覆盖
Returns:
SimpleNamespace: 包含所有必需属性的对象
"""
verbose = kwargs.get('verbose', False)
model_json_path = kwargs.get('model_json_path')
model_data = SimpleNamespace()
# ========== 基本信息 ==========
model_data.model_path = model_path
model_data.model_name = os.path.splitext(os.path.basename(model_path))[0]
model_data.model_basename = model_data.model_name
model_data.process_method = MDX_ARCH_TYPE
model_data.is_mdx_ckpt = model_path.endswith('.ckpt')
model_data.is_mdx_c = False
model_data.is_roformer = False # Roformer support
model_data.is_target_instrument = False # MDX-C target instrument mode
model_data.mdx_c_configs = None
model_data.mdx_model_stems = []
model_data.mdx_stem_count = 1
# ========== 设备设置 ==========
use_gpu = kwargs.get('use_gpu', cuda_available)
model_data.is_gpu_conversion = 0 if use_gpu else -1
model_data.device_set = kwargs.get('device_set', '0')
model_data.is_use_opencl = False
model_data.is_use_directml = kwargs.get('is_use_directml', False) # For AMD GPUs
# ========== 处理参数 ==========
model_data.mdx_segment_size = kwargs.get('mdx_segment_size', 256)
model_data.overlap_mdx = kwargs.get('overlap_mdx', 0.25)
model_data.overlap_mdx23 = kwargs.get('overlap_mdx23', 2) # GUI 默认是 2
model_data.mdx_batch_size = kwargs.get('mdx_batch_size', 1)
model_data.margin = kwargs.get('margin', 0)
model_data.chunks = kwargs.get('chunks', 0)
model_data.overlap = 0.25
# ========== 输出设置 ==========
model_data.wav_type_set = kwargs.get('wav_type_set', 'PCM_24') # 默认 24-bit
model_data.save_format = kwargs.get('save_format', 'WAV')
model_data.mp3_bit_set = kwargs.get('mp3_bit_set', None)
model_data.is_normalization = kwargs.get('is_normalization', True)
# ========== 输出控制 ==========
primary_only = kwargs.get('primary_only', False)
secondary_only = kwargs.get('secondary_only', False)
# Alias 支持
if kwargs.get('dry_only', False) or kwargs.get('vocals_only', False):
primary_only = True
if kwargs.get('no_dry_only', False) or kwargs.get('instrumental_only', False):
secondary_only = True
if primary_only and secondary_only:
secondary_only = False
if verbose:
print("Warning: Both primary-only and secondary-only specified, using primary-only")
model_data.is_primary_stem_only = primary_only
model_data.is_secondary_stem_only = secondary_only
# ========== 二级模型和预处理 ==========
model_data.is_secondary_model_activated = False
model_data.is_secondary_model = False
model_data.secondary_model = None
model_data.secondary_model_scale = None
model_data.primary_model_primary_stem = None
model_data.is_pre_proc_model = False
model_data.is_primary_model_primary_stem_only = False
model_data.is_primary_model_secondary_stem_only = False
# ========== Vocal Split ==========
model_data.vocal_split_model = None
model_data.is_vocal_split_model = False
model_data.is_save_inst_vocal_splitter = False
model_data.is_inst_only_voc_splitter = False
model_data.is_save_vocal_only = False
# ========== Denoise/Deverb ==========
model_data.is_denoise = kwargs.get('is_denoise', False)
model_data.is_denoise_model = kwargs.get('is_denoise_model', False)
model_data.DENOISER_MODEL = kwargs.get('denoiser_model', None)
model_data.DEVERBER_MODEL = kwargs.get('deverber_model', None)
model_data.is_deverb_vocals = False
model_data.deverb_vocal_opt = None
# ========== Pitch ==========
model_data.is_pitch_change = False
model_data.semitone_shift = 0.0
model_data.is_match_frequency_pitch = False
# ========== Ensemble ==========
model_data.is_ensemble_mode = False
model_data.ensemble_primary_stem = None
model_data.ensemble_secondary_stem = None
model_data.is_multi_stem_ensemble = False
model_data.is_4_stem_ensemble = False
# ========== 其他标志 ==========
model_data.mixer_path = None
model_data.model_samplerate = 44100
model_data.model_capacity = (32, 128)
model_data.is_vr_51_model = False
model_data.mdxnet_stem_select = kwargs.get('mdxnet_stem_select', ALL_STEMS)
model_data.is_mdx_combine_stems = kwargs.get('is_mdx_combine_stems', False)
model_data.is_invert_spec = kwargs.get('is_invert_spec', False)
model_data.is_mixer_mode = False
model_data.is_karaoke = False
model_data.is_bv_model = False
model_data.bv_model_rebalance = 0
model_data.is_sec_bv_rebalance = False
model_data.is_demucs_pre_proc_model_inst_mix = False
model_data.is_mdx_c_seg_def = kwargs.get('is_mdx_c_seg_def', True)
# MDX 参数默认值(可能被后续加载覆盖)
model_data.compensate = kwargs.get('compensate', 1.035)
model_data.mdx_dim_f_set = kwargs.get('mdx_dim_f_set', 3072)
model_data.mdx_dim_t_set = kwargs.get('mdx_dim_t_set', 8)
model_data.mdx_n_fft_scale_set = kwargs.get('mdx_n_fft_scale_set', 6144)
model_data.primary_stem = None
model_data.primary_stem_native = None
model_data.secondary_stem = None
# ========== 加载模型参数 ==========
_load_model_config(model_data, model_path, **kwargs)
return model_data
# ============================================================================
# IMPORTANT:
# This logic MUST stay behavior-identical to UVR GUI.
# Do NOT refactor, "optimize", or reinterpret unless UVR itself changes.
# ============================================================================
def _load_model_config(model_data, model_path, **kwargs):
"""
加载模型配置 - 完全复制 UVR GUI 的 pop_up_mdx_model() 行为
回退链(与 GUI 完全一致):
1. 用户提供的配置文件(--json)
2. 哈希查找(model_data.json + hash_mapper)
3. 从模型文件自动检测(.ckpt → hyper_parameters / .onnx → tensor shape)
4. CLI 参数覆盖
5. UVR GUI 默认值
"""
verbose = kwargs.get('verbose', False)
model_json_path = kwargs.get('model_json_path')
# 计算模型哈希(与 UVR.py get_model_hash() 完全一致)
model_hash = get_model_hash(model_path)
if verbose and model_hash:
print(f"Model hash: {model_hash}")
# ========== 步骤 1: 用户提供的配置文件(--json)==========
if model_json_path and os.path.isfile(model_json_path):
try:
if model_json_path.endswith('.yaml') or model_json_path.endswith('.yml'):
# YAML 配置(MDX-C/Roformer 模型)
with open(model_json_path, 'r', encoding='utf-8') as f:
yaml_config = yaml.load(f, Loader=yaml.FullLoader)
model_data.is_mdx_c = True
model_data.is_mdx_ckpt = False
model_data.mdx_c_configs = ConfigDict(yaml_config)
if verbose:
print(f"Loaded config from YAML: {model_json_path}")
training = model_data.mdx_c_configs.get('training', {})
if training.get('target_instrument'):
target = training['target_instrument']
model_data.mdx_model_stems = [target]
model_data.primary_stem = target
else:
instruments = training.get('instruments', ['Vocals', 'Instrumental'])
model_data.mdx_model_stems = instruments
model_data.mdx_stem_count = len(instruments)
model_data.primary_stem = instruments[0] if instruments else VOCAL_STEM
model_data.primary_stem_native = model_data.primary_stem
model_data.secondary_stem = secondary_stem(model_data.primary_stem)
return
else:
# JSON 配置
with open(model_json_path, 'r', encoding='utf-8') as f:
config = json.load(f)
if verbose:
print(f"Loaded config from JSON: {model_json_path}")
_apply_config(model_data, config, kwargs, verbose, model_path)
return
except Exception as e:
print(f"Warning: Cannot load from config file: {e}")
# ========== 步骤 2: 哈希查找(与 UVR get_model_data() 一致)==========
# 2a: 首先检查单独的 {hash}.json 文件(UVR.py 第 741-744 行)
if model_hash:
model_dir = os.path.dirname(model_path)
hash_json_paths = [
os.path.join(model_dir, 'model_data', f'{model_hash}.json'),
os.path.join(os.path.expanduser('~'), 'AppData', 'Local', 'Programs',
'Ultimate Vocal Remover', 'models', 'MDX_Net_Models', 'model_data', f'{model_hash}.json'),
]
for hash_json_path in hash_json_paths:
if os.path.isfile(hash_json_path):
try:
with open(hash_json_path, 'r', encoding='utf-8') as f:
config = json.load(f)
if verbose:
print(f"Loaded config from hash JSON: {os.path.basename(hash_json_path)}")
_apply_config(model_data, config, kwargs, verbose, model_path)
return
except Exception as e:
print(f"Warning: Cannot load {hash_json_path}: {e}")
# 2b: 检查 model_data.json 中的哈希映射
model_data_db, db_path = load_model_data_json(model_path=model_path)
if model_hash and model_hash in model_data_db:
config = model_data_db[model_hash]
if verbose:
print(f"Loaded config from model_data.json (hash: {model_hash[:8]}...)")
_apply_config(model_data, config, kwargs, verbose, model_path)
return
# ========== 步骤 3: 从模型文件自动检测(pop_up_mdx_model 的核心逻辑)==========
auto_detected = _auto_detect_from_model_file(model_data, model_path, kwargs, verbose)
if auto_detected:
return
# ========== 步骤 4: 使用 CLI 参数和 UVR GUI 默认值 ==========
if verbose:
print("Using CLI arguments + UVR GUI defaults")
# 使用 CLI 参数覆盖,否则使用 UVR GUI 的默认值
model_data.mdx_dim_f_set = kwargs.get('mdx_dim_f_set', 3072)
model_data.mdx_dim_t_set = kwargs.get('mdx_dim_t_set', 8)
model_data.mdx_n_fft_scale_set = kwargs.get('mdx_n_fft_scale_set', 6144)
model_data.compensate = kwargs.get('compensate', 1.035)
model_data.primary_stem = kwargs.get('primary_stem', VOCAL_STEM)
model_data.primary_stem_native = model_data.primary_stem
model_data.secondary_stem = secondary_stem(model_data.primary_stem)
def _auto_detect_from_model_file(model_data, model_path, kwargs, verbose=False):
"""
从模型文件自动检测参数 - 完全复制 UVR pop_up_mdx_model() 逻辑
.ckpt: 加载 hyper_parameters 获取 dim_f, dim_t, n_fft, target_name
.onnx: 从 tensor shape 推断 dim_f, dim_t,n_fft 使用默认值 6144
返回 True 表示成功检测,False 表示需要回退到默认值
"""
is_ckpt = model_path.endswith('.ckpt')
is_onnx = model_path.endswith('.onnx')
if is_ckpt:
# ===== .ckpt 模型: 与 pop_up_mdx_model() 第 4615-4626 行完全一致 =====
try:
checkpoint = torch.load(model_path, map_location=lambda storage, loc: storage)
if 'hyper_parameters' not in checkpoint:
# 没有 hyper_parameters,可能是 MDX-C 模型
if verbose:
print("Detected .ckpt without hyper_parameters, may need YAML config")
return False
params = checkpoint['hyper_parameters']
if verbose:
print("Auto-detected parameters from checkpoint hyper_parameters")
# 与 UVR 完全一致的参数提取
model_data.mdx_dim_f_set = params.get('dim_f', 3072)
# dim_t: UVR 使用 int(math.log(model_params['dim_t'], 2))
dim_t_raw = params.get('dim_t', 256)
model_data.mdx_dim_t_set = int(math.log(dim_t_raw, 2)) if dim_t_raw > 0 else 8
model_data.mdx_n_fft_scale_set = params.get('n_fft', 6144)
# 允许 CLI 参数覆盖 compensate
model_data.compensate = kwargs.get('compensate', 1.035)
# 与 UVR 第 4623-4625 行完全一致: 从 target_name 推断 primary_stem
target_name = params.get('target_name', '').lower()
primary_stem = VOCAL_STEM # 默认值
# STEM_SET_MENU 的检查(简化版,覆盖常见情况)
stem_mapping = {
'vocals': VOCAL_STEM,
'instrumental': INST_STEM,
'drums': DRUM_STEM,
'bass': BASS_STEM,
'other': INST_STEM, # UVR: "INST_STEM if model_params['target_name'] == OTHER_STEM.lower() else stem"
}
for key, stem in stem_mapping.items():
if key in target_name:
primary_stem = stem
break
# 允许 CLI 参数覆盖 primary_stem
model_data.primary_stem = kwargs.get('primary_stem', primary_stem)
model_data.primary_stem_native = model_data.primary_stem
model_data.secondary_stem = secondary_stem(model_data.primary_stem)
if verbose:
print(f" dim_f={model_data.mdx_dim_f_set}, dim_t={2**model_data.mdx_dim_t_set}, "
f"n_fft={model_data.mdx_n_fft_scale_set}, primary_stem={model_data.primary_stem}")
return True
except Exception as e:
if verbose:
print(f"Warning: Cannot auto-detect from checkpoint: {e}")
return False
elif is_onnx:
# ===== .onnx 模型: 与 pop_up_mdx_model() 第 4608-4613 行完全一致 =====
try:
import onnx
model = onnx.load(model_path)
# 与 UVR 完全一致: 从输入 tensor shape 获取 dim_f, dim_t
model_shapes = [[d.dim_value for d in _input.type.tensor_type.shape.dim]
for _input in model.graph.input][0]
dim_f = model_shapes[2]
dim_t = int(math.log(model_shapes[3], 2))
n_fft = 6144 # UVR 对 ONNX 使用硬编码默认值 '6144'
if verbose:
print("Auto-detected parameters from ONNX tensor shape")
model_data.mdx_dim_f_set = dim_f
model_data.mdx_dim_t_set = dim_t
model_data.mdx_n_fft_scale_set = kwargs.get('mdx_n_fft_scale_set', n_fft)
model_data.compensate = kwargs.get('compensate', 1.035)
# ONNX 无法从模型推断 primary_stem,使用 CLI 参数或默认值
model_data.primary_stem = kwargs.get('primary_stem', VOCAL_STEM)
model_data.primary_stem_native = model_data.primary_stem
model_data.secondary_stem = secondary_stem(model_data.primary_stem)
if verbose:
print(f" dim_f={dim_f}, dim_t={2**dim_t}, n_fft={n_fft}, primary_stem={model_data.primary_stem}")
return True
except ImportError:
if verbose:
print("Warning: onnx package not installed, cannot auto-detect ONNX model parameters")
return False
except Exception as e:
if verbose:
print(f"Warning: Cannot auto-detect from ONNX: {e}")
return False
return False
def _apply_config(model_data, config, kwargs, verbose=False, model_path=None):
"""应用配置到 model_data"""
# 检查是否是 MDX-C / Roformer 模型
if 'config_yaml' in config:
model_data.is_mdx_c = True
config_yaml = config['config_yaml']
config_path = find_mdx_c_config_path(config_yaml, model_path)
if config_path and os.path.isfile(config_path):
with open(config_path, 'r') as f:
# 使用 FullLoader 与 UVR.py 保持一致(支持 !!python/tuple 等标签)
yaml_config = yaml.load(f, Loader=yaml.FullLoader)
model_data.mdx_c_configs = ConfigDict(yaml_config)
if verbose:
print(f"Loaded MDX-C config: {config_yaml}")
# 从 training 配置获取 stems
training = model_data.mdx_c_configs.get('training', {})
if training.get('target_instrument'):
target = training['target_instrument']
model_data.mdx_model_stems = [target]
model_data.primary_stem = target
model_data.is_target_instrument = True # UVR.py line 553
else:
instruments = training.get('instruments', ['Vocals', 'Instrumental'])
model_data.mdx_model_stems = instruments
model_data.mdx_stem_count = len(instruments)
model_data.primary_stem = instruments[0] if instruments else VOCAL_STEM
model_data.primary_stem_native = model_data.primary_stem
model_data.secondary_stem = secondary_stem(model_data.primary_stem)
# 检查并设置是否是 Roformer 模型
# 首先尝试从配置文件读取
model_data.is_roformer = config.get('is_roformer', False)
# 自动检测:如果 YAML 中有特定参数,则是 Roformer/SCNet 模型
# 这与 separate.py 中的判断逻辑一致
model_config = model_data.mdx_c_configs.get('model', {})
if 'num_bands' in model_config or 'freqs_per_bands' in model_config:
model_data.is_roformer = True
if verbose and not config.get('is_roformer', False):
print("Auto-detected as Roformer model (based on YAML config)")
elif 'band_SR' in model_config or 'sources' in model_config:
# SCNet model detection
model_data.is_roformer = True # SCNet 也使用 is_roformer=True 的处理路径
if verbose:
print("Auto-detected as SCNet model (based on YAML config)")
if model_data.is_roformer:
if verbose:
model_type = config.get('model_type', 'Roformer')
print(f"Model type: {model_type}")
else:
print(f"Warning: Config file not found: {config_yaml}")
model_data.is_mdx_c = False
else:
# 标准 MDX-Net 模型
model_data.mdx_dim_f_set = config.get('mdx_dim_f_set', 3072)
model_data.mdx_dim_t_set = config.get('mdx_dim_t_set', 8)
model_data.mdx_n_fft_scale_set = config.get('mdx_n_fft_scale_set', 6144)
model_data.compensate = config.get('compensate', kwargs.get('compensate', 1.035))
model_data.primary_stem = config.get('primary_stem', VOCAL_STEM)
model_data.primary_stem_native = model_data.primary_stem
model_data.secondary_stem = secondary_stem(model_data.primary_stem)
model_data.is_karaoke = config.get('is_karaoke', False)
def create_process_data(audio_file, export_path, audio_file_base=None,
progress_manager: ProgressManager = None, **kwargs):
"""
创建 process_data 字典
Args:
audio_file: 输入音频文件路径
export_path: 输出目录路径
audio_file_base: 输出文件基名
progress_manager: 进度管理器实例(可选)
**kwargs: 其他参数
"""
if audio_file_base is None:
audio_file_base = os.path.splitext(os.path.basename(audio_file))[0]
verbose = kwargs.get('verbose', False)
# 如果提供了 progress_manager,使用它创建回调
if progress_manager is not None:
callbacks = create_progress_callbacks(progress_manager, total_iterations=100)
set_progress_bar = callbacks['set_progress_bar']
write_to_console = callbacks['write_to_console']
process_iteration = callbacks['process_iteration']
else:
# 无进度管理器时使用简单的回调
def set_progress_bar(step=0, inference_iterations=0):
pass
def write_to_console(progress_text='', base_text=''):
if verbose:
msg = f"{base_text}{progress_text}".strip()
if msg:
print(msg)
def process_iteration():
pass
def noop_cache_callback(process_method, model_name=None):
return (None, None)
def noop_cache_holder(process_method, sources, model_name):
pass
return {
'model_data': None,
'export_path': export_path,
'audio_file_base': audio_file_base,
'audio_file': audio_file,
'set_progress_bar': set_progress_bar,
'write_to_console': write_to_console,
'process_iteration': process_iteration,
'cached_source_callback': noop_cache_callback,
'cached_model_source_holder': noop_cache_holder,
'list_all_models': [],
'is_ensemble_master': False,
'is_4_stem_ensemble': False
}
def run_mdx_headless(
model_path,
audio_file,
export_path,
audio_file_base=None,
use_gpu=None,
device_set='0',
is_use_directml=False,
mdx_segment_size=256,
overlap_mdx=0.25,
overlap_mdx23=2,
mdx_batch_size=1,
wav_type_set='PCM_24',
model_json_path=None,
primary_only=False,
secondary_only=False,
dry_only=False,
no_dry_only=False,
vocals_only=False,
instrumental_only=False,
stem=None,
verbose=True,
progress_manager: ProgressManager = None,
**kwargs
):
"""
Headless MDX-Net 运行器主函数
直接使用 UVR 原有的 SeperateMDX 和 SeperateMDXC 类
Args:
model_path: 模型文件路径或模型名称(支持自动下载)
audio_file: 输入音频文件路径
export_path: 输出目录路径
progress_manager: 进度管理器实例(可选)
...
"""
start_time = time.time()
# 如果没有提供 progress_manager,创建一个默认的
pm = progress_manager or ProgressManager(verbose=verbose)
pm.set_file_name(os.path.basename(audio_file))
# 解析模型路径(支持模型名称和自动下载)
pm.start_stage(ProgressStage.INITIALIZING, "Resolving model path")
# Create download progress callback from progress manager
from progress import create_download_progress_callback
download_callback = create_download_progress_callback(pm)
resolved_model_path = resolve_model_path(model_path, verbose=False, progress_callback=download_callback)
pm.set_model_name(os.path.basename(resolved_model_path))
pm.finish_stage("Model path resolved")
# 验证输入
if not os.path.isfile(audio_file):
raise FileNotFoundError(f"Audio file not found: {audio_file}")
if not os.path.isdir(export_path):
os.makedirs(export_path, exist_ok=True)
# 处理 stem 参数
mdxnet_stem_select = ALL_STEMS
if stem:
stem_map = {
'all': ALL_STEMS,
'vocals': VOCAL_STEM,
'drums': DRUM_STEM,
'bass': BASS_STEM,
'other': OTHER_STEM
}
stem_lower = stem.lower()
if stem_lower not in stem_map:
raise ValueError(f"Invalid stem: {stem}")
mdxnet_stem_select = stem_map[stem_lower]
# 转换 wav_type 名称为 soundfile 格式
wav_type_map = {
'PCM_U8': 'PCM_U8',
'PCM_16': 'PCM_16',
'PCM_24': 'PCM_24',
'PCM_32': 'PCM_32',
'FLOAT': 'FLOAT',
'DOUBLE': 'DOUBLE',
'32-bit Float': 'FLOAT',
'64-bit Float': 'DOUBLE'
}
wav_type = wav_type_map.get(wav_type_set, 'PCM_24')