Download scoring.py from Emin009/HAKEM: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/Emin009/HAKEM/resolve/main/scoring.py
- Command line
-
hf download hf://spaces/Emin009/HAKEM/scoring.py
-
curl -L -o scoring.py https://huggingface.co/spaces/Emin009/HAKEM/resolve/main/scoring.py
10.2 kB
| """Frozen Whisper candidate likelihoods; no task-specific training.""" | |
| import os | |
| from functools import lru_cache | |
| from threading import RLock | |
| import numpy as np | |
| import torch | |
| from scipy.signal import resample_poly | |
| from math import gcd | |
| from transformers import WhisperProcessor, WhisperForConditionalGeneration | |
| from transformers.modeling_outputs import BaseModelOutput | |
| from rapidfuzz.distance import Levenshtein | |
| MODEL = 'openai/whisper-tiny' | |
| REVISION = '169d4a4341b33bc18d8881c4b69c2e104e1cc0af' | |
| LANGUAGES = {'Hassaniya / Arabic': 'ar', 'English': 'en', 'French': 'fr', | |
| 'Spanish': 'es', 'Portuguese': 'pt', 'German': 'de', 'Hausa': 'ha', | |
| 'Swahili': 'sw', 'Hindi': 'hi', 'Chinese': 'zh'} | |
| LOCK = RLock() | |
| def load_model(): | |
| # Offline by default: deploying requires an explicit environment choice. | |
| offline = os.getenv('HAKEM_ALLOW_MODEL_DOWNLOAD', '0') != '1' | |
| torch.set_num_threads(int(os.getenv('HAKEM_CPU_THREADS', '4'))) | |
| processor = WhisperProcessor.from_pretrained(MODEL, revision=REVISION, local_files_only=offline) | |
| device = os.getenv('HAKEM_DEVICE', 'cpu') | |
| if device not in ('cpu', 'cuda'): | |
| raise ValueError('HAKEM_DEVICE must be cpu or cuda.') | |
| model = WhisperForConditionalGeneration.from_pretrained( | |
| MODEL, revision=REVISION, local_files_only=offline, | |
| torch_dtype=torch.float32, attn_implementation='eager').to(device).eval() | |
| model.requires_grad_(False) | |
| return processor, model | |
| def catalogue(text): | |
| rows = tuple(s.strip() for s in text.splitlines() if s.strip()) | |
| if not 2 <= len(rows) <= 32: | |
| raise ValueError('Enter between 2 and 32 candidates, one per line.') | |
| if len(set(rows)) != len(rows): | |
| raise ValueError('Remove duplicate candidates.') | |
| if any(len(s) > 120 for s in rows): | |
| raise ValueError('Keep each candidate within 120 characters.') | |
| return rows | |
| def waveform(audio): | |
| if audio is None: | |
| raise ValueError('Record or upload audio first.') | |
| sr, wave = audio | |
| sr = int(sr) | |
| wave = np.asarray(wave) | |
| if not 8000 <= sr <= 192000 or wave.ndim not in (1, 2) or wave.size == 0: | |
| raise ValueError('Use a valid mono or stereo recording.') | |
| if wave.shape[0] / sr > 12: | |
| raise ValueError('Keep the recording within 12 seconds.') | |
| if np.issubdtype(wave.dtype, np.integer): | |
| if wave.dtype == np.uint8: | |
| wave = (wave.astype(np.float32) - 128) / 128 | |
| else: | |
| wave = wave.astype(np.float32) / (float(np.iinfo(wave.dtype).max) + 1) | |
| else: | |
| wave = wave.astype(np.float32) | |
| if wave.ndim == 2: | |
| wave = wave.mean(axis=1) | |
| if not np.isfinite(wave).all(): | |
| raise ValueError('The recording contains invalid samples.') | |
| if sr != 16000: | |
| divisor = gcd(sr, 16000) | |
| wave = resample_poly(wave, 16000 // divisor, sr // divisor).astype(np.float32) | |
| if len(wave) < 1600: | |
| raise ValueError('Record at least 0.1 seconds of speech.') | |
| if np.sqrt(np.mean(wave.astype(np.float64) ** 2)) < 1e-5: | |
| raise ValueError('The input is silent. Record audible speech.') | |
| return wave | |
| def encode(wave, processor, model): | |
| features = processor.feature_extractor(wave, sampling_rate=16000, return_tensors='pt').input_features | |
| return model.model.encoder(features.to(model.device)).last_hidden_state | |
| def sequences(rows, language, tokenizer): | |
| if language not in LANGUAGES.values(): | |
| raise ValueError('Choose a supported language prompt.') | |
| prefix = tokenizer.convert_tokens_to_ids([ | |
| '<|startoftranscript|>', f'<|{language}|>', '<|transcribe|>', '<|notimestamps|>']) | |
| targets = [tokenizer(' ' + row, add_special_tokens=False).input_ids + [tokenizer.eos_token_id] | |
| for row in rows] | |
| if any(len(t) > 64 for t in targets): | |
| raise ValueError('A candidate exceeds 63 text tokens; shorten it.') | |
| return prefix, targets | |
| def likelihoods(encoded, rows, language, processor, model, batch_size=8): | |
| prefix, targets = sequences(rows, language, processor.tokenizer) | |
| scores = [] | |
| for start in range(0, len(rows), batch_size): | |
| group = [prefix + target for target in targets[start:start + batch_size]] | |
| length = max(map(len, group)) | |
| ids = torch.full((len(group), length), processor.tokenizer.eos_token_id, dtype=torch.long, device=encoded.device) | |
| mask = torch.zeros((len(group), length - 1), dtype=torch.bool, device=encoded.device) | |
| for i, seq in enumerate(group): | |
| ids[i, :len(seq)] = torch.tensor(seq, device=encoded.device) | |
| mask[i, len(prefix) - 1:len(seq) - 1] = True | |
| logits = model(encoder_outputs=(encoded.expand(len(group), -1, -1),), | |
| decoder_input_ids=ids, use_cache=False).logits[:, :-1].float() | |
| token_scores = logits.log_softmax(-1).gather(-1, ids[:, 1:, None]).squeeze(-1) | |
| scores.extend((token_scores * mask).sum(1).cpu().numpy().tolist()) | |
| return np.asarray(scores, dtype=np.float64) | |
| def silence_scores(rows, language): | |
| # Only text-derived silence scores are cached; visitor audio is not cached here. | |
| processor, model = load_model() | |
| with torch.inference_mode(): | |
| encoded = encode(np.zeros(32000, dtype=np.float32), processor, model) | |
| return likelihoods(encoded, rows, language, processor, model) | |
| def fold(text): | |
| # Same Unicode alphanumeric normalization as the paper's T-match runner. | |
| return ''.join(c for c in str(text).lower() if c.isalnum()) | |
| def match_transcript(transcript, rows): | |
| hypothesis = fold(transcript) | |
| similarity = np.asarray([1 - Levenshtein.normalized_distance(hypothesis, fold(row)) for row in rows]) | |
| best = float(similarity.max()) | |
| tied = [row for row, score in zip(rows, similarity) if score == best] | |
| return tied, similarity | |
| def _run(audio, text, language_label, transcribe=False): | |
| import time | |
| rows = catalogue(text) | |
| wave = waveform(audio) | |
| language = LANGUAGES.get(language_label) | |
| if language is None: | |
| raise ValueError('Choose a language from the menu.') | |
| started = time.monotonic() | |
| with LOCK, torch.inference_mode(): | |
| processor, model = load_model() | |
| prior = silence_scores(rows, language) | |
| encoded = encode(wave, processor, model) | |
| speech = likelihoods(encoded, rows, language, processor, model) | |
| transcript, capped = None, False | |
| decode_seconds = None | |
| if transcribe: | |
| decode_started = time.monotonic() | |
| result = model.generate( | |
| encoder_outputs=BaseModelOutput(last_hidden_state=encoded), | |
| language=language, task='transcribe', return_timestamps=False, | |
| num_beams=10, do_sample=False, length_penalty=1.0, | |
| max_new_tokens=128, renormalize_logits=False, return_dict_in_generate=True) | |
| sequence = result.sequences[0].tolist() | |
| transcript = processor.tokenizer.decode(sequence, skip_special_tokens=True).strip() | |
| capped = sequence[-1] != processor.tokenizer.eos_token_id | |
| decode_seconds = round(time.monotonic() - decode_started, 3) | |
| corrected = speech - prior | |
| order = np.argsort(-corrected, kind='stable') | |
| table = [[rows[i], round(corrected[i], 3), round(speech[i], 3), round(prior[i], 3)] for i in order] | |
| details = { | |
| 'model': MODEL, 'revision': REVISION, 'precision': 'float32', 'device': str(model.device), | |
| 'candidate_count': len(rows), 'audio_seconds': round(len(wave) / 16000, 3), | |
| 'elapsed_seconds': round(time.monotonic() - started, 3), | |
| 'scope': 'Closed catalogue; scores are not probabilities or calibrated confidence.', | |
| 'silence_reference_seconds': 2, 'additional_weight_training': False} | |
| if transcribe: | |
| details.update({'transcription_seconds': decode_seconds, 'transcription_token_cap_reached': capped, | |
| 'decoder': {'num_beams': 10, 'max_new_tokens': 128, 'do_sample': False}, | |
| 't_match': 'Lowercase Unicode alphanumeric text; highest normalized Levenshtein similarity. All exact ties reported.'}) | |
| return rows, corrected, order, table, details, transcript | |
| def select(audio, text, language_label): | |
| rows, _, order, table, details, _ = _run(audio, text, language_label) | |
| return rows[order[0]], table, details | |
| def compare(audio, text, language_label, expected=''): | |
| expected = expected.strip() | |
| initial_rows = catalogue(text) | |
| if expected and expected not in initial_rows: | |
| raise ValueError('The expected item must exactly match a candidate, or leave it blank.') | |
| # Expected item is used ONLY after both methods run. It never enters the model or matcher. | |
| rows, corrected, order, table, details, transcript = _run(audio, text, language_label, transcribe=True) | |
| t_ties, similarities = match_transcript(transcript, rows) | |
| h_ties = [row for row, score in zip(rows, corrected) if score == corrected.max()] | |
| h_display = h_ties[0] if len(h_ties) == 1 else 'Tie: ' + ' | '.join(h_ties) | |
| t_display = t_ties[0] if len(t_ties) == 1 else 'Tie: ' + ' | '.join(t_ties) | |
| for ranked_row, row_index in zip(table, order): | |
| ranked_row.append(round(float(similarities[row_index]), 4)) | |
| if not expected: | |
| assessment = 'Enter the expected item to check this recording. Agreement alone does not establish correctness.' | |
| else: | |
| def outcome(ties): | |
| if len(ties) == 1: | |
| return 'correct' if ties[0] == expected else 'incorrect' | |
| return 'tied (includes expected item)' if expected in ties else 'incorrect (tie excludes expected item)' | |
| assessment = f'This recording: HAKEM is {outcome(h_ties)}; T-match is {outcome(t_ties)}. A single recording is not an accuracy benchmark.' | |
| if details['transcription_token_cap_reached']: | |
| assessment += ' Whisper reached the token limit; its transcript may be incomplete.' | |
| details.update({'hakem_tied_candidates': h_ties, 't_match_tied_candidates': t_ties, | |
| 'expected_item_used_for_inference': False}) | |
| return h_display, t_display, transcript, assessment, table, details | |