ASR-Platform / app.py
SMS-Sajadi's picture
Some small changes
f532cfc
Raw History Blame Contribute Delete
29.2 kB
#!/usr/bin/env python3 """Gradio app for private Hugging Face Hub-hosted Icefall Conformer CTC models.""" from __future__ import annotations # Must be imported before torch/torchaudio for Hugging Face ZeroGPU. import spaces import gc import logging import os import re import threading import time from dataclasses import fields, replace from pathlib import Path from typing import Any, Optional, Sequence import gradio as gr import torch import torchaudio from pretrained_sms import ConformerPipeline from asr_catalog import AppConfig, DEFAULT_MODEL_NAME, MODELS, MODEL_CACHE_DIR from dashboard import build_dashboard, launch_dashboard # ============================================================================= # 3. PRIVATE HUGGING FACE HUB DOWNLOADER # ============================================================================= def get_huggingface_token() -> str: """Read the Space secret without exposing it in logs or UI output. Add a Space Secret named HF_TOKEN. A narrowly-scoped read token for the private model repository is sufficient. """ token = ( os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN") ) if not token: raise RuntimeError( "Hugging Face authentication token not found. Add a Space Secret " "named HF_TOKEN containing a read-access token for your private " "model repository, then restart the Space." ) return token def _safe_repo_filename(filename: str) -> str: """Validate a repository-relative path; reject absolute paths/traversal.""" normalized = filename.replace("\\", "/").strip() path = Path(normalized) if not normalized or path.is_absolute() or ".." in path.parts: raise ValueError(f"Invalid Hugging Face repository filename: {filename!r}") return path.as_posix() def download_huggingface_file( repo_id: str, filename: str, local_dir: str | Path, revision: str = "main", force_download: bool = False, ) -> Path: """Download one file from a private Hugging Face model repository. Hugging Face Hub handles file caching and revision metadata under local_dir. The returned path is suitable for passing to the Icefall checkpoint loader. """ if not repo_id or "/" not in repo_id: raise ValueError( "Each model in MODELS must have repo_id='owner/repository-name'." ) filename = _safe_repo_filename(filename) local_dir = Path(local_dir) local_dir.mkdir(parents=True, exist_ok=True) try: from huggingface_hub import hf_hub_download except ImportError as exc: raise RuntimeError( "huggingface_hub is not installed. Add it to requirements.txt." ) from exc token = get_huggingface_token() logging.info( "Fetching %s from private Hugging Face repo %s (revision=%s)", filename, repo_id, revision, ) try: downloaded_path = hf_hub_download( repo_id=repo_id, filename=filename, repo_type="model", revision=revision, token=token, local_dir=str(local_dir), force_download=force_download, ) except Exception as exc: # Do not include the token in the exception or logging output. message = str(exc) if "401" in message or "403" in message: reason = ( "Access was denied. Check that HF_TOKEN is a valid read token " "and that its fine-grained permissions include this private model repo." ) elif "404" in message or "Repository Not Found" in message: reason = ( "The model repository or requested file was not found. Check repo_id, " "filename, revision, and access permissions. Private repos may also " "appear as not found when the token lacks access." ) else: reason = f"Hugging Face Hub download failed: {message}" raise RuntimeError(reason) from exc downloaded_path = Path(downloaded_path) if not downloaded_path.is_file() or downloaded_path.stat().st_size == 0: raise RuntimeError( f"Hugging Face Hub returned an invalid or empty file: {downloaded_path}" ) logging.info( "File available locally: %s (%.2f MB)", downloaded_path, downloaded_path.stat().st_size / (1024 * 1024), ) return downloaded_path # ============================================================================= # 4. AUDIO LOADING # ============================================================================= def read_audio_files( filenames: Sequence[str], expected_sample_rate: int = 16000, ) -> list[torch.Tensor]: waves = [] for filename in filenames: wave, sample_rate = torchaudio.load(str(filename)) # Convert stereo/multichannel to mono. if wave.ndim == 2: wave = wave.mean(dim=0) elif wave.ndim != 1: raise ValueError( f"Unexpected audio shape: {wave.shape}" ) # Resample if necessary. if sample_rate != expected_sample_rate: wave = torchaudio.functional.resample( wave, orig_freq=sample_rate, new_freq=expected_sample_rate, ) wave = wave.to( dtype=torch.float32 ).contiguous() if wave.numel() == 0: raise ValueError( f"Empty audio file: {filename}" ) if not torch.isfinite(wave).all(): raise ValueError( f"Audio contains NaN or Inf: {filename}" ) waves.append(wave) return waves # ============================================================================= # 5. MODEL MANAGER AND INFERENCE # ============================================================================= class ASRApplication: """ Manages model downloads, initialization, model switching, and transcription. Only one model is kept in memory at a time. Downloaded checkpoints are cached locally by Hugging Face Hub. """ def __init__( self, base_config: AppConfig, model_catalog: dict[str, dict[str, Any]], ): if not model_catalog: raise ValueError( "MODELS must contain at least one model." ) self.base_config = base_config self.model_catalog = model_catalog self._lock = threading.RLock() self.pipeline: Optional[ConformerPipeline] = None self.config: Optional[AppConfig] = None self.active_model_name: Optional[str] = None self.device = "CPU (model not loaded)" self.num_parameters = 0 # Exact (and estimated) parameter counts per model name, so the UI can # show them before and after the pipeline is initialized. self._param_counts: dict[str, int] = {} if base_config.num_threads > 0: torch.set_num_threads(base_config.num_threads) @staticmethod def _model_slug(model_name: str) -> str: slug = re.sub( r"[^a-zA-Z0-9._-]+", "_", model_name.strip(), ).strip("_.") return slug or "model" def _model_local_dir( self, model_name: str, ) -> Path: return MODEL_CACHE_DIR / self._model_slug(model_name) def _checkpoint_path( self, model_name: str, entry: dict[str, Any], ) -> Path: filename = _safe_repo_filename( str(entry.get("filename") or "checkpoint.pt") ) return self._model_local_dir(model_name) / filename def _download_model_assets( self, model_name: str, entry: dict[str, Any], ) -> tuple[ Path, Optional[Path], Optional[Path], Optional[Path], Optional[Path], Optional[Path], ]: """Download checkpoint and optional assets from one Hub repo. Besides the checkpoint, the optional BPE model and tokens.txt and the HLG.pt, G.pt and words.txt decoding assets (used when the decoding method is not ctc-decoding) are fetched from the same repository when their *_filename keys are present in the catalog entry. """ repo_id = str(entry.get("repo_id", "")).strip() revision = str(entry.get("revision", "main")) local_dir = self._model_local_dir(model_name) def _fetch_optional(filename_key: str) -> Optional[Path]: filename = entry.get(filename_key) if not filename: return None return download_huggingface_file( repo_id=repo_id, filename=str(filename), local_dir=local_dir, revision=revision, ) checkpoint_path = download_huggingface_file( repo_id=repo_id, filename=str(entry.get("filename") or "checkpoint.pt"), local_dir=local_dir, revision=revision, ) bpe_path = _fetch_optional("bpe_filename") tokens_path = _fetch_optional("tokens_filename") hlg_path = _fetch_optional("HLG_filename") g_path = _fetch_optional("G_filename") words_path = _fetch_optional("words_filename") return ( checkpoint_path, bpe_path, tokens_path, hlg_path, g_path, words_path, ) @staticmethod def _estimate_parameter_count(checkpoint_path: Path) -> Optional[int]: """Count parameters in a downloaded checkpoint without loading weights. Tensor shapes are read on the meta device (or memory-mapped) so the dashboard can display a parameter count before the pipeline exists. The exact count measured on the loaded model replaces this value later. Returns None when the checkpoint cannot be inspected. """ try: import torch except ImportError: return None path = Path(checkpoint_path) if not path.is_file(): return None obj = None for load_kwargs in ( dict(map_location="meta", weights_only=True), dict(map_location="cpu", mmap=True, weights_only=True), dict(map_location="cpu", weights_only=True), dict(map_location="cpu"), ): try: obj = torch.load(str(path), **load_kwargs) break except Exception: continue if obj is None: return None if isinstance(obj, dict): for key in ("model", "state_dict", "weights", "model_state_dict"): inner = obj.get(key) if isinstance(inner, dict) and inner: obj = inner break if not isinstance(obj, dict): return None total = 0 try: for name, value in obj.items(): key_text = str(name).lower() if any(token in key_text for token in ( "optimizer", "exp_avg", "exp_avg_sq", "scaler", )): continue if torch.is_tensor(value): total += value.numel() except Exception: return None return total or None def _model_config( self, model_name: str, checkpoint_path: Path, bpe_path: Optional[Path] = None, tokens_path: Optional[Path] = None, hlg_path: Optional[Path] = None, g_path: Optional[Path] = None, words_path: Optional[Path] = None, ) -> AppConfig: entry = self.model_catalog[model_name] overrides = dict(entry.get("config", {})) valid_fields = { field.name for field in fields(AppConfig) } unknown = sorted( set(overrides) - valid_fields ) if unknown: raise ValueError( f"Unknown AppConfig overrides: {unknown}" ) if "checkpoint" in overrides: raise ValueError( "Do not put checkpoint in model config." ) if bpe_path is not None: if "bpe_model" in overrides: raise ValueError( "Specify either config.bpe_model or bpe_filename, not both." ) overrides["bpe_model"] = str(bpe_path) if tokens_path is not None: if "tokens" in overrides: raise ValueError( "Specify either config.tokens or tokens_filename, not both." ) overrides["tokens"] = str(tokens_path) if hlg_path is not None: if "HLG" in overrides: raise ValueError( "Specify either config.HLG or HLG_filename, not both." ) overrides["HLG"] = str(hlg_path) if g_path is not None: if "G" in overrides: raise ValueError( "Specify either config.G or G_filename, not both." ) overrides["G"] = str(g_path) if words_path is not None: if "words_file" in overrides: raise ValueError( "Specify either config.words_file or words_filename, not both." ) overrides["words_file"] = str(words_path) config = replace( self.base_config, checkpoint=str(checkpoint_path), **overrides, ) config.validate_assets() return config def _release_active_pipeline(self): old_pipeline = self.pipeline self.pipeline = None self.config = None self.active_model_name = None self.device = "CPU (model not loaded)" self.num_parameters = 0 if old_pipeline is not None: del old_pipeline gc.collect() # CPU-only inference does not require CUDA cache management. def load_model(self, model_name: str) -> str: """ Fetch and initialize the selected model from a private Hugging Face repo. Hugging Face Hub manages the local cache and revision metadata. """ with self._lock: if model_name not in self.model_catalog: raise ValueError( f"Unknown model: {model_name}" ) if ( self.active_model_name == model_name and self.pipeline is not None ): return self.model_information() entry = self.model_catalog[model_name] ( checkpoint_path, bpe_path, tokens_path, hlg_path, g_path, words_path, ) = self._download_model_assets( model_name, entry, ) config = self._model_config( model_name, checkpoint_path, bpe_path=bpe_path, tokens_path=tokens_path, hlg_path=hlg_path, g_path=g_path, words_path=words_path, ) params = config.pipeline_params() # Keep only one model in memory. self._release_active_pipeline() logging.info( "Loading model '%s' on %s", model_name, params.device, ) try: pipeline = ConformerPipeline( sound_reader=lambda paths, sr=config.sample_rate: read_audio_files( paths, expected_sample_rate=sr, ), model_path=params.checkpoint, params=params, ) except Exception: logging.exception( "Failed to initialize model '%s'", model_name, ) self._release_active_pipeline() raise self.pipeline = pipeline self.config = config self.active_model_name = model_name self.device = str(pipeline.device) self.num_parameters = sum( parameter.numel() for parameter in pipeline.model.parameters() ) # Replace the checkpoint-based estimate with the exact count. self._param_counts[model_name] = self.num_parameters logging.info( "Model '%s' ready: %.3f M parameters", model_name, self.num_parameters / 1e6, ) return self.model_information() def model_information( self, model_name: Optional[str] = None, ) -> str: """Describe the active model or a selected model before loading.""" if model_name is None: model_name = self.active_model_name cfg = self.config loaded = ( self.pipeline is not None and cfg is not None ) else: if model_name not in self.model_catalog: return f"Unknown model: {model_name}" entry = self.model_catalog[model_name] checkpoint_path = self._checkpoint_path( model_name, entry, ) overrides = dict(entry.get("config", {})) cfg = replace( self.base_config, checkpoint=str(checkpoint_path), **overrides, ) loaded = ( self.active_model_name == model_name and self.pipeline is not None ) if model_name is None or cfg is None: return "No model is currently loaded." description = self.model_catalog[ model_name ].get("description", "") cached = self._param_counts.get(model_name) if cached: parameter_text = f"{cached / 1e6:.3f} M" elif loaded: parameter_text = f"{self.num_parameters / 1e6:.3f} M" else: parameter_text = "Calculated when the model is initialized" device_text = self.device if loaded else "CPU" lines = [ f"**Selected model:** {model_name}" ] if description: lines.append( f"**Description:** {description}" ) lines.extend([ f"**Parameters:** {parameter_text}", f"**Encoder dimension:** {cfg.encoder_dim}", f"**Attention heads:** {cfg.nhead}", f"**Recurrent encoder:** {'Yes' if cfg.use_recurrence else 'No'}", ]) if cfg.use_recurrence: loops = ( cfg.max_loops if cfg.max_loops > 0 else cfg.num_loops ) lines.append( f"**Loops:** {loops}" ) lines.extend([ f"**CTC feedback:** {'Yes' if cfg.use_ctc_feedback else 'No'}", f"**Decoder:** k2 ({cfg.method})", f"**Device:** {device_text}", ]) return "\n\n".join(lines) def select_model(self, model_name: str): """Download and validate the selected Hub checkpoint without loading the model.""" try: if model_name not in self.model_catalog: raise ValueError( f"Unknown model: {model_name}" ) entry = self.model_catalog[model_name] ( checkpoint_path, bpe_path, tokens_path, hlg_path, g_path, words_path, ) = self._download_model_assets( model_name, entry, ) self._model_config( model_name, checkpoint_path, bpe_path=bpe_path, tokens_path=tokens_path, hlg_path=hlg_path, g_path=g_path, words_path=words_path, ) # Make the parameter count visible in the UI before the model is # ever initialized: shapes are read straight from the checkpoint. if model_name not in self._param_counts: estimated = self._estimate_parameter_count(checkpoint_path) if estimated: self._param_counts[model_name] = estimated logging.info( "Estimated %.3f M parameters for '%s'", estimated / 1e6, model_name, ) already_loaded = ( self.active_model_name == model_name and self.pipeline is not None ) if already_loaded: status = f"Model ready: **{model_name}**" else: status = ( f"Model files cached for **{model_name}**. " "It will be initialized when you run recognition." ) return status, self.model_information(model_name) except Exception as exc: logging.exception( "Could not select model '%s'", model_name, ) return ( f"**Model selection failed:** {exc}", self.model_information(), ) def _validate_audio( self, audio_path: str, ) -> tuple[float, int, int]: if ( not audio_path or not Path(audio_path).is_file() ): raise gr.Error( "Please upload an audio file or record your voice." ) # SoundFile first, torchaudio fallback. try: import soundfile as sf info = sf.info(audio_path) sample_rate = int(info.samplerate) num_frames = int(info.frames) num_channels = int(info.channels) except Exception as soundfile_error: logging.debug( "SoundFile metadata read failed: %s", soundfile_error, ) try: waveform, sample_rate = torchaudio.load( audio_path ) sample_rate = int(sample_rate) if waveform.ndim == 1: num_channels = 1 num_frames = int(waveform.shape[0]) elif waveform.ndim == 2: num_channels = int(waveform.shape[0]) num_frames = int(waveform.shape[1]) else: raise ValueError( f"Unexpected audio shape: {tuple(waveform.shape)}" ) del waveform except Exception as audio_error: raise gr.Error( "Unable to read audio. " f"SoundFile: {soundfile_error}; " f"torchaudio: {audio_error}" ) from audio_error if ( sample_rate <= 0 or num_frames <= 0 or num_channels <= 0 ): raise gr.Error( "The audio file is empty or invalid." ) duration = num_frames / sample_rate if duration > self.config.max_audio_seconds: raise gr.Error( f"Audio duration is {duration:.1f} seconds. " f"Maximum allowed duration is " f"{self.config.max_audio_seconds:.0f} seconds." ) return duration, sample_rate, num_channels def transcribe( self, audio_path: Optional[str], model_name: str, ): if audio_path is None: raise gr.Error( "Upload an audio file or record your voice first." ) with self._lock: try: if ( self.active_model_name != model_name or self.pipeline is None ): self.load_model(model_name) if ( self.pipeline is None or self.config is None ): raise RuntimeError( "The selected model is not loaded." ) ( audio_duration, original_sr, channels, ) = self._validate_audio(audio_path) previous_duration = ( self.pipeline.total_audio_duration ) wall_start = time.perf_counter() hypotheses = self.pipeline( [audio_path] ) wall_elapsed = ( time.perf_counter() - wall_start ) measured_audio_duration = ( self.pipeline.total_audio_duration - previous_duration ) except gr.Error: raise except Exception as exc: logging.exception("Transcription failed") raise gr.Error( f"Transcription failed: {exc}" ) from exc transcription = ( hypotheses[0] if hypotheses else "" ) duration_for_rtf = ( measured_audio_duration or audio_duration ) end_to_end_rtf = ( wall_elapsed / max(duration_for_rtf, 1e-8) ) performance = ( f"Model: {model_name}\n" f"Audio duration: {audio_duration:.2f} s\n" f"Original sample rate: {original_sr} Hz\n" f"Channels: {channels}\n" f"End-to-end processing: {wall_elapsed:.3f} s\n" f"End-to-end RTF: {end_to_end_rtf:.4f}\n" f"Device: {self.device}" ) return transcription, performance # ============================================================================= # 6. SHARED AND SEPARATE INFERENCE HANDLERS # ============================================================================= ASR_APP: Optional[ASRApplication] = None def _run_transcription( audio_path: Optional[str], model_name: str, ): """Shared implementation for CPU and GPU entry points.""" if ASR_APP is None: raise gr.Error( "The ASR application has not been initialized." ) return ASR_APP.transcribe( audio_path, model_name, ) def transcribe_cpu_handler( audio_path: Optional[str], model_name: str, ): """Actual inference handler. Runs exclusively on CPU.""" return _run_transcription( audio_path, model_name, ) @spaces.GPU(duration=60) def transcribe_gpu_handler( audio_path: Optional[str], model_name: str, ): """GPU-decorated entry point retained for ZeroGPU compatibility.""" return _run_transcription( audio_path, model_name, ) # ============================================================================= # 7. GRADIO INTERFACE # ============================================================================= def build_demo(asr: ASRApplication) -> gr.Blocks: return build_dashboard( asr.model_catalog, asr.base_config, select_model=asr.select_model, model_info=asr.model_information, transcribe=transcribe_cpu_handler, gpu_handler=transcribe_gpu_handler, ) # ============================================================================= # 8. ENTRY POINT # ============================================================================= def main(): global ASR_APP logging.basicConfig( level=logging.INFO, format=( "%(asctime)s %(levelname)s " "[%(filename)s:%(lineno)d] %(message)s" ), ) base_config = AppConfig() ASR_APP = ASRApplication( base_config=base_config, model_catalog=MODELS, ) logging.info( "Preparing default model: %s", DEFAULT_MODEL_NAME, ) # Download and validate the checkpoint at startup. # Actual CPU model initialization is deferred until transcription. status, _ = ASR_APP.select_model( DEFAULT_MODEL_NAME ) logging.info( "Default model setup: %s", status, ) demo = build_demo(ASR_APP) launch_dashboard(demo) if __name__ == "__main__": main()
#!/usr/bin/env python3
"""Gradio app for private Hugging Face Hub-hosted Icefall Conformer CTC models."""
from __future__ import annotations
# Must be imported before torch/torchaudio for Hugging Face ZeroGPU.
import spaces
import gc
import logging
import os
import re
import threading
import time
from dataclasses import fields, replace
from pathlib import Path
from typing import Any, Optional, Sequence
import gradio as gr
import torch
import torchaudio
from pretrained_sms import ConformerPipeline
from asr_catalog import AppConfig, DEFAULT_MODEL_NAME, MODELS, MODEL_CACHE_DIR
from dashboard import build_dashboard, launch_dashboard
# =============================================================================
# 3. PRIVATE HUGGING FACE HUB DOWNLOADER
# =============================================================================
def get_huggingface_token() -> str:
"""Read the Space secret without exposing it in logs or UI output.
Add a Space Secret named HF_TOKEN. A narrowly-scoped read token for the
private model repository is sufficient.
"""
token = (
os.getenv("HF_TOKEN")
or os.getenv("HUGGINGFACE_HUB_TOKEN")
or os.getenv("HUGGING_FACE_HUB_TOKEN")
)
if not token:
raise RuntimeError(
"Hugging Face authentication token not found. Add a Space Secret "
"named HF_TOKEN containing a read-access token for your private "
"model repository, then restart the Space."
)
return token
def _safe_repo_filename(filename: str) -> str:
"""Validate a repository-relative path; reject absolute paths/traversal."""
normalized = filename.replace("\\", "/").strip()
path = Path(normalized)
if not normalized or path.is_absolute() or ".." in path.parts:
raise ValueError(f"Invalid Hugging Face repository filename: {filename!r}")
return path.as_posix()
def download_huggingface_file(
repo_id: str,
filename: str,
local_dir: str | Path,
revision: str = "main",
force_download: bool = False,
) -> Path:
"""Download one file from a private Hugging Face model repository.
Hugging Face Hub handles file caching and revision metadata under local_dir.
The returned path is suitable for passing to the Icefall checkpoint loader.
"""
if not repo_id or "/" not in repo_id:
raise ValueError(
"Each model in MODELS must have repo_id='owner/repository-name'."
)
filename = _safe_repo_filename(filename)
local_dir = Path(local_dir)
local_dir.mkdir(parents=True, exist_ok=True)
try:
from huggingface_hub import hf_hub_download
except ImportError as exc:
raise RuntimeError(
"huggingface_hub is not installed. Add it to requirements.txt."
) from exc
token = get_huggingface_token()
logging.info(
"Fetching %s from private Hugging Face repo %s (revision=%s)",
filename,
repo_id,
revision,
)
try: