"""Opt-in staging FP16 adapter for our candidates; NCAIR remains the detector and fallback.""" import io import json import os from pathlib import Path import shutil import subprocess import tempfile import time import numpy as np import soundfile as sf from .asr_pipeline import TranscriptionResult from .candidates import CANDIDATES, candidate_lang, ct2_enabled from .speech_gate import speech_regions def prepare_model(cache_dir, lang='ha'): """Atomic, locked conversion of immutable weights and their own tokenizer.""" c = CANDIDATES[lang] from filelock import FileLock from huggingface_hub import snapshot_download root = Path(cache_dir) / 'narratifai-ct2' root.mkdir(parents=True, exist_ok=True) target = root / (c['revision'] + '-fp16-ct2-4.5.0') manifest = {'revision': c['revision'], 'repo': c['path'], 'precision': 'float16', 'converter': '4.5.0'} with FileLock(str(target) + '.lock', timeout=600): marker = target / 'narratifai.json' if marker.exists() and json.loads(marker.read_text()) == manifest and all( (target / name).is_file() for name in ('model.bin', 'config.json', 'tokenizer.json', 'preprocessor_config.json')): return target source = snapshot_download(c['path'], revision=c['revision'], cache_dir=cache_dir) staging = Path(tempfile.mkdtemp(prefix='convert-', dir=root)) try: # Conversion lives in a child process so its large CPU allocations are freed. subprocess.run(['ct2-transformers-converter', '--model', source, '--output_dir', str(staging), '--copy_files', 'preprocessor_config.json', '--quantization', 'float16', '--force'], check=True, timeout=600) from transformers import WhisperTokenizerFast WhisperTokenizerFast.from_pretrained(source).backend_tokenizer.save(str(staging / 'tokenizer.json')) (staging / 'narratifai.json').write_text(json.dumps(manifest)) if target.exists(): shutil.rmtree(target) staging.rename(target) finally: if staging.exists(): shutil.rmtree(staging) return target def preload_cuda_libraries(): """CTranslate2 links cuBLAS 12 and cuDNN 9 by name. The Space has no system CUDA: they come with the Torch wheels (site-packages/nvidia/*/lib), which the loader only searches if LD_LIBRARY_PATH said so at process start. Loading them globally first lets CTranslate2 find them already loaded.""" import ctypes import site import sys bases = [b for b in dict.fromkeys(sys.path + site.getsitepackages()) if b] loaded = [] for package in ('cublas', 'cudnn'): for base in bases: libdir = Path(base) / 'nvidia' / package / 'lib' if not libdir.is_dir(): continue # Base libraries before the ones that depend on them. names = sorted(libdir.glob('lib*.so*'), key=lambda f: ( 0 if f.name.startswith(('libcublasLt', 'libcudnn.so')) else 1, f.name)) for lib in names: try: ctypes.CDLL(str(lib), mode=ctypes.RTLD_GLOBAL) loaded.append(lib.name) except OSError: pass break return loaded class CandidateCT2Pipeline: def __init__(self, model_key, registry, config): self.lang = candidate_lang(model_key) if not self.lang: raise ValueError('CT2 adapter is restricted to our candidates') self.model_key, self.registry, self.config = model_key, registry, config self.pipeline = None def _initialize_pipeline(self): if not ct2_enabled(self.lang): raise ValueError('CT2 candidate requires explicit staging flags') if self.pipeline is None: if self.registry.device.type != 'cuda': raise RuntimeError('FP16 candidate requires CUDA') self.registry.unload_all_except(self.model_key) preload_cuda_libraries() from faster_whisper import WhisperModel path = prepare_model(self.registry.cache_dir, self.lang) self.pipeline = WhisperModel(str(path), device='cuda', compute_type='float16') self.registry.current_model = self.model_key def close(self): if self.pipeline is not None: self.pipeline.model.unload_model() self.pipeline = None def transcribe(self, audio, **kwargs): started = time.perf_counter() if not ct2_enabled(self.lang): raise ValueError('CT2 candidate is disabled') if isinstance(audio, (str, Path, bytes)): audio, sr = sf.read(io.BytesIO(audio) if isinstance(audio, bytes) else audio, dtype='float32') if sr != 16000: raise ValueError('Adapter requires 16 kHz audio') audio = np.asarray(audio, dtype=np.float32) regions = speech_regions(audio) segments = [] if regions: self._initialize_pipeline() for region in regions: begin, end = region['start'], region['end'] decoded, _ = self.pipeline.transcribe( audio[begin:end], language=CANDIDATES[self.lang]['token'], task='transcribe', beam_size=1, temperature=(0., .2, .4, .6, .8, 1.), condition_on_previous_text=False, vad_filter=False, no_speech_threshold=.6, log_prob_threshold=-1., compression_ratio_threshold=2.4, word_timestamps=False, ) for segment in decoded: text = segment.text.strip() start = max(begin / 16000, min(end / 16000, begin / 16000 + segment.start)) stop = max(start, min(end / 16000, begin / 16000 + segment.end)) if text and stop > start: segments.append({'id': len(segments), 'start': start, 'end': stop, 'text': text}) return TranscriptionResult( text=' '.join(s['text'] for s in segments), language=self.lang, segments=segments, model_used=self.model_key, audio_duration=len(audio) / 16000, processing_time=time.perf_counter() - started, ) HausaCT2Pipeline = CandidateCT2Pipeline # the first candidate's name