@modelform/react-native 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -109,6 +109,69 @@ metric, and entries of one item share `save` and `item`:
109
109
  For anything beyond a demo, implement `EntryStore` over your own storage, such as SQLite. Keep each entry's `save` and
110
110
  `item` so groups can be read back.
111
111
 
112
+ ### Dictation
113
+
114
+ Number, duration, text and choice inputs show a microphone button when the form has a speech recognizer. What's said
115
+ becomes the value ("seventy two point five" → 72.5, "went for a swim" picks Swim), and dictated text is added after a
116
+ multi-line field's text. On the web, the browser's speech recognition is used where there is one (Chrome, Edge,
117
+ Safari; not Firefox). On phones, pass a `SpeechRecognizer`, for example over
118
+ [expo-speech-recognition](https://github.com/jamsch/expo-speech-recognition):
119
+
120
+ ```tsx
121
+ import { ExpoSpeechRecognitionModule } from 'expo-speech-recognition';
122
+ import type { SpeechRecognizer } from '@modelform/react-native';
123
+
124
+ const speech: SpeechRecognizer = {
125
+ start(o) {
126
+ const subs: { remove(): void }[] = [];
127
+ const end = () => {
128
+ subs.forEach((s) => s.remove());
129
+ o.onEnd();
130
+ };
131
+ ExpoSpeechRecognitionModule.requestPermissionsAsync().then(({ granted }) => {
132
+ if (!granted) return o.onError('Microphone access is off'), end();
133
+ subs.push(
134
+ ExpoSpeechRecognitionModule.addListener('result', (e) => o.onText(e.results[0]?.transcript ?? '', e.isFinal)),
135
+ ExpoSpeechRecognitionModule.addListener('error', (e) => e.error !== 'aborted' && o.onError(e.message)),
136
+ ExpoSpeechRecognitionModule.addListener('end', end),
137
+ );
138
+ ExpoSpeechRecognitionModule.start({ lang: o.lang ?? 'en-US', interimResults: true, contextualStrings: o.hints });
139
+ });
140
+ return { stop: () => ExpoSpeechRecognitionModule.stop(), abort: () => ExpoSpeechRecognitionModule.abort() };
141
+ },
142
+ };
143
+
144
+ <InputForm dashboard={form} store={store} speech={speech} />;
145
+ ```
146
+
147
+ `speech={null}` turns dictation off. `spokenValue(panel, text)` and the parsers behind it are exported for filling
148
+ forms by other means. The native recognizer is shared, so a real adapter should also wait for the previous session's
149
+ `end` before starting the next one; otherwise that late event ends the new session too.
150
+
151
+ ### Filling the whole form by voice
152
+
153
+ With a recognizer, the form also gets a microphone beside Save. Say several values in one go ("weight seventy two
154
+ point five, slept seven hours, mood four, went for a swim"), tap again to stop, and the form fills what it understood.
155
+ Filled inputs are outlined and marked "From voice" until edited; nothing is recorded until Save, and Undo puts the form
156
+ back as it was before the fill. Listening is `continuous`, so pauses don't cut it off: an adapter should pass that on
157
+ (expo-speech-recognition takes `continuous: true`) and deliver the whole transcript as one final `onText` when it
158
+ stops.
159
+
160
+ What was said goes to a `FormFiller`, `(form, said) => Promise<FillResult>`. The default, `ruleFiller`, needs no model:
161
+ a value is what follows a field's name, and fields not named are found by unit ("72.5 kilos") or by a choice only one
162
+ field has. To use a model, wrap whatever generates text in `modelFiller`; it prompts with `fillPrompt`, passes
163
+ `fillSchema` for guided generation, reads the reply with `readFill` (so a model can only enter what typing could), and
164
+ with a fallback fills what the model left out:
165
+
166
+ ```tsx
167
+ import { modelFiller, ruleFiller } from '@modelform/react-native';
168
+
169
+ const filler = modelFiller((instructions, prompt, schema) => myModel.generate({ instructions, prompt, schema }), ruleFiller);
170
+ <InputForm dashboard={form} store={store} speech={speech} filler={filler} />;
171
+ ```
172
+
173
+ `filler={null}` turns whole-form filling off and keeps per-field dictation. Groups' fields and counters aren't filled.
174
+
112
175
  ## Bundled dashboards
113
176
 
114
177
  `modelform dashboards [dir] [--watch]` writes an `index.ts` that imports every `.json` file in a folder, so
@@ -1567,6 +1567,481 @@ function queryErrors(results) {
1567
1567
  return Object.entries(results ?? {}).filter(([, r]) => r.error).map(([refId, r]) => `${refId}: ${r.error}`).join("\n");
1568
1568
  }
1569
1569
 
1570
+ // src/core/speech.ts
1571
+ var UNITS = {
1572
+ zero: 0,
1573
+ oh: 0,
1574
+ nought: 0,
1575
+ one: 1,
1576
+ two: 2,
1577
+ three: 3,
1578
+ four: 4,
1579
+ five: 5,
1580
+ six: 6,
1581
+ seven: 7,
1582
+ eight: 8,
1583
+ nine: 9,
1584
+ ten: 10,
1585
+ eleven: 11,
1586
+ twelve: 12,
1587
+ thirteen: 13,
1588
+ fourteen: 14,
1589
+ fifteen: 15,
1590
+ sixteen: 16,
1591
+ seventeen: 17,
1592
+ eighteen: 18,
1593
+ nineteen: 19
1594
+ };
1595
+ var TENS = { twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 };
1596
+ var SCALES = { hundred: 100, thousand: 1e3, million: 1e6 };
1597
+ var NEGATIVE = /* @__PURE__ */ new Set(["minus", "negative"]);
1598
+ var isNumberWord = (w) => w in UNITS || w in TENS || w in SCALES;
1599
+ function words(text) {
1600
+ return text.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/(\d),(\d{3})\b/g, "$1$2").replace(/(\d),(\d)/g, "$1.$2").replace(/[^a-z0-9.:\s-]/g, " ").replace(/(?<![\d])-(?=\d)/g, " minus ").replace(/-/g, " ").replace(/\.(?!\d)/g, " ").split(/\s+/).filter(Boolean);
1601
+ }
1602
+ function wordsToInteger(ws) {
1603
+ if (!ws.length) return null;
1604
+ if (ws.some((w) => w in SCALES)) {
1605
+ let total = 0;
1606
+ let current = 0;
1607
+ for (const w of ws) {
1608
+ if (w in UNITS) current += UNITS[w];
1609
+ else if (w in TENS) current += TENS[w];
1610
+ else if (w === "hundred") current = (current || 1) * 100;
1611
+ else if (w in SCALES) {
1612
+ total += (current || 1) * SCALES[w];
1613
+ current = 0;
1614
+ } else return null;
1615
+ }
1616
+ return total + current;
1617
+ }
1618
+ const groups = [];
1619
+ for (let i = 0; i < ws.length; i++) {
1620
+ const w = ws[i];
1621
+ const next = ws[i + 1];
1622
+ const nextUnit = next != null && next in UNITS && UNITS[next] > 0 && UNITS[next] < 10;
1623
+ if (w in TENS) {
1624
+ groups.push(String(TENS[w] + (nextUnit ? UNITS[next] : 0)));
1625
+ if (nextUnit) i++;
1626
+ } else if (w === "oh" && nextUnit) {
1627
+ groups.push(`0${UNITS[next]}`);
1628
+ i++;
1629
+ } else if (w in UNITS) groups.push(String(UNITS[w]));
1630
+ else return null;
1631
+ }
1632
+ return Number(groups.map((g, i) => i === 0 ? g : g.padStart(2, "0")).join(""));
1633
+ }
1634
+ function parseSpokenNumber(text) {
1635
+ const ws = words(text);
1636
+ let i = 0;
1637
+ let sign = 1;
1638
+ for (; i < ws.length; i++) {
1639
+ const w = ws[i];
1640
+ if (NEGATIVE.has(w)) sign = -1;
1641
+ else if (/^\d/.test(w) || isNumberWord(w) || w === "a" && ws[i + 1] in SCALES || w === "point" && ws[i + 1] && (/^\d/.test(ws[i + 1]) || ws[i + 1] in UNITS)) break;
1642
+ else if (w !== "and") sign = 1;
1643
+ }
1644
+ if (i >= ws.length) return null;
1645
+ const digits = /^(\d+(?:\.\d+)?)$/.exec(ws[i]);
1646
+ if (digits) {
1647
+ let n = Number(digits[1]);
1648
+ const rest = ws.slice(i + 1);
1649
+ if (!digits[1].includes(".") && rest[0] === "point") n = Number(`${digits[1]}.${fractionDigits(rest.slice(1)) ?? 0}`);
1650
+ else if (rest[0] === "and" && rest[1] === "a" && rest[2] === "half") n += 0.5;
1651
+ return sign * n;
1652
+ }
1653
+ const whole = [];
1654
+ for (; i < ws.length; i++) {
1655
+ const w = ws[i];
1656
+ if (isNumberWord(w)) whole.push(w);
1657
+ else if (w === "a" && ws[i + 1] in SCALES) whole.push("one");
1658
+ else if (w === "and" && ws[i + 1] && isNumberWord(ws[i + 1]) && whole.some((x) => x in SCALES)) continue;
1659
+ else break;
1660
+ }
1661
+ const intPart = whole.length ? wordsToInteger(whole) : 0;
1662
+ if (intPart == null) return null;
1663
+ if (ws[i] === "point") {
1664
+ const frac = fractionDigits(ws.slice(i + 1));
1665
+ return frac == null ? sign * intPart : sign * Number(`${intPart}.${frac}`);
1666
+ }
1667
+ if (ws[i] === "and" && ws[i + 1] === "a" && ws[i + 2] === "half") return sign * (intPart + 0.5);
1668
+ if (ws[i] === "and" && ws[i + 1] === "a" && ws[i + 2] === "quarter") return sign * (intPart + 0.25);
1669
+ if (!whole.length) return null;
1670
+ return sign * intPart;
1671
+ }
1672
+ function fractionDigits(ws) {
1673
+ if (ws[0] && /^\d+$/.test(ws[0])) return ws[0];
1674
+ let out = "";
1675
+ for (let i = 0; i < ws.length; i++) {
1676
+ const w = ws[i];
1677
+ if (w in UNITS && UNITS[w] < 10) out += UNITS[w];
1678
+ else if (w in TENS) {
1679
+ const next = ws[i + 1];
1680
+ if (next in UNITS && UNITS[next] > 0 && UNITS[next] < 10) {
1681
+ out += TENS[w] + UNITS[next];
1682
+ i++;
1683
+ } else out += TENS[w];
1684
+ } else if (w in UNITS) out += UNITS[w];
1685
+ else break;
1686
+ }
1687
+ return out || null;
1688
+ }
1689
+ function parseSpokenDuration(text) {
1690
+ const clock = /(?:(\d+):)?(\d+):(\d{1,2})(?:\.(\d+))?|(\d+):(\d{1,2})(?:\.(\d+))?/.exec(text);
1691
+ if (clock) {
1692
+ if (clock[3] != null) {
1693
+ const [h, m, s, f] = [Number(clock[1] ?? 0), Number(clock[2]), Number(clock[3]), clock[4] ?? "0"];
1694
+ return clock[1] != null ? h * 3600 + m * 60 + s + Number(`0.${f}`) : m * 60 + s + Number(`0.${f}`);
1695
+ }
1696
+ }
1697
+ const lower = text.toLowerCase().replace(/\ban hour\b/g, "one hour").replace(/\ba minute\b/g, "one minute").replace(/(\S+) (hours?|minutes?) and a half/g, "$1 and a half $2");
1698
+ const parts = lower.split(/\b(hours?|hrs?|minutes?|mins?|seconds?|secs?)\b/);
1699
+ const scale = (unit) => unit.startsWith("h") ? 3600 : unit.startsWith("m") ? 60 : 1;
1700
+ let total = 0;
1701
+ let found = false;
1702
+ let last = 0;
1703
+ for (let i = 0; i < parts.length; i += 2) {
1704
+ const n = parseSpokenNumber(parts[i]);
1705
+ const unit = parts[i + 1];
1706
+ const s = unit != null ? scale(unit) : last === 3600 ? 60 : last === 60 ? 1 : 0;
1707
+ if (unit != null) last = s;
1708
+ if (n == null || !s) continue;
1709
+ total += n * s;
1710
+ found = true;
1711
+ }
1712
+ if (found) return Math.round(total * 100) / 100;
1713
+ return null;
1714
+ }
1715
+ var normalize = (s) => words(s).join(" ");
1716
+ var singular = (w) => w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w;
1717
+ var loose = (s) => normalize(s).split(" ").map(singular).join(" ");
1718
+ function matchChoices(text, choices2) {
1719
+ const said = ` ${loose(text)} `;
1720
+ const hits = [];
1721
+ const byLength = [...choices2].sort((a, b) => b.label.length - a.label.length);
1722
+ for (const c of byLength) {
1723
+ const label = loose(c.label);
1724
+ if (!label) continue;
1725
+ let from = 0;
1726
+ for (; ; ) {
1727
+ const at = said.indexOf(` ${label} `, from);
1728
+ if (at < 0) break;
1729
+ const end = at + label.length + 1;
1730
+ if (!hits.some((h) => at < h.end && end > h.at)) hits.push({ at, end, value: c.value });
1731
+ from = at + 1;
1732
+ }
1733
+ }
1734
+ if (!hits.length) {
1735
+ const n = parseSpokenNumber(text);
1736
+ const c = n == null ? void 0 : choices2.find((x) => x.value === n || Number(x.label) === n || x.value === String(n));
1737
+ return c ? [c.value] : [];
1738
+ }
1739
+ const seen = /* @__PURE__ */ new Set();
1740
+ return hits.sort((a, b) => a.at - b.at).map((h) => h.value).filter((v) => !seen.has(v) && seen.add(v));
1741
+ }
1742
+ var YES = /* @__PURE__ */ new Set(["yes", "yeah", "yep", "yup", "true", "on", "done", "did", "checked", "correct", "affirmative"]);
1743
+ var NO = /* @__PURE__ */ new Set(["no", "nope", "nah", "false", "off", "not", "didnt", "didn", "unchecked", "negative"]);
1744
+ function parseSpokenYesNo(text) {
1745
+ const ws = words(text.replace(/['’]/g, ""));
1746
+ if (ws.some((w) => NO.has(w))) return false;
1747
+ if (ws.some((w) => YES.has(w))) return true;
1748
+ return null;
1749
+ }
1750
+ function spokenValue(panel, said, current = null, choices2) {
1751
+ const text = said.trim();
1752
+ if (!text) return { problem: "Didn\u2019t hear anything" };
1753
+ const o = panel.options;
1754
+ const quoted = `\u201C${text}\u201D`;
1755
+ switch (panel.type) {
1756
+ case "input-text": {
1757
+ if (o.suggest || typeof current !== "string" || !current.trim()) return { value: text };
1758
+ return { value: `${current.trimEnd()} ${text}` };
1759
+ }
1760
+ case "input-number":
1761
+ case "input-rating": {
1762
+ const n = parseSpokenNumber(text);
1763
+ if (n == null) return { problem: `Heard ${quoted}, not a number` };
1764
+ const step = panel.type === "input-rating" ? 1 : o.step ?? 1;
1765
+ return { value: Number.isInteger(step) ? Math.round(n) : n };
1766
+ }
1767
+ case "input-slider": {
1768
+ const min = o.min ?? 0;
1769
+ const max = o.max ?? 10;
1770
+ const step = o.step ?? 1;
1771
+ if (o.labels?.length) {
1772
+ const [hit] = matchChoices(text, o.labels.map((label, i) => ({ label, value: i })));
1773
+ if (typeof hit === "number") {
1774
+ const raw = o.labels.length === 1 ? min : min + hit / (o.labels.length - 1) * (max - min);
1775
+ return { value: Number((Math.round((raw - min) / step) * step + min).toFixed((String(step).split(".")[1] ?? "").length)) };
1776
+ }
1777
+ }
1778
+ const n = parseSpokenNumber(text);
1779
+ if (n == null) return { problem: `Heard ${quoted}, not a number` };
1780
+ return { value: Number.isInteger(step) ? Math.round(n) : n };
1781
+ }
1782
+ case "input-duration": {
1783
+ const s = parseSpokenDuration(text) ?? parseSpokenNumber(text);
1784
+ return s == null ? { problem: `Heard ${quoted}, not a time` } : { value: s };
1785
+ }
1786
+ case "input-select": {
1787
+ const options = choices2 ?? o.choices ?? [];
1788
+ const hits = matchChoices(text, options);
1789
+ if (!hits.length) return { problem: `Heard ${quoted}, not one of the choices` };
1790
+ if (!o.multi) return { value: hits[0] };
1791
+ const had = Array.isArray(current) ? current : current == null ? [] : [current];
1792
+ return { value: [...had, ...hits.filter((h) => !had.includes(h))] };
1793
+ }
1794
+ case "input-toggle": {
1795
+ const yes = parseSpokenYesNo(text);
1796
+ return yes == null ? { problem: `Heard ${quoted}, not yes or no` } : { value: yes };
1797
+ }
1798
+ default:
1799
+ return { problem: "This input doesn\u2019t take dictation" };
1800
+ }
1801
+ }
1802
+ var DICTATION_TYPES = ["input-number", "input-text", "input-select", "input-duration"];
1803
+ var takesDictation = (panel) => DICTATION_TYPES.includes(panel.type);
1804
+ function dictationHints(panel, choices2) {
1805
+ const out = (choices2 ?? panel.options.choices ?? []).map((c) => c.label);
1806
+ if (panel.options.unit) out.push(panel.options.unit);
1807
+ return out;
1808
+ }
1809
+
1810
+ // src/core/formFill.ts
1811
+ var choicesOf = (p, runtime) => (p.options.choicesFrom ? runtime[p.options.choicesFrom] : p.options.choices) ?? [];
1812
+ function fillForm(dashboard, choices2 = {}) {
1813
+ const fields = [];
1814
+ const panels = {};
1815
+ for (const p of plainInputPanels(dashboard)) {
1816
+ const o = p.options;
1817
+ if (p.type === "input-counter" || panels[o.metric]) continue;
1818
+ const base = { key: o.metric, label: p.title || o.metric };
1819
+ let field2;
1820
+ switch (p.type) {
1821
+ case "input-number":
1822
+ field2 = { ...base, type: "number", unit: o.unit, min: o.min, max: o.max };
1823
+ break;
1824
+ case "input-rating":
1825
+ field2 = { ...base, type: "number", min: Math.round(o.min ?? 1), max: Math.round(o.max ?? 5) };
1826
+ break;
1827
+ case "input-slider":
1828
+ field2 = { ...base, type: "number", unit: o.unit, min: o.min ?? 0, max: o.max ?? 10, choices: o.labels?.length ? o.labels : void 0 };
1829
+ break;
1830
+ case "input-duration":
1831
+ field2 = { ...base, type: "duration" };
1832
+ break;
1833
+ case "input-select": {
1834
+ const labels = choicesOf(p, choices2).map((c) => c.label);
1835
+ if (!labels.length) continue;
1836
+ field2 = { ...base, type: o.multi ? "choices" : "choice", choices: labels };
1837
+ break;
1838
+ }
1839
+ case "input-toggle":
1840
+ field2 = { ...base, type: "boolean" };
1841
+ break;
1842
+ case "input-text":
1843
+ field2 = { ...base, type: "text" };
1844
+ break;
1845
+ default:
1846
+ continue;
1847
+ }
1848
+ fields.push(Object.fromEntries(Object.entries(field2).filter(([, v]) => v !== void 0)));
1849
+ panels[o.metric] = p;
1850
+ }
1851
+ return { fields, panels, choices: choices2 };
1852
+ }
1853
+ function describe(f) {
1854
+ const range = f.min != null && f.max != null ? `, from ${f.min} to ${f.max}` : f.min != null ? `, ${f.min} or more` : f.max != null ? `, at most ${f.max}` : "";
1855
+ switch (f.type) {
1856
+ case "number":
1857
+ return `a number${f.unit ? ` in ${f.unit}` : ""}${range}${f.choices ? ` (${f.choices.join(" \u2026 ")} along the scale)` : ""}`;
1858
+ case "duration":
1859
+ return "a duration in seconds";
1860
+ case "choice":
1861
+ return `one of: ${f.choices.map((c) => JSON.stringify(c)).join(", ")}`;
1862
+ case "choices":
1863
+ return `a list of any of: ${f.choices.map((c) => JSON.stringify(c)).join(", ")}`;
1864
+ case "boolean":
1865
+ return "true or false";
1866
+ case "text":
1867
+ return "text, in the user\u2019s words";
1868
+ }
1869
+ }
1870
+ function fillSchema(form) {
1871
+ const properties = {};
1872
+ for (const f of form.fields) {
1873
+ const description = `${f.label}: ${describe(f)}`;
1874
+ switch (f.type) {
1875
+ case "number":
1876
+ case "duration":
1877
+ properties[f.key] = { type: "number", description, ...f.min != null && { minimum: f.min }, ...f.max != null && { maximum: f.max } };
1878
+ break;
1879
+ case "choice":
1880
+ properties[f.key] = { type: "string", enum: f.choices, description };
1881
+ break;
1882
+ case "choices":
1883
+ properties[f.key] = { type: "array", items: { type: "string", enum: f.choices }, description };
1884
+ break;
1885
+ case "boolean":
1886
+ properties[f.key] = { type: "boolean", description };
1887
+ break;
1888
+ case "text":
1889
+ properties[f.key] = { type: "string", description };
1890
+ break;
1891
+ }
1892
+ }
1893
+ return { type: "object", properties, required: [], additionalProperties: false };
1894
+ }
1895
+ function fillPrompt(form, said) {
1896
+ const instructions = [
1897
+ "You fill in a form from what the user said.",
1898
+ "Reply with one JSON object and nothing else. Its keys are field keys from the list below.",
1899
+ "Only include fields the user gave a value for; leave the others out. Never guess or make up values.",
1900
+ "Numbers are plain numbers without units. Choices use the exact text listed."
1901
+ ].join(" ");
1902
+ const list = form.fields.map((f) => `- ${f.key}: ${f.label}, ${describe(f)}`).join("\n");
1903
+ const example = form.fields.find((f) => f.type === "number");
1904
+ const prompt = [
1905
+ `Fields:
1906
+ ${list}`,
1907
+ example ? `Example: if the user said "${example.label.toLowerCase()} 3" the answer is {"${example.key}": 3}` : "",
1908
+ `The user said: "${said.replace(/"/g, "'")}"`,
1909
+ "JSON:"
1910
+ ].filter(Boolean).join("\n\n");
1911
+ return { instructions, prompt };
1912
+ }
1913
+ function parseFillAnswer(answer) {
1914
+ if (answer && typeof answer === "object" && !Array.isArray(answer)) return answer;
1915
+ if (typeof answer !== "string") return null;
1916
+ const start = answer.indexOf("{");
1917
+ const end = answer.lastIndexOf("}");
1918
+ if (start < 0 || end <= start) return null;
1919
+ try {
1920
+ const v = JSON.parse(answer.slice(start, end + 1));
1921
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
1922
+ } catch {
1923
+ return null;
1924
+ }
1925
+ }
1926
+ function asSaid(v) {
1927
+ if (v == null) return null;
1928
+ if (typeof v === "boolean") return v ? "yes" : "no";
1929
+ if (typeof v === "number") return Number.isFinite(v) ? String(v) : null;
1930
+ if (typeof v === "string") return v.trim() || null;
1931
+ if (Array.isArray(v)) return v.map(asSaid).filter(Boolean).join(", ") || null;
1932
+ return null;
1933
+ }
1934
+ function readFill(form, answer) {
1935
+ const result = { values: {}, problems: [] };
1936
+ const obj = parseFillAnswer(answer);
1937
+ if (!obj) return { values: {}, problems: [{ key: "", problem: "The answer wasn\u2019t a JSON object" }] };
1938
+ for (const f of form.fields) {
1939
+ const raw = obj[f.key];
1940
+ const panel = form.panels[f.key];
1941
+ const choices2 = choicesOf(panel, form.choices);
1942
+ if (panel.type === "input-select" && !panel.options.multi) {
1943
+ const byValue = choices2.find((c) => c.value === raw);
1944
+ if (byValue) {
1945
+ result.values[f.key] = byValue.value;
1946
+ continue;
1947
+ }
1948
+ }
1949
+ const said = asSaid(raw);
1950
+ if (said == null) continue;
1951
+ const r = spokenValue(panel, said, null, choices2);
1952
+ if ("value" in r) result.values[f.key] = r.value;
1953
+ else result.problems.push({ key: f.key, problem: r.problem });
1954
+ }
1955
+ return result;
1956
+ }
1957
+ var UNIT_WORDS = {
1958
+ kg: ["kg", "kgs", "kilo", "kilos", "kilogram", "kilograms"],
1959
+ lb: ["lb", "lbs", "pound", "pounds"],
1960
+ h: ["h", "hr", "hrs", "hour", "hours"],
1961
+ min: ["min", "mins", "minute", "minutes"],
1962
+ s: ["s", "sec", "secs", "second", "seconds"],
1963
+ km: ["km", "kms", "kilometer", "kilometers", "kilometre", "kilometres", "k"],
1964
+ mi: ["mi", "mile", "miles"],
1965
+ m: ["m", "meter", "meters", "metre", "metres"]
1966
+ };
1967
+ var NUMBER_WORD = "(?:-?\\d+(?:[.,]\\d+)?|zero|oh|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|point|and|a|half|quarter|minus)";
1968
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1969
+ function namesOf(f) {
1970
+ const names = /* @__PURE__ */ new Set([f.label.toLowerCase(), f.key.toLowerCase().replace(/[-_]+/g, " ")]);
1971
+ return [...names].filter((n) => n.trim().length > 1);
1972
+ }
1973
+ var LEAD = /^[\s,:;.-]*(?:(?:is|was|were|of|at|about|around|to|=)\b[\s,:;.-]*)*/i;
1974
+ function ruleFill(form, said) {
1975
+ const lower = said.toLowerCase();
1976
+ const hits = [];
1977
+ for (const f of form.fields)
1978
+ for (const name of namesOf(f)) {
1979
+ const re = new RegExp(`(?<![\\p{L}\\p{N}])${escape(name)}(?![\\p{L}\\p{N}])`, "gu");
1980
+ for (const m of lower.matchAll(re)) {
1981
+ const at = m.index;
1982
+ const end = at + m[0].length;
1983
+ if (!hits.some((h) => at < h.end && end > h.at)) hits.push({ key: f.key, at, end });
1984
+ }
1985
+ }
1986
+ hits.sort((a, b) => a.at - b.at);
1987
+ const segments = {};
1988
+ const used = [];
1989
+ hits.forEach((h, i) => {
1990
+ const stop = i + 1 < hits.length ? hits[i + 1].at : said.length;
1991
+ if (h.key in segments) return;
1992
+ segments[h.key] = said.slice(h.end, stop).replace(LEAD, "").replace(/[\s,;.]+$/, "");
1993
+ used.push([h.at, stop]);
1994
+ });
1995
+ const answer = {};
1996
+ for (const f of form.fields) if (segments[f.key]) answer[f.key] = segments[f.key];
1997
+ const rest = used.reduceRight((text, [a, b]) => text.slice(0, a) + " ".repeat(b - a) + text.slice(b), said);
1998
+ for (const f of form.fields) {
1999
+ if (f.key in answer) continue;
2000
+ if (f.type === "number" && f.unit) {
2001
+ const words2 = UNIT_WORDS[f.unit.toLowerCase()] ?? [f.unit.toLowerCase()];
2002
+ const unitRe = new RegExp(`(?<![\\p{L}\\p{N}])((?:${NUMBER_WORD}[\\s-]+)+)(?:${words2.map(escape).join("|")})(?![\\p{L}\\p{N}])`, "iu");
2003
+ const m = unitRe.exec(rest);
2004
+ if (m && m[1].trim()) answer[f.key] = m[1];
2005
+ } else if ((f.type === "choice" || f.type === "choices") && f.choices) {
2006
+ const options = f.choices.map((label) => ({ label, value: label }));
2007
+ const hits2 = matchChoices(rest, options);
2008
+ const shared = form.fields.some(
2009
+ (g) => g !== f && !(g.key in answer) && (g.type === "choice" || g.type === "choices") && matchChoices(rest, (g.choices ?? []).map((l) => ({ label: l, value: l }))).length
2010
+ );
2011
+ if (hits2.length && !shared) answer[f.key] = f.type === "choices" ? hits2 : hits2[0];
2012
+ }
2013
+ }
2014
+ return readFill(form, answer);
2015
+ }
2016
+ var ruleFiller = async (form, said) => ruleFill(form, said);
2017
+ function modelFiller(generate, fallback) {
2018
+ return async (form, said) => {
2019
+ let result = null;
2020
+ try {
2021
+ const { instructions, prompt } = fillPrompt(form, said);
2022
+ result = readFill(form, await generate(instructions, prompt, fillSchema(form)));
2023
+ if (result.problems.some((p) => p.key === "")) result = null;
2024
+ } catch {
2025
+ result = null;
2026
+ }
2027
+ if (!fallback) return result ?? { values: {}, problems: [{ key: "", problem: "The model couldn\u2019t fill the form" }] };
2028
+ const rules = await fallback(form, said);
2029
+ if (!result) return rules;
2030
+ const values = { ...rules.values, ...result.values };
2031
+ const problems = [...result.problems, ...rules.problems.filter((p) => !(p.key in values))];
2032
+ return { values, problems };
2033
+ };
2034
+ }
2035
+ function fillHints(form) {
2036
+ const out = /* @__PURE__ */ new Set();
2037
+ for (const f of form.fields) {
2038
+ out.add(f.label);
2039
+ if (f.unit) out.add(f.unit);
2040
+ for (const c of f.choices ?? []) out.add(c);
2041
+ }
2042
+ return [...out];
2043
+ }
2044
+
1570
2045
  // src/core/local.ts
1571
2046
  var LOCAL_DATASOURCE_TYPE = "modelform-local";
1572
2047
  var LEGACY_LOCAL_DATASOURCE_TYPE = "dashkit-local";
@@ -11996,6 +12471,23 @@ export {
11996
12471
  GrafanaClient,
11997
12472
  GrafanaDataSource,
11998
12473
  fromWire,
12474
+ parseSpokenNumber,
12475
+ parseSpokenDuration,
12476
+ matchChoices,
12477
+ parseSpokenYesNo,
12478
+ spokenValue,
12479
+ DICTATION_TYPES,
12480
+ takesDictation,
12481
+ dictationHints,
12482
+ fillForm,
12483
+ fillSchema,
12484
+ fillPrompt,
12485
+ parseFillAnswer,
12486
+ readFill,
12487
+ ruleFill,
12488
+ ruleFiller,
12489
+ modelFiller,
12490
+ fillHints,
11999
12491
  LOCAL_DATASOURCE_TYPE,
12000
12492
  isLocalDatasource,
12001
12493
  LocalDataSource,