"""Donate audio for credits (narratifai.com/donate). Two kinds of donation, both checked here before any credit is given: read one Yoruba, Igbo or Hausa sentence read aloud. Accepted when our model hears roughly that sentence (character error rate under READ_MAX_CER, ignoring tone marks): this proves it was really read. upload a recording of 30 s to 10 min. Accepted when it has enough real speech and the language detector is sure it is the chosen language. Rewards: 1 credit per 5 accepted sentences, and 1 credit per complete usable speech minute per upload. Uploads wait for human approval. """ import unicodedata import math from typing import Optional, Tuple import numpy as np LANGUAGES = {"yo", "ig", "ha"} READ_MIN_SPEECH_SEC = 1.0 READ_MAX_SEC = 30.0 READ_MAX_CER = 0.55 # measured: 120 FLEURS readings, no wrong sentence accepted (read_threshold_modal.py) UPLOAD_MIN_SEC = 30.0 UPLOAD_MAX_SEC = 600.0 UPLOAD_MIN_SPEECH_SHARE = 0.4 UPLOAD_MIN_LANG_PROB = 0.6 MIN_SPEECH_DBFS = -45.0 # quieter than this is silence or hiss, not speech MAX_WORDS_PER_MIN = 200 def normalise(text: str) -> str: """Lower case, tone marks and dots removed, letters and spaces only.""" text = unicodedata.normalize("NFD", text.lower()) text = "".join(c for c in text if not unicodedata.combining(c)) text = text.replace("ɓ", "b").replace("ɗ", "d").replace("ƙ", "k").replace("ƴ", "y") text = "".join(c if c.isalpha() or c.isspace() else " " for c in text) return " ".join(text.split()) def cer(heard: str, expected: str) -> float: a, b = normalise(heard).replace(" ", ""), normalise(expected).replace(" ", "") if not b: return 1.0 prev = list(range(len(b) + 1)) for i, x in enumerate(a, 1): cur = [i] for j, y in enumerate(b, 1): cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y))) prev = cur return prev[-1] / len(b) def speech_seconds(audio: np.ndarray, sr: int) -> float: """Unpadded learned-VAD speech duration, never waveform energy or file length. A tone or normalized noise must not generate cash rewards. Detection errors fail the donation check instead of falling back to permissive energy gates. """ if sr != 16000: raise ValueError("Donation speech measurement requires 16 kHz audio") audio = np.asarray(audio, dtype=np.float32) if audio.ndim != 1 or not np.isfinite(audio).all(): raise ValueError("Finite mono audio required") if not audio.size or not np.any(audio): return 0.0 from faster_whisper.vad import get_speech_timestamps, VadOptions spans = get_speech_timestamps(audio, VadOptions( threshold=0.5, min_speech_duration_ms=250, min_silence_duration_ms=100, speech_pad_ms=0, ), sampling_rate=sr) # Union/clamp spans defensively; overlapping regions must not pay twice. total, end = 0, 0 for span in sorted(spans, key=lambda x: x['start']): start = max(end, 0, int(span['start'])) stop = min(len(audio), int(span['end'])) total += max(0, stop - start) end = max(end, stop) return total / sr def judge_read(duration: float, speech: float, transcript: str, prompt: str) -> Tuple[bool, Optional[str]]: if not all(math.isfinite(v) for v in (duration, speech)) or duration <= 0 or speech < 0 or speech > duration + 0.1: return False, "We could not measure this recording. Please record it again." if duration > READ_MAX_SEC: return False, "Recordings of one sentence should be under 30 seconds." if speech < READ_MIN_SPEECH_SEC: return False, "We couldn't hear any speech. Try again a little closer to the microphone." if not normalise(prompt) or not normalise(transcript): return False, "We could not hear the sentence. Please try again." if cer(transcript, prompt) > READ_MAX_CER: return False, "That didn't sound like the sentence shown. Please read it as written." return True, None def judge_upload(duration: float, speech: float, language: str, heard: Optional[str], prob: float) -> Tuple[bool, Optional[str]]: if not all(math.isfinite(v) for v in (duration, speech, prob)) or duration <= 0 or speech < 0 or speech > duration + 0.1 or not 0 <= prob <= 1: return False, "We could not measure this recording. Please record it again." if language not in LANGUAGES: return False, "Choose Yoruba, Igbo or Hausa." if duration < UPLOAD_MIN_SEC: return False, "Recordings need to be at least 30 seconds long." if duration > UPLOAD_MAX_SEC: return False, "Recordings can be up to 10 minutes long." if speech < UPLOAD_MIN_SPEECH_SHARE * duration: return False, "There wasn't enough speech in this recording." if heard != language or prob < UPLOAD_MIN_LANG_PROB: return False, "This didn't sound like the language you chose." return True, None def upload_words(text: str, speech: float) -> int: """Words our model heard in an upload, capped at a plausible speaking rate.""" if not math.isfinite(speech) or speech <= 0: return 0 return min(len(text.split()), int(MAX_WORDS_PER_MIN * speech / 60)) def upload_credits(speech: float) -> int: """Whole usable minutes in this recording; partial minutes earn no credit.""" if isinstance(speech, bool) or not math.isfinite(speech) or speech <= 0: return 0 return math.floor(min(speech, UPLOAD_MAX_SEC) / 60)