dsh-tinyasr 1.5.0 → 1.7.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/CHANGELOG.md CHANGED
@@ -3,6 +3,23 @@
3
3
  All notable changes to this plugin. Entries up to 1.11.0 are local pre-release iterations of the
4
4
  1.0 line; the public package starts at 1.2.0.
5
5
 
6
+ ## 1.7.0 — 6 December 2026
7
+
8
+ - Mobile voice works with the local recognizer: the plugin bridges the DSH speech registry to the
9
+ call shape the mobile plugin's `host` provider expects (`resolve()` without a request and
10
+ `transcribe(audio, { signal })`). The provider choice on the phone stays zero-configuration, and
11
+ the audio never leaves the computer.
12
+ - `lib/mobile-bridge.js` with unit tests, including one against the real `dsh-mobile-plugin`
13
+ `host.js` when the plugin is installed.
14
+
15
+ ## 1.6.0 — 6 December 2026
16
+
17
+ - The cleanup model is an explicit choice, not the chat's model: the default is
18
+ `deepseek-account/deepseek-flash`, and the card lists every model the connected providers
19
+ advertise (`GET /api/tinyasr/models`) in a dropdown with **Apply** and **Reset**. Working with
20
+ another model in the chat no longer changes dictation cleanup.
21
+ - Reset returns to DeepSeek Flash, not to the session model.
22
+
6
23
  ## 1.5.0 — 6 December 2026
7
24
 
8
25
  - The cleanup model picker is back in the settings card: it shows the session default and lets you
package/README.md CHANGED
@@ -113,7 +113,7 @@ dsh plugin --profile <profile> add dsh-tinyasr
113
113
  | `autoLanguages` | Языки многоязычного прохода `auto` (по умолчанию `ru, en`). |
114
114
  | `primaryLanguage`, `fallbackLanguage` | Языки стратегии `ru-first`. |
115
115
  | `polish` | Правка расшифровки моделью DeepSeek (включена по умолчанию). |
116
- | `polishProvider`, `polishModel` | `auto` — модель текущей сессии; можно указать любую подключённую к Harness пару провайдер/модель. |
116
+ | `polishProvider`, `polishModel` | По умолчанию `deepseek-account` / `deepseek-flash`; в карточке выбирается любая подключённая к Harness пара из списка. |
117
117
  | `polishTimeoutMs` | Базовый таймаут правки; для длинных расшифровок дедлайн растёт, максимум 30 с. |
118
118
  | `terms`, `fixes` | Предпочтительные написания и литеральные замены до обращения к модели. |
119
119
  | `dataDir` | Телеметрия, глоссарий, настройки и локальный корпус точности. |
@@ -128,9 +128,10 @@ dsh plugin --profile <profile> add dsh-tinyasr
128
128
  11,6 % до 1,7 %.
129
129
 
130
130
  **Правка текста** (DeepSeek cleanup) — это второй запрос у выбранной модели: она исправляет
131
- орфографию, пунктуацию, числа, время и термины, но не переписывает смысл. По умолчанию берётся
132
- модель текущей сессии; в карточке можно задать любого подключённого провайдера и модель
133
- (например, `deepseek-flash`), а `Сбросить` возвращает сессионную. Ответ валидируется по длине и
131
+ орфографию, пунктуацию, числа, время и термины, но не переписывает смысл. По умолчанию
132
+ используется `deepseek-account/deepseek-flash` независимо от модели чата; в карточке есть список
133
+ всех моделей подключённых провайдеров — выберите нужную и нажмите `Применить`, а `Сбросить`
134
+ вернёт DeepSeek Flash. Ответ валидируется по длине и
134
135
  форме; при ошибке, отказе или таймауте остаётся исходная расшифровка.
135
136
 
136
137
  **Глоссарий** открывается кнопкой **Управлять**: поиск, добавление пар и удаление вариантов.
@@ -160,6 +161,25 @@ dsh plugin --profile <profile> add dsh-tinyasr
160
161
  | Правка DeepSeek | ~1–3 с |
161
162
  | Загрузка модели при старте процесса | ~0,12 с |
162
163
 
164
+ ## Мобильный телефон
165
+
166
+ Голосовой ввод в мобильном приложении DSH (плагин `dsh-mobile-plugin`) по умолчанию идёт через
167
+ провайдера **«宿主语音识别» (host)** — то есть через распознавание, установленное на компьютере.
168
+ Плагин добавляет совместимость между этим провайдером и реестром речи DSH, поэтому телефон
169
+ использует **тот же локальный tinyasr**, что и микрофон в браузере: без облака, без ключей и без
170
+ отправки аудио наружу.
171
+
172
+ Порядок:
173
+
174
+ 1. Подключите телефон к DSH (кнопка подключения в мобильном плагине) и откройте на телефоне
175
+ настройки голосового ввода.
176
+ 2. Выберите провайдера **«宿主语音识别»** — он уже стоит по умолчанию.
177
+ 3. Язык оставьте **auto**: движок сам определяет русский или английский (стратегия `ru-first`).
178
+
179
+ Ограничения этого пути: мобильный провайдер `host` принимает записи до 120 секунд и 8 МБ, а в
180
+ списке языков панели нет русского — поэтому «auto» и есть правильный выбор. Аудио обрабатывается
181
+ на компьютере и в облако не уходит.
182
+
163
183
  ## Требования
164
184
 
165
185
  - macOS на Apple Silicon (arm64): сборка `tinyasr-cli`/`tinyasr-serve` под эту машину.
package/client.js CHANGED
@@ -92,12 +92,10 @@ window.__ModuleLoader__.load({
92
92
  fromLabel: 'Если слышно так',
93
93
  toLabel: 'Писать так',
94
94
  modelTitle: 'Модель правки',
95
- modelAuto: 'Как в сессии — по умолчанию',
96
- modelProvider: 'Провайдер, например deepseek-account',
97
- modelName: 'Модель, например deepseek-flash',
95
+ modelEmpty: 'Модели не найдены — проверьте, что провайдеры подключены.',
98
96
  modelApply: 'Применить',
99
97
  modelReset: 'Сбросить',
100
- modelHint: 'Любая модель, подключённая к Harness. По умолчанию — модель текущей сессии.',
98
+
101
99
  micStart: 'Начать запись',
102
100
  micStop: 'Остановить запись',
103
101
  micBusy: 'Расшифровка…',
@@ -160,12 +158,10 @@ window.__ModuleLoader__.load({
160
158
  fromLabel: 'Heard as',
161
159
  toLabel: 'Write as',
162
160
  modelTitle: 'Cleanup model',
163
- modelAuto: 'Session default',
164
- modelProvider: 'Provider, e.g. deepseek-account',
165
- modelName: 'Model, e.g. deepseek-flash',
161
+ modelEmpty: 'No models found — check that providers are connected.',
166
162
  modelApply: 'Apply',
167
163
  modelReset: 'Reset',
168
- modelHint: 'Any model connected to Harness. The session default is used unless set.',
164
+
169
165
  micStart: 'Start recording',
170
166
  micStop: 'Stop recording',
171
167
  micBusy: 'Transcribing…',
@@ -291,15 +287,21 @@ window.__ModuleLoader__.load({
291
287
  const [open, setOpen] = React.useState(false)
292
288
  const [query, setQuery] = React.useState('')
293
289
  const [expanded, setExpanded] = React.useState({})
294
- const [modelOpen, setModelOpen] = React.useState(false)
295
- const [providerText, setProviderText] = React.useState('')
296
- const [modelText, setModelText] = React.useState('')
290
+ const [models, setModels] = React.useState([])
291
+ const [modelChoice, setModelChoice] = React.useState('')
297
292
 
298
293
  const read = React.useCallback(async () => {
299
- const response = await fetch('/api/tinyasr/state', { credentials: 'same-origin' })
294
+ const [response, modelsResponse] = await Promise.all([
295
+ fetch('/api/tinyasr/state', { credentials: 'same-origin' }),
296
+ fetch('/api/tinyasr/models', { credentials: 'same-origin' }).catch(() => undefined),
297
+ ])
300
298
  if (response.status === 401 || response.status === 403) throw new Error('unauthorized')
301
299
  if (!response.ok) throw new Error(`${response.status}`)
302
300
  setState(await response.json())
301
+ if (modelsResponse !== undefined && modelsResponse.ok) {
302
+ const payload = await modelsResponse.json().catch(() => ({}))
303
+ setModels(Array.isArray(payload.models) ? payload.models : [])
304
+ }
303
305
  }, [])
304
306
 
305
307
  React.useEffect(() => {
@@ -429,8 +431,16 @@ window.__ModuleLoader__.load({
429
431
  }, ...languages.map(([value, label]) => h('option', { key: value, value }, label))),
430
432
  }
431
433
 
432
- const polishProvider = settings.polishProvider ?? 'auto'
433
- const polishModel = settings.polishModel ?? 'auto'
434
+ const defaultPair = state.polishDefault ?? { provider: 'auto', model: 'auto' }
435
+ const chosen = settings.polishProvider !== undefined && settings.polishProvider !== 'auto'
436
+ ? { provider: settings.polishProvider, model: settings.polishModel }
437
+ : defaultPair
438
+ const pairKey = (pair) => `${pair.provider}||${pair.model}`
439
+ const options = [...models]
440
+ if (chosen.provider !== 'auto' && !options.some(option => option.provider === chosen.provider && option.model === chosen.model)) {
441
+ options.unshift({ provider: chosen.provider, model: chosen.model, name: chosen.model, providerName: chosen.provider })
442
+ }
443
+ const activeChoice = modelChoice === '' ? pairKey(chosen) : modelChoice
434
444
  const polishControl = {
435
445
  head: h('button', {
436
446
  type: 'button', role: 'switch', 'aria-checked': polishOn, 'aria-label': t('polish'),
@@ -438,41 +448,30 @@ window.__ModuleLoader__.load({
438
448
  onClick: () => { void send('/api/tinyasr/settings', { polish: !polishOn }) },
439
449
  }, h('span', { className: 'tasr-knob' })),
440
450
  body: h('div', { className: 'tasr-model' },
441
- h('button', {
442
- type: 'button', className: 'tasr-link', disabled: !polishOn,
443
- onClick: () => {
444
- const next = !modelOpen
445
- setModelOpen(next)
446
- if (next) {
447
- setProviderText(polishProvider === 'auto' ? '' : polishProvider)
448
- setModelText(polishModel === 'auto' ? '' : polishModel)
449
- }
450
- },
451
- }, polishProvider === 'auto' ? t('modelAuto') : `${polishProvider} / ${polishModel}`),
452
- modelOpen && h('div', { className: 'tasr-field' },
453
- h('input', {
454
- className: 'tasr-input', placeholder: t('modelProvider'), value: providerText,
455
- disabled: !polishOn, onChange: event => setProviderText(event.target.value),
456
- }),
457
- h('input', {
458
- className: 'tasr-input', placeholder: t('modelName'), value: modelText,
459
- disabled: !polishOn, onChange: event => setModelText(event.target.value),
460
- }),
461
- h('div', { style: { display: 'flex', gap: '8px' } },
462
- h('button', {
463
- type: 'button', className: 'tasr-btn tasr-btn-primary', disabled: !polishOn,
464
- onClick: () => {
465
- void send('/api/tinyasr/settings', {
466
- polishProvider: providerText.trim() === '' ? 'auto' : providerText.trim(),
467
- polishModel: modelText.trim() === '' ? 'auto' : modelText.trim(),
468
- })
469
- },
470
- }, t('modelApply')),
471
- h('button', {
472
- type: 'button', className: 'tasr-btn', disabled: !polishOn,
473
- onClick: () => { void send('/api/tinyasr/settings', { polishProvider: 'auto', polishModel: 'auto' }) },
474
- }, t('modelReset'))),
475
- h('p', { className: 'tasr-note' }, t('modelHint'))))
451
+ h('label', { className: 'tasr-label', for: 'tasr-model' }, t('modelTitle')),
452
+ h('select', {
453
+ id: 'tasr-model', className: 'tasr-input tasr-select', value: activeChoice, disabled: !polishOn,
454
+ onChange: event => setModelChoice(event.target.value),
455
+ }, ...options.map(option => h('option', {
456
+ key: `${option.provider}||${option.model}`, value: `${option.provider}||${option.model}`,
457
+ }, `${option.name ?? option.model} — ${option.providerName ?? option.provider}`))),
458
+ options.length === 0 && h('p', { className: 'tasr-note' }, t('modelEmpty')),
459
+ h('div', { style: { display: 'flex', gap: '8px' } },
460
+ h('button', {
461
+ type: 'button', className: 'tasr-btn tasr-btn-primary', disabled: !polishOn || models.length === 0,
462
+ onClick: () => {
463
+ const [provider, model] = activeChoice.split('||')
464
+ if (provider === undefined || model === undefined) return
465
+ void send('/api/tinyasr/settings', { polishProvider: provider, polishModel: model })
466
+ },
467
+ }, t('modelApply')),
468
+ h('button', {
469
+ type: 'button', className: 'tasr-btn', disabled: !polishOn,
470
+ onClick: () => {
471
+ setModelChoice('')
472
+ void send('/api/tinyasr/settings', { polishProvider: defaultPair.provider, polishModel: defaultPair.model })
473
+ },
474
+ }, t('modelReset'))))
476
475
  }
477
476
 
478
477
  const glossaryControl = {
@@ -47,8 +47,9 @@
47
47
  primaryLanguage: ru
48
48
  fallbackLanguage: en
49
49
  polish: true
50
- polishProvider: auto
51
- polishModel: auto
50
+ # Product default for the cleanup pass; any connected pair can be chosen in the card.
51
+ polishProvider: deepseek-account
52
+ polishModel: deepseek-flash
52
53
  polishTimeoutMs: 6000
53
54
  polishMaxTokens: 3000
54
55
  terms:
package/cordis.patch.yml CHANGED
@@ -47,8 +47,9 @@
47
47
  primaryLanguage: ru
48
48
  fallbackLanguage: en
49
49
  polish: true
50
- polishProvider: auto
51
- polishModel: auto
50
+ # Product default for the cleanup pass; any connected pair can be chosen in the card.
51
+ polishProvider: deepseek-account
52
+ polishModel: deepseek-flash
52
53
  polishTimeoutMs: 6000
53
54
  polishMaxTokens: 3000
54
55
  terms:
package/index.js CHANGED
@@ -24,6 +24,7 @@ import { Glossary } from './lib/glossary.js'
24
24
  import { SettingsStore } from './lib/settings.js'
25
25
  import { registerRoutes } from './lib/routes.js'
26
26
  import { registerLiveRoutes } from './lib/live.js'
27
+ import { installMobileVoiceBridge } from './lib/mobile-bridge.js'
27
28
  import { ResidentWorker } from './lib/worker.js'
28
29
 
29
30
  /** Expand `~` in a configured path; a literal `~` directory is never intended. */
@@ -510,6 +511,9 @@ export function apply(ctx, config) {
510
511
  const settings = new SettingsStore(resolved.settingsPath)
511
512
  const glossary = new Glossary(resolved.glossaryPath)
512
513
  const provider = new TinyAsrProvider(ctx, resolved, ctx.logger, { settings, glossary })
514
+ // Let the mobile plugin's `host` voice provider reach this recognizer.
515
+ const speech = typeof ctx.get === 'function' ? ctx.get('speechToText') : ctx.speechToText
516
+ ctx.effect(() => installMobileVoiceBridge(speech))
513
517
  ctx.effect(() => {
514
518
  const unregister = ctx.speechToText.register({
515
519
  info: provider.info,
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Compatibility bridge between the DSH speech registry and the mobile plugin's
3
+ * `host` voice provider.
4
+ *
5
+ * The mobile plugin (dsh-mobile-plugin) delegates voice recognition to the host
6
+ * through `ctx.speechToText` using an older shape:
7
+ *
8
+ * service.resolve() -> a provider-like object with `.id` and `.transcribe(audio, opts)`
9
+ * service.transcribe(audioBuffer, opts) -> `{text}`
10
+ *
11
+ * The current registry (0.2.x) instead exposes:
12
+ *
13
+ * resolve({ audio, providerId?, language? }) -> { provider, audio, language }
14
+ * transcribe({ provider, audio, language }, signal) -> result
15
+ *
16
+ * Without adaptation the mobile "host" provider resolves to `undefined` and its
17
+ * transcription call throws, so the phone silently depends on cloud providers.
18
+ * This wrapper accepts both shapes and never changes the registry for the other
19
+ * callers: a request-shaped call passes straight through.
20
+ *
21
+ * @param {object} service - the `speechToText` registry service.
22
+ * @returns {() => void} remover that restores the original methods.
23
+ */
24
+ export function installMobileVoiceBridge(service) {
25
+ if (service === undefined || service === null) return () => {}
26
+ if (typeof service.resolve !== 'function' || typeof service.transcribe !== 'function') return () => {}
27
+ if (service.__tinyasrBridge === true) return () => {}
28
+
29
+ const originalResolve = service.resolve
30
+ const originalTranscribe = service.transcribe
31
+ const resolve = originalResolve.bind(service)
32
+ const transcribe = originalTranscribe.bind(service)
33
+
34
+ const signalOf = (value) => {
35
+ if (value instanceof AbortSignal) return value
36
+ if (value !== null && typeof value === 'object' && value.signal instanceof AbortSignal) return value.signal
37
+ return new AbortController().signal
38
+ }
39
+
40
+ // What the mobile bridge believes a resolved provider looks like.
41
+ const legacy = {
42
+ get id() {
43
+ try { return String(service.snapshot()?.selection?.providerId ?? '') } catch { return '' }
44
+ },
45
+ get info() {
46
+ try { return service.snapshot()?.providers?.find(entry => entry.id === legacy.id) ?? {} } catch { return {} }
47
+ },
48
+ transcribe(audio, options) {
49
+ return transcribe(resolve({ audio }), signalOf(options))
50
+ },
51
+ }
52
+
53
+ service.resolve = (request) => (request === undefined ? legacy : resolve(request))
54
+ service.transcribe = (spec, signal) => {
55
+ const raw = ArrayBuffer.isView(spec) || spec instanceof ArrayBuffer
56
+ return raw ? transcribe(resolve({ audio: spec }), signalOf(signal)) : transcribe(spec, signal)
57
+ }
58
+ service.__tinyasrBridge = true
59
+
60
+ return () => {
61
+ if (service.__tinyasrBridge !== true) return
62
+ service.resolve = originalResolve
63
+ service.transcribe = originalTranscribe
64
+ delete service.__tinyasrBridge
65
+ }
66
+ }
package/lib/routes.js CHANGED
@@ -178,6 +178,7 @@ export function registerRoutes(ctx, { config, settings, glossary, provider, logg
178
178
  resident: config.resident === true,
179
179
  autoLanguages: config.autoLanguages,
180
180
  strategy: config.strategy,
181
+ polishDefault: { provider: config.polishProvider, model: config.polishModel },
181
182
  })
182
183
  } catch (error) {
183
184
  logger?.warn?.('tinyasr: settings read failed', error)
@@ -186,6 +187,43 @@ export function registerRoutes(ctx, { config, settings, glossary, provider, logg
186
187
  },
187
188
  })
188
189
 
190
+ // Models the connected providers advertise; the card offers them as the cleanup model.
191
+ const offModels = webServer.register({
192
+ kind: 'exact',
193
+ path: `${PREFIX}/models`,
194
+ handler: async (req, res) => {
195
+ if (!guarded(req, res)) return
196
+ if (req.method !== 'GET') return methodNotAllowed(res, ['GET'])
197
+ const llm = ctx.get?.('llm')
198
+ if (llm === undefined) { sendJson(res, 200, { models: [] }); return }
199
+ const models = []
200
+ try {
201
+ for (const provider of llm.listProviders()) {
202
+ try {
203
+ const registration = llm.registration(provider.id)
204
+ const list = await registration.adapter.listModels(provider)
205
+ for (const model of list) {
206
+ const id = typeof model?.id === 'string' ? model.id : typeof model === 'string' ? model : undefined
207
+ if (id === undefined) continue
208
+ models.push({
209
+ provider: provider.id,
210
+ model: id,
211
+ name: typeof model?.name === 'string' ? model.name : id,
212
+ providerName: typeof provider.name === 'string' ? provider.name : provider.id,
213
+ })
214
+ }
215
+ } catch (error) {
216
+ logger?.warn?.('tinyasr: models unavailable for provider', provider.id, error)
217
+ }
218
+ }
219
+ } catch (error) {
220
+ logger?.warn?.('tinyasr: model discovery failed', error)
221
+ }
222
+ models.sort((a, b) => `${a.provider}/${a.model}`.localeCompare(`${b.provider}/${b.model}`))
223
+ sendJson(res, 200, { models, current: { provider: config.polishProvider, model: config.polishModel } })
224
+ },
225
+ })
226
+
189
227
  const offSettings = webServer.register({
190
228
  kind: 'exact',
191
229
  path: `${PREFIX}/settings`,
@@ -345,6 +383,7 @@ export function registerRoutes(ctx, { config, settings, glossary, provider, logg
345
383
 
346
384
  return () => {
347
385
  offState()
386
+ offModels()
348
387
  offSettings()
349
388
  offGlossary()
350
389
  offSelftest()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tinyasr",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "description": "Offline Russian and English dictation for the DeepSeek Harness Web GUI through the local tinyasr recognizer, with an optional model cleanup pass.",