"""Model discovery and PTH/Index pairing logic.""" from __future__ import annotations import json import re import shutil from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import Any from ..config import get_settings @dataclass class ModelInfo: name: str pth_path: str | None = None index_path: str | None = None pth_size: int = 0 index_size: int = 0 modified_at: datetime | None = None sample_rate: int | None = None recommended_pitch: int | None = None notes: str = "" conversion_preset: dict[str, Any] | None = None status: str = "einsatzbereit" candidates: list[str] = field(default_factory=list) def to_dict(self) -> dict[str, Any]: return { "name": self.name, "pth_path": self.pth_path, "index_path": self.index_path, "pth_size": self.pth_size, "index_size": self.index_size, "modified_at": self.modified_at.isoformat() if self.modified_at else None, "sample_rate": self.sample_rate, "recommended_pitch": self.recommended_pitch, "notes": self.notes, "conversion_preset": self.conversion_preset, "status": self.status, "candidates": self.candidates, } # Known model presets (editable by user) MODEL_PRESETS: dict[str, dict[str, Any]] = { "Elevenlabs-Anna": { "recommended_pitch": 15, "notes": "Empfohlener Pitch: +15 Halbtöne", }, } def discover_models(models_dir: Path | None = None) -> list[ModelInfo]: """Scan the models directory for .pth and .index files and pair them.""" settings = get_settings() base_dir = models_dir or settings.models_dir if not base_dir.exists(): return [] # Find all .pth and .index files (excluding pretraineds, embedders, predictors) pth_files: dict[str, Path] = {} index_files: dict[str, Path] = {} skip_dirs = {"pretraineds", "embedders", "predictors", "formant"} for p in base_dir.rglob("*.pth"): # Skip files in excluded directories rel = p.relative_to(base_dir) if any(part in skip_dirs for part in rel.parts[:-1]): continue name = p.stem # D_/G_ files are resumable training checkpoints, not inference models. if name.startswith(("D_", "G_")): continue pth_files[name] = p for p in base_dir.rglob("*.index"): rel = p.relative_to(base_dir) if any(part in skip_dirs for part in rel.parts[:-1]): continue name = p.stem index_files[name] = p # Index files used by epoch-suffixed inference checkpoints are not separate # models. Suppress their otherwise confusing "PTH-Datei fehlt" ghost card. paired_index_names: set[str] = set() for pth_name in pth_files: if pth_name in index_files: paired_index_names.add(pth_name) continue candidates = _find_index_candidates(pth_name, index_files) if len(candidates) == 1: paired_index_names.add(candidates[0]) # Pair models models: list[ModelInfo] = [] unpaired_indexes = set(index_files) - paired_index_names all_names = set(pth_files) | unpaired_indexes for name in sorted(all_names): pth = pth_files.get(name) index = index_files.get(name) info = ModelInfo(name=name) if pth: info.pth_path = str(pth) info.pth_size = pth.stat().st_size info.modified_at = datetime.fromtimestamp(pth.stat().st_mtime) config_path = pth.parent / "config.json" if config_path.is_file(): try: config_data = json.loads(config_path.read_text(encoding="utf-8")) info.sample_rate = int(config_data.get("data", {}).get("sample_rate")) except (OSError, ValueError, TypeError, json.JSONDecodeError): pass metadata_path = pth.with_suffix(".meta.json") if metadata_path.is_file(): try: metadata = json.loads(metadata_path.read_text(encoding="utf-8")) pitch = metadata.get("recommended_pitch") info.recommended_pitch = int(pitch) if pitch is not None else None info.notes = str(metadata.get("notes", "")) conversion_preset = metadata.get("conversion_preset") if isinstance(conversion_preset, dict): info.conversion_preset = conversion_preset except (OSError, ValueError, TypeError, json.JSONDecodeError): pass else: info.status = "PTH-Datei fehlt" if index: info.index_path = str(index) info.index_size = index.stat().st_size elif pth: # Look for candidate index files candidates = _find_index_candidates(name, index_files) if len(candidates) == 1: index = index_files[candidates[0]] info.index_path = str(index) info.index_size = index.stat().st_size elif candidates: info.status = "mehrere Indizes gefunden" info.candidates = candidates else: info.status = "Index fehlt" if not pth and not index: info.status = "nicht geprüft" # Apply preset preset = next((value for key, value in MODEL_PRESETS.items() if key.lower() == name.lower()), None) if preset is None: preset = next( (value for prefix, value in MODEL_PRESETS.items() if name.lower().startswith(prefix.lower())), None, ) if preset and info.recommended_pitch is None: info.recommended_pitch = preset.get("recommended_pitch") info.notes = preset.get("notes", "") models.append(info) return models def _find_index_candidates(model_name: str, index_files: dict[str, Path]) -> list[str]: """Find index files that might belong to a model (fuzzy matching).""" candidates = [] normalized = re.sub(r"[^a-z0-9]", "", model_name.lower()) for idx_name in index_files: idx_normalized = re.sub(r"[^a-z0-9]", "", idx_name.lower()) # Check if one is a prefix/suffix of the other or shares significant overlap if normalized in idx_normalized or idx_normalized in normalized: candidates.append(idx_name) elif len(normalized) > 4 and len(idx_normalized) > 4: # Check for common prefix of at least 4 chars common = 0 for a, b in zip(normalized, idx_normalized): if a == b: common += 1 else: break if common >= 4: candidates.append(idx_name) return candidates def get_model(name: str, models_dir: Path | None = None) -> ModelInfo | None: """Get a specific model by name.""" for m in discover_models(models_dir): if m.name == name: return m return None def models_without_index(models_dir: Path | None = None) -> list[ModelInfo]: """Return models that have a PTH but no paired index.""" return [ m for m in discover_models(models_dir) if m.pth_path and not m.index_path ] def validate_model_name(value: str) -> str: """Return a safe human-readable model name suitable for one filename.""" value = " ".join(value.strip().split()) if not value or len(value) > 120: raise ValueError("Modellname muss zwischen 1 und 120 Zeichen lang sein") # Human-readable names may contain punctuation such as commas, parentheses # or typographic dashes. Only characters that can escape/create paths or # cannot safely be represented in a filename are forbidden. if value in {".", ".."} or any( char in {"/", "\\", "\0"} or ord(char) < 32 or ord(char) == 127 for char in value ): raise ValueError( "Modellname darf keine Schrägstriche oder Steuerzeichen enthalten" ) return value def _model_root(models_dir: Path | None = None) -> Path: return (models_dir or get_settings().models_dir).resolve() def _safe_model_file(path: Path, root: Path) -> Path: resolved = path.resolve() try: resolved.relative_to(root) except ValueError as exc: raise ValueError("Modelldatei liegt außerhalb des Modellverzeichnisses") from exc return resolved def _read_model_metadata(pth: Path) -> dict[str, Any]: metadata_path = pth.with_suffix(".meta.json") if not metadata_path.is_file(): return {} try: value = json.loads(metadata_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ValueError(f"Modelldaten für '{pth.stem}' sind beschädigt") from exc if not isinstance(value, dict): raise TypeError(f"Modelldaten für '{pth.stem}' haben ein ungültiges Format") return value def _write_model_metadata(pth: Path, metadata: dict[str, Any]) -> None: metadata_path = pth.with_suffix(".meta.json") if not metadata: metadata_path.unlink(missing_ok=True) return temporary = metadata_path.with_name(f".{metadata_path.name}.tmp") temporary.write_text( json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8", ) temporary.replace(metadata_path) def save_model_conversion_preset( name: str, preset: dict[str, Any], models_dir: Path | None = None, ) -> ModelInfo: """Persist conversion defaults next to one ready-to-use model.""" name = validate_model_name(name) root = _model_root(models_dir) model = get_model(name, root) if model is None or not model.pth_path: raise FileNotFoundError(f"Modell '{name}' nicht gefunden") pth = _safe_model_file(Path(model.pth_path), root) metadata = _read_model_metadata(pth) metadata["conversion_preset"] = preset _write_model_metadata(pth, metadata) updated = get_model(name, root) if updated is None: raise RuntimeError("Gespeichertes Modell konnte nicht wiedergefunden werden") return updated def delete_model_conversion_preset( name: str, models_dir: Path | None = None, ) -> ModelInfo: """Remove only the saved conversion defaults and preserve other metadata.""" name = validate_model_name(name) root = _model_root(models_dir) model = get_model(name, root) if model is None or not model.pth_path: raise FileNotFoundError(f"Modell '{name}' nicht gefunden") pth = _safe_model_file(Path(model.pth_path), root) metadata = _read_model_metadata(pth) metadata.pop("conversion_preset", None) _write_model_metadata(pth, metadata) updated = get_model(name, root) if updated is None: raise RuntimeError("Modell konnte nicht wiedergefunden werden") return updated def rename_model(source_name: str, target_name: str, models_dir: Path | None = None) -> ModelInfo: """Rename one inference PTH and its index without breaking shared indexes.""" source_name = validate_model_name(source_name) target_name = validate_model_name(target_name) root = _model_root(models_dir) source = get_model(source_name, root) if source is None or not source.pth_path: raise FileNotFoundError(f"Modell '{source_name}' nicht gefunden") if source_name == target_name: return source if get_model(target_name, root) is not None: raise FileExistsError(f"Modell '{target_name}' existiert bereits") source_pth = _safe_model_file(Path(source.pth_path), root) target_pth = source_pth.with_name(f"{target_name}.pth") if target_pth.exists(): raise FileExistsError(f"Zieldatei '{target_pth.name}' existiert bereits") source_index = _safe_model_file(Path(source.index_path), root) if source.index_path else None source_metadata = source_pth.with_suffix(".meta.json") target_index = source_pth.with_name(f"{target_name}.index") if source_index else None if target_index and target_index.exists(): raise FileExistsError(f"Zieldatei '{target_index.name}' existiert bereits") # An epoch checkpoint may share the run's index with sibling checkpoints. index_users = [m for m in discover_models(root) if m.name != source_name and m.index_path == source.index_path] source_pth.rename(target_pth) if source_metadata.is_file(): source_metadata.rename(target_pth.with_suffix(".meta.json")) if source_index and target_index: if index_users: shutil.copy2(source_index, target_index) else: source_index.rename(target_index) renamed = get_model(target_name, root) if renamed is None: raise RuntimeError("Umbenanntes Modell konnte nicht wiedergefunden werden") return renamed def finalize_training_model( source_model_name: str, checkpoint_name: str, final_model_name: str, *, delete_other_checkpoints: bool = True, delete_training_checkpoints: bool = True, models_dir: Path | None = None, ) -> tuple[ModelInfo, list[str]]: """Promote one inference checkpoint and optionally remove the run's leftovers.""" source_model_name = validate_model_name(source_model_name) checkpoint_name = validate_model_name(checkpoint_name) final_model_name = validate_model_name(final_model_name) root = _model_root(models_dir) run_dir = _safe_model_file(root / source_model_name, root) if not run_dir.is_dir(): raise FileNotFoundError(f"Trainingslauf '{source_model_name}' nicht gefunden") checkpoint = _safe_model_file(run_dir / f"{checkpoint_name}.pth", root) if not checkpoint.is_file() or checkpoint.parent != run_dir: raise FileNotFoundError(f"Checkpoint '{checkpoint_name}' nicht gefunden") if not checkpoint.stem.startswith(f"{source_model_name}_"): raise ValueError("Der Checkpoint gehört nicht zu diesem Trainingslauf") indexes = sorted(run_dir.glob("*.index")) source_index = next((p for p in indexes if p.stem == source_model_name), None) if source_index is None and len(indexes) == 1: source_index = indexes[0] if source_index is None: raise FileNotFoundError("Kein eindeutiger Index für den Trainingslauf gefunden") source_info = get_model(checkpoint_name, root) target_pth = run_dir / f"{final_model_name}.pth" target_index = run_dir / f"{final_model_name}.index" existing_final = get_model(final_model_name, root) reuses_run_index = ( final_model_name == source_model_name and target_index.resolve() == source_index.resolve() ) existing_is_run_placeholder = ( reuses_run_index and (existing_final is None or not existing_final.pth_path) ) if existing_final is not None and not existing_is_run_placeholder: raise FileExistsError(f"Modell '{final_model_name}' existiert bereits") if target_pth.exists() or (target_index.exists() and not reuses_run_index): raise FileExistsError("Eine Zieldatei mit diesem Modellnamen existiert bereits") checkpoint.rename(target_pth) if not reuses_run_index: shutil.copy2(source_index, target_index) if source_info and (source_info.recommended_pitch is not None or source_info.notes): target_pth.with_suffix(".meta.json").write_text( json.dumps( { "recommended_pitch": source_info.recommended_pitch, "notes": source_info.notes, }, ensure_ascii=False, indent=2, ), encoding="utf-8", ) deleted: list[str] = [] if delete_other_checkpoints: for path in run_dir.glob(f"{source_model_name}_*.pth"): if path.is_file(): deleted.append(path.name) path.unlink() # The run index is no longer needed once no epoch model remains. if source_index != target_index and source_index.exists(): deleted.append(source_index.name) source_index.unlink() if delete_training_checkpoints: for pattern in ("D_*.pth", "G_*.pth"): for path in run_dir.glob(pattern): if path.is_file(): deleted.append(path.name) path.unlink() finalized = get_model(final_model_name, root) if finalized is None or not finalized.pth_path or not finalized.index_path: raise RuntimeError("Fertiges Modell konnte nicht vollständig veröffentlicht werden") return finalized, deleted