Spaces:
Paused
Paused
Download src/transcription/engine.py from Consulawtech/NarratifAI: direct link, hf CLI and curl.
- Browser
- Download file 36.7 kB
-
https://huggingface.co/spaces/Consulawtech/NarratifAI/resolve/main/src/transcription/engine.py
- Command line
-
hf download hf://spaces/Consulawtech/NarratifAI/src/transcription/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/Consulawtech/NarratifAI/resolve/main/src/transcription/engine.py
36.7 kB
| """ | |
| Main transcription engine orchestrating all components | |
| Author: Maaldeens | |
| License: MIT | |
| """ | |
| from pathlib import Path | |
| from typing import Optional, Dict, List, Tuple | |
| import logging | |
| import time | |
| import os | |
| import uuid | |
| import yaml | |
| import soundfile as sf | |
| from ..audio_processor.validator import AudioValidator | |
| from ..audio_processor.converter import AudioConverter | |
| from ..audio_processor.enhance import enhance, report_dict | |
| from ..audio_processor.chunker import AudioChunker | |
| from ..models.registry import ModelRegistry | |
| from ..models.asr_pipeline import ASRPipeline, TranscriptionResult | |
| from ..diarization.engine import DiarizationEngine | |
| from .whisper_pieces import strip_caption_name, whisper_pieces | |
| from .language_runs import ( | |
| ENGLISH_WORDS, ISLAND_MIN_SEC, MIN_LID_SEC, Run, build_runs, candidates_for, dominant_language, drop_repeats, looks_english, | |
| label_windows, mark_english_islands, pieces, scoring_codes, speech_windows, turn_cuts, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Languages with a dedicated model. NATIVE_ASR=0 turns this off. | |
| NATIVE_MODELS = {"yo": "ncair-yoruba", "ig": "ncair-igbo", "ha": "ncair-hausa"} | |
| NATIVE_FALLBACK = "whisper-large-v3" | |
| def native_asr_enabled() -> bool: | |
| return os.getenv("NATIVE_ASR", "1") != "0" | |
| def mixed_language_enabled() -> bool: | |
| return os.getenv("MIXED_LANGUAGE", "1") != "0" | |
| # Whisper's language ID needs a general Whisper model, not a fine-tune. | |
| DETECTOR_MODEL = NATIVE_FALLBACK | |
| # Whisper has no language token for these; transcribe without forcing one. | |
| NO_WHISPER_TOKEN = {"ig"} | |
| # When Yoruba/Igbo/Hausa is chosen, English is decided piece by piece by | |
| # letting both models read the piece and keeping English only when Whisper is | |
| # clearly surer of its English reading than the dedicated model is of its own, | |
| # and the English reading is made of English words. Whisper's language guess | |
| # alone can't tell an isolated Yoruba word from an English one (Beginner's | |
| # Yoruba vocabulary drills: "TΓ³pΓ©", "owΓ³" scored as English); the dedicated | |
| # model reads those confidently. Measured Oct 2026: English sentences about | |
| # -0.05 (Whisper) vs -0.3..-0.8 (Yoruba model); Yoruba words the reverse. | |
| ENGLISH_CANDIDATE_MARGIN = 0.0 # Whisper LID must lean English at all to be checked | |
| ENGLISH_CONFIDENCE_MARGIN = 0.30 # Whisper's English must beat the native reading by this | |
| ENGLISH_WORD_SHARE = 0.5 # ...at least half its words must be English words | |
| # A full English sentence (5+ words, mostly English words) only needs Whisper | |
| # to be ahead: on Nigerian-accented English the Yoruba model is about as sure | |
| # as Whisper ("Nigeria records 122 new COVID-19 infections": -0.40 vs -0.47), | |
| # and invented English only ever showed up on 1-4 word pieces. | |
| # Auto-detect: Whisper's language guess calls Yoruba names and words English, | |
| # so a sample of pieces is read by the Yoruba/Hausa model and by Whisper; when | |
| # the dedicated model is the surer reader of at least half, the recording is | |
| # treated as that language (its English parts are still kept in English). | |
| PROBE_PIECES = 8 | |
| PROBE_NATIVE_SHARE = 0.5 | |
| ENGLISH_SENTENCE_WORDS = 5 | |
| ENGLISH_SENTENCE_SHARE = 0.6 | |
| # ...and it must say something: fillers and spelled letters ("Oh, yeah", | |
| # "See me", "E-Y-E") are what Whisper invents for short Yoruba words. | |
| ENGLISH_FILLERS = frozenset("oh ah eh uh um hmm hm yeah yes yep no hi hey hello hola okay ok so me see " | |
| "wow whoa bye ya yo ha huh oops".split()) | |
| class TranscriptionEngine: | |
| """Main transcription engine orchestrating the entire pipeline.""" | |
| def __init__(self, config_path: Optional[str] = None): | |
| self.config = self._load_config(config_path) | |
| self.temp_dir = Path(self.config.get("system", {}).get("temp_dir", "/app/temp")) | |
| self.temp_dir.mkdir(exist_ok=True, parents=True) | |
| self.validator = AudioValidator( | |
| max_file_size_mb=self.config.get("system", {}).get("max_file_size_mb", 500) | |
| ) | |
| audio_cfg = self.config.get("audio", {}) | |
| # FIX: default noise_reduction to False β consistent with settings.yaml | |
| self.converter = AudioConverter( | |
| target_sr=audio_cfg.get("target_sample_rate", 16000), | |
| target_channels=audio_cfg.get("target_channels", 1), | |
| target_dbfs=audio_cfg.get("target_dbfs", -20), | |
| apply_noise_reduction=audio_cfg.get("noise_reduction", False), | |
| ) | |
| self.chunker = AudioChunker( | |
| chunk_duration=audio_cfg.get("chunk_duration_sec", 30), | |
| overlap_duration=audio_cfg.get("chunk_overlap_sec", 2), | |
| target_sr=audio_cfg.get("target_sample_rate", 16000), | |
| ) | |
| self.registry = ModelRegistry(config_path) | |
| self._pipeline: Optional[ASRPipeline] = None | |
| self.current_model_key = self.config.get("models", {}).get("default", "whisper-medium") | |
| self.diarization = DiarizationEngine() | |
| def _load_config(self, config_path: Optional[str]) -> Dict: | |
| if config_path and Path(config_path).exists(): | |
| with open(config_path, 'r') as f: | |
| return yaml.safe_load(f) | |
| return {} | |
| def set_model(self, model_key: str): | |
| available = self.registry.list_available_models() | |
| if model_key not in available: | |
| raise ValueError(f"Model '{model_key}' not available. Options: {list(available.keys())}") | |
| self.current_model_key = model_key | |
| self._pipeline = None | |
| logger.info(f"Model changed to: {model_key}") | |
| def _get_pipeline(self) -> ASRPipeline: | |
| if self._pipeline is None: | |
| self._pipeline = ASRPipeline( | |
| self.current_model_key, | |
| self.registry, | |
| self.config.get("transcription", {}), | |
| ) | |
| return self._pipeline | |
| def transcribe_file(self, file_path: str, **kwargs) -> TranscriptionResult: | |
| logger.info(f"Processing file: {file_path}") | |
| diarize = kwargs.pop("diarization", False) | |
| num_speakers = kwargs.pop("num_speakers", None) | |
| progress_callback = kwargs.pop("progress_callback", None) | |
| job_token = uuid.uuid4().hex[:8] | |
| started = time.time() | |
| is_valid, metadata, error = self.validator.is_valid_audio(file_path) | |
| if not is_valid: | |
| raise ValueError(f"Invalid audio file: {error}") | |
| processed_path = self.converter.preprocess(file_path) | |
| lead_in = getattr(self.converter, "last_trim_offset", 0.0) | |
| audio, sr = sf.read(processed_path) | |
| # Use sample-count duration β always exact regardless of container format. | |
| # metadata.duration comes from sf.info() on the original MP3/M4A which | |
| # silently returns wrong values for VBR files, causing should_chunk() to | |
| # return False on 25-minute recordings and sending them to the HF pipeline | |
| # as a single block (no app-level overlap, no context between chunks). | |
| actual_duration = len(audio) / sr | |
| # Clean-up levels (off / light / full), set separately for the words and | |
| # for speaker detection: each benefits from different treatment. A | |
| # failed clean-up never fails the job; the converted audio is used. | |
| # Defaults from an evaluation on AMI meetings (headset, room mic, added | |
| # noise; Whisper small and large-v3) and FLEURS Yoruba (clean, noisy): | |
| # "light" lowered word errors in every condition; "full" noise reduction | |
| # helped English a little more but hurt the Yoruba model, and neither | |
| # changed how well speakers were told apart. | |
| asr_level = kwargs.pop("enhance_asr", None) or os.getenv("AUDIO_ENHANCE_ASR", "light") | |
| diar_level = kwargs.pop("enhance_diarization", None) or os.getenv("AUDIO_ENHANCE_DIARIZATION", "off") | |
| diar_path = processed_path | |
| self.last_enhance = {} | |
| try: | |
| raw = audio | |
| if asr_level != "off": | |
| audio, rep = enhance(raw, sr, asr_level) | |
| self.last_enhance["asr"] = report_dict(rep) | |
| if diar_level != "off": | |
| if diar_level == asr_level: | |
| diar_audio = audio | |
| else: | |
| diar_audio, rep = enhance(raw, sr, diar_level) | |
| self.last_enhance["diarization"] = report_dict(rep) | |
| diar_path = str(Path(processed_path).with_name(Path(processed_path).stem + "_diar.wav")) | |
| sf.write(diar_path, diar_audio, sr) | |
| if self.last_enhance: | |
| logger.info(f"Audio clean-up: {self.last_enhance}") | |
| except Exception as e: | |
| logger.warning(f"Audio clean-up skipped: {type(e).__name__}: {e}") | |
| audio, diar_path = raw, processed_path | |
| requested = [l for l in (kwargs.pop("languages", None) or ([kwargs["language"]] if kwargs.get("language") else [])) if l] | |
| job_model = self.current_model_key | |
| self._plan_windows = None | |
| # Speaker turns come first when speakers are wanted: the dedicated | |
| # Yoruba/Igbo/Hausa models transcribe piece by piece, and cutting | |
| # pieces at turn boundaries keeps each sentence to one voice. | |
| speaker_turns = None | |
| if diarize and self.diarization.is_available(): | |
| try: | |
| speaker_turns = self.diarization.diarize(str(diar_path), num_speakers=num_speakers) | |
| except Exception as e: | |
| logger.warning(f"Diarization failed: {e}. Returning transcript without speakers.") | |
| self._turn_cuts = turn_cuts(speaker_turns) if speaker_turns else [] | |
| try: | |
| # One Nigerian language chosen, alone or with English: that model | |
| # reads it and English is kept where it really is English. | |
| natives = [l for l in requested if l in NATIVE_MODELS] | |
| native_choice = (len(natives) == 1 and all(l in NATIVE_MODELS or l == "en" for l in requested) | |
| and native_asr_enabled() and mixed_language_enabled() and actual_duration >= 3 | |
| and NATIVE_MODELS[natives[0]] in self.registry.list_available_models()) | |
| native_lang = natives[0] if native_choice else None | |
| if not requested and native_asr_enabled() and mixed_language_enabled() and actual_duration >= 3: | |
| native_lang = self._probe_native_language(audio, sr, job_model) | |
| plan = None if native_lang else self._language_plan(audio, sr, requested, actual_duration) | |
| if native_lang: | |
| result = self._transcribe_native_with_english(audio, sr, native_lang, job_model, kwargs, progress_callback) | |
| result.audio_duration = metadata.duration | |
| result.processing_time = time.time() - started | |
| elif plan and len({r.language for r in plan}) > 1: | |
| result = self._transcribe_mixed(audio, sr, plan, job_model, kwargs, progress_callback) | |
| result.audio_duration = metadata.duration | |
| result.processing_time = time.time() - started | |
| else: | |
| if plan: | |
| kwargs["language"] = plan[0].language | |
| elif not kwargs.get("language"): | |
| # Language ID by windows failed or had nothing to work on. | |
| detected = self._get_pipeline().detect_language(audio, sr) | |
| if detected: | |
| kwargs["language"] = detected | |
| lang = kwargs.get("language") | |
| if lang: | |
| logger.info(f"Language: {lang}") | |
| self._use_model(self._model_for(lang, job_model)) | |
| if lang in NO_WHISPER_TOKEN and not self.current_model_key.startswith("ncair-"): | |
| kwargs.pop("language", None) | |
| if self.current_model_key.startswith("ncair-"): | |
| result = self._transcribe_native(audio, sr, metadata, kwargs, progress_callback, started) | |
| else: | |
| result = self._transcribe_single(audio, sr, processed_path, actual_duration, metadata, job_token, | |
| kwargs, progress_callback, started) | |
| if lang: | |
| result.language = lang | |
| # --- Speaker diarization --- | |
| if diarize and result.segments: | |
| if speaker_turns: | |
| try: | |
| result.segments = self.diarization.align_speakers(result.segments, speaker_turns) | |
| result.segments = self.diarization.refine_speakers( | |
| str(diar_path), result.segments, num_speakers=num_speakers) | |
| except Exception as e: | |
| logger.warning(f"Speaker labelling failed: {e}. Returning transcript without speakers.") | |
| elif not self.diarization.is_available(): | |
| logger.warning("Diarization requested but not available (pyannote.audio missing or HF_TOKEN not set).") | |
| # Leading silence was trimmed before transcription; shift every | |
| # timestamp back onto the original recording's timeline. | |
| if lead_in > 0 and result.segments: | |
| for seg in result.segments: | |
| seg["start"] = round(seg["start"] + lead_in, 3) | |
| seg["end"] = round(seg["end"] + lead_in, 3) | |
| finally: | |
| Path(processed_path).unlink(missing_ok=True) | |
| if diar_path != processed_path: | |
| Path(diar_path).unlink(missing_ok=True) | |
| return result | |
| # ββ Models ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _use_model(self, model_key: str) -> ASRPipeline: | |
| """Switch to `model_key` (loading it once); a native model that can't | |
| load (e.g. gated terms not accepted) falls back to large-v3.""" | |
| if model_key != self.current_model_key: | |
| self.set_model(model_key) | |
| if self.current_model_key in NATIVE_MODELS.values(): | |
| try: | |
| self._get_pipeline()._initialize_pipeline() | |
| except Exception as e: | |
| logger.error(f"{self.current_model_key} unavailable, using {NATIVE_FALLBACK}: {e}") | |
| self.set_model(NATIVE_FALLBACK) | |
| # Callers reach into .pipeline (its tokenizer, its model) straight away, | |
| # so the model must be loaded before it is handed back. | |
| pipe = self._get_pipeline() | |
| pipe._initialize_pipeline() | |
| return pipe | |
| def _model_for(self, lang: Optional[str], job_model: str) -> str: | |
| """Dedicated model for Yoruba/Igbo/Hausa, otherwise the job's model | |
| (large-v3 when the job was started on a dedicated model).""" | |
| available = self.registry.list_available_models() | |
| native = NATIVE_MODELS.get(lang or "") | |
| if native and native_asr_enabled() and native in available: | |
| return native | |
| if job_model in NATIVE_MODELS.values(): | |
| return NATIVE_FALLBACK if NATIVE_FALLBACK in available else self.config.get("models", {}).get("default", job_model) | |
| return job_model | |
| # ββ Language plan βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _language_plan(self, audio, sr: int, requested, duration: float) -> Optional[List[Run]]: | |
| """Where each language is spoken, or None to fall back to one language. | |
| Auto-detect chooses between the app's languages; one picked language | |
| may switch to English; several picked languages switch between those. | |
| """ | |
| if not mixed_language_enabled() or duration < 8: | |
| return None | |
| if requested == ["en"]: | |
| return [Run("en", 0.0, duration)] | |
| candidates, implied = candidates_for(requested, ASRPipeline.AUTO_DETECT_LANGUAGES) | |
| if len(candidates) < 2: | |
| return None | |
| windows = speech_windows(audio, sr) | |
| if not windows: | |
| return None | |
| # Windows from ISLAND_MIN_SEC are scored so short English phrases can be | |
| # found; only those from MIN_LID_SEC vote in the language sequence. | |
| judged = [i for i, w in enumerate(windows) if w.end - w.start >= ISLAND_MIN_SEC] | |
| if not judged: | |
| return None | |
| detector_key = DETECTOR_MODEL if DETECTOR_MODEL in self.registry.list_available_models() else self.current_model_key | |
| try: | |
| detector = self._use_model(detector_key) | |
| clip = lambda w: audio[int(w.start * sr): int(w.end * sr)] | |
| scored = detector.language_scores([clip(windows[i]) for i in judged], scoring_codes(candidates, implied), sr) | |
| except Exception as e: | |
| logger.warning(f"Language plan failed, using one language: {e}") | |
| return None | |
| if not any(scored): | |
| return None | |
| scores: List[Optional[Dict[str, float]]] = [None] * len(windows) | |
| for i, sc in zip(judged, scored): | |
| scores[i] = sc | |
| prior = ASRPipeline.LANGUAGE_PRIOR if not requested else {} | |
| if requested: | |
| dominant = requested[0] | |
| else: | |
| # Main language: the one that wins the most speech time. | |
| time_by_lang: Dict[str, float] = {} | |
| for w, sc in zip(windows, scores): | |
| if sc: | |
| best = max(candidates, key=lambda c: sc.get(c, -1e9) + prior.get(c, 0.0)) | |
| time_by_lang[best] = time_by_lang.get(best, 0.0) + (w.end - w.start) | |
| dominant = max(time_by_lang, key=time_by_lang.get) | |
| voting = [sc if (w.end - w.start) >= MIN_LID_SEC else None for w, sc in zip(windows, scores)] | |
| label_windows(windows, voting, candidates, dominant, prior, implied, fill_with_dominant=bool(requested)) | |
| islands = mark_english_islands(windows, scores, candidates, dominant) | |
| if islands: | |
| logger.info(f"Short English phrases kept in English: {islands}") | |
| self._plan_windows = windows | |
| runs = build_runs(windows, dominant) | |
| if len(runs) > 1: | |
| logger.info("Languages by time: " + ", ".join(f"{r.language} {r.start:.0f}-{r.end:.0f}s" for r in runs)) | |
| return runs | |
| # ββ Transcription paths βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _transcribe_single(self, audio, sr, processed_path, actual_duration, metadata, job_token, | |
| kwargs, progress_callback, started) -> TranscriptionResult: | |
| """One language on a Whisper model: the speech cut at pauses into | |
| pieces of up to 28 s, read in GPU batches (see whisper_pieces).""" | |
| if audio.ndim > 1: | |
| audio = audio.mean(axis=1) | |
| total = len(audio) / sr | |
| spans = whisper_pieces(audio, sr) or [(0.0, total)] | |
| logger.info(f"{len(spans)} pieces for {total:.0f}s of audio") | |
| if progress_callback: | |
| progress_callback(0, len(spans)) | |
| # Greedy decoding for long recordings (see ASRPipeline.transcribe). | |
| long_form = self.chunker.should_chunk(actual_duration) | |
| clips = [audio[int(a * sr): int(b * sr)] for a, b in spans] | |
| parts = self._get_pipeline().transcribe_pieces( | |
| clips, sr, on_batch=progress_callback, long_form=long_form, **kwargs) | |
| segments: List[Dict] = [] | |
| language = None | |
| for (a, b), part in zip(spans, parts): | |
| language = language or part.language | |
| segs = [dict(x) for x in part.segments or []] | |
| if not segs and (part.text or "").strip(): | |
| segs = [{"start": 0.0, "end": b - a, "text": part.text.strip()}] | |
| for seg in segs: | |
| text = strip_caption_name(seg.get("text") or "") | |
| if not text: | |
| continue | |
| # A piece's last segment has no end from Whisper; keep every | |
| # segment inside its own piece. | |
| s0 = round(min(a + seg["start"], b), 3) | |
| e0 = round(min(a + seg["end"], b), 3) | |
| segments.append({"start": s0, "end": e0 if e0 > s0 else round(b, 3), "text": text}) | |
| segments = drop_repeats(segments) | |
| for i, seg in enumerate(segments): | |
| seg["id"] = i | |
| result = TranscriptionResult( | |
| text=" ".join(seg["text"] for seg in segments), | |
| language=language, | |
| segments=segments or None, | |
| audio_duration=metadata.duration, | |
| model_used=self.current_model_key, | |
| ) | |
| result.processing_time = time.time() - started | |
| return result | |
| def _transcribe_pieces(self, pipe: ASRPipeline, audio, sr, spans, kwargs, lang: Optional[str], | |
| on_piece=None) -> List[Dict]: | |
| """Transcribe each (start, end) span on its own and return segments on | |
| the recording's timeline. Segment ends are kept inside their span: | |
| the dedicated models' own timestamps can run past the audio.""" | |
| pad = 0.15 | |
| total = len(audio) / sr | |
| out: List[Dict] = [] | |
| for s0, e0 in spans: | |
| start, end = max(0.0, s0 - pad), min(total, e0 + pad) | |
| piece = audio[int(start * sr): int(end * sr)] | |
| part = pipe.transcribe(piece, long_form=True, **kwargs) | |
| segs = drop_repeats([dict(x) for x in part.segments or []]) | |
| if not segs and (part.text or "").strip(): | |
| segs = [{"start": 0.0, "end": end - start, "text": part.text.strip()}] | |
| for seg in segs: | |
| if not (seg.get("text") or "").strip(): | |
| continue | |
| seg["start"] = round(min(start + seg["start"], end), 3) | |
| seg["end"] = round(min(start + seg["end"], end), 3) | |
| if seg["end"] <= seg["start"]: | |
| seg["end"] = round(end, 3) | |
| if lang: | |
| seg["language"] = lang | |
| out.append(seg) | |
| if on_piece: | |
| on_piece() | |
| return out | |
| def _english_word_share(self, text: str, tokenizer) -> float: | |
| """Share of words that are English words: in our list, or a single | |
| whole-word token in Whisper's (English-trained) vocabulary. Yoruba | |
| words Whisper merely spells out ("Latibi", "Owu") split into pieces.""" | |
| words = ["".join(ch for ch in w.split("'")[0] if ch.isalpha()) for w in text.split()] | |
| words = [w for w in words if w] | |
| if not words: | |
| return 0.0 | |
| hits = 0 | |
| for w in words: | |
| if not w.isascii(): | |
| continue | |
| if w.lower() in ENGLISH_WORDS or len(tokenizer.encode(" " + w.lower(), add_special_tokens=False)) == 1: | |
| hits += 1 | |
| return hits / len(words) | |
| def _says_something(text: str) -> bool: | |
| """A number, or an English word of 4+ letters that isn't a filler.""" | |
| for w in text.split(): | |
| w = "".join(ch for ch in w.lower() if ch.isalnum()) | |
| if any(ch.isdigit() for ch in w) or (len(w) >= 4 and w.isascii() and w.isalpha() and w not in ENGLISH_FILLERS): | |
| return True | |
| return False | |
| def _probe_native_language(self, audio, sr, job_model: str) -> Optional[str]: | |
| """Auto-detect: is this mostly Yoruba or Hausa? Returns the language, | |
| or None to carry on with the usual language plan.""" | |
| available = self.registry.list_available_models() | |
| if DETECTOR_MODEL not in available: | |
| return None | |
| total_sec = len(audio) / sr | |
| spans = pieces(speech_windows(audio, sr), 0.0, total_sec) or [] | |
| spans = [sp for sp in spans if sp[1] - sp[0] >= 0.4] # alphabet drills are single letters | |
| if len(spans) < 3: | |
| return None | |
| step = max(1, len(spans) // PROBE_PIECES) | |
| sample = spans[::step][:PROBE_PIECES] | |
| clips = [audio[int(a * sr): int(b * sr)] for a, b in sample] | |
| try: | |
| detector = self._use_model(DETECTOR_MODEL) | |
| # Which dedicated language is closest (Igbo has no Whisper token). | |
| totals: Dict[str, float] = {} | |
| for sc in detector.language_scores(clips, ["yo", "ha"], sr): | |
| for c, v in (sc or {}).items(): | |
| totals[c] = totals.get(c, 0.0) + v | |
| lang = max(totals, key=totals.get) if totals else "yo" | |
| if NATIVE_MODELS.get(lang) not in available: | |
| return None | |
| whisper_read = detector.decode_with_confidence(clips, None, sr) | |
| native_read = self._use_model(NATIVE_MODELS[lang]).decode_with_confidence(clips, None, sr) | |
| except Exception as e: | |
| logger.warning(f"Language probe skipped: {type(e).__name__}") | |
| return None | |
| wins = sum(1 for (wt, ws), (nt, ns) in zip(whisper_read, native_read) | |
| if nt and ns is not None and (ws is None or ns > ws)) | |
| logger.info(f"Language probe: {lang} model surer on {wins}/{len(sample)} sample pieces") | |
| return lang if wins >= PROBE_NATIVE_SHARE * len(sample) else None | |
| def _transcribe_native_with_english(self, audio, sr, lang: str, job_model: str, kwargs, | |
| progress_callback) -> TranscriptionResult: | |
| """A chosen Yoruba/Igbo/Hausa recording, piece by piece, with English | |
| kept where it really is English (see ENGLISH_CONFIDENCE_MARGIN).""" | |
| total_sec = len(audio) / sr | |
| windows = speech_windows(audio, sr) | |
| spans = pieces(windows, 0.0, total_sec, cuts=getattr(self, "_turn_cuts", ())) or [(0.0, total_sec)] | |
| pad = 0.15 | |
| clip = lambda a, b: audio[int(max(0.0, a - pad) * sr): int(min(total_sec, b + pad) * sr)] | |
| clips = [clip(a, b) for a, b in spans] | |
| # 1. Which pieces might be English at all (Whisper's language guess). | |
| candidates: List[int] = [] | |
| detector_key = DETECTOR_MODEL if DETECTOR_MODEL in self.registry.list_available_models() else None | |
| if detector_key: | |
| try: | |
| detector = self._use_model(detector_key) | |
| codes = scoring_codes([lang, "en"], "ig" if lang == "ig" else None) | |
| for i, sc in enumerate(detector.language_scores(clips, codes, sr)): | |
| if sc and "en" in sc: | |
| others = [v for c, v in sc.items() if c != "en"] | |
| if others and sc["en"] - max(others) > ENGLISH_CANDIDATE_MARGIN: | |
| candidates.append(i) | |
| except Exception as e: | |
| logger.warning(f"English check skipped: {type(e).__name__}") | |
| done, total = [0], [len(spans) + len(candidates)] | |
| if progress_callback: | |
| progress_callback(0, total[0]) | |
| def tick(): | |
| done[0] += 1 | |
| if progress_callback: | |
| progress_callback(min(done[0], total[0]), total[0]) | |
| # 2. Whisper's English reading of each candidate, and how sure it is. | |
| # It only refines the transcript, so if it fails the recording is read | |
| # entirely by the dedicated model instead of failing the job. | |
| english: Dict[int, Tuple[str, Optional[float]]] = {} | |
| tokenizer = None | |
| if candidates: | |
| try: | |
| en_pipe = self._use_model(self._model_for("en", job_model)) | |
| tokenizer = en_pipe.pipeline.tokenizer | |
| for i, reading in zip(candidates, en_pipe.decode_with_confidence([clips[i] for i in candidates], "en", sr)): | |
| english[i] = reading | |
| tick() | |
| except Exception as e: | |
| logger.warning(f"English reading skipped: {type(e).__name__}: {e}") | |
| english, candidates = {}, [] | |
| total[0] = len(spans) | |
| # 3. The dedicated model reads every piece; for candidates its own | |
| # confidence is compared with Whisper's. | |
| nat_pipe = self._use_model(self._model_for(lang, job_model)) | |
| nat_kwargs = dict(kwargs) | |
| nat_kwargs["language"] = None if lang in NO_WHISPER_TOKEN else lang | |
| native_read = dict(zip(candidates, nat_pipe.decode_with_confidence([clips[i] for i in candidates], None, sr))) if candidates else {} | |
| # Clear English first; then pieces next to clear English only need | |
| # Whisper to be ahead at all (English explanations break into short | |
| # pieces such as "means" or "for example"). | |
| keep: Dict[int, bool] = {} | |
| for i in english: | |
| en_text, en_score = english[i] | |
| nat_text, nat_score = native_read.get(i, ("", None)) | |
| share = self._english_word_share(en_text, tokenizer) if en_text else 0.0 | |
| n_words = len([w for w in en_text.split() if any(ch.isalpha() for ch in w)]) | |
| ahead = en_score is not None and (nat_score is None or en_score > nat_score) | |
| clearly = en_score is not None and (nat_score is None or en_score > nat_score + ENGLISH_CONFIDENCE_MARGIN) | |
| keep[i] = bool(en_text) and ( | |
| (clearly and share >= ENGLISH_WORD_SHARE and self._says_something(en_text)) | |
| or (ahead and n_words >= ENGLISH_SENTENCE_WORDS and share >= ENGLISH_SENTENCE_SHARE)) | |
| changed = True | |
| while changed: | |
| changed = False | |
| for i in english: | |
| if keep[i]: | |
| continue | |
| near = any(keep.get(j) and (abs(spans[j][1] - spans[i][0]) < 1.5 or abs(spans[i][1] - spans[j][0]) < 1.5) | |
| for j in (i - 1, i + 1)) | |
| en_text, en_score = english[i] | |
| nat_score = native_read.get(i, ("", None))[1] | |
| if near and en_text and en_score is not None and (nat_score is None or en_score > nat_score) \ | |
| and self._english_word_share(en_text, tokenizer) >= ENGLISH_WORD_SHARE: | |
| keep[i] = changed = True | |
| self._english_decisions = [(spans[i], english[i][0], native_read.get(i, ("", None))[0], english[i][1], | |
| native_read.get(i, ("", None))[1], keep[i]) for i in sorted(english)] | |
| segments: List[Dict] = [] | |
| chose_english = 0 | |
| for i, span in enumerate(spans): | |
| if keep.get(i): | |
| a, b = span | |
| segments.append({"start": round(a, 3), "end": round(b, 3), "text": english[i][0], "language": "en"}) | |
| chose_english += 1 | |
| tick() | |
| else: | |
| segments += self._transcribe_pieces(nat_pipe, audio, sr, [span], nat_kwargs, lang, tick) | |
| segments.sort(key=lambda x: x["start"]) | |
| for i, seg in enumerate(segments): | |
| seg["id"] = i | |
| languages = [lang, "en"] if chose_english else [] | |
| logger.info(f"{lang} recording: {len(spans)} pieces, {len(candidates)} checked for English, {chose_english} kept in English") | |
| return TranscriptionResult( | |
| text=" ".join(x["text"] for x in segments if x.get("text")).strip(), | |
| language=lang, | |
| segments=segments or None, | |
| model_used=self.current_model_key if not chose_english else f"{NATIVE_FALLBACK}+{self.current_model_key}", | |
| languages=languages, | |
| ) | |
| def _transcribe_native(self, audio, sr, metadata, kwargs, progress_callback, started) -> TranscriptionResult: | |
| """Yoruba/Igbo/Hausa models get sentence-sized pieces cut at pauses: | |
| on long stretches they drop words and return one segment with a wrong | |
| end time, which broke paragraphs and the replay highlight.""" | |
| windows = getattr(self, "_plan_windows", None) or speech_windows(audio, sr) | |
| spans = pieces(windows, 0.0, len(audio) / sr, cuts=getattr(self, "_turn_cuts", ())) or [(0.0, len(audio) / sr)] | |
| done = [0] | |
| if progress_callback: | |
| progress_callback(0, len(spans)) | |
| def tick(): | |
| done[0] += 1 | |
| if progress_callback: | |
| progress_callback(done[0], len(spans)) | |
| segs = self._transcribe_pieces(self._get_pipeline(), audio, sr, spans, kwargs, None, tick) | |
| for i, seg in enumerate(segs): | |
| seg["id"] = i | |
| return TranscriptionResult( | |
| text=" ".join(s["text"] for s in segs).strip(), | |
| language=kwargs.get("language"), | |
| segments=segs or None, | |
| audio_duration=metadata.duration, | |
| model_used=self.current_model_key, | |
| processing_time=time.time() - started, | |
| ) | |
| def _transcribe_mixed(self, audio, sr, runs: List[Run], job_model: str, kwargs, | |
| progress_callback) -> TranscriptionResult: | |
| """Transcribe each language's parts with that language's model, loading | |
| each model once, then put the segments back in time order.""" | |
| order = list(dict.fromkeys(r.language for r in runs)) | |
| main_lang = dominant_language(runs) | |
| # Pinned English phrases are checked once transcribed; those that turn | |
| # out not to be English are redone by the main language's model, so | |
| # English goes first. | |
| if any(r.pinned for r in runs) and "en" in order and main_lang != "en": | |
| order = ["en"] + [l for l in order if l != "en"] | |
| windows = getattr(self, "_plan_windows", None) or [] | |
| cuts = getattr(self, "_turn_cuts", ()) | |
| spans_by_run = {id(r): (pieces(windows, r.start, r.end, cuts=cuts) or [(r.start, r.end)]) for r in runs} | |
| total = [sum(len(v) for v in spans_by_run.values())] | |
| done = [0] | |
| if progress_callback: | |
| progress_callback(0, total[0]) | |
| def tick(): | |
| done[0] += 1 | |
| if progress_callback: | |
| progress_callback(min(done[0], total[0]), total[0]) | |
| segments: List[Dict] = [] | |
| models_used = [] | |
| for lang in order: | |
| pipe = self._use_model(self._model_for(lang, job_model)) | |
| models_used.append(self.current_model_key) | |
| run_kwargs = dict(kwargs) | |
| run_kwargs["language"] = None if lang in NO_WHISPER_TOKEN else lang | |
| native = self.current_model_key.startswith("ncair-") | |
| for r in [r for r in runs if r.language == lang]: | |
| # Dedicated models need one sentence at a time; Whisper does | |
| # better with the whole section and its context. | |
| spans = spans_by_run[id(r)] if native else [(r.start, r.end)] | |
| got = self._transcribe_pieces(pipe, audio, sr, spans, run_kwargs, lang, tick) | |
| if r.pinned and lang == "en" and not looks_english(" ".join(g.get("text", "") for g in got)): | |
| # Whisper thought this was English, but its English | |
| # transcript has no English words (a name, say). | |
| r.language = main_lang | |
| spans_by_run[id(r)] = pieces(windows, r.start, r.end, cuts=cuts) or [(r.start, r.end)] | |
| total[0] += len(spans_by_run[id(r)]) | |
| continue | |
| segments += got | |
| if not native: | |
| for _ in spans_by_run[id(r)][1:]: | |
| tick() | |
| segments.sort(key=lambda s: s["start"]) | |
| for i, seg in enumerate(segments): | |
| seg["id"] = i | |
| main = dominant_language(runs) | |
| heard = [main] + [l for l in order if l != main] | |
| logger.info(f"Mixed-language transcript: {heard} using {models_used}") | |
| return TranscriptionResult( | |
| text=" ".join(s["text"] for s in segments if s.get("text")).strip(), | |
| language=main, | |
| segments=segments or None, | |
| model_used="+".join(dict.fromkeys(models_used)), | |
| languages=heard, | |
| ) | |
| def transcribe_bytes(self, audio_bytes: bytes, filename: str = "audio", **kwargs) -> TranscriptionResult: | |
| suffix = Path(filename).suffix or ".bin" | |
| temp_path = self.temp_dir / f"upload_{uuid.uuid4().hex[:8]}_{Path(filename).stem}{suffix}" | |
| with open(temp_path, 'wb') as f: | |
| f.write(audio_bytes) | |
| try: | |
| return self.transcribe_file(str(temp_path), **kwargs) | |
| finally: | |
| temp_path.unlink(missing_ok=True) | |
| def get_available_models(self) -> Dict: | |
| return self.registry.list_available_models() | |
| def get_current_model_info(self) -> Dict: | |
| return self.registry.list_available_models().get(self.current_model_key, {}) | |