Spaces:
Sleeping
Sleeping
Download src/models/registry.py from ConsulawTechnologies/NarratifAI: direct link, hf CLI and curl.
- Browser
- Download file 6.95 kB
-
https://huggingface.co/spaces/ConsulawTechnologies/NarratifAI/resolve/main/src/models/registry.py
- Command line
-
hf download hf://spaces/ConsulawTechnologies/NarratifAI/src/models/registry.py
-
curl -L -o registry.py https://huggingface.co/spaces/ConsulawTechnologies/NarratifAI/resolve/main/src/models/registry.py
6.95 kB
| """ | |
| Model registry for dynamic model loading | |
| Author: Maaldeens | |
| License: MIT | |
| """ | |
| import torch | |
| from transformers import ( | |
| WhisperProcessor, | |
| WhisperForConditionalGeneration, | |
| pipeline | |
| ) | |
| from typing import Dict, Any, Optional, Tuple | |
| import logging | |
| import yaml | |
| from pathlib import Path | |
| import gc | |
| import os | |
| logger = logging.getLogger(__name__) | |
| class ModelRegistry: | |
| """Registry for managing ASR models with caching and device management.""" | |
| def __init__(self, config_path: Optional[str] = None): | |
| self.models = {} | |
| self.processors = {} | |
| self.pipelines = {} | |
| self.config = self._load_config(config_path) | |
| self.device = self._get_device() | |
| self.current_model = None | |
| # Respect HF_HOME env var for persistent model caching across restarts | |
| self.cache_dir = os.getenv( | |
| "HF_HOME", | |
| self.config.get("models", {}).get("cache_dir", "/app/model_cache") | |
| ) | |
| def _load_config(self, config_path: Optional[str] = None) -> Dict: | |
| if config_path and Path(config_path).exists(): | |
| with open(config_path, 'r') as f: | |
| return yaml.safe_load(f) | |
| return {"models": {"available": {}}} | |
| def _get_device(self) -> torch.device: | |
| if torch.cuda.is_available(): | |
| return torch.device("cuda") | |
| elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available(): | |
| return torch.device("mps") | |
| return torch.device("cpu") | |
| def load_model(self, model_key: str, force_reload: bool = False) -> Tuple[Any, Any]: | |
| if not force_reload and model_key in self.models: | |
| logger.info(f"Using cached model: {model_key}") | |
| return self.models[model_key], self.processors[model_key] | |
| available_models = self.config.get("models", {}).get("available", {}) | |
| if model_key not in available_models: | |
| default = self.config.get("models", {}).get("default", "whisper-medium") | |
| if default in available_models: | |
| logger.warning(f"Model {model_key} not found, using default: {default}") | |
| model_key = default | |
| else: | |
| logger.warning(f"Using fallback model path: openai/whisper-{model_key}") | |
| return self._load_whisper_model(f"openai/whisper-{model_key}", model_key, force_reload) | |
| model_config = available_models.get(model_key, {}) | |
| model_path = model_config.get("path", f"openai/whisper-{model_key}") | |
| return self._load_whisper_model(model_path, model_key, force_reload) | |
| def _load_whisper_model(self, model_path: str, model_key: str, force_reload: bool) -> Tuple[Any, Any]: | |
| logger.info(f"Loading Whisper model: {model_key} from {model_path}") | |
| try: | |
| if force_reload and model_key in self.models: | |
| del self.models[model_key] | |
| del self.processors[model_key] | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| processor = WhisperProcessor.from_pretrained( | |
| model_path, | |
| cache_dir=self.cache_dir | |
| ) | |
| # FIX: Do NOT pass use_safetensors=True — many Whisper checkpoints | |
| # only ship .bin weights; safetensors would raise FileNotFoundError. | |
| # transformers auto-selects the best available format. | |
| model = WhisperForConditionalGeneration.from_pretrained( | |
| model_path, | |
| torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32, | |
| low_cpu_mem_usage=True, | |
| cache_dir=self.cache_dir | |
| ) | |
| model = model.to(self.device) | |
| model.eval() | |
| self.models[model_key] = model | |
| self.processors[model_key] = processor | |
| self.current_model = model_key | |
| logger.info(f"Successfully loaded {model_key} on {self.device}") | |
| return model, processor | |
| except Exception as e: | |
| logger.error(f"Failed to load model {model_key}: {e}") | |
| raise | |
| def unload_all_except(self, keep_key: str) -> None: | |
| """Free every cached Whisper model/pipeline except `keep_key`. | |
| Models used to stay cached forever, so switching small -> large-v3 | |
| kept both on the GPU and a long large-v3 job ran a 16 GB T4 out of | |
| memory. | |
| """ | |
| dropped = [k for k in list(self.models) if k != keep_key] | |
| for key in dropped: | |
| self.models.pop(key, None) | |
| self.processors.pop(key, None) | |
| self.pipelines.pop(key, None) | |
| if dropped: | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| logger.info(f"Unloaded models {dropped} to free memory for {keep_key}") | |
| def create_pipeline(self, model_key: str, **kwargs) -> Any: | |
| if model_key in self.pipelines and not kwargs.get("force_reload", False): | |
| return self.pipelines[model_key] | |
| self.unload_all_except(model_key) | |
| model, processor = self.load_model(model_key) | |
| # Match pipeline dtype to model dtype so audio tensors aren't rejected. | |
| # Model is loaded as float16 on CUDA; without this the pipeline feeds | |
| # float32 inputs into float16 weights → "Input type / weight type mismatch". | |
| torch_dtype = ( | |
| torch.float16 if self.device.type == "cuda" else torch.float32 | |
| ) | |
| pipe = pipeline( | |
| task="automatic-speech-recognition", | |
| model=model, | |
| tokenizer=processor.tokenizer, | |
| feature_extractor=processor.feature_extractor, | |
| device=self.device, | |
| torch_dtype=torch_dtype, | |
| # Safety net: HF-level chunking handles any audio that slips past | |
| # our app-level chunker (e.g. metadata duration wrong for MP3/M4A). | |
| # Whisper's max window is 30s; without this it errors on long audio. | |
| chunk_length_s=30, | |
| stride_length_s=5, | |
| ) | |
| self.pipelines[model_key] = pipe | |
| return pipe | |
| def list_available_models(self) -> Dict[str, Dict]: | |
| available = self.config.get("models", {}).get("available", {}) | |
| if not available: | |
| available = { | |
| "whisper-tiny": {"path": "openai/whisper-tiny", "type": "whisper", "size": "39M", "speed": "~32x"}, | |
| "whisper-small": {"path": "openai/whisper-small", "type": "whisper", "size": "244M", "speed": "~8x"}, | |
| "whisper-medium": {"path": "openai/whisper-medium", "type": "whisper", "size": "769M", "speed": "~2x"}, | |
| "whisper-large-v3": {"path": "openai/whisper-large-v3", "type": "whisper", "size": "1.5B", "speed": "1x"}, | |
| } | |
| return available | |
| def get_current_model(self) -> Optional[str]: | |
| return self.current_model | |