"""Tests for model discovery and PTH/Index pairing.""" import json from pathlib import Path def _make_pth(dir: Path, name: str, size: int = 1000000) -> Path: p = dir / f"{name}.pth" p.write_bytes(b"x" * min(size, 100)) # Small for tests return p def _make_index(dir: Path, name: str, size: int = 50000) -> Path: p = dir / f"{name}.index" p.write_bytes(b"x" * min(size, 100)) return p def test_discover_empty_dir(tmp_dirs): from app.services.models import discover_models models = discover_models(tmp_dirs["models"]) assert models == [] def test_discover_pth_only(tmp_dirs): from app.services.models import discover_models _make_pth(tmp_dirs["models"], "TestModel") models = discover_models(tmp_dirs["models"]) assert len(models) == 1 assert models[0].name == "TestModel" assert models[0].status == "Index fehlt" assert models[0].pth_path is not None assert models[0].index_path is None def test_discover_index_only(tmp_dirs): from app.services.models import discover_models _make_index(tmp_dirs["models"], "TestModel") models = discover_models(tmp_dirs["models"]) assert len(models) == 1 assert models[0].name == "TestModel" assert models[0].status == "PTH-Datei fehlt" def test_discover_paired(tmp_dirs): from app.services.models import discover_models _make_pth(tmp_dirs["models"], "TestModel") _make_index(tmp_dirs["models"], "TestModel") models = discover_models(tmp_dirs["models"]) assert len(models) == 1 assert models[0].name == "TestModel" assert models[0].status == "einsatzbereit" assert models[0].pth_path is not None assert models[0].index_path is not None def test_discover_reads_sample_rate_from_training_config(tmp_dirs): from app.services.models import discover_models model_dir = tmp_dirs["models"] / "Anna" model_dir.mkdir() _make_pth(model_dir, "Anna_20e_100s") _make_index(model_dir, "Anna") (model_dir / "config.json").write_text( json.dumps({"data": {"sample_rate": 48000}}), encoding="utf-8" ) model = next(m for m in discover_models(tmp_dirs["models"]) if m.pth_path) assert model.sample_rate == 48000 def test_discover_multiple_models(tmp_dirs): from app.services.models import discover_models _make_pth(tmp_dirs["models"], "ModelA") _make_index(tmp_dirs["models"], "ModelA") _make_pth(tmp_dirs["models"], "ModelB") models = discover_models(tmp_dirs["models"]) assert len(models) == 2 names = {m.name for m in models} assert names == {"ModelA", "ModelB"} def test_skip_pretrained_dirs(tmp_dirs): from app.services.models import discover_models pretrained = tmp_dirs["models"] / "pretraineds" / "hifi-gan" pretrained.mkdir(parents=True) _make_pth(pretrained, "f0G40k") models = discover_models(tmp_dirs["models"]) assert len(models) == 0 def test_elevenlabs_anna_preset(tmp_dirs): from app.services.models import discover_models _make_pth(tmp_dirs["models"], "Elevenlabs-Anna") _make_index(tmp_dirs["models"], "Elevenlabs-Anna") models = discover_models(tmp_dirs["models"]) anna = next(m for m in models if m.name == "Elevenlabs-Anna") assert anna.recommended_pitch == 15 assert "Pitch" in anna.notes def test_models_without_index(tmp_dirs): from app.services.models import models_without_index _make_pth(tmp_dirs["models"], "NoIndex") _make_pth(tmp_dirs["models"], "WithIndex") _make_index(tmp_dirs["models"], "WithIndex") result = models_without_index(tmp_dirs["models"]) assert len(result) == 1 assert result[0].name == "NoIndex" def test_get_model(tmp_dirs): from app.services.models import get_model _make_pth(tmp_dirs["models"], "FindMe") _make_index(tmp_dirs["models"], "FindMe") model = get_model("FindMe", tmp_dirs["models"]) assert model is not None assert model.name == "FindMe" assert get_model("NonExistent", tmp_dirs["models"]) is None def test_model_to_dict(tmp_dirs): from app.services.models import discover_models _make_pth(tmp_dirs["models"], "DictTest") _make_index(tmp_dirs["models"], "DictTest") models = discover_models(tmp_dirs["models"]) d = models[0].to_dict() assert "name" in d assert "pth_path" in d assert "index_path" in d assert "status" in d assert "recommended_pitch" in d assert "conversion_preset" in d def test_save_and_delete_model_conversion_preset_preserves_metadata(tmp_dirs): from app.services.models import ( delete_model_conversion_preset, save_model_conversion_preset, ) pth = _make_pth(tmp_dirs["models"], "Wayne Steele") _make_index(tmp_dirs["models"], "Wayne Steele") pth.with_suffix(".meta.json").write_text( json.dumps({"recommended_pitch": 0, "notes": "Testnotiz"}), encoding="utf-8", ) preset = { "pitch": 0, "f0_method": "rmvpe", "index_rate": 0.45, "protect": 0.2, "volume_envelope": 1.0, "export_format": "FLAC", "f0_autotune": False, "split_audio": False, } saved = save_model_conversion_preset("Wayne Steele", preset, tmp_dirs["models"]) assert saved.conversion_preset == preset assert saved.notes == "Testnotiz" deleted = delete_model_conversion_preset("Wayne Steele", tmp_dirs["models"]) assert deleted.conversion_preset is None assert deleted.notes == "Testnotiz" metadata = json.loads(pth.with_suffix(".meta.json").read_text(encoding="utf-8")) assert "conversion_preset" not in metadata def test_ambiguous_index_candidates(tmp_dirs): """When multiple index files could match, report candidates.""" from app.services.models import discover_models _make_pth(tmp_dirs["models"], "MyVoice") _make_index(tmp_dirs["models"], "MyVoice_v1") _make_index(tmp_dirs["models"], "MyVoice_v2") models = discover_models(tmp_dirs["models"]) myvoice = next(m for m in models if m.name == "MyVoice") assert myvoice.status == "mehrere Indizes gefunden" assert len(myvoice.candidates) >= 1 def test_unique_index_candidate_is_paired(tmp_dirs): """Epoch-suffixed inference PTHs use the model's one unambiguous index.""" from app.services.models import discover_models _make_pth(tmp_dirs["models"], "Elevenlabs-Anna_200e_8200s") expected = _make_index(tmp_dirs["models"], "Elevenlabs-Anna") models = discover_models(tmp_dirs["models"]) epoch = next(m for m in models if m.name.endswith("200e_8200s")) assert epoch.status == "einsatzbereit" assert epoch.index_path == str(expected) assert epoch.recommended_pitch == 15 assert all(model.name != "Elevenlabs-Anna" for model in models) def test_elevenlabs_preset_matching_is_case_insensitive(tmp_dirs): from app.services.models import discover_models _make_pth(tmp_dirs["models"], "ElevenLabs-Anna-Dataset_20e_100s") _make_index(tmp_dirs["models"], "ElevenLabs-Anna-Dataset") model = next(m for m in discover_models(tmp_dirs["models"]) if m.pth_path) assert model.recommended_pitch == 15 def test_training_checkpoints_are_not_exposed_as_models(tmp_dirs): """Large resume checkpoints must not clutter the inference-model chooser.""" from app.services.models import discover_models _make_pth(tmp_dirs["models"], "D_1234") _make_pth(tmp_dirs["models"], "G_1234") _make_pth(tmp_dirs["models"], "ReadyVoice") _make_index(tmp_dirs["models"], "ReadyVoice") assert [model.name for model in discover_models(tmp_dirs["models"])] == ["ReadyVoice"] def test_model_names_allow_human_readable_spaces(): from app.services.models import validate_model_name assert validate_model_name(" Anna Broadcast Excited Journalistic ") == "Anna Broadcast Excited Journalistic" def test_model_names_allow_human_readable_punctuation(): from app.services.models import validate_model_name assert validate_model_name("Anna – Broadcast, Excited (Journalistic)") == ( "Anna – Broadcast, Excited (Journalistic)" ) def test_model_names_reject_path_characters(): import pytest from app.services.models import validate_model_name with pytest.raises(ValueError, match="Schrägstriche"): validate_model_name("Anna/../BritishWoman") def test_rename_model_renames_pth_and_index(tmp_dirs): from app.services.models import rename_model _make_pth(tmp_dirs["models"], "Anna") _make_index(tmp_dirs["models"], "Anna") renamed = rename_model("Anna", "Anna Broadcast", tmp_dirs["models"]) assert renamed.name == "Anna Broadcast" assert (tmp_dirs["models"] / "Anna Broadcast.pth").is_file() assert (tmp_dirs["models"] / "Anna Broadcast.index").is_file() assert not (tmp_dirs["models"] / "Anna.pth").exists() assert not (tmp_dirs["models"] / "Anna.index").exists() def test_finalize_training_selects_one_checkpoint_and_removes_rest(tmp_dirs): from app.services.models import finalize_training_model run = tmp_dirs["models"] / "Anna-Training" run.mkdir() _make_pth(run, "Anna-Training_20e_100s") _make_pth(run, "Anna-Training_40e_200s") _make_pth(run, "D_200") _make_pth(run, "G_200") _make_index(run, "Anna-Training") model, deleted = finalize_training_model( "Anna-Training", "Anna-Training_40e_200s", "Anna Broadcast Excited Journalistic", models_dir=tmp_dirs["models"], ) assert model.name == "Anna Broadcast Excited Journalistic" assert model.status == "einsatzbereit" assert (run / "Anna Broadcast Excited Journalistic.pth").is_file() assert (run / "Anna Broadcast Excited Journalistic.index").is_file() assert not list(run.glob("Anna-Training_*.pth")) assert not list(run.glob("D_*.pth")) assert not list(run.glob("G_*.pth")) assert "Anna-Training_20e_100s.pth" in deleted def test_finalize_training_can_keep_other_and_resume_checkpoints(tmp_dirs): from app.services.models import finalize_training_model run = tmp_dirs["models"] / "Anna-Training" run.mkdir() _make_pth(run, "Anna-Training_20e_100s") _make_pth(run, "Anna-Training_40e_200s") _make_pth(run, "D_200") _make_index(run, "Anna-Training") model, deleted = finalize_training_model( "Anna-Training", "Anna-Training_40e_200s", "Anna Final", delete_other_checkpoints=False, delete_training_checkpoints=False, models_dir=tmp_dirs["models"], ) assert model.status == "einsatzbereit" assert deleted == [] assert (run / "Anna-Training_20e_100s.pth").is_file() assert (run / "D_200.pth").is_file() assert (run / "Anna-Training.index").is_file() def test_finalize_training_can_use_run_name_as_final_model_name(tmp_dirs): """The run's index is not a collision when the final name stays unchanged.""" from app.services.models import finalize_training_model run = tmp_dirs["models"] / "Wayne Steele" run.mkdir() _make_pth(run, "Wayne Steele_120e_4920s") _make_pth(run, "Wayne Steele_140e_5740s") _make_index(run, "Wayne Steele") model, deleted = finalize_training_model( "Wayne Steele", "Wayne Steele_140e_5740s", "Wayne Steele", models_dir=tmp_dirs["models"], ) assert model.name == "Wayne Steele" assert model.status == "einsatzbereit" assert (run / "Wayne Steele.pth").is_file() assert (run / "Wayne Steele.index").is_file() assert not list(run.glob("Wayne Steele_*e_*s.pth")) assert "Wayne Steele_120e_4920s.pth" in deleted def test_finalize_api_and_rename_api(client, tmp_dirs): run = tmp_dirs["models"] / "Anna-Training" run.mkdir() _make_pth(run, "Anna-Training_20e_100s") _make_index(run, "Anna-Training") response = client.post("/api/models/finalize", json={ "source_model_name": "Anna-Training", "checkpoint_name": "Anna-Training_20e_100s", "final_model_name": "Anna Broadcast", "delete_other_checkpoints": True, "delete_training_checkpoints": True, }) assert response.status_code == 200 assert response.json()["model"]["name"] == "Anna Broadcast" response = client.patch("/api/models/Anna%20Broadcast", json={"new_name": "Anna Journalistic"}) assert response.status_code == 200 assert response.json()["model"]["name"] == "Anna Journalistic" def test_model_conversion_preset_api(client, tmp_dirs): _make_pth(tmp_dirs["models"], "Wayne Steele") _make_index(tmp_dirs["models"], "Wayne Steele") payload = { "pitch": 0, "f0_method": "rmvpe", "index_rate": 0.45, "protect": 0.2, "volume_envelope": 1.0, "export_format": "FLAC", "f0_autotune": False, "split_audio": False, } response = client.put("/api/models/Wayne%20Steele/conversion-preset", json=payload) assert response.status_code == 200 assert response.json()["model"]["conversion_preset"] == payload response = client.delete("/api/models/Wayne%20Steele/conversion-preset") assert response.status_code == 200 assert response.json()["model"]["conversion_preset"] is None def test_model_changes_are_blocked_during_active_job(client, tmp_dirs): from app.jobs.enums import JobType from app.jobs.models import Job _make_pth(tmp_dirs["models"], "Anna") _make_index(tmp_dirs["models"], "Anna") active = Job(type=JobType.CONVERT, model_name="Anna") active.mark_running() with client.app.state.job_queue._lock: client.app.state.job_queue._running[active.id] = active try: response = client.patch("/api/models/Anna", json={"new_name": "Anna Neu"}) assert response.status_code == 409 assert (tmp_dirs["models"] / "Anna.pth").is_file() finally: with client.app.state.job_queue._lock: client.app.state.job_queue._running.pop(active.id, None)