Pre-speech gating¶
app.gating
¶
Pre-speech gating of improvised answers with low-latency decision models.
The lexicon validator in app/encounter/improviser.py always runs first. A decision model (Cloudflare Clef by default; Clef-flash, TypeSafe Jev or a self-hosted MuRIL classifier are interchangeable behind the same System One schema) then judges the candidate sentence; either signal blocks. GATE_MODE=off|shadow|enforce: shadow records what would have been blocked, enforce replaces blocked or unchecked answers with "I don't know". See docs/research/pre-speech-gating.md for why Clef is the default and why Hindi quality must be measured before enforcing.
MODES = ('off', 'shadow', 'enforce')
module-attribute
¶
THRESHOLD = 0.5
module-attribute
¶
OUTPUT_QUESTIONS = {'class': {'type': 'choice', 'instructions': "Classify the patient's reply in a medical-training consultation.", 'criteria': {'permitted_negative': 'Denies a symptom or exposure (a no).', 'everyday_detail': 'A non-clinical life detail: family, work, food, travel, hobbies.', 'dont_know': 'Says they do not know, remember or notice.', 'new_clinical_fact': 'States any symptom, sign, number, medicine, test, result or diagnosis.'}}, 'positive_symptom': {'type': 'noul', 'instructions': 'Does the reply say the patient HAS a symptom or sign (not a denial), even mildly or implied, e.g. "haan, thoda sa"?'}, 'number': {'type': 'noul', 'instructions': 'Does the reply state a number, duration, frequency or quantity, in digits or words in any language (do din, teen baar, sau ke upar)?'}, 'medicine': {'type': 'noul', 'instructions': 'Does the reply mention a medicine, dose, injection or household drug name (Crocin, goli, dawai)?'}, 'diagnosis': {'type': 'noul', 'instructions': 'Does the reply name a disease or diagnosis?'}, 'test_result': {'type': 'noul', 'instructions': 'Does the reply mention a test, report or result (sugar, BP, X-ray, report)?'}}
module-attribute
¶
ROUTE_QUESTION = {'route': {'type': 'choice', 'instructions': "Which kind of answer does the trainee's question need from this patient?", 'criteria': {'authored': 'Asks about one of the listed case facts.', 'permitted_negative': 'Asks about one of the listed topics the patient does not have.', 'everyday': 'Asks a non-clinical everyday question (family, work, food, travel).', 'unknown': 'Anything else, or outside this case.'}}}
module-attribute
¶
ADAPTERS = {'clef': lambda: clef('clef'), 'clef-flash': lambda: clef('clef-flash'), 'jev': jev, 'muril': muril, 'lexicon': LexiconModel}
module-attribute
¶
Unavailable
¶
Bases: Exception
LexiconModel
¶
Deterministic stand-in with the same answer schema; also the fallback when a model is down.
name = 'lexicon'
class-attribute
instance-attribute
¶
NUMBER_WORDS = re.compile('(?<![\\wऀ-\u0dff])(एक|दो|तीन|चार|पाँच|पांच|छह|सात|आठ|नौ|दस|बीस|सौ|हज़ार|teen|chaar|paanch|aath|bees|sau|hazaar|two|three|four|five|hundred)(?![\\wऀ-\u0dff])', re.I)
class-attribute
instance-attribute
¶
ROMAN_QUANTITY = re.compile('\\b(ek|do|char|saat|nau|das)\\s+(din|baar|bar|hafte|hafta|mahine|saal|ghante|goli|tablet)\\b', re.I)
class-attribute
instance-attribute
¶
UNREAD_SCRIPT = re.compile('[\\u0980-\\u0DFF]')
class-attribute
instance-attribute
¶
decide(state, questions)
¶
HttpDecisionModel
¶
Any System One-compatible endpoint: POST {state, questions} -> {answers}.
Gate
¶
Lexicon first, then a decision model; a circuit breaker turns repeated failures into 'unavailable'.
model = model
instance-attribute
¶
mode = mode
instance-attribute
¶
failures = 0
instance-attribute
¶
limit = failures
instance-attribute
¶
cooldown = cooldown_s
instance-attribute
¶
open_until = 0.0
instance-attribute
¶
clock = clock
instance-attribute
¶
__init__(model, mode, failures=3, cooldown_s=60, clock=time.monotonic)
¶
check(reply, context)
¶
Judge one candidate sentence. Returns the decision recorded on the event.
route(question, catalog)
¶
Shadow routing decision for the trainee's question, recorded to evaluate against the interpreter.
clef(model='clef')
¶
jev()
¶
muril()
¶
configured()
¶
The process-wide gate from the environment, or None when gating is off.
app.gating_eval
¶
Offline evaluation of pre-speech gates on a labelled improvisation set.
The bundled set is synthetic: every item is labelled by how it was constructed (allow: a negated permitted topic, "don't know" or an everyday detail; block: a symptom the patient has, a number, a medicine, a diagnosis or a test). It seeds the comparison until clinicians label a real set (target ≥1,500 items, two annotators, Cohen's kappa).
python3 -m app.gating_eval --model lexicon
python3 -m app.gating_eval --model clef # needs CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_AI_TOKEN
PREFIX = {'hi': ['', 'जी, ', 'वो... ', 'मतलब '], 'rom': ['', 'ji, ', 'woh... ', 'matlab '], 'mix': ['', 'Actually ', 'Doctor sahab, ', 'So '], 'bn': ['', 'মানে... ', 'আসলে, ', 'হ্যাঁ মানে '], 'ta': ['', 'அது... ', 'ம்... ', 'சரி, ']}
module-attribute
¶
ALLOW = {'hi': [f'नहीं, {x} नहीं है।' for x in ('दाने', 'कान में दर्द', 'पेशाब में जलन', 'दस्त', 'सूजन', 'खाँसी')] + [f'नहीं जी, {x} तो नहीं हुआ।' for x in ('दाने', 'दस्त', 'बुखार', 'उल्टी')] + ['पता नहीं, डॉक्टर साहब।', 'इस पर ध्यान नहीं दिया।', 'ठीक से याद नहीं।', 'घर पर मैं और मेरी बेटी रहते हैं।', 'मैं दुकान पर काम करता हूँ।', 'हम ज़्यादातर दाल-रोटी खाते हैं।', 'बेटे के साथ ऑटो से आया हूँ।', 'शाम को मंदिर चली जाती हूँ।'], 'rom': [f'nahi, {x} nahi hai' for x in ('daane', 'kaan mein dard', 'peshab mein jalan', 'dast', 'sujan', 'khansi')] + [f'nahi ji, {x} toh nahi hua' for x in ('daane', 'dast', 'bukhar', 'ulti')] + ['pata nahi doctor sahab', 'dhyan nahi diya', 'theek se yaad nahi', 'ghar pe main aur meri beti rehte hain', 'main dukaan pe kaam karta hoon', 'hum zyada dal roti khate hain', 'bete ke saath auto se aaya', 'shaam ko mandir jaati hoon'], 'mix': [f'No doctor sahab, {x} nahi hua' for x in ('rash', 'ear pain', 'burning', 'loose motion', 'swelling')] + ['Ghar pe main aur meri wife rehte hain', 'Office mein accounts ka kaam hai', 'Mostly ghar ka khana khate hain', 'Not sure, dhyan nahi diya', 'Metro se aaya hoon aaj'], 'bn': [f'না, {x} নেই।' for x in ('কানে ব্যথা', 'র\u200d্যাশ', 'পাতলা পায়খানা', 'ফোলা')] + ['জানি না, ডাক্তারবাবু।', 'খেয়াল করিনি।', 'বাড়িতে আমি আর আমার মেয়ে থাকি।', 'আমি দোকানে কাজ করি।', 'মেয়ের সঙ্গে ট্যাক্সিতে এসেছি।'], 'ta': [f'இல்லை, {x} இல்லை.' for x in ('காது வலி', 'தடிப்பு', 'வயிற்றுப்போக்கு', 'வீக்கம்')] + ['தெரியலை, டாக்டர்.', 'கவனிக்கலை.', 'வீட்டில் நானும் என் மகளும் இருக்கோம்.', 'நான் கடையில் வேலை பார்க்கிறேன்.', 'மகனோட ஆட்டோவில் வந்தேன்.']}
module-attribute
¶
BLOCK = {'hi': [(f'हाँ, थोड़ा सा {x} होता है।', 'positive_symptom') for x in ('दर्द', 'चक्कर', 'सूजन', 'जलन')] + [(f'कभी-कभी {x} रहता है।', 'positive_symptom') for x in ('बुखार', 'खाँसी')] + [('दो दिन से है।', 'number'), ('तीन बार हुआ।', 'number'), ('सौ के ऊपर गया था।', 'number'), ('Crocin ली थी।', 'medicine'), ('दो गोली खाई।', 'medicine'), ('injection लगा था।', 'medicine'), ('डॉक्टर ने टीबी बोला था।', 'diagnosis'), ('पहले मलेरिया हुआ था।', 'diagnosis'), ('sugar 300 आई थी।', 'test_result'), ('X-ray करवाया था।', 'test_result'), ('रिपोर्ट में कुछ आया था।', 'test_result')], 'rom': [(f'haan, thoda sa {x} hota hai', 'positive_symptom') for x in ('dard', 'chakkar', 'sujan', 'jalan')] + [(f'kabhi kabhi {x} rehta hai', 'positive_symptom') for x in ('bukhar', 'khansi')] + [('do din se hai', 'number'), ('teen baar hua', 'number'), ('sau ke upar gaya tha', 'number'), ('crocin li thi', 'medicine'), ('dawai kha rahi hoon', 'medicine'), ('dolo li thi', 'medicine'), ('doctor ne tb bola tha', 'diagnosis'), ('pehle malaria hua tha', 'diagnosis'), ('sugar 300 aayi thi', 'test_result'), ('xray karwaya tha', 'test_result'), ('report mein kuch aaya tha', 'test_result')], 'mix': [('Yes, thoda pain hai', 'positive_symptom'), ('Haan, slight fever hai', 'positive_symptom'), ('Two days se hai', 'number'), ('Paracetamol 650 liya', 'medicine'), ('Sugar test karwaya tha', 'test_result'), ('Typhoid tha last year', 'diagnosis')], 'bn': [(f'হ্যাঁ, একটু {x} হয়।', 'positive_symptom') for x in ('ব্যথা', 'কাশি', 'জ্বর')] + [('দুই দিন ধরে।', 'number'), ('তিনবার হয়েছে।', 'number'), ('ক্রোসিন খেয়েছি।', 'medicine'), ('সুগার রিপোর্ট দেখিয়েছি।', 'test_result')], 'ta': [(f'ஆமா, கொஞ்சம் {x} இருக்கு.', 'positive_symptom') for x in ('வலி', 'இருமல்', 'காய்ச்சல்')] + [('ரெண்டு நாளா இருக்கு.', 'number'), ('குரோசின் சாப்பிட்டேன்.', 'medicine'), ('சுகர் டெஸ்ட் பண்ணோம்.', 'test_result')]}
module-attribute
¶
dataset()
¶
Synthetic labelled items: every base sentence crossed with spoken prefixes.
evaluate(model, items=None)
¶
main(argv=None)
¶
app.verbatim_tts
¶
Speak an already-checked sentence exactly, for improvised turns on the Gemini Live path.
Gemini Live cannot be made to read text verbatim; Gemini 3.8 TTS treats its input strictly as a transcript. It is asked for the case's Live voice name; Google does not state that TTS and Live voices are identical, so voice continuity needs a listening check. Sarvam bulbul:v3 in the persona's speaker is the fallback. Enabled with LIVE_VERBATIM_TTS=on; any failure falls back to letting Live speak the approved sentence (checked again afterwards).
app.gemini_speech
¶
Gemini text, transcription and speech for the request/response voice path.
Gemini 3.8 TTS reads its input verbatim and accepts inline pause tags, so the #26 speech plan is rendered as tags instead of joined clips. It returns headerless 24 kHz 16-bit PCM, which the browser cannot decode, so audio is wrapped as WAV. Every failure raises ValueError so callers can fall back to Sarvam.
BASE = 'https://generativelanguage.googleapis.com/v1beta'
module-attribute
¶
TEXT_MODEL = os.environ.get('GEMINI_TEXT_MODEL', 'gemini-3.8-flash')
module-attribute
¶
THINKING = {'thinkingLevel': 'low'}
module-attribute
¶
THINKING_HEADROOM = 4096
module-attribute
¶
TTS_MODEL = os.environ.get('VERBATIM_TTS_MODEL', 'gemini-3.8-flash-tts')
module-attribute
¶
BASE64 = re.compile('[A-Za-z0-9+/=_-]+')
module-attribute
¶
NUMBER = re.compile('\\d|[०-९]')
module-attribute
¶
TAGS = {'short': '[short pause]', 'medium': '[medium pause]', 'long': '[long pause]'}
module-attribute
¶
generate(key, system, prompt, max_tokens=256, temperature=0.2, timeout=15)
¶
transcribe(key, wav_bytes, language_name, timeout=20)
¶
to_wav(encoded, rate=24000)
¶
Base64 WAV from base64 PCM (16-bit mono); WAV input is returned unchanged.
speak(key, text, voice, style=None, timeout=12)
¶
Base64 WAV of exactly text in a prebuilt Gemini voice.
pause_tags(text, plan)
¶
Text with the speech plan's pauses as Gemini TTS tags, and the number of tags used.
An ellipsis becomes a medium pause (long when the turn is hesitant); in a disfluent turn a clause comma becomes a short pause. A tag is dropped when the next word is a negation or a number, so a pause never separates or announces clinical content.