arach commited on
Commit
35717ca
Β·
1 Parent(s): 2a217dc

πŸ§ͺ add segment classifier, protocol processor test harness, and full chain tests

Browse files

- Part 4 blog: segment classifier synopsis with processor + chain test results
- Segment classifier: training script, eval harness, 50 labeled mixed dictations
- Protocol processor: updated with needs-llm detector, test harness (92 unit + 100 eval)
- Full chain test: 12 cases through classifier β†’ model β†’ reassembly
- Model weights: segment-classifier-model.json, needs-llm-model.json
- Eval data: 100 dictation-to-command pairs across 31 categories

blog/part4-segment-classifier.md ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Part 4: Splitting the Stream
2
+
3
+ > The whole-text classifier asks "should this go to the model?" The segment classifier asks "which words?"
4
+
5
+ <!-- METADATA
6
+ slug: splitting-the-stream
7
+ series: teaching-a-tiny-model-to-hear-bash
8
+ part: 4
9
+ date: TBD
10
+ tags: classifier, segmentation, on-device-ml, voice, dictation, logistic-regression
11
+ author: Arach
12
+ -->
13
+
14
+ ## Series context
15
+
16
+ - **Part 1** β€” Fine-tuned a 1.5B model to reconstruct bash from dictation. 97% accuracy, 3GB RAM, 0.7s inference.
17
+ - **Part 2** β€” Split architecture: deterministic processor for symbols, LLM for language understanding.
18
+ - **Part 3** β€” A classifier trained in 40ms gates whether input needs an LLM at all. 100% accuracy on held-out data.
19
+ - **Part 4** (this post) β€” Mixed dictations break the gate. A per-word classifier segments the stream so only the command parts hit the model.
20
+
21
+ ## The problem Part 3 didn't solve
22
+
23
+ Part 3's classifier works on whole utterances. Clean protocol input goes to the processor. Fuzzy input goes to the LLM. But real dictation isn't one or the other β€” it's both at once.
24
+
25
+ "I want to check the directory ls dash la and then we can talk about the project timeline."
26
+
27
+ If you send all of that to the fused model β€” a quantized 0.6B fine-tuned exclusively on bash reconstruction β€” you get hallucinated garbage where the natural speech was. The model has never seen conversational English. It tries to reconstruct "I want to check the directory" as if it were dictated protocol and produces something unrecognizable.
28
+
29
+ If you skip the model entirely, the protocol segment "ls dash la" passes through as raw dictated text. The user sees the words "ls dash la" instead of `ls -la`.
30
+
31
+ The gate needs to operate inside the sentence, not around it.
32
+
33
+ ## First attempt: heuristics
34
+
35
+ The obvious approach: maintain a set of protocol words ("dash", "dot", "slash", "space"), scan the text, mark any word that matches, expand a window around matches to capture adjacent command tokens like "ls" or "git".
36
+
37
+ This works for the simple cases. Then it breaks:
38
+
39
+ - "at three o'clock" β€” "at" is in protocol vocab (for @), "three" is a number word. Flagged as protocol. Now the model tries to reconstruct a meeting time as bash.
40
+ - "the performance numbers look really good" β€” clean pass. Correct.
41
+ - "talkie-dev dash-help" β€” hyphens embedded in words. The heuristic checks for standalone "dash" but not for syntax characters inside words. Missed.
42
+
43
+ Every edge case is another rule. Every rule has its own edge cases. This is the exact problem the Part 3 classifier solved for whole-text routing. Same insight applies here β€” learn the boundary instead of coding it.
44
+
45
+ ## The vocabulary split
46
+
47
+ The key insight that made training work: not all protocol words are equally diagnostic.
48
+
49
+ "dash" almost never appears in natural English speech. If someone says "dash", they mean a hyphen. Strong signal.
50
+
51
+ "at" appears constantly in natural speech. "I arrived at the office at nine." Two uses of "at", zero protocol intent. Weak signal.
52
+
53
+ Split the vocabulary into two tiers:
54
+
55
+ **Strong protocol** (28 words): dash, dot, slash, space, colon, underscore, tilde, hash, pipe, backtick, semicolon, equals, backslash, capital, caps, camel, snake, pascal, kebab, paren, brace, bracket, ampersand, percent, caret, dollar, minus, asterisk.
56
+
57
+ **Weak protocol** (30 words): at, star, bang, question, comma, quote, plus, open, close, new, line, all, case, one, two, three, four, five, six, seven, eight, nine, ten, zero, back, sign, mark, double, single, less.
58
+
59
+ A strong protocol word is almost always protocol. A weak protocol word is only protocol when it appears near strong ones. "at" next to "tilde slash dot" is protocol. "at" next to "the office" is not.
60
+
61
+ ## Per-word features
62
+
63
+ 14 features per word, extracted with a Β±2 context window:
64
+
65
+ | # | Feature | What it captures |
66
+ |---|---------|-----------------|
67
+ | 0 | is_strong_protocol | Unambiguous protocol word |
68
+ | 1 | is_weak_protocol | Ambiguous protocol word |
69
+ | 2 | is_expanded_symbol | Already-converted symbol (-, ., /) |
70
+ | 3 | has_syntax_chars | Contains syntax characters |
71
+ | 4 | word_length_norm | Length / 10 |
72
+ | 5 | is_short_word | Length <= 3 |
73
+ | 6 | context_strong_density | Fraction of Β±2 window that's strong protocol |
74
+ | 7 | context_any_density | Fraction of Β±2 window that's any protocol |
75
+ | 8 | left_is_strong | Left neighbor is strong protocol |
76
+ | 9 | right_is_strong | Right neighbor is strong protocol |
77
+ | 10 | is_number_like | Number word or digit |
78
+ | 11 | strong_neighbor_count | Raw count of strong protocol in window |
79
+ | 12 | is_all_lower | All lowercase letters |
80
+ | 13 | position_ratio | Position / total words |
81
+
82
+ The most powerful feature: `strong_neighbor_count` (weight +1.04). Being near unambiguous protocol words is the single strongest signal that a word is part of a command. This is the learned version of the Β±2 expansion heuristic β€” but the model decides how much weight to give it rather than a hard-coded rule.
83
+
84
+ ## Training
85
+
86
+ Synthetic mixed dictations: natural English fragments (from user manuals, business writing, HR policies, medical literature) concatenated with actual bash command dictations. 600 examples producing ~8,000 labeled words.
87
+
88
+ Same logistic regression as Part 3. Same gradient descent. Trains in under a second.
89
+
90
+ ## Two-pass architecture
91
+
92
+ The classifier identifies protocol **anchor words** β€” the unambiguous markers that a command is present. Then a deterministic expansion captures adjacent command tokens (the "ls" next to "dash la", the "git" before "dash dash help").
93
+
94
+ ```
95
+ "I want to check the directory ls dash la and then discuss the timeline"
96
+ ↓ ML classifier
97
+ Word scores: 0.1 0.1 0.1 0.1 0.1 0.2 0.3 [0.9] 0.4 0.1 0.1 0.1 0.1 0.1
98
+ ↑ anchor: "dash"
99
+ ↓ Β±2 expansion
100
+ Segments: [natural: "I want to check the directory"]
101
+ [protocol: "ls dash la"]
102
+ [natural: "and then discuss the timeline"]
103
+ ```
104
+
105
+ Only the protocol segment goes to the fused model. Natural speech passes through untouched.
106
+
107
+ ## Results
108
+
109
+ Evaluated on 50 hand-labeled mixed dictations β€” real-world patterns from documentation, business writing, legal text, and technical manuals mixed with bash commands.
110
+
111
+ ```
112
+ WORD-LEVEL
113
+ Accuracy: 92.5%
114
+ Precision: 84.7%
115
+ Recall: 99.4%
116
+ F1: 0.915
117
+
118
+ EXAMPLE-LEVEL
119
+ Pure natural text: 19/21 perfect (90%)
120
+ Mixed text: protocol segments found in all 29 cases
121
+
122
+ FALSE POSITIVE RATE: 12.2%
123
+ FALSE NEGATIVE RATE: 0.6%
124
+ ```
125
+
126
+ The asymmetry is deliberate. A false negative means a protocol segment passes through as raw text β€” the user sees "dash la" instead of `-la`. Annoying but comprehensible. A false positive means natural speech gets sent to the fused model β€” the model hallucinates on English and produces garbage. Much worse.
127
+
128
+ So we optimized for recall (99.4%) at the cost of precision (84.7%). Miss almost nothing, accept some boundary bleed.
129
+
130
+ The false positives are almost entirely transition words at command boundaries β€” "with", "run", "use", "to" β€” words that sit right before the command starts. Including them in the protocol segment is harmless; the fused model ignores them.
131
+
132
+ ## The two-classifier architecture
133
+
134
+ This is the full routing stack now:
135
+
136
+ ```
137
+ Raw transcription
138
+ |
139
+ v
140
+ [ NeedsLLMClassifier ] ← whole-text: "does this need cleanup?"
141
+ | β†’ routes to frontier model (Claude, GPT)
142
+ v
143
+ [ ProtocolSegmentClassifier ] ← per-word: "which words are commands?"
144
+ | β†’ routes segments to fused Qwen3 0.6B
145
+ v
146
+ Output: natural speech untouched, commands reconstructed
147
+ ```
148
+
149
+ Two classifiers, two jobs, two scales:
150
+ - **NeedsLLMClassifier**: whole-dictation gate for quality cleanup with a large model
151
+ - **ProtocolSegmentClassifier**: per-word segmentation for fast on-device command reconstruction
152
+
153
+ Both are logistic regression. Both are under 1KB of weights. Both run in microseconds. The expensive operations β€” the LLM inference, the embedding lookup β€” only happen when the classifiers say they should.
154
+
155
+ ## The procedural processor
156
+
157
+ The segment classifier decides *which words* go to the model. But what does the model actually replace? A deterministic procedural processor that needs no neural network at all.
158
+
159
+ The processor is a token scanner with a symbol vocabulary:
160
+ - "dash" β†’ `-`, "dot" β†’ `.`, "slash" β†’ `/`, "pipe" β†’ `|`
161
+ - Two-word: "open paren" β†’ `(`, "dash dash" β†’ `--`, "and and" β†’ `&&`
162
+ - Numbers: "eight zero eight zero" β†’ `8080`, "forty two" β†’ `42`
163
+ - Casing: "capital A" β†’ `A`, "all caps POST" β†’ `POST`, "camel case get user" β†’ `getUserProfile`
164
+ - "space" as explicit token separator
165
+
166
+ A test harness validates the processor against 100 real commands across 31 categories (git, docker, curl, ssh, kubernetes, terraform, etc.) plus 92 isolated unit tests for every feature:
167
+
168
+ ```
169
+ UNIT TESTS: 92/92 (100%)
170
+ symbols, synonyms, two-word, three-word, numbers,
171
+ casing, directives, spacing, mixed commands, redirects
172
+
173
+ EVAL TESTS: 100 commands across 31 categories
174
+ Exact match: 96/100 (96.0%)
175
+ Case-insensitive: 100/100 (100.0%)
176
+ Median latency: 11us per command
177
+
178
+ git: 8/8 docker: 7/7 kubernetes: 5/5 ssh: 3/3
179
+ python: 6/6 rust: 3/3 go: 3/3 brew: 4/4 ...
180
+ ```
181
+
182
+ The 4 non-exact matches are all casing edge cases β€” `all caps` scope interacting with adjacent `capital` directives. Every symbol, number, and structural transformation is correct. At 11 microseconds per command, the processor adds essentially zero latency.
183
+
184
+ This is the piece the fused model is meant to replace for fuzzy input. When the dictation is clean protocol, the processor handles it directly β€” no model needed. The model only activates for segments where the dictation is ambiguous or natural-sounding.
185
+
186
+ ## End-to-end chain test
187
+
188
+ The full pipeline runs without a microphone β€” synthetic test cases simulate mixed dictations through every stage:
189
+
190
+ ```
191
+ Dictation text
192
+ |
193
+ v
194
+ [ ProtocolSegmentClassifier ] ← ML: which words are commands?
195
+ |
196
+ v
197
+ [ Procedural Processor ] ← deterministic: symbols, numbers, casing
198
+ or
199
+ [ Fused Model (Qwen3 0.6B) ] ← neural: ambiguous reconstructions
200
+ |
201
+ v
202
+ Reassembled output
203
+ ```
204
+
205
+ 12 test cases covering simple commands, pure protocol, pure natural speech, sandwiched commands, two-command bridges, and complex multi-flag commands (SSH with IPs, iptables, curl with headers):
206
+
207
+ ```
208
+ CLASSIFIER SEGMENTATION: 12/12 correct
209
+ - 3 pure natural correctly passed through (no model call)
210
+ - 9 command cases correctly detected protocol segments
211
+
212
+ MODEL INFERENCE:
213
+ - Simple commands (ls -la, ps -aux): correct
214
+ - Medium commands (git push, npm install): correct
215
+ - Complex commands (iptables, curl): drops arguments
216
+ ```
217
+
218
+ The classifier is the strong link. The model is the current bottleneck on complex commands β€” a 0.6B model can reconstruct simple-to-medium bash but struggles with long multi-flag commands. This is a training data and model capacity issue, not a pipeline issue.
219
+
220
+ ## What's next
221
+
222
+ 1. **Better training data.** The current training set is synthetic β€” programmatically assembled from fragments. Real mixed dictations from actual users would capture patterns the synthetic data misses.
223
+
224
+ 2. **Model capacity.** The 0.6B fused model handles simple commands well but drops arguments on complex ones (iptables, curl with headers). Either more targeted training data or stepping up to 1.5B for the fused model.
225
+
226
+ 3. **Number word bridging.** Removing number words from protocol vocabulary eliminated false positives on natural speech ("the board voted six to three") but created a gap: isolated number sequences between protocol anchors (like IP address digits) can fall outside the Β±2 expansion window.
227
+
228
+ The classifier is deployed and running in Talkie's live dictation pipeline. Every dictation in iTerm2 now goes through the segment classifier before hitting the fused model. Natural speech stays natural. Commands get reconstructed. The user doesn't know which words went where.
229
+
230
+ ## Code references
231
+
232
+ - `datasets/train-segment-classifier.py` β€” training pipeline, synthetic data generation
233
+ - `datasets/eval-segment-classifier.py` β€” evaluation harness with boundary analysis
234
+ - `datasets/eval-segment-classifier.json` β€” 50 labeled mixed dictation examples
235
+ - `datasets/test-protocol-processor.py` β€” processor test harness (92 unit tests + 100 eval commands)
236
+ - `datasets/test-full-chain.py` β€” end-to-end chain test (classifier + model + reassembly)
237
+ - `datasets/procedural-processor.py` β€” deterministic protocol processor
238
+ - `datasets/eval-independent.json` β€” 100 labeled dictation-to-command pairs across 31 categories
239
+ - `macOS/TalkieKit/Sources/TalkieKit/ProtocolSegmentClassifier.swift` β€” deployed classifier
240
+ - `macOS/TalkieKit/Sources/TalkieKit/NeedsLLMClassifier.swift` β€” whole-text classifier (Part 3)
eval/segment-classifier.json ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": 1,
4
+ "text": "According to the installation guide you need to run sudo apt get install dash y build dash essential",
5
+ "natural": "According to the installation guide you need to run",
6
+ "protocol": "sudo apt get install dash y build dash essential",
7
+ "note": "Documentation-style intro + package install"
8
+ },
9
+ {
10
+ "id": 2,
11
+ "text": "The troubleshooting section recommends checking the logs with tail dash f slash var slash log slash syslog",
12
+ "natural": "The troubleshooting section recommends checking the logs with",
13
+ "protocol": "tail dash f slash var slash log slash syslog",
14
+ "note": "Manual reference + log tailing"
15
+ },
16
+ {
17
+ "id": 3,
18
+ "text": "Before deploying to production make sure the tests pass by running npm space test space dash dash coverage",
19
+ "natural": "Before deploying to production make sure the tests pass by running",
20
+ "protocol": "npm space test space dash dash coverage",
21
+ "note": "Process instruction + npm command"
22
+ },
23
+ {
24
+ "id": 4,
25
+ "text": "The quarterly revenue exceeded expectations by a significant margin and the board was pleased with the results",
26
+ "natural": "The quarterly revenue exceeded expectations by a significant margin and the board was pleased with the results",
27
+ "protocol": "",
28
+ "note": "Pure business English"
29
+ },
30
+ {
31
+ "id": 5,
32
+ "text": "First clone the repository with git space clone space https colon slash slash github dot com slash user slash repo",
33
+ "natural": "First clone the repository with",
34
+ "protocol": "git space clone space https colon slash slash github dot com slash user slash repo",
35
+ "note": "Setup instruction + git clone with URL"
36
+ },
37
+ {
38
+ "id": 6,
39
+ "text": "I was reading the man page and it says you should use grep dash r dash i space quote pattern quote space dot",
40
+ "natural": "I was reading the man page and it says you should use",
41
+ "protocol": "grep dash r dash i space quote pattern quote space dot",
42
+ "note": "Casual reference to documentation + grep"
43
+ },
44
+ {
45
+ "id": 7,
46
+ "text": "Please ensure that all participants have signed the non disclosure agreement before the meeting on Thursday",
47
+ "natural": "Please ensure that all participants have signed the non disclosure agreement before the meeting on Thursday",
48
+ "protocol": "",
49
+ "note": "Pure business/legal English"
50
+ },
51
+ {
52
+ "id": 8,
53
+ "text": "The user manual states that the default configuration file is located at tilde slash dot config slash app slash settings dot yaml",
54
+ "natural": "The user manual states that the default configuration file is located at",
55
+ "protocol": "tilde slash dot config slash app slash settings dot yaml",
56
+ "note": "Manual reference + config path"
57
+ },
58
+ {
59
+ "id": 9,
60
+ "text": "If the service is unresponsive try restarting it with systemctl space restart space nginx",
61
+ "natural": "If the service is unresponsive try restarting it with",
62
+ "protocol": "systemctl space restart space nginx",
63
+ "note": "Troubleshooting instruction + systemctl"
64
+ },
65
+ {
66
+ "id": 10,
67
+ "text": "According to the latest market analysis the demand for renewable energy solutions has increased by twelve percent year over year",
68
+ "natural": "According to the latest market analysis the demand for renewable energy solutions has increased by twelve percent year over year",
69
+ "protocol": "",
70
+ "note": "Market analysis with 'percent' used naturally"
71
+ },
72
+ {
73
+ "id": 11,
74
+ "text": "To check disk usage across all mounted volumes run df space dash h space pipe space sort space dash k space two",
75
+ "natural": "To check disk usage across all mounted volumes run",
76
+ "protocol": "df space dash h space pipe space sort space dash k space two",
77
+ "note": "Instruction + piped df command"
78
+ },
79
+ {
80
+ "id": 12,
81
+ "text": "The firmware update procedure requires you to first back up your settings and then flash the device using dd space if equals slash dev slash sda space of equals slash dev slash sdb space bs equals four capital M",
82
+ "natural": "The firmware update procedure requires you to first back up your settings and then flash the device using",
83
+ "protocol": "dd space if equals slash dev slash sda space of equals slash dev slash sdb space bs equals four capital M",
84
+ "note": "Technical manual + dd command"
85
+ },
86
+ {
87
+ "id": 13,
88
+ "text": "Our team has been working on improving the customer onboarding experience and we expect to see a measurable impact by the end of the quarter",
89
+ "natural": "Our team has been working on improving the customer onboarding experience and we expect to see a measurable impact by the end of the quarter",
90
+ "protocol": "",
91
+ "note": "Pure corporate English"
92
+ },
93
+ {
94
+ "id": 14,
95
+ "text": "Set the environment variable by adding export space all caps NODE underscore ENV equals production to your shell profile",
96
+ "natural": "Set the environment variable by adding ||| to your shell profile",
97
+ "protocol": "export space all caps NODE underscore ENV equals production",
98
+ "note": "Instruction + export command"
99
+ },
100
+ {
101
+ "id": 15,
102
+ "text": "The warranty does not cover damage caused by improper handling or exposure to extreme temperatures as outlined in section three point two",
103
+ "natural": "The warranty does not cover damage caused by improper handling or exposure to extreme temperatures as outlined in section three point two",
104
+ "protocol": "",
105
+ "note": "Legal/warranty language with 'three point two' naturally"
106
+ },
107
+ {
108
+ "id": 16,
109
+ "text": "I need to find all the large files so let me run find space dot space dash type space f space dash size space plus one hundred capital M",
110
+ "natural": "I need to find all the large files so let me run",
111
+ "protocol": "find space dot space dash type space f space dash size space plus one hundred capital M",
112
+ "note": "Conversational + find command"
113
+ },
114
+ {
115
+ "id": 17,
116
+ "text": "chmod space seven five five space slash usr slash local slash bin slash deploy dot sh and then run it with dot slash deploy dot sh",
117
+ "natural": "and then run it with",
118
+ "protocol": "chmod space seven five five space slash usr slash local slash bin slash deploy dot sh ||| dot slash deploy dot sh",
119
+ "note": "Two commands with natural bridge"
120
+ },
121
+ {
122
+ "id": 18,
123
+ "text": "The safety data sheet indicates that the chemical should be stored at temperatures between two and eight degrees celsius in a well ventilated area",
124
+ "natural": "The safety data sheet indicates that the chemical should be stored at temperatures between two and eight degrees celsius in a well ventilated area",
125
+ "protocol": "",
126
+ "note": "Safety manual with numbers naturally"
127
+ },
128
+ {
129
+ "id": 19,
130
+ "text": "To connect to the database use psql space dash h space localhost space dash capital U space postgres space dash d space mydb",
131
+ "natural": "To connect to the database use",
132
+ "protocol": "psql space dash h space localhost space dash capital U space postgres space dash d space mydb",
133
+ "note": "Instruction + psql command"
134
+ },
135
+ {
136
+ "id": 20,
137
+ "text": "The annual performance review cycle begins in January and all managers should complete their assessments by the end of February",
138
+ "natural": "The annual performance review cycle begins in January and all managers should complete their assessments by the end of February",
139
+ "protocol": "",
140
+ "note": "HR/corporate with 'all' naturally"
141
+ },
142
+ {
143
+ "id": 21,
144
+ "text": "You can check the container status with docker space ps space dash a and remove stopped ones with docker space container space prune",
145
+ "natural": "You can check the container status with ||| and remove stopped ones with",
146
+ "protocol": "docker space ps space dash a ||| docker space container space prune",
147
+ "note": "Two docker commands with natural bridge"
148
+ },
149
+ {
150
+ "id": 22,
151
+ "text": "The operating instructions state that the device should be powered off before opening the case and all four screws must be removed carefully",
152
+ "natural": "The operating instructions state that the device should be powered off before opening the case and all four screws must be removed carefully",
153
+ "protocol": "",
154
+ "note": "Hardware manual with 'opening', 'case', 'all', 'four' naturally"
155
+ },
156
+ {
157
+ "id": 23,
158
+ "text": "Let me SSH into the server real quick ssh space dash i space tilde slash dot ssh slash id underscore rsa space ubuntu at one nine two dot one six eight dot one dot one zero",
159
+ "natural": "Let me SSH into the server real quick",
160
+ "protocol": "ssh space dash i space tilde slash dot ssh slash id underscore rsa space ubuntu at one nine two dot one six eight dot one dot one zero",
161
+ "note": "Casual intro + SSH with key and IP"
162
+ },
163
+ {
164
+ "id": 24,
165
+ "text": "According to the employee handbook all new hires must complete the security training within their first two weeks and sign the acceptable use policy",
166
+ "natural": "According to the employee handbook all new hires must complete the security training within their first two weeks and sign the acceptable use policy",
167
+ "protocol": "",
168
+ "note": "HR policy with 'all', 'new', 'sign', 'two' naturally"
169
+ },
170
+ {
171
+ "id": 25,
172
+ "text": "The API documentation says to authenticate with curl space dash capital X space all caps POST space dash capital H space quote Authorization colon space Bearer space dollar token quote space https colon slash slash api dot example dot com slash auth",
173
+ "natural": "The API documentation says to authenticate with",
174
+ "protocol": "curl space dash capital X space all caps POST space dash capital H space quote Authorization colon space Bearer space dollar token quote space https colon slash slash api dot example dot com slash auth",
175
+ "note": "Doc reference + complex curl"
176
+ },
177
+ {
178
+ "id": 26,
179
+ "text": "The research paper concludes that there is a statistically significant correlation between sleep quality and cognitive performance across all age groups",
180
+ "natural": "The research paper concludes that there is a statistically significant correlation between sleep quality and cognitive performance across all age groups",
181
+ "protocol": "",
182
+ "note": "Academic English with 'all' naturally"
183
+ },
184
+ {
185
+ "id": 27,
186
+ "text": "To watch the logs in real time use kubectl space logs space dash f space dash n space default space pod slash my dash app",
187
+ "natural": "To watch the logs in real time use",
188
+ "protocol": "kubectl space logs space dash f space dash n space default space pod slash my dash app",
189
+ "note": "Instruction + kubectl logs"
190
+ },
191
+ {
192
+ "id": 28,
193
+ "text": "I think the issue is that the firewall is blocking port eight zero eight zero so try iptables space dash capital A space INPUT space dash p space tcp space dash dash dport space eight zero eight zero space dash j space ACCEPT",
194
+ "natural": "I think the issue is that the firewall is blocking port eight zero eight zero so try",
195
+ "protocol": "iptables space dash capital A space INPUT space dash p space tcp space dash dash dport space eight zero eight zero space dash j space ACCEPT",
196
+ "note": "Diagnostic reasoning + iptables"
197
+ },
198
+ {
199
+ "id": 29,
200
+ "text": "The building code requires that all electrical installations comply with the national standards and be inspected by a certified professional within thirty days",
201
+ "natural": "The building code requires that all electrical installations comply with the national standards and be inspected by a certified professional within thirty days",
202
+ "protocol": "",
203
+ "note": "Building regulations with 'all', 'code' naturally"
204
+ },
205
+ {
206
+ "id": 30,
207
+ "text": "Create a compressed archive with tar space dash czvf space backup dot tar dot gz space slash home slash user slash documents",
208
+ "natural": "Create a compressed archive with",
209
+ "protocol": "tar space dash czvf space backup dot tar dot gz space slash home slash user slash documents",
210
+ "note": "Short instruction + tar command"
211
+ },
212
+ {
213
+ "id": 31,
214
+ "text": "The product recall affects all units manufactured between March and June of last year and customers should contact support for a replacement",
215
+ "natural": "The product recall affects all units manufactured between March and June of last year and customers should contact support for a replacement",
216
+ "protocol": "",
217
+ "note": "Product recall notice"
218
+ },
219
+ {
220
+ "id": 32,
221
+ "text": "First I want to list everything in the directory ls dash la and then after that we need to discuss the project timeline for next quarter",
222
+ "natural": "First I want to list everything in the directory ||| and then after that we need to discuss the project timeline for next quarter",
223
+ "protocol": "ls dash la",
224
+ "note": "Command sandwiched between two natural segments"
225
+ },
226
+ {
227
+ "id": 33,
228
+ "text": "The maintenance schedule requires that all HVAC systems be serviced twice a year with filters replaced at each visit",
229
+ "natural": "The maintenance schedule requires that all HVAC systems be serviced twice a year with filters replaced at each visit",
230
+ "protocol": "",
231
+ "note": "Maintenance manual with 'all', 'at' naturally"
232
+ },
233
+ {
234
+ "id": 34,
235
+ "text": "Generate a new SSH key with ssh dash keygen space dash t space ed two five five one nine space dash capital C space quote your email at example dot com quote",
236
+ "natural": "Generate a new SSH key with",
237
+ "protocol": "ssh dash keygen space dash t space ed two five five one nine space dash capital C space quote your email at example dot com quote",
238
+ "note": "Instruction + ssh-keygen with email"
239
+ },
240
+ {
241
+ "id": 35,
242
+ "text": "The clinical trial demonstrated that the new treatment reduced symptoms in approximately sixty five percent of participants compared to the placebo group",
243
+ "natural": "The clinical trial demonstrated that the new treatment reduced symptoms in approximately sixty five percent of participants compared to the placebo group",
244
+ "protocol": "",
245
+ "note": "Medical/clinical with 'new', 'five', 'percent' naturally"
246
+ },
247
+ {
248
+ "id": 36,
249
+ "text": "Add the upstream remote with git space remote space add space upstream space https colon slash slash github dot com slash original slash repo dot git",
250
+ "natural": "Add the upstream remote with",
251
+ "protocol": "git space remote space add space upstream space https colon slash slash github dot com slash original slash repo dot git",
252
+ "note": "Git instruction + remote add"
253
+ },
254
+ {
255
+ "id": 37,
256
+ "text": "The lease agreement stipulates that the tenant is responsible for all utilities including water gas and electricity and must maintain the property in good condition",
257
+ "natural": "The lease agreement stipulates that the tenant is responsible for all utilities including water gas and electricity and must maintain the property in good condition",
258
+ "protocol": "",
259
+ "note": "Legal/lease with 'all' naturally"
260
+ },
261
+ {
262
+ "id": 38,
263
+ "text": "I want to search through the codebase so do grep space dash rn space quote TODO quote space dash dash include equals star dot ts space dot and then pipe that to wc space dash l to count them",
264
+ "natural": "I want to search through the codebase so do ||| and then pipe that to ||| to count them",
265
+ "protocol": "grep space dash rn space quote TODO quote space dash dash include equals star dot ts space dot ||| wc space dash l",
266
+ "note": "Conversational with two commands and natural bridges"
267
+ },
268
+ {
269
+ "id": 39,
270
+ "text": "The insurance policy covers all pre existing conditions after a waiting period of ninety days and copayments are set at twenty dollars per visit",
271
+ "natural": "The insurance policy covers all pre existing conditions after a waiting period of ninety days and copayments are set at twenty dollars per visit",
272
+ "protocol": "",
273
+ "note": "Insurance language with 'all', 'at', 'dollars' naturally"
274
+ },
275
+ {
276
+ "id": 40,
277
+ "text": "Alright so the deployment script needs to run rsync space dash avz space dash e space ssh space dot slash build slash space deploy at prod dot example dot com colon slash var slash www slash html slash",
278
+ "natural": "Alright so the deployment script needs to run",
279
+ "protocol": "rsync space dash avz space dash e space ssh space dot slash build slash space deploy at prod dot example dot com colon slash var slash www slash html slash",
280
+ "note": "Casual intro + rsync deployment"
281
+ },
282
+ {
283
+ "id": 41,
284
+ "text": "The zoning regulations require that all new construction projects obtain a permit from the planning commission before breaking ground",
285
+ "natural": "The zoning regulations require that all new construction projects obtain a permit from the planning commission before breaking ground",
286
+ "protocol": "",
287
+ "note": "Municipal regulations with 'all', 'new' naturally"
288
+ },
289
+ {
290
+ "id": 42,
291
+ "text": "Check if the process is running with ps space aux space pipe space grep space node and kill it with kill space dash nine space followed by the PID",
292
+ "natural": "Check if the process is running with ||| and kill it with ||| followed by the PID",
293
+ "protocol": "ps space aux space pipe space grep space node ||| kill space dash nine",
294
+ "note": "Two commands with natural connectors"
295
+ },
296
+ {
297
+ "id": 43,
298
+ "text": "The nutritional information on the label shows that one serving contains approximately two hundred and fifty calories with twelve grams of protein",
299
+ "natural": "The nutritional information on the label shows that one serving contains approximately two hundred and fifty calories with twelve grams of protein",
300
+ "protocol": "",
301
+ "note": "Nutrition label language with numbers naturally"
302
+ },
303
+ {
304
+ "id": 44,
305
+ "text": "Set up the cron job with crontab space dash e and add the line star space slash five space star space star space star space star space slash usr slash local slash bin slash backup dot sh",
306
+ "natural": "Set up the cron job with ||| and add the line",
307
+ "protocol": "crontab space dash e ||| star space slash five space star space star space star space star space slash usr slash local slash bin slash backup dot sh",
308
+ "note": "Crontab setup with two protocol segments"
309
+ },
310
+ {
311
+ "id": 45,
312
+ "text": "The terms of service prohibit the redistribution of content without prior written consent from the copyright holder as outlined in article seven",
313
+ "natural": "The terms of service prohibit the redistribution of content without prior written consent from the copyright holder as outlined in article seven",
314
+ "protocol": "",
315
+ "note": "Legal TOS with 'seven' naturally"
316
+ },
317
+ {
318
+ "id": 46,
319
+ "text": "To extract the archive use tar space dash xzvf space archive dot tar dot gz space dash capital C space slash opt slash app",
320
+ "natural": "To extract the archive use",
321
+ "protocol": "tar space dash xzvf space archive dot tar dot gz space dash capital C space slash opt slash app",
322
+ "note": "Instruction + tar extract"
323
+ },
324
+ {
325
+ "id": 47,
326
+ "text": "The environmental impact assessment found that the proposed development would affect three protected habitats and recommended additional mitigation measures",
327
+ "natural": "The environmental impact assessment found that the proposed development would affect three protected habitats and recommended additional mitigation measures",
328
+ "protocol": "",
329
+ "note": "Environmental report with 'three' naturally"
330
+ },
331
+ {
332
+ "id": 48,
333
+ "text": "Spin up a quick web server with python space dash m space http dot server space eight zero eight zero and then open your browser to localhost colon eight zero eight zero",
334
+ "natural": "Spin up a quick web server with ||| and then open your browser to",
335
+ "protocol": "python space dash m space http dot server space eight zero eight zero ||| localhost colon eight zero eight zero",
336
+ "note": "Python http server + localhost reference"
337
+ },
338
+ {
339
+ "id": 49,
340
+ "text": "The board of directors unanimously approved the merger and all outstanding shares will be converted at a ratio of one point five to one",
341
+ "natural": "The board of directors unanimously approved the merger and all outstanding shares will be converted at a ratio of one point five to one",
342
+ "protocol": "",
343
+ "note": "Corporate/financial with 'all', 'at', 'one', 'point', 'five' naturally"
344
+ },
345
+ {
346
+ "id": 50,
347
+ "text": "Mount the network share with mount space dash t space nfs space one nine two dot one six eight dot one dot ten colon slash exports slash data space slash mnt slash network",
348
+ "natural": "Mount the network share with",
349
+ "protocol": "mount space dash t space nfs space one nine two dot one six eight dot one dot ten colon slash exports slash data space slash mnt slash network",
350
+ "note": "Instruction + NFS mount with IP"
351
+ },
352
+ {
353
+ "id": 51,
354
+ "text": "The man page says that rsync can transfer files to or from a remote host using SSH so you would type rsync space dash avz space dash e space quote ssh space dash p space two two two two quote space host colon slash path slash to slash source space slash path slash to slash destination",
355
+ "natural": "The man page says that rsync can transfer files to or from a remote host using SSH so you would type",
356
+ "protocol": "rsync space dash avz space dash e space quote ssh space dash p space two two two two quote space host colon slash path slash to slash source space slash path slash to slash destination",
357
+ "note": "Man page reference + rsync over custom SSH port"
358
+ },
359
+ {
360
+ "id": 52,
361
+ "text": "Agent forwarding should be enabled with caution since users with the ability to bypass file permissions on the remote host can access the local agent through the forwarded connection",
362
+ "natural": "Agent forwarding should be enabled with caution since users with the ability to bypass file permissions on the remote host can access the local agent through the forwarded connection",
363
+ "protocol": "",
364
+ "note": "SSH man page prose β€” security warning, no commands"
365
+ },
366
+ {
367
+ "id": 53,
368
+ "text": "To use archive mode which recursively copies directories and preserves permissions run rsync space dash a space slash path slash to slash source space slash path slash to slash destination",
369
+ "natural": "To use archive mode which recursively copies directories and preserves permissions run",
370
+ "protocol": "rsync space dash a space slash path slash to slash source space slash path slash to slash destination",
371
+ "note": "tldr-style explanation + rsync archive"
372
+ },
373
+ {
374
+ "id": 54,
375
+ "text": "An input line is normally made up of fields separated by white space or by the regular expression assigned to the field separator variable",
376
+ "natural": "An input line is normally made up of fields separated by white space or by the regular expression assigned to the field separator variable",
377
+ "protocol": "",
378
+ "note": "awk man page prose β€” 'line', 'space' used in CS context naturally"
379
+ },
380
+ {
381
+ "id": 55,
382
+ "text": "You can download a file and save it with the name from the URL by running curl space dash capital O space https colon slash slash example dot com slash filename dot zip",
383
+ "natural": "You can download a file and save it with the name from the URL by running",
384
+ "protocol": "curl space dash capital O space https colon slash slash example dot com slash filename dot zip",
385
+ "note": "tldr curl + download"
386
+ },
387
+ {
388
+ "id": 56,
389
+ "text": "The sed utility reads the specified files or the standard input if no files are specified modifying the input as specified by a list of commands",
390
+ "natural": "The sed utility reads the specified files or the standard input if no files are specified modifying the input as specified by a list of commands",
391
+ "protocol": "",
392
+ "note": "sed man page prose β€” technical but no protocol"
393
+ },
394
+ {
395
+ "id": 57,
396
+ "text": "For SSH tunneling with dynamic port forwarding which creates a SOCKS proxy on localhost port one zero eight zero use ssh space dash capital D space one zero eight zero space username at remote underscore host",
397
+ "natural": "For SSH tunneling with dynamic port forwarding which creates a SOCKS proxy on localhost port one zero eight zero use",
398
+ "protocol": "ssh space dash capital D space one zero eight zero space username at remote underscore host",
399
+ "note": "SSH tunneling explanation + command"
400
+ },
401
+ {
402
+ "id": 58,
403
+ "text": "This option is equivalent to setting the GIT_NO_LAZY_FETCH environment variable to one and is useful together with git cat file to see if an object is locally available",
404
+ "natural": "This option is equivalent to setting the GIT_NO_LAZY_FETCH environment variable to one and is useful together with git cat file to see if an object is locally available",
405
+ "protocol": "",
406
+ "note": "git man page prose β€” mentions commands inline but as references not dictated"
407
+ },
408
+ {
409
+ "id": 59,
410
+ "text": "Send JSON data to an API endpoint with curl space dash d space quote open brace quote name quote colon quote bob quote close brace quote space dash capital H space quote Content dash Type colon space application slash json quote space https colon slash slash example dot com slash users",
411
+ "natural": "Send JSON data to an API endpoint with",
412
+ "protocol": "curl space dash d space quote open brace quote name quote colon quote bob quote close brace quote space dash capital H space quote Content dash Type colon space application slash json quote space https colon slash slash example dot com slash users",
413
+ "note": "Complex curl with JSON body and headers"
414
+ },
415
+ {
416
+ "id": 60,
417
+ "text": "The chmod utility exits zero on success and greater than zero if an error occurs and only the owner of a file or the super user is permitted to change the mode",
418
+ "natural": "The chmod utility exits zero on success and greater than zero if an error occurs and only the owner of a file or the super user is permitted to change the mode",
419
+ "protocol": "",
420
+ "note": "chmod man page prose β€” technical description no commands"
421
+ },
422
+ {
423
+ "id": 61,
424
+ "text": "To create a gzipped archive from a directory using relative paths run tar space dash czf space target dot tar dot gz space dash capital C space slash path slash to slash directory space dot",
425
+ "natural": "To create a gzipped archive from a directory using relative paths run",
426
+ "protocol": "tar space dash czf space target dot tar dot gz space dash capital C space slash path slash to slash directory space dot",
427
+ "note": "tldr tar + relative path archive"
428
+ },
429
+ {
430
+ "id": 62,
431
+ "text": "Grep is used for simple patterns and basic regular expressions whereas egrep can handle extended regular expressions and fgrep is quicker but can only handle fixed patterns",
432
+ "natural": "Grep is used for simple patterns and basic regular expressions whereas egrep can handle extended regular expressions and fgrep is quicker but can only handle fixed patterns",
433
+ "protocol": "",
434
+ "note": "grep man page description β€” technical prose no protocol"
435
+ },
436
+ {
437
+ "id": 63,
438
+ "text": "To connect to a remote server using a specific identity file and a non standard port use ssh space dash i space tilde slash dot ssh slash my underscore key space dash p space two two two two space user at example dot com",
439
+ "natural": "To connect to a remote server using a specific identity file and a non standard port use",
440
+ "protocol": "ssh space dash i space tilde slash dot ssh slash my underscore key space dash p space two two two two space user at example dot com",
441
+ "note": "SSH connection with identity file and custom port"
442
+ },
443
+ {
444
+ "id": 64,
445
+ "text": "The find utility recursively descends the directory tree for each path listed evaluating an expression in terms of each file in the tree",
446
+ "natural": "The find utility recursively descends the directory tree for each path listed evaluating an expression in terms of each file in the tree",
447
+ "protocol": "",
448
+ "note": "find man page prose β€” no commands"
449
+ },
450
+ {
451
+ "id": 65,
452
+ "text": "Use the dry run flag to simulate the transfer before actually running it rsync space dash dash dry dash run space dash avz space source slash space destination slash",
453
+ "natural": "Use the dry run flag to simulate the transfer before actually running it",
454
+ "protocol": "rsync space dash dash dry dash run space dash avz space source slash space destination slash",
455
+ "note": "rsync dry-run from tldr"
456
+ },
457
+ {
458
+ "id": 66,
459
+ "text": "The contract shall remain in force for a period of twenty four months from the date of execution unless terminated earlier by either party with thirty days written notice",
460
+ "natural": "The contract shall remain in force for a period of twenty four months from the date of execution unless terminated earlier by either party with thirty days written notice",
461
+ "protocol": "",
462
+ "note": "Legal contract with numbers naturally"
463
+ },
464
+ {
465
+ "id": 67,
466
+ "text": "To forward a local port to a remote service through an SSH tunnel without opening a shell use ssh space dash capital L space nine nine nine nine colon localhost colon eighty space dash capital N space dash capital T space user at remote underscore host",
467
+ "natural": "To forward a local port to a remote service through an SSH tunnel without opening a shell use",
468
+ "protocol": "ssh space dash capital L space nine nine nine nine colon localhost colon eighty space dash capital N space dash capital T space user at remote underscore host",
469
+ "note": "SSH local port forwarding from tldr"
470
+ },
471
+ {
472
+ "id": 68,
473
+ "text": "Curl attempts to reuse connections when doing multiple transfers so that getting many files from the same server does not use multiple connects and setup handshakes which improves speed",
474
+ "natural": "Curl attempts to reuse connections when doing multiple transfers so that getting many files from the same server does not use multiple connects and setup handshakes which improves speed",
475
+ "protocol": "",
476
+ "note": "curl man page prose β€” technical explanation no commands"
477
+ },
478
+ {
479
+ "id": 69,
480
+ "text": "Delete files on the destination that don't exist on the source by using rsync space dash r space dash dash delete space rsync colon slash slash host colon slash path slash to slash source space slash path slash to slash destination",
481
+ "natural": "Delete files on the destination that don't exist on the source by using",
482
+ "protocol": "rsync space dash r space dash dash delete space rsync colon slash slash host colon slash path slash to slash source space slash path slash to slash destination",
483
+ "note": "rsync with delete and rsync protocol URL"
484
+ },
485
+ {
486
+ "id": 70,
487
+ "text": "The municipal water treatment facility processes approximately four point five million gallons per day and must maintain compliance with all federal and state regulations",
488
+ "natural": "The municipal water treatment facility processes approximately four point five million gallons per day and must maintain compliance with all federal and state regulations",
489
+ "protocol": "",
490
+ "note": "Government/utility with 'point', 'all' naturally"
491
+ },
492
+ {
493
+ "id": 71,
494
+ "text": "Pass a configuration parameter to git by using the dash c flag for example git space dash c space user dot name equals quote John Doe quote space commit",
495
+ "natural": "Pass a configuration parameter to git by using the dash c flag for example",
496
+ "protocol": "git space dash c space user dot name equals quote John Doe quote space commit",
497
+ "note": "git man page example + config parameter"
498
+ },
499
+ {
500
+ "id": 72,
501
+ "text": "Specifying the location of the git directory using the git dir option turns off repository discovery that tries to find a directory with a git subdirectory",
502
+ "natural": "Specifying the location of the git directory using the git dir option turns off repository discovery that tries to find a directory with a git subdirectory",
503
+ "protocol": "",
504
+ "note": "git man page prose β€” mentions 'git dir' naturally not as command"
505
+ },
506
+ {
507
+ "id": 73,
508
+ "text": "To send form encoded data as a POST request use curl space dash capital X space POST space dash d space quote name equals bob quote space http colon slash slash example dot com slash form",
509
+ "natural": "To send form encoded data as a POST request use",
510
+ "protocol": "curl space dash capital X space POST space dash d space quote name equals bob quote space http colon slash slash example dot com slash form",
511
+ "note": "curl POST from tldr"
512
+ },
513
+ {
514
+ "id": 74,
515
+ "text": "The school district requires that all students in grades three through eight take the standardized assessment each spring and results are shared with parents within six weeks",
516
+ "natural": "The school district requires that all students in grades three through eight take the standardized assessment each spring and results are shared with parents within six weeks",
517
+ "protocol": "",
518
+ "note": "Education policy with 'all', 'three', 'eight', 'six' naturally"
519
+ },
520
+ {
521
+ "id": 75,
522
+ "text": "Extract files matching a specific pattern from a tar archive using tar space dash xf space source dot tar space dash dash wildcards space quote star dot html quote",
523
+ "natural": "Extract files matching a specific pattern from a tar archive using",
524
+ "protocol": "tar space dash xf space source dot tar space dash dash wildcards space quote star dot html quote",
525
+ "note": "tar wildcard extraction from tldr"
526
+ },
527
+ {
528
+ "id": 76,
529
+ "text": "The prescription requires the patient to take one tablet twice daily with food and return for a follow up appointment in four weeks to assess progress",
530
+ "natural": "The prescription requires the patient to take one tablet twice daily with food and return for a follow up appointment in four weeks to assess progress",
531
+ "protocol": "",
532
+ "note": "Medical prescription with 'one', 'four' naturally"
533
+ },
534
+ {
535
+ "id": 77,
536
+ "text": "You can also use SSH jumping to connect through a jump host to a remote server ssh space dash capital J space user at jump underscore host space user at remote underscore host",
537
+ "natural": "You can also use SSH jumping to connect through a jump host to a remote server",
538
+ "protocol": "ssh space dash capital J space user at jump underscore host space user at remote underscore host",
539
+ "note": "SSH jump host from tldr"
540
+ },
541
+ {
542
+ "id": 78,
543
+ "text": "The restaurant inspection report noted three minor violations including improper food storage temperature and recommended a follow up inspection within fourteen days",
544
+ "natural": "The restaurant inspection report noted three minor violations including improper food storage temperature and recommended a follow up inspection within fourteen days",
545
+ "protocol": "",
546
+ "note": "Health inspection with 'three' naturally"
547
+ },
548
+ {
549
+ "id": 79,
550
+ "text": "Run git as if it was started in a different path by using the dash capital C flag git space dash capital C space slash path slash to slash repo space status",
551
+ "natural": "Run git as if it was started in a different path by using the dash capital C flag",
552
+ "protocol": "git space dash capital C space slash path slash to slash repo space status",
553
+ "note": "git -C from man page"
554
+ },
555
+ {
556
+ "id": 80,
557
+ "text": "The homeowners association bylaws state that exterior modifications require written approval from the architectural review committee and work must be completed within ninety days of approval",
558
+ "natural": "The homeowners association bylaws state that exterior modifications require written approval from the architectural review committee and work must be completed within ninety days of approval",
559
+ "protocol": "",
560
+ "note": "HOA bylaws with no protocol"
561
+ },
562
+ {
563
+ "id": 81,
564
+ "text": "Resolve a hostname to a custom IP address for testing with curl space dash v space dash dash resolve space example dot com colon eighty colon one two seven dot zero dot zero dot one space http colon slash slash example dot com",
565
+ "natural": "Resolve a hostname to a custom IP address for testing with",
566
+ "protocol": "curl space dash v space dash dash resolve space example dot com colon eighty colon one two seven dot zero dot zero dot one space http colon slash slash example dot com",
567
+ "note": "curl resolve from tldr β€” complex with IP"
568
+ },
569
+ {
570
+ "id": 82,
571
+ "text": "The fire marshal determined that the maximum occupancy for the conference room is seventy five persons and all exits must remain unobstructed at all times during events",
572
+ "natural": "The fire marshal determined that the maximum occupancy for the conference room is seventy five persons and all exits must remain unobstructed at all times during events",
573
+ "protocol": "",
574
+ "note": "Fire safety with 'all', 'at', 'five' naturally"
575
+ },
576
+ {
577
+ "id": 83,
578
+ "text": "If the regular expression matches a portion of the input the matching line will be printed to standard output along with any context lines specified by the dash A and dash B options",
579
+ "natural": "If the regular expression matches a portion of the input the matching line will be printed to standard output along with any context lines specified by the dash A and dash B options",
580
+ "protocol": "",
581
+ "note": "grep man page prose β€” mentions 'dash A' but as inline reference not dictated command"
582
+ },
583
+ {
584
+ "id": 84,
585
+ "text": "List the contents of a tar file verbosely with tar space dash tvf space slash path slash to slash archive dot tar",
586
+ "natural": "List the contents of a tar file verbosely with",
587
+ "protocol": "tar space dash tvf space slash path slash to slash archive dot tar",
588
+ "note": "tldr tar list"
589
+ },
590
+ {
591
+ "id": 85,
592
+ "text": "The grant application must be submitted by March fifteenth and all supporting documentation including letters of recommendation must be received no later than April first",
593
+ "natural": "The grant application must be submitted by March fifteenth and all supporting documentation including letters of recommendation must be received no later than April first",
594
+ "protocol": "",
595
+ "note": "Academic grant with 'all' naturally"
596
+ },
597
+ {
598
+ "id": 86,
599
+ "text": "To pass client certificate and key for mutual TLS authentication use curl space dash capital E space client dot pem space dash dash key space key dot pem space dash k space https colon slash slash example dot com",
600
+ "natural": "To pass client certificate and key for mutual TLS authentication use",
601
+ "protocol": "curl space dash capital E space client dot pem space dash dash key space key dot pem space dash k space https colon slash slash example dot com",
602
+ "note": "curl mTLS from tldr"
603
+ },
604
+ {
605
+ "id": 87,
606
+ "text": "The vehicle recall notice indicates that approximately twelve thousand units are affected and owners should schedule service at their nearest authorized dealer within the next sixty days",
607
+ "natural": "The vehicle recall notice indicates that approximately twelve thousand units are affected and owners should schedule service at their nearest authorized dealer within the next sixty days",
608
+ "protocol": "",
609
+ "note": "Vehicle recall with 'at' naturally"
610
+ },
611
+ {
612
+ "id": 88,
613
+ "text": "Pipe all git output into less if standard output is a terminal by using git space dash p space log or equivalently git space dash dash paginate space log",
614
+ "natural": "Pipe all git output into less if standard output is a terminal by using ||| or equivalently",
615
+ "protocol": "git space dash p space log ||| git space dash dash paginate space log",
616
+ "note": "git pager options β€” two equivalent commands"
617
+ },
618
+ {
619
+ "id": 89,
620
+ "text": "The archaeological survey identified artifacts dating back approximately two thousand three hundred years and the site has been designated as a protected cultural heritage area",
621
+ "natural": "The archaeological survey identified artifacts dating back approximately two thousand three hundred years and the site has been designated as a protected cultural heritage area",
622
+ "protocol": "",
623
+ "note": "Archaeology with 'two', 'three' naturally"
624
+ },
625
+ {
626
+ "id": 90,
627
+ "text": "Change the mode of a file hierarchy recursively with chmod space dash capital R space seven five five space slash var slash www slash html and use the dash v flag to see what changed",
628
+ "natural": "Change the mode of a file hierarchy recursively with ||| and use the dash v flag to see what changed",
629
+ "protocol": "chmod space dash capital R space seven five five space slash var slash www slash html",
630
+ "note": "chmod recursive from man page"
631
+ },
632
+ {
633
+ "id": 91,
634
+ "text": "In an emergency all personnel must evacuate through the nearest marked exit and proceed to the designated assembly point in the north parking lot",
635
+ "natural": "In an emergency all personnel must evacuate through the nearest marked exit and proceed to the designated assembly point in the north parking lot",
636
+ "protocol": "",
637
+ "note": "Emergency procedures with 'all', 'point' naturally"
638
+ },
639
+ {
640
+ "id": 92,
641
+ "text": "The permit application requires three copies of the site plan and all adjacent property owners within two hundred feet must be notified by certified mail at least ten days before the hearing",
642
+ "natural": "The permit application requires three copies of the site plan and all adjacent property owners within two hundred feet must be notified by certified mail at least ten days before the hearing",
643
+ "protocol": "",
644
+ "note": "Zoning permit with 'three', 'all', 'two', 'ten', 'at' naturally"
645
+ },
646
+ {
647
+ "id": 93,
648
+ "text": "Use sed to replace all occurrences of a pattern in a file by running sed space dash i space quote s slash old slash new slash g quote space filename dot txt",
649
+ "natural": "Use sed to replace all occurrences of a pattern in a file by running",
650
+ "protocol": "sed space dash i space quote s slash old slash new slash g quote space filename dot txt",
651
+ "note": "sed in-place replacement"
652
+ },
653
+ {
654
+ "id": 94,
655
+ "text": "The flight departs at seven forty five in the morning from gate B twelve and passengers should arrive at least two hours before departure for international travel",
656
+ "natural": "The flight departs at seven forty five in the morning from gate B twelve and passengers should arrive at least two hours before departure for international travel",
657
+ "protocol": "",
658
+ "note": "Travel with 'at', 'seven', 'five', 'two' naturally"
659
+ },
660
+ {
661
+ "id": 95,
662
+ "text": "Print the number of lines words and bytes in each file with wc space dash lwc space star dot txt and sort the results by running pipe space sort space dash n",
663
+ "natural": "Print the number of lines words and bytes in each file with ||| and sort the results by running",
664
+ "protocol": "wc space dash lwc space star dot txt ||| pipe space sort space dash n",
665
+ "note": "wc + sort piped"
666
+ },
667
+ {
668
+ "id": 96,
669
+ "text": "The laboratory safety protocol mandates that all chemicals must be stored in properly labeled containers and material safety data sheets must be available within ten feet of the storage area",
670
+ "natural": "The laboratory safety protocol mandates that all chemicals must be stored in properly labeled containers and material safety data sheets must be available within ten feet of the storage area",
671
+ "protocol": "",
672
+ "note": "Lab safety with 'all', 'ten' naturally"
673
+ },
674
+ {
675
+ "id": 97,
676
+ "text": "To search for a pattern recursively while ignoring case and showing line numbers use grep space dash rni space quote error quote space slash var slash log slash",
677
+ "natural": "To search for a pattern recursively while ignoring case and showing line numbers use",
678
+ "protocol": "grep space dash rni space quote error quote space slash var slash log slash",
679
+ "note": "grep recursive from man page"
680
+ },
681
+ {
682
+ "id": 98,
683
+ "text": "The city council voted six to three in favor of the rezoning proposal and all affected residents will receive written notification within fifteen business days",
684
+ "natural": "The city council voted six to three in favor of the rezoning proposal and all affected residents will receive written notification within fifteen business days",
685
+ "protocol": "",
686
+ "note": "City council with 'six', 'three', 'all' naturally"
687
+ },
688
+ {
689
+ "id": 99,
690
+ "text": "Find all files modified in the last seven days with find space dot space dash type space f space dash mtime space dash seven and then delete them by piping to xargs space rm",
691
+ "natural": "Find all files modified in the last seven days with ||| and then delete them by piping to",
692
+ "protocol": "find space dot space dash type space f space dash mtime space dash seven ||| xargs space rm",
693
+ "note": "find + xargs piped β€” two protocol segments"
694
+ },
695
+ {
696
+ "id": 100,
697
+ "text": "The annual report indicates that revenue grew by eight point two percent compared to the previous fiscal year and operating expenses remained flat at approximately thirty four million dollars",
698
+ "natural": "The annual report indicates that revenue grew by eight point two percent compared to the previous fiscal year and operating expenses remained flat at approximately thirty four million dollars",
699
+ "protocol": "",
700
+ "note": "Financial report with 'eight', 'point', 'two', 'percent', 'four', 'at' naturally"
701
+ }
702
+ ]
pipeline/needs-llm-model.json ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "weights": [
3
+ -1.7262899181892912,
4
+ -4.262508378155058,
5
+ -0.9437095996085207,
6
+ 2.1420661962764926,
7
+ 3.324701471305833,
8
+ 0.14425229651354413,
9
+ -3.2102164965682594,
10
+ 0.30804019879345856,
11
+ 0.9174257808985996,
12
+ -0.09508729183500425
13
+ ],
14
+ "bias": 2.6924004765246026,
15
+ "features": [
16
+ "space_ratio",
17
+ "space_present",
18
+ "protocol_ratio",
19
+ "filler_count",
20
+ "intent_count",
21
+ "correction_count",
22
+ "starts_casing",
23
+ "word_count",
24
+ "non_protocol_ratio",
25
+ "avg_word_len"
26
+ ],
27
+ "threshold": 0.5,
28
+ "protocol_vocab": [
29
+ "all",
30
+ "ampersand",
31
+ "and",
32
+ "angle",
33
+ "append",
34
+ "asterisk",
35
+ "at",
36
+ "back",
37
+ "backslash",
38
+ "backtick",
39
+ "bang",
40
+ "brace",
41
+ "bracket",
42
+ "camel",
43
+ "capital",
44
+ "caps",
45
+ "caret",
46
+ "case",
47
+ "close",
48
+ "colon",
49
+ "comma",
50
+ "curly",
51
+ "dash",
52
+ "dollar",
53
+ "dot",
54
+ "double",
55
+ "eight",
56
+ "eighteen",
57
+ "eighty",
58
+ "eleven",
59
+ "equals",
60
+ "fifteen",
61
+ "fifty",
62
+ "five",
63
+ "forty",
64
+ "forward",
65
+ "four",
66
+ "fourteen",
67
+ "hash",
68
+ "hashtag",
69
+ "hundred",
70
+ "hyphen",
71
+ "kebab",
72
+ "less",
73
+ "line",
74
+ "mark",
75
+ "minus",
76
+ "new",
77
+ "nine",
78
+ "nineteen",
79
+ "ninety",
80
+ "one",
81
+ "open",
82
+ "paren",
83
+ "parenthesis",
84
+ "pascal",
85
+ "percent",
86
+ "period",
87
+ "pipe",
88
+ "plus",
89
+ "question",
90
+ "quote",
91
+ "redirect",
92
+ "screaming",
93
+ "semicolon",
94
+ "seven",
95
+ "seventeen",
96
+ "seventy",
97
+ "sign",
98
+ "single",
99
+ "six",
100
+ "sixteen",
101
+ "sixty",
102
+ "slash",
103
+ "snake",
104
+ "space",
105
+ "star",
106
+ "ten",
107
+ "than",
108
+ "thirteen",
109
+ "thirty",
110
+ "thousand",
111
+ "three",
112
+ "tilde",
113
+ "twelve",
114
+ "twenty",
115
+ "two",
116
+ "underscore",
117
+ "zero"
118
+ ],
119
+ "filler_words": [
120
+ "actually",
121
+ "alright",
122
+ "basically",
123
+ "hmm",
124
+ "like",
125
+ "ok",
126
+ "okay",
127
+ "right",
128
+ "so",
129
+ "uh",
130
+ "um",
131
+ "umm",
132
+ "well",
133
+ "yeah"
134
+ ],
135
+ "intent_phrases": [
136
+ "i want",
137
+ "i wanna",
138
+ "can you",
139
+ "let's",
140
+ "let me",
141
+ "we need",
142
+ "type out",
143
+ "should be",
144
+ "go ahead",
145
+ "i need",
146
+ "i think",
147
+ "we want",
148
+ "the command",
149
+ "just do",
150
+ "run it",
151
+ "make it",
152
+ "change",
153
+ "set the",
154
+ "for the",
155
+ "use the",
156
+ "add the"
157
+ ],
158
+ "correction_phrases": [
159
+ "no wait",
160
+ "wait no",
161
+ "scratch",
162
+ "not that",
163
+ "go back",
164
+ "actually no",
165
+ "never mind",
166
+ "hold on",
167
+ "start over"
168
+ ],
169
+ "casing_starters": [
170
+ "camel",
171
+ "kebab",
172
+ "pascal",
173
+ "screaming",
174
+ "snake"
175
+ ]
176
+ }
pipeline/segment-classifier-model.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "classifier": "ProtocolSegmentClassifier",
3
+ "description": "Per-word logistic regression for protocol segment detection",
4
+ "features": [
5
+ "is_strong_protocol",
6
+ "is_weak_protocol",
7
+ "is_expanded_symbol",
8
+ "has_syntax_chars",
9
+ "word_length_norm",
10
+ "is_short_word",
11
+ "context_strong_density",
12
+ "context_any_density",
13
+ "left_is_strong",
14
+ "right_is_strong",
15
+ "is_number_like",
16
+ "strong_neighbor_count",
17
+ "is_all_lower",
18
+ "position_ratio"
19
+ ],
20
+ "weights": [
21
+ 0.33411720958159186,
22
+ -0.01883618036579912,
23
+ 0.0,
24
+ 0.0,
25
+ -0.09512784613770699,
26
+ -0.27082908357760427,
27
+ 0.2582600934920609,
28
+ 0.24189819020570574,
29
+ 0.3569088147419212,
30
+ 0.33751703709094505,
31
+ 0.09194955109384083,
32
+ 1.0515119624353424,
33
+ -0.17715608130670168,
34
+ -0.11667765899752854
35
+ ],
36
+ "bias": -1.126425236495759,
37
+ "threshold": 0.5
38
+ }
processor/procedural.py CHANGED
@@ -232,12 +232,104 @@ def consume_casing(words, i):
232
  return result, j
233
 
234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  def process_dictation(text):
236
  """Convert dictated text to syntax using purely procedural rules."""
 
 
 
 
 
 
 
 
237
  words = text.split()
238
  output = []
239
  i = 0
240
  n = len(words)
 
 
241
 
242
  while i < n:
243
  w = words[i]
@@ -245,6 +337,7 @@ def process_dictation(text):
245
  # ── "space" β†’ literal space ──
246
  if w == 'space':
247
  output.append(' ')
 
248
  i += 1
249
  continue
250
 
@@ -253,6 +346,7 @@ def process_dictation(text):
253
  triple = (words[i], words[i+1], words[i+2])
254
  if triple in THREE_WORD_SYMBOLS:
255
  output.append(THREE_WORD_SYMBOLS[triple])
 
256
  i += 3
257
  continue
258
 
@@ -260,6 +354,7 @@ def process_dictation(text):
260
  cased, new_i = consume_casing(words, i)
261
  if cased is not None:
262
  output.append(cased)
 
263
  i = new_i
264
  continue
265
 
@@ -267,13 +362,18 @@ def process_dictation(text):
267
  if i + 1 < n:
268
  pair = (words[i], words[i+1])
269
  if pair in TWO_WORD_SYMBOLS:
270
- output.append(TWO_WORD_SYMBOLS[pair])
 
 
 
 
271
  i += 2
272
  continue
273
 
274
  # ── "all caps <word>" ──
275
  if w == 'all' and i + 2 < n and words[i+1] == 'caps':
276
  output.append(words[i+2].upper())
 
277
  i += 3
278
  continue
279
 
@@ -284,12 +384,17 @@ def process_dictation(text):
284
  output.append(next_w.upper())
285
  else:
286
  output.append(next_w[0].upper() + next_w[1:])
 
287
  i += 2
288
  continue
289
 
290
  # ── Single-word symbols ──
291
  if w in SYMBOLS and SYMBOLS[w] is not None:
292
- output.append(SYMBOLS[w])
 
 
 
 
293
  i += 1
294
  continue
295
 
@@ -298,11 +403,16 @@ def process_dictation(text):
298
  num_str, new_i = consume_number(words, i)
299
  if num_str is not None:
300
  output.append(num_str)
 
301
  i = new_i
302
  continue
303
 
304
  # ── Regular word β†’ pass through ──
 
 
 
305
  output.append(w)
 
306
  i += 1
307
 
308
  return ''.join(output)
 
232
  return result, j
233
 
234
 
235
+ # ── ML-based needs_llm detector ─────────────────────────────────────────
236
+ # Replaces the old heuristic is_protocol(). Loads weights from
237
+ # needs-llm-model.json and does feature extraction + dot product + sigmoid.
238
+ # No sklearn needed at runtime.
239
+
240
+ import math as _math
241
+
242
+ _NLM_MODEL = None # cached on first call
243
+
244
+
245
+ def _load_nlm_model():
246
+ """Load the trained model weights from JSON (cached)."""
247
+ global _NLM_MODEL
248
+ if _NLM_MODEL is not None:
249
+ return _NLM_MODEL
250
+
251
+ import os
252
+ model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'needs-llm-model.json')
253
+ with open(model_path) as f:
254
+ _NLM_MODEL = json.load(f)
255
+ # Convert lists to frozensets for fast lookup
256
+ _NLM_MODEL['_protocol_vocab'] = frozenset(_NLM_MODEL['protocol_vocab'])
257
+ _NLM_MODEL['_filler_words'] = frozenset(_NLM_MODEL['filler_words'])
258
+ _NLM_MODEL['_casing_starters'] = frozenset(_NLM_MODEL['casing_starters'])
259
+ return _NLM_MODEL
260
+
261
+
262
+ def _extract_features(text, model):
263
+ """Extract 10 numeric features from dictated text."""
264
+ words = text.lower().split()
265
+ n = len(words)
266
+ if n == 0:
267
+ return [0.0] * 10
268
+
269
+ protocol_vocab = model['_protocol_vocab']
270
+ filler_words = model['_filler_words']
271
+ casing_starters = model['_casing_starters']
272
+ intent_phrases = model['intent_phrases']
273
+ correction_phrases = model['correction_phrases']
274
+
275
+ space_count = words.count('space')
276
+ space_ratio = space_count / n
277
+ space_present = 1.0 if space_count > 0 else 0.0
278
+ protocol_count = sum(1 for w in words if w in protocol_vocab)
279
+ protocol_ratio = protocol_count / n
280
+ filler_count = sum(1 for w in words if w in filler_words)
281
+
282
+ text_lower = text.lower()
283
+ intent_count = sum(1 for p in intent_phrases if p in text_lower)
284
+ correction_count = sum(1 for p in correction_phrases if p in text_lower)
285
+
286
+ starts_casing = 1.0 if words[0] in casing_starters else 0.0
287
+ word_count = n / 20.0
288
+ non_protocol_ratio = 1.0 - protocol_ratio
289
+ avg_word_len = sum(len(w) for w in words) / n
290
+
291
+ return [
292
+ space_ratio, space_present, protocol_ratio, filler_count,
293
+ intent_count, correction_count, starts_casing, word_count,
294
+ non_protocol_ratio, avg_word_len,
295
+ ]
296
+
297
+
298
+ def needs_llm(text):
299
+ """Does this dictated input need LLM normalization?
300
+
301
+ Returns True if the input is fuzzy/natural/chaotic and needs LLM.
302
+ Returns False if the input is clean protocol and the processor can handle it.
303
+
304
+ Uses a trained logistic regression model (10 features, dot product + sigmoid).
305
+ """
306
+ model = _load_nlm_model()
307
+ features = _extract_features(text, model)
308
+ weights = model['weights']
309
+ bias = model['bias']
310
+ threshold = model['threshold']
311
+
312
+ logit = sum(f * w for f, w in zip(features, weights)) + bias
313
+ prob = 1.0 / (1.0 + _math.exp(-logit))
314
+ return prob >= threshold
315
+
316
+
317
  def process_dictation(text):
318
  """Convert dictated text to syntax using purely procedural rules."""
319
+ # Normalize alternative casing/caps forms before splitting
320
+ text = re.sub(r'\bcamel[-_]?case\b', 'camel case', text, flags=re.IGNORECASE)
321
+ text = re.sub(r'\bpascal[-_]?case\b', 'pascal case', text, flags=re.IGNORECASE)
322
+ text = re.sub(r'\bsnake[-_]?case\b', 'snake case', text, flags=re.IGNORECASE)
323
+ text = re.sub(r'\bkebab[-_]?case\b', 'kebab case', text, flags=re.IGNORECASE)
324
+ text = re.sub(r'\bscreaming[-_]?case\b', 'screaming case', text, flags=re.IGNORECASE)
325
+ text = re.sub(r'\ball[-_]caps\b', 'all caps', text, flags=re.IGNORECASE)
326
+
327
  words = text.split()
328
  output = []
329
  i = 0
330
  n = len(words)
331
+ in_quote = False
332
+ last_was_word = False
333
 
334
  while i < n:
335
  w = words[i]
 
337
  # ── "space" β†’ literal space ──
338
  if w == 'space':
339
  output.append(' ')
340
+ last_was_word = False
341
  i += 1
342
  continue
343
 
 
346
  triple = (words[i], words[i+1], words[i+2])
347
  if triple in THREE_WORD_SYMBOLS:
348
  output.append(THREE_WORD_SYMBOLS[triple])
349
+ last_was_word = False
350
  i += 3
351
  continue
352
 
 
354
  cased, new_i = consume_casing(words, i)
355
  if cased is not None:
356
  output.append(cased)
357
+ last_was_word = False
358
  i = new_i
359
  continue
360
 
 
362
  if i + 1 < n:
363
  pair = (words[i], words[i+1])
364
  if pair in TWO_WORD_SYMBOLS:
365
+ sym = TWO_WORD_SYMBOLS[pair]
366
+ output.append(sym)
367
+ if sym in ('"', "'"):
368
+ in_quote = not in_quote
369
+ last_was_word = False
370
  i += 2
371
  continue
372
 
373
  # ── "all caps <word>" ──
374
  if w == 'all' and i + 2 < n and words[i+1] == 'caps':
375
  output.append(words[i+2].upper())
376
+ last_was_word = False
377
  i += 3
378
  continue
379
 
 
384
  output.append(next_w.upper())
385
  else:
386
  output.append(next_w[0].upper() + next_w[1:])
387
+ last_was_word = False
388
  i += 2
389
  continue
390
 
391
  # ── Single-word symbols ──
392
  if w in SYMBOLS and SYMBOLS[w] is not None:
393
+ sym = SYMBOLS[w]
394
+ output.append(sym)
395
+ if sym in ('"', "'"):
396
+ in_quote = not in_quote
397
+ last_was_word = False
398
  i += 1
399
  continue
400
 
 
403
  num_str, new_i = consume_number(words, i)
404
  if num_str is not None:
405
  output.append(num_str)
406
+ last_was_word = False
407
  i = new_i
408
  continue
409
 
410
  # ── Regular word β†’ pass through ──
411
+ # Inside quotes, insert spaces between consecutive regular words
412
+ if in_quote and last_was_word:
413
+ output.append(' ')
414
  output.append(w)
415
+ last_was_word = True
416
  i += 1
417
 
418
  return ''.join(output)
scripts/eval-segment-classifier.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Evaluate the ProtocolSegmentClassifier against labeled mixed dictation examples.
4
+
5
+ Measures:
6
+ 1. Word-level accuracy (is each word correctly classified?)
7
+ 2. Segment boundary accuracy (does the classifier find the right start/end?)
8
+ 3. False positive rate on pure natural text
9
+ 4. False negative rate on protocol segments
10
+ """
11
+
12
+ import json
13
+ import numpy as np
14
+ from pathlib import Path
15
+ import importlib
16
+ _mod = importlib.import_module("train-segment-classifier")
17
+ extract_features = _mod.extract_features
18
+ is_protocol_word = _mod.is_protocol_word
19
+ is_strong_protocol = _mod.is_strong_protocol
20
+ STRONG_PROTOCOL = _mod.STRONG_PROTOCOL
21
+ WEAK_PROTOCOL = _mod.WEAK_PROTOCOL
22
+ EXPANDED_SYMBOLS = _mod.EXPANDED_SYMBOLS
23
+
24
+
25
+ def load_model(path: str) -> tuple[np.ndarray, float]:
26
+ """Load trained model from JSON."""
27
+ with open(path) as f:
28
+ model = json.load(f)
29
+ return np.array(model["weights"]), model["bias"]
30
+
31
+
32
+ def classify_words(words: list[str], weights: np.ndarray, bias: float, threshold: float = 0.5) -> list[tuple[str, float, bool]]:
33
+ """Classify each word and return (word, probability, is_protocol)."""
34
+ results = []
35
+ n = len(words)
36
+ for i, word in enumerate(words):
37
+ ctx_start = max(0, i - 2)
38
+ ctx_end = min(n, i + 3)
39
+ context = words[ctx_start:ctx_end]
40
+ features = extract_features(word, context, i, n)
41
+ logit = np.dot(features, weights) + bias
42
+ prob = 1.0 / (1.0 + np.exp(-logit))
43
+ results.append((word, prob, prob >= threshold))
44
+ return results
45
+
46
+
47
+ def expand_anchors(is_anchor: list[bool], n: int, radius: int = 2) -> list[bool]:
48
+ """Expand anchor words Β±radius to capture adjacent command tokens."""
49
+ expanded = [False] * n
50
+ for i in range(n):
51
+ if is_anchor[i]:
52
+ for j in range(max(0, i - radius), min(n, i + radius + 1)):
53
+ expanded[j] = True
54
+ return expanded
55
+
56
+
57
+ def build_segments(words: list[str], in_protocol: list[bool]) -> list[tuple[str, str]]:
58
+ """Build (kind, text) segments from word-level classifications."""
59
+ segments = []
60
+ current_kind = "protocol" if in_protocol[0] else "natural"
61
+ current_words = [words[0]]
62
+
63
+ for i in range(1, len(words)):
64
+ kind = "protocol" if in_protocol[i] else "natural"
65
+ if kind == current_kind:
66
+ current_words.append(words[i])
67
+ else:
68
+ segments.append((current_kind, " ".join(current_words)))
69
+ current_kind = kind
70
+ current_words = [words[i]]
71
+ segments.append((current_kind, " ".join(current_words)))
72
+ return segments
73
+
74
+
75
+ def label_words_from_example(example: dict) -> list[int]:
76
+ """
77
+ Label each word in the text as natural (0) or protocol (1)
78
+ based on the 'natural' and 'protocol' fields.
79
+
80
+ The protocol field may contain ||| to indicate multiple protocol segments.
81
+ The natural field may contain ||| to indicate natural segments between protocol segments.
82
+ """
83
+ text = example["text"]
84
+ words = text.split()
85
+ natural_parts = [p.strip() for p in example["natural"].split("|||") if p.strip()]
86
+ protocol_parts = [p.strip() for p in example["protocol"].split("|||") if p.strip()]
87
+
88
+ labels = [0] * len(words)
89
+
90
+ # Mark protocol words
91
+ for proto_part in protocol_parts:
92
+ proto_words = proto_part.split()
93
+ if not proto_words:
94
+ continue
95
+
96
+ # Find this sequence in the text
97
+ plen = len(proto_words)
98
+ for start in range(len(words) - plen + 1):
99
+ if words[start:start + plen] == proto_words:
100
+ for j in range(start, start + plen):
101
+ labels[j] = 1
102
+ break
103
+
104
+ return labels
105
+
106
+
107
+ def evaluate(eval_path: str, model_path: str):
108
+ """Run full evaluation."""
109
+ with open(eval_path) as f:
110
+ examples = json.load(f)
111
+
112
+ weights, bias = load_model(model_path)
113
+
114
+ print("=" * 70)
115
+ print("PROTOCOL SEGMENT CLASSIFIER EVALUATION")
116
+ print(f" Model: {model_path}")
117
+ print(f" Eval set: {len(examples)} examples")
118
+ print("=" * 70)
119
+
120
+ # Aggregate metrics
121
+ total_words = 0
122
+ correct_words = 0
123
+ tp = fp = fn = tn = 0
124
+
125
+ # Per-category tracking
126
+ pure_natural_count = 0
127
+ pure_natural_correct = 0
128
+ mixed_count = 0
129
+ mixed_correct = 0
130
+
131
+ # Detailed results
132
+ errors = []
133
+
134
+ for ex in examples:
135
+ text = ex["text"]
136
+ words = text.split()
137
+ n = len(words)
138
+ is_pure_natural = not ex["protocol"].strip()
139
+
140
+ # Get ground truth labels
141
+ gt_labels = label_words_from_example(ex)
142
+
143
+ # Classify
144
+ results = classify_words(words, weights, bias)
145
+ anchors = [r[2] for r in results]
146
+ predicted = expand_anchors(anchors, n)
147
+
148
+ # Word-level metrics
149
+ for i in range(n):
150
+ pred = 1 if predicted[i] else 0
151
+ gt = gt_labels[i]
152
+ total_words += 1
153
+ if pred == gt:
154
+ correct_words += 1
155
+ if pred == 1 and gt == 1:
156
+ tp += 1
157
+ elif pred == 1 and gt == 0:
158
+ fp += 1
159
+ elif pred == 0 and gt == 1:
160
+ fn += 1
161
+ else:
162
+ tn += 1
163
+
164
+ # Example-level tracking
165
+ example_correct = all(
166
+ (1 if predicted[i] else 0) == gt_labels[i]
167
+ for i in range(n)
168
+ )
169
+
170
+ if is_pure_natural:
171
+ pure_natural_count += 1
172
+ if example_correct:
173
+ pure_natural_correct += 1
174
+ else:
175
+ mixed_count += 1
176
+ if example_correct:
177
+ mixed_correct += 1
178
+
179
+ # Collect errors for display
180
+ if not example_correct:
181
+ pred_segments = build_segments(words, predicted)
182
+ gt_segments = build_segments(words, [bool(l) for l in gt_labels])
183
+ errors.append({
184
+ "id": ex["id"],
185
+ "note": ex.get("note", ""),
186
+ "words": words,
187
+ "gt": gt_labels,
188
+ "pred": [1 if p else 0 for p in predicted],
189
+ "pred_segments": pred_segments,
190
+ "gt_segments": gt_segments,
191
+ })
192
+
193
+ # Print results
194
+ word_acc = correct_words / total_words if total_words else 0
195
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0
196
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0
197
+ f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
198
+
199
+ print(f"\n{'WORD-LEVEL METRICS':─^70}")
200
+ print(f" Accuracy: {word_acc:.1%} ({correct_words}/{total_words})")
201
+ print(f" Precision: {precision:.1%} (protocol words correctly identified)")
202
+ print(f" Recall: {recall:.1%} (protocol words found)")
203
+ print(f" F1: {f1:.3f}")
204
+ print(f" Confusion: TP={tp} FP={fp} FN={fn} TN={tn}")
205
+
206
+ print(f"\n{'EXAMPLE-LEVEL METRICS':─^70}")
207
+ print(f" Pure natural (no protocol): {pure_natural_correct}/{pure_natural_count} perfect")
208
+ print(f" Mixed (natural + protocol): {mixed_correct}/{mixed_count} perfect")
209
+ total_ex = pure_natural_count + mixed_count
210
+ total_correct = pure_natural_correct + mixed_correct
211
+ print(f" Overall: {total_correct}/{total_ex} perfect ({100*total_correct/total_ex:.0f}%)")
212
+
213
+ # Show errors
214
+ if errors:
215
+ print(f"\n{'ERRORS':─^70}")
216
+ for err in errors:
217
+ print(f"\n #{err['id']}: {err['note']}")
218
+ # Show words with color coding
219
+ parts = []
220
+ for i, word in enumerate(err["words"]):
221
+ gt = err["gt"][i]
222
+ pred = err["pred"][i]
223
+ if gt == pred:
224
+ if gt == 1:
225
+ parts.append(f"\033[92m{word}\033[0m") # green = correct protocol
226
+ else:
227
+ parts.append(word) # plain = correct natural
228
+ elif pred == 1 and gt == 0:
229
+ parts.append(f"\033[91m[FP:{word}]\033[0m") # red = false positive
230
+ else:
231
+ parts.append(f"\033[93m[FN:{word}]\033[0m") # yellow = false negative
232
+ print(f" {' '.join(parts)}")
233
+
234
+ # Summary
235
+ print(f"\n{'SUMMARY':─^70}")
236
+ fp_rate = fp / (fp + tn) if (fp + tn) > 0 else 0
237
+ fn_rate = fn / (fn + tp) if (fn + tp) > 0 else 0
238
+ print(f" False positive rate: {fp_rate:.1%} (natural words misclassified as protocol)")
239
+ print(f" False negative rate: {fn_rate:.1%} (protocol words missed)")
240
+ print(f" Key concern: FP on natural text β†’ model hallucinates on speech")
241
+ print(f" Secondary: FN on protocol β†’ falls through as raw dictation")
242
+
243
+ return word_acc, precision, recall, f1
244
+
245
+
246
+ if __name__ == "__main__":
247
+ eval_path = Path(__file__).parent / "eval-segment-classifier.json"
248
+ model_path = Path(__file__).parent / "segment-classifier-model.json"
249
+ evaluate(str(eval_path), str(model_path))
scripts/test-full-chain.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ End-to-end test of the segment classifier + fused model chain.
4
+
5
+ Simulates the full dictation pipeline without a microphone:
6
+ 1. Takes mixed dictation text (natural + protocol)
7
+ 2. Runs ProtocolSegmentClassifier to extract segments
8
+ 3. Sends protocol segments to TalkieInference via talkie-dev CLI
9
+ 4. Reassembles output and compares against expected
10
+
11
+ Usage:
12
+ python3 test-full-chain.py # run all test cases
13
+ python3 test-full-chain.py --case 3 # run specific case
14
+ python3 test-full-chain.py --classifier-only # skip model, just test segmentation
15
+ """
16
+
17
+ import json
18
+ import subprocess
19
+ import sys
20
+ import time
21
+ import importlib
22
+ from pathlib import Path
23
+ import numpy as np
24
+
25
+ # Import classifier from training script
26
+ _mod = importlib.import_module("train-segment-classifier")
27
+ extract_features = _mod.extract_features
28
+ is_protocol_word = _mod.is_protocol_word
29
+ is_strong_protocol = _mod.is_strong_protocol
30
+
31
+ # Load model
32
+ MODEL_PATH = Path(__file__).parent / "segment-classifier-model.json"
33
+ with open(MODEL_PATH) as f:
34
+ _model = json.load(f)
35
+ WEIGHTS = np.array(_model["weights"])
36
+ BIAS = _model["bias"]
37
+ THRESHOLD = _model.get("threshold", 0.5)
38
+
39
+ # The model ID for the fused bash reconstruction model
40
+ MODEL_ID = "arach/qwen3-0.6b-bash-v1"
41
+ SYSTEM_PROMPT = "You are a dictation-to-bash converter. The input is a segment of dictated speech containing a command. Words like 'space', 'dash', 'dot', 'slash', 'colon', 'underscore', 'tilde', 'quote' are literal symbols. Number words like 'eight zero eight zero' mean '8080'. 'capital' means uppercase the next letter. 'all caps' means uppercase the next word. Ignore filler words like 'so', 'try', 'run', 'do', 'with'. Output ONLY the reconstructed command, nothing else."
42
+
43
+
44
+ # ─── Test cases ───
45
+
46
+ TEST_CASES = [
47
+ {
48
+ "input": "I want to check the directory ls dash la",
49
+ "expected_natural": "I want to check the directory",
50
+ "expected_command": "ls -la",
51
+ "note": "Simple mixed: natural + short command"
52
+ },
53
+ {
54
+ "input": "let me see what's running ps dash aux",
55
+ "expected_natural": "let me see what's running",
56
+ "expected_command": "ps -aux",
57
+ "note": "Casual intro + ps"
58
+ },
59
+ {
60
+ "input": "git space push space dash u space origin space main",
61
+ "expected_natural": "",
62
+ "expected_command": "git push -u origin main",
63
+ "note": "Pure protocol, no natural speech"
64
+ },
65
+ {
66
+ "input": "the meeting is at three o'clock tomorrow afternoon",
67
+ "expected_natural": "the meeting is at three o'clock tomorrow afternoon",
68
+ "expected_command": "",
69
+ "note": "Pure natural, should NOT trigger model"
70
+ },
71
+ {
72
+ "input": "can you run git space clone space https colon slash slash github dot com slash user slash repo for me",
73
+ "expected_natural": "can you run ... for me",
74
+ "expected_command": "git clone https://github.com/user/repo",
75
+ "note": "Command sandwiched in natural speech"
76
+ },
77
+ {
78
+ "input": "alright first do cd space tilde slash projects and then run npm space install",
79
+ "expected_natural": "alright first do ... and then run",
80
+ "expected_command": "cd ~/projects | npm install",
81
+ "note": "Two commands with natural bridge"
82
+ },
83
+ {
84
+ "input": "the quarterly report shows revenue increased by twelve percent year over year",
85
+ "expected_natural": "the quarterly report shows revenue increased by twelve percent year over year",
86
+ "expected_command": "",
87
+ "note": "Business English with 'percent' β€” should NOT trigger"
88
+ },
89
+ {
90
+ "input": "ssh space dash i space tilde slash dot ssh slash id underscore rsa space root at one nine two dot one six eight dot one dot one",
91
+ "expected_natural": "",
92
+ "expected_command": "ssh -i ~/.ssh/id_rsa root@192.168.1.1",
93
+ "note": "Complex SSH command with IP"
94
+ },
95
+ {
96
+ "input": "I think the problem is the firewall so try iptables space dash capital A space INPUT space dash p space tcp space dash dash dport space eight zero eight zero space dash j space ACCEPT",
97
+ "expected_natural": "I think the problem is the firewall so try",
98
+ "expected_command": "iptables -A INPUT -p tcp --dport 8080 -j ACCEPT",
99
+ "note": "Diagnostic reasoning + iptables"
100
+ },
101
+ {
102
+ "input": "according to the handbook all new employees must complete training within two weeks",
103
+ "expected_natural": "according to the handbook all new employees must complete training within two weeks",
104
+ "expected_command": "",
105
+ "note": "HR policy with 'all', 'new', 'two' β€” pure natural"
106
+ },
107
+ {
108
+ "input": "to find large files run find space dot space dash type space f space dash size space plus one hundred capital M",
109
+ "expected_natural": "to find large files run",
110
+ "expected_command": "find . -type f -size +100M",
111
+ "note": "Instruction + find command"
112
+ },
113
+ {
114
+ "input": "curl space dash capital X space all caps POST space dash capital H space quote Content dash Type colon space application slash json quote space https colon slash slash api dot example dot com slash users",
115
+ "expected_natural": "",
116
+ "expected_command": "curl -X POST -H \"Content-Type: application/json\" https://api.example.com/users",
117
+ "note": "Complex curl β€” pure protocol"
118
+ },
119
+ ]
120
+
121
+
122
+ def classify_words(words, weights, bias, threshold=0.5):
123
+ """Classify each word. Returns list of (word, prob, is_protocol)."""
124
+ results = []
125
+ n = len(words)
126
+ for i, word in enumerate(words):
127
+ ctx_start = max(0, i - 2)
128
+ ctx_end = min(n, i + 3)
129
+ context = words[ctx_start:ctx_end]
130
+ features = extract_features(word, context, i, n)
131
+ logit = float(np.dot(features, weights) + bias)
132
+ prob = 1.0 / (1.0 + np.exp(-logit))
133
+ results.append((word, prob, prob >= threshold))
134
+ return results
135
+
136
+
137
+ def extract_segments(text, weights, bias, threshold=0.5, expansion=2):
138
+ """Run classifier + expansion, return segments."""
139
+ words = text.split()
140
+ if not words:
141
+ return []
142
+
143
+ results = classify_words(words, weights, bias, threshold)
144
+ anchors = [r[2] for r in results]
145
+
146
+ # Expand
147
+ n = len(words)
148
+ expanded = [False] * n
149
+ for i in range(n):
150
+ if anchors[i]:
151
+ for j in range(max(0, i - expansion), min(n, i + expansion + 1)):
152
+ expanded[j] = True
153
+
154
+ # Build segments
155
+ segments = []
156
+ current_kind = "protocol" if expanded[0] else "natural"
157
+ current_words = [words[0]]
158
+
159
+ for i in range(1, n):
160
+ kind = "protocol" if expanded[i] else "natural"
161
+ if kind == current_kind:
162
+ current_words.append(words[i])
163
+ else:
164
+ segments.append({"kind": current_kind, "text": " ".join(current_words)})
165
+ current_kind = kind
166
+ current_words = [words[i]]
167
+ segments.append({"kind": current_kind, "text": " ".join(current_words)})
168
+
169
+ return segments
170
+
171
+
172
+ def call_inference(prompt, model_id=MODEL_ID, system_prompt=SYSTEM_PROMPT, timeout=30):
173
+ """Call talkie-dev inference generate and return the output."""
174
+ cmd = [
175
+ "talkie-dev", "inference", "generate", prompt,
176
+ "--model", model_id,
177
+ "--system", system_prompt,
178
+ "--temp", "0",
179
+ "--tokens", "120",
180
+ "--json",
181
+ ]
182
+ try:
183
+ result = subprocess.run(
184
+ cmd,
185
+ capture_output=True,
186
+ text=True,
187
+ timeout=timeout,
188
+ cwd=str(Path(__file__).parent.parent)
189
+ )
190
+ if result.returncode != 0:
191
+ return None, f"exit {result.returncode}: {result.stderr.strip()}"
192
+ # Output is JSON β€” parse and extract text field
193
+ try:
194
+ data = json.loads(result.stdout.strip())
195
+ text = data.get("text", "").strip()
196
+ # Strip <think>...</think> tags from Qwen3 reasoning
197
+ import re
198
+ text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
199
+ # Also strip unclosed <think> tags
200
+ text = re.sub(r'<think>.*', '', text, flags=re.DOTALL).strip()
201
+ return text, None
202
+ except json.JSONDecodeError:
203
+ # Fallback: try first line
204
+ lines = result.stdout.strip().split("\n")
205
+ return lines[0].strip() if lines else "", None
206
+ except subprocess.TimeoutExpired:
207
+ return None, "timeout"
208
+ except Exception as e:
209
+ return None, str(e)
210
+
211
+
212
+ def run_test(case, idx, classifier_only=False):
213
+ """Run a single test case through the full chain."""
214
+ text = case["input"]
215
+ note = case["note"]
216
+
217
+ print(f"\n{'='*70}")
218
+ print(f" TEST {idx}: {note}")
219
+ print(f"{'='*70}")
220
+ print(f" INPUT: {text}")
221
+
222
+ # Step 1: Segment
223
+ t0 = time.time()
224
+ segments = extract_segments(text, WEIGHTS, BIAS)
225
+ seg_ms = (time.time() - t0) * 1000
226
+
227
+ protocol_segments = [s for s in segments if s["kind"] == "protocol"]
228
+ natural_segments = [s for s in segments if s["kind"] == "natural"]
229
+
230
+ print(f"\n SEGMENTS ({seg_ms:.1f}ms):")
231
+ for s in segments:
232
+ marker = "\033[91mPROTO\033[0m" if s["kind"] == "protocol" else "\033[92mNATRL\033[0m"
233
+ print(f" [{marker}] {s['text']}")
234
+
235
+ has_protocol = len(protocol_segments) > 0
236
+ expected_has_protocol = bool(case["expected_command"])
237
+
238
+ if has_protocol != expected_has_protocol:
239
+ if has_protocol:
240
+ print(f"\n \033[91mFALSE POSITIVE: detected protocol in pure natural text!\033[0m")
241
+ else:
242
+ print(f"\n \033[93mFALSE NEGATIVE: missed protocol segment!\033[0m")
243
+ return {"pass": False, "reason": "segmentation"}
244
+
245
+ if not has_protocol:
246
+ print(f"\n \033[92mPASS\033[0m β€” correctly identified as pure natural speech (no model call)")
247
+ return {"pass": True, "reason": "natural_passthrough"}
248
+
249
+ if classifier_only:
250
+ print(f"\n [classifier-only mode, skipping model inference]")
251
+ return {"pass": True, "reason": "classifier_only"}
252
+
253
+ # Step 2: Send protocol segments to model
254
+ print(f"\n MODEL INFERENCE:")
255
+ result_parts = []
256
+ total_ms = 0
257
+
258
+ for segment in segments:
259
+ if segment["kind"] == "natural":
260
+ result_parts.append(segment["text"])
261
+ continue
262
+
263
+ t0 = time.time()
264
+ model_output, error = call_inference(segment["text"])
265
+ infer_ms = (time.time() - t0) * 1000
266
+ total_ms += infer_ms
267
+
268
+ if error:
269
+ print(f" \033[91mERROR\033[0m: {error}")
270
+ result_parts.append(segment["text"]) # fallback
271
+ else:
272
+ print(f" IN: {segment['text']}")
273
+ print(f" OUT: {model_output} ({infer_ms:.0f}ms)")
274
+ result_parts.append(model_output or segment["text"])
275
+
276
+ # Step 3: Reassemble
277
+ assembled = " ".join(result_parts).strip()
278
+ expected = case["expected_command"]
279
+
280
+ print(f"\n ASSEMBLED: {assembled}")
281
+ print(f" EXPECTED: {expected}")
282
+ print(f" LATENCY: {total_ms:.0f}ms (model only)")
283
+
284
+ # Fuzzy match β€” check if the command part is present
285
+ # (natural prefix/suffix might be included due to boundary bleed)
286
+ if expected and expected in assembled:
287
+ print(f"\n \033[92mPASS\033[0m β€” command correctly reconstructed")
288
+ return {"pass": True, "reason": "match"}
289
+ elif expected:
290
+ print(f"\n \033[93mCHECK\033[0m β€” command may differ, review above")
291
+ return {"pass": None, "reason": "fuzzy"}
292
+ else:
293
+ print(f"\n \033[92mPASS\033[0m")
294
+ return {"pass": True, "reason": "no_command"}
295
+
296
+
297
+ def main():
298
+ import argparse
299
+ parser = argparse.ArgumentParser(description="Test segment classifier + model chain")
300
+ parser.add_argument("--case", type=int, help="Run specific test case (1-indexed)")
301
+ parser.add_argument("--classifier-only", action="store_true", help="Skip model inference, just test segmentation")
302
+ args = parser.parse_args()
303
+
304
+ print("=" * 70)
305
+ print(" FULL CHAIN TEST: Classifier β†’ Segmentation β†’ Model β†’ Assembly")
306
+ if args.classifier_only:
307
+ print(" MODE: classifier-only (no model inference)")
308
+ print("=" * 70)
309
+
310
+ cases = TEST_CASES
311
+ if args.case:
312
+ if 1 <= args.case <= len(TEST_CASES):
313
+ cases = [TEST_CASES[args.case - 1]]
314
+ else:
315
+ print(f"Invalid case number. Must be 1-{len(TEST_CASES)}")
316
+ sys.exit(1)
317
+
318
+ results = []
319
+ for i, case in enumerate(cases):
320
+ idx = args.case if args.case else i + 1
321
+ result = run_test(case, idx, classifier_only=args.classifier_only)
322
+ results.append(result)
323
+
324
+ # Summary
325
+ print(f"\n{'='*70}")
326
+ print(f" SUMMARY")
327
+ print(f"{'='*70}")
328
+ passed = sum(1 for r in results if r["pass"] is True)
329
+ failed = sum(1 for r in results if r["pass"] is False)
330
+ check = sum(1 for r in results if r["pass"] is None)
331
+ print(f" Passed: {passed}/{len(results)}")
332
+ if failed: print(f" Failed: {failed}")
333
+ if check: print(f" Check: {check} (review manually)")
334
+
335
+ # Breakdown
336
+ natural_ok = sum(1 for r in results if r["reason"] == "natural_passthrough")
337
+ match_ok = sum(1 for r in results if r["reason"] == "match")
338
+ if natural_ok: print(f" Natural passthrough: {natural_ok}")
339
+ if match_ok: print(f" Command reconstructed: {match_ok}")
340
+
341
+
342
+ if __name__ == "__main__":
343
+ main()
scripts/test-protocol-processor.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Test harness for the procedural dictation protocol processor.
3
+
4
+ Tests the deterministic symbol/number/casing engine that converts
5
+ dictated protocol words into actual syntax β€” no LLM needed.
6
+
7
+ Covers:
8
+ - Symbol mapping: "dash" β†’ "-", "dot" β†’ ".", "slash" β†’ "/", etc.
9
+ - Two-word symbols: "open paren" β†’ "(", "dash dash" β†’ "--", etc.
10
+ - Three-word symbols: "two redirect ampersand" β†’ "2>&"
11
+ - Number words: "eight zero eight zero" β†’ "8080", "forty two" β†’ "42"
12
+ - Casing: "capital A" β†’ "A", "all caps POST" β†’ "POST"
13
+ - Casing directives: "camel case get user" β†’ "getUser"
14
+ - Spacing: "space" as explicit token separator
15
+ - Full commands: git, docker, curl, ssh, etc.
16
+
17
+ Usage:
18
+ python3 test-protocol-processor.py # run full suite
19
+ python3 test-protocol-processor.py --category git # filter by category
20
+ python3 test-protocol-processor.py --verbose # show all cases, not just errors
21
+ python3 test-protocol-processor.py --unit # run unit tests only (no eval file)
22
+ python3 test-protocol-processor.py --eval FILE # use custom eval file
23
+ """
24
+
25
+ import json
26
+ import re
27
+ import sys
28
+ import time
29
+ from pathlib import Path
30
+ from collections import defaultdict
31
+
32
+ # Import processor
33
+ sys.path.insert(0, str(Path(__file__).parent))
34
+ from importlib import import_module
35
+ _proc = import_module("procedural-processor")
36
+ process_dictation = _proc.process_dictation
37
+ consume_number = _proc.consume_number
38
+ consume_casing = _proc.consume_casing
39
+ SYMBOLS = _proc.SYMBOLS
40
+ TWO_WORD_SYMBOLS = _proc.TWO_WORD_SYMBOLS
41
+ THREE_WORD_SYMBOLS = _proc.THREE_WORD_SYMBOLS
42
+
43
+
44
+ # ── Colors ──────────────────────────────────────────────────────────────
45
+
46
+ GREEN = "\033[92m"
47
+ RED = "\033[91m"
48
+ YELLOW = "\033[93m"
49
+ DIM = "\033[2m"
50
+ BOLD = "\033[1m"
51
+ RESET = "\033[0m"
52
+
53
+
54
+ # ── Unit Tests ──────────────────────────────────────────────────────────
55
+ # These test individual features of the processor in isolation.
56
+
57
+ UNIT_TESTS = {
58
+ "symbols_basic": [
59
+ ("dash", "-"),
60
+ ("dot", "."),
61
+ ("slash", "/"),
62
+ ("pipe", "|"),
63
+ ("tilde", "~"),
64
+ ("hash", "#"),
65
+ ("at", "@"),
66
+ ("dollar", "$"),
67
+ ("percent", "%"),
68
+ ("caret", "^"),
69
+ ("ampersand", "&"),
70
+ ("equals", "="),
71
+ ("plus", "+"),
72
+ ("colon", ":"),
73
+ ("semicolon", ";"),
74
+ ("underscore", "_"),
75
+ ("comma", ","),
76
+ ("backslash", "\\"),
77
+ ("quote", '"'),
78
+ ("backtick", "`"),
79
+ ("star", "*"),
80
+ ("bang", "!"),
81
+ ("redirect", ">"),
82
+ ],
83
+ "symbols_synonyms": [
84
+ ("minus", "-"),
85
+ ("hyphen", "-"),
86
+ ("period", "."),
87
+ ("asterisk", "*"),
88
+ ("hashtag", "#"),
89
+ ],
90
+ "two_word_symbols": [
91
+ ("single quote", "'"),
92
+ ("open paren", "("),
93
+ ("close paren", ")"),
94
+ ("open brace", "{"),
95
+ ("close brace", "}"),
96
+ ("open bracket", "["),
97
+ ("close bracket", "]"),
98
+ ("open angle", "<"),
99
+ ("close angle", ">"),
100
+ ("open curly", "{"),
101
+ ("close curly", "}"),
102
+ ("less than", "<"),
103
+ ("question mark", "?"),
104
+ ("dash dash", "--"),
105
+ ("double dash", "--"),
106
+ ("and and", "&&"),
107
+ ("pipe pipe", "||"),
108
+ ("dot dot", ".."),
109
+ ("forward slash", "/"),
110
+ ("back slash", "\\"),
111
+ ("equals sign", "="),
112
+ ("at sign", "@"),
113
+ ("dollar sign", "$"),
114
+ ("open parenthesis", "("),
115
+ ("close parenthesis", ")"),
116
+ ("new line", "\n"),
117
+ ],
118
+ "three_word_symbols": [
119
+ ("two redirect ampersand", "2>&"),
120
+ ],
121
+ "numbers_single": [
122
+ ("zero", "0"),
123
+ ("one", "1"),
124
+ ("five", "5"),
125
+ ("nine", "9"),
126
+ ("ten", "10"),
127
+ ("twelve", "12"),
128
+ ("nineteen", "19"),
129
+ ],
130
+ "numbers_compound": [
131
+ ("twenty", "20"),
132
+ ("forty two", "42"),
133
+ ("ninety nine", "99"),
134
+ ],
135
+ "numbers_multiplier": [
136
+ ("one hundred", "100"),
137
+ ("three thousand", "3000"),
138
+ ("five hundred", "500"),
139
+ ],
140
+ "numbers_digit_sequence": [
141
+ ("one nine two", "192"),
142
+ ("eight zero eight zero", "8080"),
143
+ ("one two seven dot zero dot zero dot one", "127.0.0.1"),
144
+ ("four four three", "443"),
145
+ ],
146
+ "casing_capital": [
147
+ ("capital a", "A"),
148
+ ("capital x", "X"),
149
+ ("capital hello", "Hello"),
150
+ ],
151
+ "casing_all_caps": [
152
+ ("all caps post", "POST"),
153
+ ("all caps get", "GET"),
154
+ ("all caps node", "NODE"),
155
+ ],
156
+ "casing_directives": [
157
+ ("camel case get user profile", "getUserProfile"),
158
+ ("snake case api key", "api_key"),
159
+ ("pascal case my component", "MyComponent"),
160
+ ("kebab case my component", "my-component"),
161
+ ("screaming case max retries", "MAX_RETRIES"),
162
+ ],
163
+ "space_handling": [
164
+ ("git space push", "git push"),
165
+ ("ls space dash la", "ls -la"),
166
+ ("a space b space c", "a b c"),
167
+ ],
168
+ "mixed_basic": [
169
+ ("git space commit space dash m space quote hello quote", 'git commit -m "hello"'),
170
+ ("echo space dollar all caps home", "echo $HOME"),
171
+ ("cd space tilde slash projects", "cd ~/projects"),
172
+ ("chmod space seven five five space script dot sh", "chmod 755 script.sh"),
173
+ ],
174
+ "append_redirect": [
175
+ ("echo space hello space append space log dot txt", "echo hello >> log.txt"),
176
+ ("cat space file space redirect space output", "cat file > output"),
177
+ ],
178
+ }
179
+
180
+
181
+ def run_unit_tests(verbose=False):
182
+ """Run isolated unit tests for each processor feature."""
183
+ print(f"\n{BOLD}UNIT TESTS{RESET}")
184
+ print("=" * 70)
185
+
186
+ total = 0
187
+ passed = 0
188
+ failed_cases = []
189
+
190
+ for group_name, cases in UNIT_TESTS.items():
191
+ group_pass = 0
192
+ group_total = len(cases)
193
+
194
+ for dictated, expected in cases:
195
+ total += 1
196
+ got = process_dictation(dictated)
197
+
198
+ # Normalize whitespace for comparison
199
+ got_norm = re.sub(r'\s+', ' ', got.strip())
200
+ exp_norm = re.sub(r'\s+', ' ', expected.strip())
201
+
202
+ if got_norm == exp_norm:
203
+ group_pass += 1
204
+ passed += 1
205
+ if verbose:
206
+ print(f" {GREEN}PASS{RESET} [{group_name}] {dictated!r} β†’ {got!r}")
207
+ else:
208
+ failed_cases.append((group_name, dictated, expected, got))
209
+ print(f" {RED}FAIL{RESET} [{group_name}] {dictated!r}")
210
+ print(f" expected: {expected!r}")
211
+ print(f" got: {got!r}")
212
+
213
+ if not verbose and group_pass == group_total:
214
+ print(f" {GREEN}PASS{RESET} {group_name}: {group_pass}/{group_total}")
215
+
216
+ print(f"\n Total: {passed}/{total} passed", end="")
217
+ if failed_cases:
218
+ print(f", {RED}{len(failed_cases)} failed{RESET}")
219
+ else:
220
+ print(f" {GREEN}(all pass){RESET}")
221
+
222
+ return passed, total, failed_cases
223
+
224
+
225
+ def run_eval_tests(eval_file, category=None, verbose=False):
226
+ """Run the processor against the eval dataset."""
227
+ print(f"\n{BOLD}EVAL TESTS{RESET} β€” {eval_file}")
228
+ print("=" * 70)
229
+
230
+ with open(eval_file) as f:
231
+ data = json.load(f)
232
+
233
+ if category:
234
+ data = [d for d in data if d.get("category", "") == category]
235
+ print(f" Filtered to category={category}: {len(data)} cases")
236
+
237
+ total = len(data)
238
+ exact = 0
239
+ ws_match = 0
240
+ ws_case_match = 0
241
+ failed_cases = []
242
+ by_category = defaultdict(lambda: {"exact": 0, "total": 0})
243
+ timings = []
244
+
245
+ for d in data:
246
+ dictated = d["dictated"]
247
+ expected = d["expected"]
248
+ cat = d.get("category", "unknown")
249
+
250
+ t0 = time.perf_counter()
251
+ got = process_dictation(dictated)
252
+ elapsed_us = (time.perf_counter() - t0) * 1_000_000
253
+ timings.append(elapsed_us)
254
+
255
+ got_ws = re.sub(r'\s+', ' ', got.strip())
256
+ exp_ws = re.sub(r'\s+', ' ', expected.strip())
257
+
258
+ is_exact = got == expected
259
+ is_ws = got_ws == exp_ws
260
+ is_wsc = got_ws.lower() == exp_ws.lower()
261
+
262
+ by_category[cat]["total"] += 1
263
+
264
+ if is_exact:
265
+ exact += 1
266
+ by_category[cat]["exact"] += 1
267
+ if verbose:
268
+ print(f" {GREEN}PASS{RESET} [{cat}] {dictated[:60]}")
269
+ else:
270
+ failed_cases.append({
271
+ "category": cat,
272
+ "dictated": dictated,
273
+ "expected": expected,
274
+ "got": got,
275
+ "ws_match": is_ws,
276
+ "wsc_match": is_wsc,
277
+ })
278
+ if is_ws:
279
+ ws_match += 1
280
+ if verbose:
281
+ print(f" {YELLOW}WS{RESET} [{cat}] whitespace diff only")
282
+ elif is_wsc:
283
+ ws_case_match += 1
284
+
285
+ if is_ws:
286
+ ws_match += (1 if is_exact else 0) # already counted
287
+ if is_wsc:
288
+ ws_case_match += (1 if is_exact else 0)
289
+
290
+ # Recount properly
291
+ ws_match = sum(1 for d in data if re.sub(r'\s+', ' ', process_dictation(d["dictated"]).strip()) == re.sub(r'\s+', ' ', d["expected"].strip()))
292
+ ws_case_match = sum(1 for d in data if re.sub(r'\s+', ' ', process_dictation(d["dictated"]).strip()).lower() == re.sub(r'\s+', ' ', d["expected"].strip()).lower())
293
+
294
+ # Summary
295
+ print(f"\n {BOLD}ACCURACY{RESET}")
296
+ print(f" Exact match: {exact}/{total} ({exact/total*100:.1f}%)")
297
+ print(f" Whitespace-norm: {ws_match}/{total} ({ws_match/total*100:.1f}%)")
298
+ print(f" WS+case-norm: {ws_case_match}/{total} ({ws_case_match/total*100:.1f}%)")
299
+
300
+ # Timing
301
+ if timings:
302
+ timings.sort()
303
+ median = timings[len(timings)//2]
304
+ p95 = timings[int(len(timings) * 0.95)]
305
+ p99 = timings[int(len(timings) * 0.99)]
306
+ print(f"\n {BOLD}TIMING{RESET} (per command)")
307
+ print(f" Median: {median:.0f}us P95: {p95:.0f}us P99: {p99:.0f}us")
308
+
309
+ # Per category
310
+ if len(by_category) > 1:
311
+ print(f"\n {BOLD}BY CATEGORY{RESET}")
312
+ for cat in sorted(by_category.keys()):
313
+ r = by_category[cat]
314
+ pct = r["exact"] / r["total"] * 100 if r["total"] else 0
315
+ bar = GREEN if pct == 100 else (YELLOW if pct >= 80 else RED)
316
+ print(f" {cat:>14}: {bar}{r['exact']}/{r['total']}{RESET} ({pct:.0f}%)")
317
+
318
+ # Errors
319
+ if failed_cases:
320
+ print(f"\n {BOLD}FAILURES{RESET} ({len(failed_cases)}):")
321
+ print(" " + "-" * 66)
322
+ for e in failed_cases[:20]:
323
+ ws_note = f" {DIM}(whitespace only){RESET}" if e["ws_match"] else ""
324
+ wsc_note = f" {DIM}(case only){RESET}" if e["wsc_match"] and not e["ws_match"] else ""
325
+ print(f" [{e['category']}]{ws_note}{wsc_note}")
326
+ print(f" input: {e['dictated'][:70]}")
327
+ print(f" expected: {e['expected'][:70]}")
328
+ print(f" got: {e['got'][:70]}")
329
+
330
+ # Show character-level diff for near-misses
331
+ exp, got = e["expected"], e["got"]
332
+ if len(exp) < 80 and len(got) < 80:
333
+ diff_pos = next((i for i in range(min(len(exp), len(got))) if exp[i] != got[i]), min(len(exp), len(got)))
334
+ if diff_pos < len(exp) or diff_pos < len(got):
335
+ print(f" diff at {diff_pos}: expected {exp[diff_pos:diff_pos+10]!r} got {got[diff_pos:diff_pos+10]!r}")
336
+ print()
337
+
338
+ if len(failed_cases) > 20:
339
+ print(f" ... and {len(failed_cases) - 20} more")
340
+
341
+ return exact, total, failed_cases
342
+
343
+
344
+ def main():
345
+ import argparse
346
+ parser = argparse.ArgumentParser(description="Test the procedural dictation processor")
347
+ parser.add_argument("--unit", action="store_true", help="Run unit tests only")
348
+ parser.add_argument("--eval", type=str, default=None, help="Eval JSON file (default: eval-independent.json)")
349
+ parser.add_argument("--category", type=str, help="Filter eval cases by category")
350
+ parser.add_argument("--verbose", "-v", action="store_true", help="Show all cases, not just failures")
351
+ args = parser.parse_args()
352
+
353
+ print("=" * 70)
354
+ print(f" PROTOCOL PROCESSOR TEST HARNESS")
355
+ print("=" * 70)
356
+
357
+ # Always run unit tests
358
+ unit_passed, unit_total, unit_failures = run_unit_tests(verbose=args.verbose)
359
+
360
+ eval_passed = eval_total = 0
361
+ eval_failures = []
362
+
363
+ if not args.unit:
364
+ eval_file = args.eval or str(Path(__file__).parent / "eval-independent.json")
365
+ if Path(eval_file).exists():
366
+ eval_passed, eval_total, eval_failures = run_eval_tests(
367
+ eval_file, category=args.category, verbose=args.verbose
368
+ )
369
+ else:
370
+ print(f"\n {YELLOW}SKIP{RESET} eval tests β€” {eval_file} not found")
371
+
372
+ # Grand summary
373
+ print(f"\n{'=' * 70}")
374
+ print(f" {BOLD}GRAND SUMMARY{RESET}")
375
+ print(f"{'=' * 70}")
376
+ print(f" Unit tests: {unit_passed}/{unit_total}", end="")
377
+ print(f" {GREEN}PASS{RESET}" if not unit_failures else f" {RED}{len(unit_failures)} FAIL{RESET}")
378
+
379
+ if eval_total:
380
+ print(f" Eval tests: {eval_passed}/{eval_total} exact ({eval_passed/eval_total*100:.1f}%)", end="")
381
+ print(f" {GREEN}PASS{RESET}" if not eval_failures else f" β€” {YELLOW}{len(eval_failures)} diff{RESET}")
382
+
383
+ total_pass = unit_passed + eval_passed
384
+ total_all = unit_total + eval_total
385
+ print(f" Combined: {total_pass}/{total_all} ({total_pass/total_all*100:.1f}%)")
386
+
387
+ sys.exit(0 if not unit_failures else 1)
388
+
389
+
390
+ if __name__ == "__main__":
391
+ main()
scripts/train-segment-classifier.py ADDED
@@ -0,0 +1,671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Train a per-word protocol segment classifier.
4
+
5
+ Purpose: Given a mixed dictation like "I want to check the directory ls dash la",
6
+ classify each word as protocol (1) or natural (0), so we can extract segments
7
+ to send to the fused Qwen3 model.
8
+
9
+ Architecture:
10
+ - Per-word logistic regression with contextual features
11
+ - Context window of Β±2 words
12
+ - Output: weights + bias β†’ port to Swift as ProtocolSegmentClassifier
13
+
14
+ Training data: Synthetic mixed dictations combining natural speech fragments
15
+ with protocol command dictations from eval-fuzzy.json.
16
+ """
17
+
18
+ import json
19
+ import numpy as np
20
+ from pathlib import Path
21
+ import re
22
+
23
+ # ─── Protocol vocabulary split into strong/weak ───
24
+ # Strong: almost never appear in natural speech
25
+ # Weak: frequently appear in natural speech, only protocol in context
26
+
27
+ STRONG_PROTOCOL = {
28
+ # Symbol words (unambiguous)
29
+ "dash", "dot", "slash", "pipe", "tilde", "hash", "dollar",
30
+ "caret", "ampersand", "equals", "underscore", "backslash",
31
+ "backtick", "semicolon", "colon",
32
+ # Synonyms
33
+ "minus", "hyphen", "asterisk", "hashtag",
34
+ # Brackets (unambiguous components)
35
+ "paren", "brace", "bracket", "parenthesis", "curly",
36
+ # Casing directives
37
+ "capital", "caps", "camel", "snake", "pascal", "kebab", "screaming",
38
+ # Space as protocol
39
+ "space",
40
+ # Redirect
41
+ "redirect", "append",
42
+ }
43
+
44
+ WEAK_PROTOCOL = {
45
+ # These appear frequently in natural speech
46
+ "at", "star", "bang", "exclamation", "question", "comma", "quote",
47
+ "period", "plus", "percent",
48
+ # Multi-word components that are also common English
49
+ "single", "open", "close", "angle", "forward", "back", "sign",
50
+ "double", "mark", "than", "less", "new", "line", "all", "case",
51
+ # Number words REMOVED β€” too ambiguous in natural speech.
52
+ # Numbers near protocol words get captured by Β±2 expansion instead.
53
+ }
54
+
55
+ PROTOCOL_VOCAB = STRONG_PROTOCOL | WEAK_PROTOCOL
56
+
57
+ # Expanded symbols (after symbolic mapping runs)
58
+ EXPANDED_SYMBOLS = {
59
+ "-", ".", "/", "\\", "_", "|", "~", "@", "#", "*",
60
+ "+", "=", ":", ";", "&", "%", "^", "!", "?", "`",
61
+ "$", "<", ">", "--", "&&", "||",
62
+ }
63
+
64
+ SYNTAX_CHARS = set("-./\\_|~@#:=")
65
+
66
+ # ─── Natural speech fragments ───
67
+
68
+ NATURAL_PHRASES = [
69
+ "I want to check the directory",
70
+ "can you run this command for me",
71
+ "let's see what happens when we",
72
+ "okay so basically I need to",
73
+ "the next thing I want to do is",
74
+ "alright let me try",
75
+ "I think we should also look at",
76
+ "and then after that",
77
+ "go ahead and type out",
78
+ "so the idea is to",
79
+ "I was thinking maybe we could",
80
+ "hold on let me think about this",
81
+ "what if we try something different",
82
+ "actually no wait",
83
+ "right so the problem is",
84
+ "I need to figure out why",
85
+ "let's debug this real quick",
86
+ "the output should show us",
87
+ "and that would give us",
88
+ "basically what I'm trying to do is",
89
+ "so first we need to",
90
+ "and then we can see if",
91
+ "alright this is important",
92
+ "I want to emphasize",
93
+ "the reason I'm doing this is",
94
+ "so we did have a classifier",
95
+ "wasn't that part of the mission",
96
+ "like if we run all of a long dictation",
97
+ "I mean we'd be lucky to get",
98
+ "there's some stuff happening",
99
+ "that was not at all what I said",
100
+ "my last dictation was",
101
+ "we're not trying to do any list extraction",
102
+ "can you give me a few different test commands",
103
+ "I don't really understand",
104
+ "we should be able to fix that",
105
+ "alright let's do a proper dictation",
106
+ "the whole point is that",
107
+ "I think the idea would be",
108
+ "we want to build a new one",
109
+ "so yeah I think like we want to",
110
+ "and that would be a cleanup job",
111
+ "with maybe a bigger model",
112
+ "right so I think the plan is",
113
+ "let me explain what's going on",
114
+ "this is getting really interesting",
115
+ "okay perfect that works",
116
+ "no that's not right",
117
+ "wait what happened there",
118
+ "I'm gonna try again",
119
+ ]
120
+
121
+ # ─── Protocol command dictations ───
122
+
123
+ PROTOCOL_COMMANDS = [
124
+ # Simple commands
125
+ "ls dash la",
126
+ "git dash dash help",
127
+ "cd dot dot",
128
+ "rm dash rf",
129
+ "mkdir dash p",
130
+ "cat slash etc slash hosts",
131
+ "chmod seven five five",
132
+ "grep dash r",
133
+ "find dot dash name",
134
+ "ps aux",
135
+ "kill dash nine",
136
+ # Medium commands
137
+ "git space push space dash u space origin space main",
138
+ "docker space run space dash dash rm space dash p space eight zero eight zero colon eight zero",
139
+ "npm space install space dash capital D space typescript",
140
+ "ssh space dash i space tilde slash dot ssh slash id underscore rsa",
141
+ "curl space dash capital X space all caps POST",
142
+ "kubectl space get space pods space dash n space kube dash system",
143
+ "brew space install space dash dash cask",
144
+ "pip space install space dash r space requirements dot txt",
145
+ "python space dash m space pytest space dash v",
146
+ "cargo space build space dash dash release",
147
+ # Complex commands with paths
148
+ "rsync space dash avz space dash e space ssh space dot slash dist slash",
149
+ "export space all caps DATABASE underscore URL equals quote postgres colon slash slash admin",
150
+ "redis dash cli space dash h space one two seven dot zero dot zero dot one",
151
+ "terraform space plan space dash var dash file equals production dot tfvars",
152
+ # Short fragments
153
+ "dash dash help",
154
+ "dash la",
155
+ "dot slash",
156
+ "slash usr slash local slash bin",
157
+ "tilde slash dot config",
158
+ "star dot js",
159
+ "dollar sign open paren",
160
+ # Tool names with hyphens
161
+ "talkie dash dev",
162
+ "visual dash studio dash code",
163
+ "docker dash compose",
164
+ "kube dash system",
165
+ "type dash script",
166
+ ]
167
+
168
+ # Additional pure natural sentences β€” includes words that overlap with protocol vocab
169
+ # (at, three, one, new, line, back, sign, case, all, open, close, etc.)
170
+ PURE_NATURAL = [
171
+ "I was just thinking about how to approach this problem differently",
172
+ "the meeting is at three o'clock tomorrow afternoon",
173
+ "can you send me the link to that document",
174
+ "I'll get back to you on that later today",
175
+ "the project deadline is next Friday",
176
+ "we should probably discuss this with the rest of the team",
177
+ "that's a great idea I hadn't thought of that",
178
+ "let me know if you need anything else from me",
179
+ "I think the best approach would be to start from scratch",
180
+ "have you seen the latest updates to the design",
181
+ "the performance numbers look really good",
182
+ "we might need to reconsider our strategy here",
183
+ "I'll set up a call with the engineering team",
184
+ "the documentation needs to be updated before release",
185
+ "this reminds me of a similar issue we had last month",
186
+ # Sentences with ambiguous protocol words used naturally
187
+ "I arrived at the office at nine this morning",
188
+ "there are three new cases to review today",
189
+ "we need to go back and sign the contract",
190
+ "one of the most important things is to stay open",
191
+ "all of the line items need to be double checked",
192
+ "the new sign at the front of the building looks great",
193
+ "I need to close out all the open tickets by five",
194
+ "she gave us a star review which was really nice",
195
+ "the question mark at the end was confusing",
196
+ "he made a plus sized version of the original",
197
+ "we should open a new line of inquiry",
198
+ "there were less than ten people at the event",
199
+ "I'm going to mark this case as resolved",
200
+ "go back to the previous page and forward it to me",
201
+ "we had one single issue in all of last quarter",
202
+ "the angle of the photo makes it look close to the sign",
203
+ "I'll be back at four thirty with the new draft",
204
+ "that's a great point about the new direction",
205
+ "we need all hands on deck for this one",
206
+ "the bottom line is we need more time",
207
+ "let me quote you on that",
208
+ "he was at a loss for words",
209
+ "the new employee starts on day one next week",
210
+ "all in all it was a pretty good quarter",
211
+ "the case study shows a ten percent improvement",
212
+ "I need to sign off on this before close of business",
213
+ "the angle was all wrong for that particular shot",
214
+ ]
215
+
216
+
217
+ def is_protocol_word(word: str) -> bool:
218
+ """Check if a word is a protocol word."""
219
+ lower = word.lower().strip(".,!?;:'\"")
220
+ if lower in PROTOCOL_VOCAB:
221
+ return True
222
+ if word.strip() in EXPANDED_SYMBOLS:
223
+ return True
224
+ # Contains syntax characters (but not contractions)
225
+ if any(c in SYNTAX_CHARS for c in lower):
226
+ if "'" not in word and "\u2019" not in word:
227
+ # Not just a trailing period on a normal word
228
+ if not (word.endswith(".") and "." not in word[:-1]):
229
+ return True
230
+ return False
231
+
232
+
233
+ def label_words(words: list[str], labels: list[int]) -> list[dict]:
234
+ """Create labeled word entries with context features."""
235
+ entries = []
236
+ n = len(words)
237
+ for i, (word, label) in enumerate(zip(words, labels)):
238
+ entry = {
239
+ "word": word,
240
+ "label": label,
241
+ "position": i,
242
+ "total_words": n,
243
+ }
244
+ entries.append(entry)
245
+ return entries
246
+
247
+
248
+ def generate_mixed_examples(n_examples: int = 500, seed: int = 42) -> list[dict]:
249
+ """Generate synthetic mixed dictations with word-level labels."""
250
+ rng = np.random.RandomState(seed)
251
+ all_labeled = []
252
+
253
+ # Pattern 1: Natural + Protocol + Natural (sandwich)
254
+ for _ in range(n_examples // 3):
255
+ nat1 = rng.choice(NATURAL_PHRASES)
256
+ cmd = rng.choice(PROTOCOL_COMMANDS)
257
+ nat2 = rng.choice(NATURAL_PHRASES)
258
+
259
+ nat1_words = nat1.split()
260
+ cmd_words = cmd.split()
261
+ nat2_words = nat2.split()
262
+
263
+ words = nat1_words + cmd_words + nat2_words
264
+ labels = [0] * len(nat1_words) + [1] * len(cmd_words) + [0] * len(nat2_words)
265
+ all_labeled.extend(label_words(words, labels))
266
+
267
+ # Pattern 2: Protocol only (full command dictation)
268
+ for _ in range(n_examples // 4):
269
+ cmd = rng.choice(PROTOCOL_COMMANDS)
270
+ words = cmd.split()
271
+ labels = [1] * len(words)
272
+ all_labeled.extend(label_words(words, labels))
273
+
274
+ # Pattern 3: Natural only (pure speech, no protocol)
275
+ for _ in range(n_examples // 4):
276
+ nat = rng.choice(PURE_NATURAL + NATURAL_PHRASES)
277
+ words = nat.split()
278
+ labels = [0] * len(words)
279
+ all_labeled.extend(label_words(words, labels))
280
+
281
+ # Pattern 4: Natural + Protocol (command at end)
282
+ for _ in range(n_examples // 6):
283
+ nat = rng.choice(NATURAL_PHRASES)
284
+ cmd = rng.choice(PROTOCOL_COMMANDS)
285
+ nat_words = nat.split()
286
+ cmd_words = cmd.split()
287
+ words = nat_words + cmd_words
288
+ labels = [0] * len(nat_words) + [1] * len(cmd_words)
289
+ all_labeled.extend(label_words(words, labels))
290
+
291
+ # Pattern 5: Protocol + Natural (command at start, explanation after)
292
+ for _ in range(n_examples // 6):
293
+ cmd = rng.choice(PROTOCOL_COMMANDS)
294
+ nat = rng.choice(NATURAL_PHRASES)
295
+ cmd_words = cmd.split()
296
+ nat_words = nat.split()
297
+ words = cmd_words + nat_words
298
+ labels = [1] * len(cmd_words) + [0] * len(nat_words)
299
+ all_labeled.extend(label_words(words, labels))
300
+
301
+ return all_labeled
302
+
303
+
304
+ def is_strong_protocol(word: str) -> bool:
305
+ """Check if a word is an unambiguous protocol word."""
306
+ lower = word.lower().strip(".,!?;:'\"")
307
+ if lower in STRONG_PROTOCOL:
308
+ return True
309
+ if word.strip() in EXPANDED_SYMBOLS:
310
+ return True
311
+ return False
312
+
313
+
314
+ def extract_features(word: str, context: list[str], position: int, total: int) -> list[float]:
315
+ """
316
+ Extract features for a single word with its context.
317
+
318
+ Features (14 total):
319
+ 0. is_strong_protocol β€” word is an unambiguous protocol word (dash, dot, slash...)
320
+ 1. is_weak_protocol β€” word is an ambiguous protocol word (at, three, one...)
321
+ 2. is_expanded_symbol β€” word is an expanded symbol (-, ., /)
322
+ 3. has_syntax_chars β€” word contains syntax characters
323
+ 4. word_length_norm β€” word length / 10 (normalized)
324
+ 5. is_short_word β€” len <= 3 (commands: ls, cd, rm)
325
+ 6. context_strong_density β€” fraction of Β±2 context words that are STRONG protocol
326
+ 7. context_any_density β€” fraction of Β±2 context words that are any protocol
327
+ 8. left_is_strong β€” immediate left neighbor is strong protocol
328
+ 9. right_is_strong β€” immediate right neighbor is strong protocol
329
+ 10. is_number_like β€” word looks like a number or number word
330
+ 11. strong_neighbor_count β€” count of strong protocol words in Β±2 window
331
+ 12. is_all_lower β€” all lowercase
332
+ 13. position_ratio β€” position / total
333
+ """
334
+ lower = word.lower().strip(".,!?;:'\"")
335
+ stripped = word.strip()
336
+
337
+ # Feature 0: is_strong_protocol
338
+ f_strong = 1.0 if lower in STRONG_PROTOCOL else 0.0
339
+
340
+ # Feature 1: is_weak_protocol
341
+ f_weak = 1.0 if lower in WEAK_PROTOCOL else 0.0
342
+
343
+ # Feature 2: is_expanded_symbol
344
+ f_symbol = 1.0 if stripped in EXPANDED_SYMBOLS else 0.0
345
+
346
+ # Feature 3: has_syntax_chars
347
+ f_syntax = 0.0
348
+ if any(c in SYNTAX_CHARS for c in lower):
349
+ if "'" not in word and "\u2019" not in word:
350
+ if not (word.endswith(".") and "." not in word[:-1]):
351
+ f_syntax = 1.0
352
+
353
+ # Feature 4: word_length_norm
354
+ f_len = len(word) / 10.0
355
+
356
+ # Feature 5: is_short_word
357
+ f_short = 1.0 if len(lower) <= 3 else 0.0
358
+
359
+ # Feature 6: context_strong_density
360
+ ctx_strong = sum(1 for w in context if is_strong_protocol(w))
361
+ f_ctx_strong = ctx_strong / max(len(context), 1)
362
+
363
+ # Feature 7: context_any_density
364
+ ctx_any = sum(1 for w in context if is_protocol_word(w))
365
+ f_ctx_any = ctx_any / max(len(context), 1)
366
+
367
+ # Feature 8: left_is_strong
368
+ f_left = 0.0
369
+ if position > 0 and len(context) > 0:
370
+ ctx_center = min(position, 2)
371
+ if ctx_center > 0 and ctx_center - 1 < len(context):
372
+ f_left = 1.0 if is_strong_protocol(context[ctx_center - 1]) else 0.0
373
+
374
+ # Feature 9: right_is_strong
375
+ f_right = 0.0
376
+ if position < total - 1 and len(context) > 0:
377
+ ctx_center = min(position, 2)
378
+ if ctx_center + 1 < len(context):
379
+ f_right = 1.0 if is_strong_protocol(context[ctx_center + 1]) else 0.0
380
+
381
+ # Feature 10: is_number_like
382
+ number_words = {"zero", "one", "two", "three", "four", "five", "six",
383
+ "seven", "eight", "nine", "ten"}
384
+ f_number = 1.0 if (lower in number_words or lower.isdigit()) else 0.0
385
+
386
+ # Feature 11: strong_neighbor_count β€” raw count, not ratio
387
+ f_strong_neighbors = float(ctx_strong)
388
+
389
+ # Feature 12: is_all_lower
390
+ f_lower = 1.0 if word.isalpha() and word == word.lower() else 0.0
391
+
392
+ # Feature 13: position_ratio
393
+ f_pos = position / max(total - 1, 1)
394
+
395
+ return [
396
+ f_strong, # 0
397
+ f_weak, # 1
398
+ f_symbol, # 2
399
+ f_syntax, # 3
400
+ f_len, # 4
401
+ f_short, # 5
402
+ f_ctx_strong, # 6
403
+ f_ctx_any, # 7
404
+ f_left, # 8
405
+ f_right, # 9
406
+ f_number, # 10
407
+ f_strong_neighbors, # 11
408
+ f_lower, # 12
409
+ f_pos, # 13
410
+ ]
411
+
412
+
413
+ def build_dataset(labeled_words: list[dict], all_words_by_sentence=None):
414
+ """Build feature matrix and label vector from labeled words."""
415
+ # Group by sentence (consecutive entries with same total_words)
416
+ sentences = []
417
+ current = []
418
+ for entry in labeled_words:
419
+ if current and (entry["position"] == 0 or entry["total_words"] != current[0]["total_words"]):
420
+ sentences.append(current)
421
+ current = []
422
+ current.append(entry)
423
+ if current:
424
+ sentences.append(current)
425
+
426
+ X = []
427
+ y = []
428
+
429
+ for sentence in sentences:
430
+ words = [e["word"] for e in sentence]
431
+ for entry in sentence:
432
+ pos = entry["position"]
433
+ # Build context window Β±2
434
+ ctx_start = max(0, pos - 2)
435
+ ctx_end = min(len(words), pos + 3)
436
+ context = words[ctx_start:ctx_end]
437
+
438
+ features = extract_features(
439
+ entry["word"], context, pos, entry["total_words"]
440
+ )
441
+ X.append(features)
442
+ y.append(entry["label"])
443
+
444
+ return np.array(X), np.array(y)
445
+
446
+
447
+ def train_logistic_regression(X, y, lr=0.05, lambda_reg=0.1, max_epochs=500, tol=1e-6):
448
+ """Train logistic regression with L2 regularization via batch gradient descent."""
449
+ n_samples, n_features = X.shape
450
+ weights = np.zeros(n_features)
451
+ bias = 0.0
452
+
453
+ prev_loss = float("inf")
454
+
455
+ for epoch in range(max_epochs):
456
+ # Forward pass
457
+ logits = X @ weights + bias
458
+ probs = 1.0 / (1.0 + np.exp(-np.clip(logits, -500, 500)))
459
+
460
+ # Loss (binary cross-entropy + L2)
461
+ eps = 1e-15
462
+ loss = -np.mean(
463
+ y * np.log(probs + eps) + (1 - y) * np.log(1 - probs + eps)
464
+ ) + 0.5 * lambda_reg * np.sum(weights ** 2)
465
+
466
+ # Convergence check
467
+ if abs(prev_loss - loss) < tol:
468
+ print(f" Converged at epoch {epoch}, loss={loss:.6f}")
469
+ break
470
+ prev_loss = loss
471
+
472
+ # Gradients
473
+ error = probs - y
474
+ grad_w = (X.T @ error) / n_samples + lambda_reg * weights
475
+ grad_b = np.mean(error)
476
+
477
+ # Update
478
+ weights -= lr * grad_w
479
+ bias -= lr * grad_b
480
+
481
+ if epoch % 50 == 0:
482
+ acc = np.mean((probs >= 0.5) == y)
483
+ print(f" Epoch {epoch}: loss={loss:.4f}, acc={acc:.3f}")
484
+
485
+ # Final accuracy
486
+ probs = 1.0 / (1.0 + np.exp(-np.clip(X @ weights + bias, -500, 500)))
487
+ acc = np.mean((probs >= 0.5) == y)
488
+ print(f" Final: loss={prev_loss:.4f}, acc={acc:.3f}")
489
+
490
+ return weights, bias
491
+
492
+
493
+ def evaluate(X, y, weights, bias, threshold=0.5):
494
+ """Evaluate classifier and print metrics."""
495
+ logits = X @ weights + bias
496
+ probs = 1.0 / (1.0 + np.exp(-np.clip(logits, -500, 500)))
497
+ preds = (probs >= threshold).astype(int)
498
+
499
+ acc = np.mean(preds == y)
500
+ tp = np.sum((preds == 1) & (y == 1))
501
+ fp = np.sum((preds == 1) & (y == 0))
502
+ fn = np.sum((preds == 0) & (y == 1))
503
+ tn = np.sum((preds == 0) & (y == 0))
504
+
505
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0
506
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0
507
+ f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
508
+
509
+ print(f"\n Accuracy: {acc:.3f} ({int(acc * len(y))}/{len(y)})")
510
+ print(f" Precision: {precision:.3f}")
511
+ print(f" Recall: {recall:.3f}")
512
+ print(f" F1: {f1:.3f}")
513
+ print(f" Confusion: TP={tp} FP={fp} FN={fn} TN={tn}")
514
+
515
+ return acc, precision, recall, f1
516
+
517
+
518
+ def test_mixed_examples(weights, bias):
519
+ """Test on hand-crafted mixed dictation examples."""
520
+ test_cases = [
521
+ # (text, expected_protocol_words)
522
+ ("I want to check the directory ls dash la", {"ls", "dash", "la"}),
523
+ ("can you run git dash dash help for me", {"git", "dash", "help"}),
524
+ ("alright let me try talkie dash dev dash dash help", {"talkie", "dash", "dev", "help"}),
525
+ ("the meeting is at three o'clock tomorrow afternoon", set()),
526
+ ("I think we should also look at cd dot dot slash src", {"cd", "dot", "slash", "src"}),
527
+ ("so basically npm space install space dash capital D", {"npm", "space", "install", "dash", "capital", "D"}),
528
+ ("let me know if you need anything else from me", set()),
529
+ ("okay go ahead and type out chmod seven five five", {"chmod", "seven", "five"}),
530
+ ("the performance numbers look really good", set()),
531
+ ("ssh dash i tilde slash dot ssh slash id underscore rsa", {"ssh", "dash", "i", "tilde", "slash", "dot", "id", "underscore", "rsa"}),
532
+ ]
533
+
534
+ print("\n─── Test Cases ───")
535
+ for text, expected_protocol in test_cases:
536
+ words = text.split()
537
+ preds = []
538
+ for i, word in enumerate(words):
539
+ ctx_start = max(0, i - 2)
540
+ ctx_end = min(len(words), i + 3)
541
+ context = words[ctx_start:ctx_end]
542
+ features = extract_features(word, context, i, len(words))
543
+ logit = np.dot(features, weights) + bias
544
+ prob = 1.0 / (1.0 + np.exp(-logit))
545
+ preds.append((word, prob, prob >= 0.5))
546
+
547
+ detected = {w for w, p, is_proto in preds if is_proto}
548
+ natural = {w for w, p, is_proto in preds if not is_proto}
549
+
550
+ # Color output
551
+ colored = []
552
+ for w, p, is_proto in preds:
553
+ if is_proto:
554
+ colored.append(f"\033[91m{w}\033[0m") # red = protocol
555
+ else:
556
+ colored.append(f"\033[92m{w}\033[0m") # green = natural
557
+ print(f" {' '.join(colored)}")
558
+
559
+ # Check accuracy
560
+ if expected_protocol:
561
+ correct = detected & expected_protocol
562
+ missed = expected_protocol - detected
563
+ false_pos = detected - expected_protocol
564
+ if missed:
565
+ print(f" MISSED: {missed}")
566
+ if false_pos:
567
+ print(f" FALSE+: {false_pos}")
568
+ elif detected:
569
+ print(f" FALSE+: {detected}")
570
+
571
+
572
+ def export_model(weights, bias, feature_names, output_path):
573
+ """Export model as JSON for porting to Swift."""
574
+ model = {
575
+ "classifier": "ProtocolSegmentClassifier",
576
+ "description": "Per-word logistic regression for protocol segment detection",
577
+ "features": feature_names,
578
+ "weights": weights.tolist(),
579
+ "bias": float(bias),
580
+ "threshold": 0.5,
581
+ }
582
+ with open(output_path, "w") as f:
583
+ json.dump(model, f, indent=2)
584
+ print(f"\nModel exported to {output_path}")
585
+
586
+
587
+ FEATURE_NAMES = [
588
+ "is_strong_protocol",
589
+ "is_weak_protocol",
590
+ "is_expanded_symbol",
591
+ "has_syntax_chars",
592
+ "word_length_norm",
593
+ "is_short_word",
594
+ "context_strong_density",
595
+ "context_any_density",
596
+ "left_is_strong",
597
+ "right_is_strong",
598
+ "is_number_like",
599
+ "strong_neighbor_count",
600
+ "is_all_lower",
601
+ "position_ratio",
602
+ ]
603
+
604
+
605
+ def main():
606
+ print("=" * 60)
607
+ print("Protocol Segment Classifier Training")
608
+ print("=" * 60)
609
+
610
+ # Generate training data
611
+ print("\n1. Generating training data...")
612
+ labeled = generate_mixed_examples(n_examples=600, seed=42)
613
+ print(f" {len(labeled)} labeled words generated")
614
+
615
+ # Count class balance
616
+ n_protocol = sum(1 for e in labeled if e["label"] == 1)
617
+ n_natural = sum(1 for e in labeled if e["label"] == 0)
618
+ print(f" Protocol: {n_protocol} ({100*n_protocol/len(labeled):.1f}%)")
619
+ print(f" Natural: {n_natural} ({100*n_natural/len(labeled):.1f}%)")
620
+
621
+ # Build feature matrix
622
+ print("\n2. Extracting features...")
623
+ X, y = build_dataset(labeled)
624
+ print(f" Feature matrix: {X.shape}")
625
+
626
+ # Split train/test (80/20)
627
+ n = len(y)
628
+ indices = np.random.RandomState(42).permutation(n)
629
+ split = int(0.8 * n)
630
+ train_idx, test_idx = indices[:split], indices[split:]
631
+ X_train, y_train = X[train_idx], y[train_idx]
632
+ X_test, y_test = X[test_idx], y[test_idx]
633
+ print(f" Train: {len(y_train)}, Test: {len(y_test)}")
634
+
635
+ # Train
636
+ print("\n3. Training logistic regression...")
637
+ weights, bias = train_logistic_regression(X_train, y_train)
638
+
639
+ # Print weights
640
+ print("\n Weights:")
641
+ for name, w in zip(FEATURE_NAMES, weights):
642
+ print(f" {name:30s} {w:+.6f}")
643
+ print(f" {'bias':30s} {bias:+.6f}")
644
+
645
+ # Evaluate on test set
646
+ print("\n4. Test set evaluation:")
647
+ evaluate(X_test, y_test, weights, bias)
648
+
649
+ # Evaluate on train set (sanity check)
650
+ print("\n5. Train set evaluation (sanity):")
651
+ evaluate(X_train, y_train, weights, bias)
652
+
653
+ # Test on hand-crafted mixed examples
654
+ print("\n6. Mixed dictation examples:")
655
+ test_mixed_examples(weights, bias)
656
+
657
+ # Export
658
+ output_path = Path(__file__).parent / "segment-classifier-model.json"
659
+ export_model(weights, bias, FEATURE_NAMES, output_path)
660
+
661
+ # Print Swift-ready constants
662
+ print("\n─── Swift Constants ───")
663
+ print(f"private static let weights: [Double] = [")
664
+ for name, w in zip(FEATURE_NAMES, weights):
665
+ print(f" {w:+.20f}, // {name}")
666
+ print(f"]")
667
+ print(f"private static let bias: Double = {bias:+.20f}")
668
+
669
+
670
+ if __name__ == "__main__":
671
+ main()