Control a web browser by speaking Nepali. Hold a key, say a command, the browser acts, and the terminal tells you it is done and ready for the next one.
One-sentence user (fill this in): "X uses it to do Y every day." It decides which commands matter first.
Status of this code: the pure logic (parsing, policy, safety, site matching, rules, metrics) is unit-tested (
pytest, 25 tests pass). The microphone, your Whisper model, the JEV model and Playwright were not run end to end by the person who wrote this; they need your machine. Add one piece at a time and test after each (see section 9).
hold F9 ──► Mic (always-open stream, 0.4 s pre-roll)
│ audio while key held
▼
SpeechGate ── Silero VAD: no speech? → [ignored]
│ trim silence, normalise volume
▼
ASR (your quantized Himalaya Whisper) → "३ नम्बर खोल"
│
▼
garbage filter (empty / looping Whisper output → [ignored])
│
▼
JEV-lite (small encoder, 3 heads): intent, complete, destructive
│
▼
decide() — plain code, the only place that chooses:
│ ignore | ask | act
▼
[ask] → you say "हो" (yes) / "होइन" (no)
│
▼
execute() — Playwright: click, scroll, search, tabs ...
│
▼
[done] ... then [ready] waiting for new input
The model never generates text and never decides to do something on its own. It only answers three fixed questions; decide() in commands.py (about 10 lines) turns the answers into an action.
[ready] waiting for new input - hold F9 and speak (Ctrl+C to quit)
[asr] transcribing 1.8s of speech ...
[heard] '३ नम्बर खोल' -> click_number (p=0.97, risky=0.01) => act
[done] clicked #3 'Login' | asr 640ms jev 14ms act 410ms total 1070ms
[ready] waiting for new input - hold F9 and speak (Ctrl+C to quit)
Status tags: ready (waiting) · asr (transcribing) · heard (what it understood) · done / failed (result) · ignored (noise, low confidence, not a command) · cancelled (you said no) · confirm (it needs a yes/no) · error (a bug; details in agent.log).
total is end of speech to action finished, your real latency number.
The same result also appears as a small toast in the bottom-right corner of the web page.
| File | Job |
|---|---|
voice_agent.py |
The program you run. Mic, loop, status lines, confirmation, logging. |
audio.py |
Persistent mic stream, push-to-talk key, auto mode, Silero VAD gate. |
asr.py |
Loads your Whisper (CTranslate2 quantized folder or HF), warm-up, transcribe(). |
jev_lite.py |
The intent model, synthetic + real training data, training, inference. |
sites.py, rules.py |
Any website, any name, no training: built-in site book, aliases.json, site-specific search URLs, and the high-precision rules (see 4.3). |
commands.py |
Pure logic: decide(), number parsing, query/target extraction, fuzzy match, risky-word check, allowlist, yes/no, aliases. Unit-tested. |
browser_agent.py |
Playwright actions, numbered hints, tabs, toasts, dictation. Also a text-only test mode. |
config.py |
Every setting; settings.json + command line. |
logs.py, label_logs.py |
Event log (logs.jsonl) and a tool to label it. |
eval.py |
Measure intent accuracy, false triggers, ASR WER/latency, real-usage report. |
metrics.py, ui.py |
Helpers. |
test_logic.py, test_sites.py |
Unit tests. |
aliases.json, eval.csv, settings.example.json |
Sample data you edit. |
python -m venv .venv
.venv\Scripts\activate # Windows (macOS/Linux: source .venv/bin/activate)
pip install -r requirements.txt
playwright install chromiumDo not put your Hugging Face token in code. If you need one: hf auth login once. A local model folder needs no token.
| Your quantized model is… | Run with |
|---|---|
A CTranslate2 / faster-whisper folder (contains model.bin) |
--asr-path path\to\folder (auto-detected; --compute-type int8) |
| A normal Hugging Face folder / hub id | --asr-path path\to\folder and, on CPU, optionally --hf-dynamic-quant |
| Not quantized yet (CPU only) | convert once: ct2-transformers-converter --model himalaya-ai/whisper-medium-nepali-final --output_dir whisper-ct2 --quantization int8 then use the first row |
| A GGML / .gguf (whisper.cpp) single file | not supported here; convert to CT2 or use a HF folder |
Put it in settings.json so you do not retype it:
{ "asr_path": "models/whisper-himalaya-ct2-int8", "compute_type": "int8", "mode": "ptt", "ptt_key": "f9", "mic": 2 }(settings.example.json is a template; copy it to settings.json.)
python voice_agent.py --list-mics # note the index of your mic
python voice_agent.py --mic 2python jev_lite.py train # ~ minutes on CPU; writes jev_lite.pt
python jev_lite.py # type text, see intent / confidence / latencyjev_lite.pt stores the intent list. If you change INTENTS later and forget to retrain, the agent stops with a clear message instead of silently doing the wrong thing.
python voice_agent.py https://duckduckgo.com # hold F9 to talk
python voice_agent.py --mode auto # hands-free (no key)
python voice_agent.py --cdp # control your own Chrome (see 4.1)
python voice_agent.py --save-audio # also keep each clip for ASR evaluationWithout a mic you can test the browser half only: python browser_agent.py https://example.com and type Nepali text.
Start Chrome like this first (Windows). Chrome 136+ ignores the debug port unless --user-data-dir is given:
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir=C:\jev-chrome
Then python voice_agent.py --cdp.
| Intent | Example |
|---|---|
| scroll_down / scroll_up | तल जाउ / माथि जाउ |
| scroll_top / scroll_bottom | माथिसम्म जाउ / तलसम्म जाउ |
| go_back / go_forward | पछाडि जाउ / अगाडि जाउ |
| refresh | पेज रिफ्रेस गर |
| search | नेपाल समाचार सर्च गर (page's search box, else DuckDuckGo) · युट्युबमा बिरामी खोज (searches ON that site) |
| click | लगइन मा क्लिक गर · any name on the page, even below the fold (fuzzy + sound match) |
| click_number | ३ नम्बर खोल (yellow numbers appear on every clickable thing) |
| open_site | युट्युब खोल · कान्तिपुर साइट खोल · hamrobazar डट कम खोल · any other name → first web result |
| new_tab / close_tab | नयाँ ट्याब खोल / ट्याब बन्द गर (close asks for confirmation) |
| play_pause | भिडियो रोक |
| press_enter | इन्टर थिच |
| dictate_on / dictate_off | लेख्न सुरु गर … लेख्न बन्द गर (types what you say into the focused field) |
You do not have to train for each website or each thing you search for. Three mechanisms do the work:
- Rules before the model decides (
rules.py). A sentence with an explicit search word (खोज, सर्च, search) and some other words is a search, whatever the words are. "साइट" or a known site name plus खोल/जाउ is open-site. The exact dictation phrases are never typed as text. The terminal marks it:[rule: search word + site youtube]. Turn off with--no-rules. - A site book (
sites.py): ~20 built-in sites (YouTube, Google, Facebook, Gmail, Wikipedia, Maps, GitHub, Amazon, Daraz, Kantipur, Onlinekhabar, Setopati, Hamro Bazar ...) with Nepali spellings and, where I know it, a search URL. Names match by sound too, so यूट्यूब / युट्युब / youtube all work.- "युट्युबमा बिरामी खोज" or "search nepali songs on youtube" → goes straight to YouTube's results.
- A site without a search URL (Kantipur ...) is searched with a
site:web search, so it works for every site. - An unknown name ("नेपाल टेलिकम साइट खोल") opens DuckDuckGo's first result for that name. Say a domain as "example डट कम खोल" to go directly.
- Names on the page. "लगइन मा क्लिक गर" first matches what is on screen; if nothing matches it searches the whole page (e.g. a video title further down), scrolls to it and clicks. A Nepali spoken name matches an English label by sound: लगइन = Login, फेसबुक = Facebook, होम = Home. If two items match equally well it refuses and asks you to say a number.
Add your own sites to aliases.json (no retraining needed; the rules use the file directly):
{
"मेरो बैंक": "https://your-bank.example",
"daraz": { "url": "https://www.daraz.com.np", "search": "https://www.daraz.com.np/catalog/?q={q}", "names": ["दराज"] }
}Retraining (python jev_lite.py train) is optional here. It makes the model itself better at free-form queries and unusual site names; the training data now uses random queries and all site names, not 8 fixed phrases.
The old version could type the sentence you said to start dictation into the box (the search intent took "लेख्न सुरु" as the query). Fixed three ways:
- The exact phrases for dictation on/off/enter are recognised by fuzzy whole-sentence match before anything else, so they can never become text or a search query.
- A search now needs a real search word (खोज/सर्च/search).
- "लेख्न सुरु गर" now focuses the page's search box by itself if nothing is focused, so you no longer need to say a number first.
While dictation is on: everything you say is typed. "इन्टर थिच" presses Enter (submits), "लेख्न बन्द गर" turns it off. For a plain search you do not need dictation at all: say "नेपाल समाचार सर्च गर".
Numbered hints. Matching Nepali speech to English button text is the weakest part. So every clickable element gets a yellow number, and "३ नम्बर खोल" works on any site. Numbers are redrawn after every action. If you scroll by hand, the numbers hide and the next number command redraws them and asks you to repeat (so you never click a stale number).
Dictation. Say "५ नम्बर खोल" to focus a text box, say "लेख्न सुरु गर", speak, then "लेख्न बन्द गर". It refuses password fields.
- Confidence gate: below
t_intent(0.8) the command is ignored, not guessed. - Ambiguity gate: if two buttons match equally well, it does nothing and tells you to say a number.
- Risky click: the model's
destructivehead and a word list on the actual element label (delete, pay, buy, logout, मेटा, भुक्तानी …) both trigger a spoken confirmation.close_tabalways asks. - Confirmation is a spoken हो / होइन, with an 8 s timeout that means no. (The old "say the same sentence again" check could not work: Whisper rarely writes the same text twice.)
- Allowlist (optional):
"allowed_sites": ["youtube.com", "ekantipur.com"]blocks actions on other sites.go_back,open_site, tab commands still work so you cannot get stuck. Empty list = no restriction. Turn it on for real users. close_tabrefuses to close the last tab (a mis-heard word can no longer quit the program).- No undo is promised: browsers cannot undo most actions.
go_forwardaftergo_backis the only "undo". - Audio stays on your computer. Clips are saved only with
--save-audio. The mic stream is open while the program runs (for the 0.4 s pre-roll) but nothing is kept or analysed unless the key is held (PTT) or speech is detected (auto).
use it ──► logs.jsonl ──► label_logs.py ──► retrain ──► eval.py ──► use it
- Run the agent (add
--save-audioif you also want to measure ASR). Every utterance is appended tologs.jsonlwith text, intent, confidence, action, timings. - Stop the agent, then
python label_logs.py. Press Enter if right; type the number of the correct intent otherwise (n= should have been ignored;t= fix the transcript). Saved after each line. - About 20% of labelled lines are assigned to a held-out eval split by a hash of the text (
logs.py: split_of). Those are never trained on, so your accuracy numbers stay honest. python jev_lite.py trainmixes your labelled train lines (repeated 5×) into the synthetic data.python eval.py jevand compare with the numbers before.
Synthetic data is made by templates plus ASR-style noise (dropped letters, typical Whisper spellings like सर्ड्स). It is a bootstrap, not the goal: a few hundred real labelled lines beat thousands of templates. Have a native speaker review FIXED, NONE_PHRASES and the templates in jev_lite.py; they were written quickly.
To add a command: add it to INTENTS (commands.py), add phrases to FIXED (jev_lite.py), add a branch to _execute (browser_agent.py), add a unit test, retrain.
To add a site: add it to aliases.json. No retraining is needed (rules read the file); retrain only if you want the model itself to learn the name.
Track these three numbers every time you change something, as the suggestions doc recommended:
| Metric | How | Target (starting point) |
|---|---|---|
| Command accuracy (wrong action rate especially) | python eval.py jev |
wrong action < 1%, recall > 90% |
| False triggers | eval.py jev (non-command rows) and, live, eval.py report |
< 2% of non-commands; < ~2 per hour with TV/people around |
| Latency (end of speech → done) | [done] line, eval.py report p50/p95 |
p50 < 2 s, p95 < 4 s |
pytest -qFill eval.csv (text,intent, UTF-8). Use real transcripts from your logs, not the training templates, and include at least 30 none lines (small talk, half sentences, TV). Reports accuracy, recall, missed, wrong action executed, false-trigger rate, per-intent precision/recall/F1, the mistakes, and common confusions. Labelled held-out log lines are added automatically (--no-logs to skip).
python eval.py jev --sweep--sweep shows recall / misses / wrong actions / false triggers for several t_intent values. Choose the threshold from the table (raise it if false triggers hurt; lower it if too many commands are missed) and set "t_intent" in settings.json.
Collect clips by running the agent with --save-audio, label them with label_logs.py (t to type the correct transcript), or write asr_eval.csv with columns wav,text[,intent]. Then run the same clips through each model:
python eval.py asr --asr-path models\whisper-original --asr-backend hf
python eval.py asr --asr-path models\whisper-ct2-int8 --compute-type int8You get WER, CER, latency p50/p95, real-time factor, and (if clips have an intent) speech → correct action with ASR and JEV together. Accept the quantized model if WER is close to the original and latency is much lower. Use at least 100 clips from your own voice and mic; 10 clips prove nothing.
Typically a few tens of milliseconds; if it is not, your ASR is competing for CPU threads.
From logs.jsonl: action counts, success rate of executed commands, most common failure messages, p50/p95 of asr_ms, jev_ms, act_ms, total_ms, and, for labelled lines, false triggers and wrong actions (plus a rough per-hour figure).
For a false-trigger test run the agent in --mode auto for 30 minutes with a TV on and do not speak commands; label the log; every executed line is a false trigger.
CLI flags override settings.json, which overrides defaults (config.py).
| Setting / flag | Default | Meaning |
|---|---|---|
asr_path / --asr-path |
himalaya-ai/whisper-medium-nepali-final | folder of your quantized model |
asr_backend |
auto | ct2 or hf (auto looks for model.bin) |
device, compute_type |
cpu, int8 | CT2 options (cuda + float16 on a GPU) |
hf_dynamic_quant |
false | torch int8 for an HF model on CPU |
mode / --mode |
ptt | ptt (hold key) or auto (voice-activated) |
ptt_key |
f9 | any pynput key name (f8, space, ctrl_r) |
mic / --mic |
system default | index from --list-mics |
thresh |
auto | loudness threshold for auto mode (auto-calibrated at start) |
use_vad / --no-vad |
true | Silero VAD gate |
t_intent |
0.8 | minimum confidence to act |
t_risky |
0.5 | destructive score that triggers confirmation |
confirm_timeout_s |
8 | silence = no |
allowed_sites / --allow |
[] | allowlist (empty = any site) |
save_audio |
false | keep clips in audio_logs/ |
profile_dir |
jev_profile | persistent Chromium profile so logins survive restarts |
beep |
false | Windows beep on done/fail |
python -m pytest -q→ all pass.python voice_agent.py --list-mics, pick the mic.python jev_lite.py train, then type a few commands inpython jev_lite.py.python browser_agent.py https://duckduckgo.com→ type commands; check numbered hints and clicks.python voice_agent.pywith PTT → say "तल जाउ". Checkasrms.- Turn on
--save-audio, use it for a day, label, retrain, evaluate (section 6–7).
| Symptom | Fix |
|---|---|
jev_lite.pt not found / "intent list changed" |
python jev_lite.py train |
cannot open the microphone |
--list-mics, try another index; close apps using the mic |
| Nothing happens when you hold F9 | Run the terminal as a normal user, not blocked by another app grabbing F9; try --ptt-key f8; on macOS grant Accessibility permission |
[ignored] no speech detected |
Mic too quiet: raise Windows input volume; or use --no-vad and set --thresh |
| ASR slow (> 3 s) | Use the int8 CT2 model, beam_size 1, short utterances; check nvidia-smi for a GPU (then --device cuda --compute-type float16) |
| Whisper writes text for silence | Keep the VAD gate on; the garbage filter drops repeated/empty text |
[failed] no single clear match |
Say the number instead: "३ नम्बर खोल" |
--cdp cannot connect |
Start Chrome with the exact flags in 4.1 |
| English words come out in Devanagari | Usually fine (names match by sound). Add spellings to names in aliases.json, or label real lines and retrain |
| It typed my command as text | Look at the [heard] line: if it says [rule: ...] or dictation, tell me the line. Dictation phrases are never typed; if one was, ASR spelled it very differently - add that spelling to _DICT_PHRASES in commands.py |
- A fixed set of commands. It cannot plan multi-step tasks or understand open requests; you grow it by adding intents and data.
- Numbered hints do not reach inside iframes or shadow DOM, and busy pages can shift between drawing and clicking.
- Whisper will still mishear some words; logging → labelling → retraining is how you close the gap.
play_pauseuses the page's<video>; sites that block autoplay need one manual click first.- Unknown site names fall back to a web search, so the first result may not be the site you meant; say a number to pick from the results.
- The sound matching is a heuristic (consonant skeleton), not real transliteration. It can pick the wrong label when two names sound alike; the ambiguity check then refuses.
- Built-in search URLs for third-party sites can change; fix them in
aliases.json. They were written from memory and are not tested here.
- Input: persistent mic stream, push-to-talk, Silero VAD gate with trimming, normalisation, auto-calibrated threshold, garbage-transcript filter.
- ASR: pluggable backend for your quantized model, warm-up call,
max_new_tokenscap on HF to stop runaway loops. - JEV: 18 intents, ASR-noise augmentation, hash-based train/val split, real-log training, checkpoint stores the intent list, LR schedule, gradient clipping, best-epoch save.
- Browser: one DOM call for hints + labels (the old code made one round-trip per element), fuzzy match no longer lets 1-letter labels match everything, new-tab popups are followed, search falls back to DuckDuckGo, scroll by viewport fraction,
Resultobjects instead of prints. - Fixed in the doc's snippets:
data-jevnumbers from earlier draws were never cleared (duplicate numbers);close_tabcouldSystemExitthe whole program; "say the same sentence again" confirmation could never match; stale hint numbers after manual scrolling;keyboard.typereplaced byinsert_textfor Devanagari; dictation into password fields blocked; there was no held-out data at all (hash-based train/eval split now). - Status:
[done] ... | totalthen[ready] waiting for new inputafter every command.