fix(live-dictate): talk to whisper.cpp's HTTP API instead of Lemonade realtime

Live dictation sent the OpenAI realtime protocol to ws://host/v1/realtime,
which only Lemonade-style servers implement.  Against the local
whisper-server on port 13305 every connection failed with
"websocket-received-error-http-response 404".

Retarget the module at whisper.cpp's native POST /inference endpoint:

- capture 16 kHz mono PCM16 with FFmpeg (now with binary process coding,
  which the old version lacked and which would have corrupted the audio)
- cut the stream into utterances with an energy-based VAD: speech starts
  above live-dictate-silence-threshold, flushes after a configurable
  silence window, with pre-roll and a max-utterance cap
- wrap each utterance in a WAV header and post it with curl, one request
  at a time so transcripts are inserted in spoken order
- insert text at the dictation marker with correct spacing, keep the
  mode-line indicator and follow-cursor behaviour
- warn when the microphone delivers pure digital silence (OS permission)

New defcustoms: live-dictate-language, -prompt, -silence-threshold,
-silence-duration, -min-utterance, -max-utterance, -preroll.

Comments in config-mac.el and packages.el updated; websocket is no
longer needed by dictation.
This commit is contained in:
Willem van den Ende
2026-11-05 12:14:30 +00:00
parent 183036a333
commit 580b213793
3 changed files with 335 additions and 229 deletions
+5 -7
View File
@@ -236,9 +236,8 @@ Returns answer with org-roam links to sources."
;;; Speech-to-text (whisper.el + streaming dictation) ;;; Speech-to-text (whisper.el + streaming dictation)
;; ;;
;; Ported from config-linux.el so both machines have the same capabilities. ;; Ported from config-linux.el so both machines have the same capabilities.
;; The pieces are already cross-platform: `whisper' and `websocket' are ;; `whisper' is declared in shared packages.el, and lisp/live-dictate.el
;; declared in shared packages.el, and lisp/live-dictate.el picks avfoundation ;; picks avfoundation for FFmpeg input on darwin by itself.
;; for FFmpeg input on darwin by itself.
;; ;;
;; Backend on this machine: homebrew's whisper.cpp server, started by hand: ;; Backend on this machine: homebrew's whisper.cpp server, started by hand:
;; ;;
@@ -247,10 +246,9 @@ Returns answer with org-roam links to sources."
;; ;;
;; Mode `remote' POSTs multipart (file, response_format=json, language) to ;; Mode `remote' POSTs multipart (file, response_format=json, language) to
;; <baseurl>/inference and parses the {"text": ...} reply -- whisper.cpp's ;; <baseurl>/inference and parses the {"text": ...} reply -- whisper.cpp's
;; native API. For a Lemonade-style OpenAI-compatible backend instead, use ;; native API. `live-dictate' (SPC A d) uses the same endpoint: it cuts the
;; `whisper-server-mode' 'openai with `whisper-openai-api-baseurl'; that is ;; microphone stream into utterances with a client-side VAD and posts each
;; also what `live-dictate' (SPC A d) requires, since it streams over ;; one as a WAV, so no WebSocket or Lemonade server is needed.
;; ws://host/v1/realtime, which whisper.cpp cannot serve.
(add-load-path! "lisp") (add-load-path! "lisp")
(autoload #'live-dictate "live-dictate" nil t) (autoload #'live-dictate "live-dictate" nil t)
+325 -219
View File
@@ -1,40 +1,45 @@
;;; live-dictate.el --- Live dictation via Lemonade realtime WebSocket -*- lexical-binding: t; -*- ;;; live-dictate.el --- Live dictation via a whisper.cpp server -*- lexical-binding: t; -*-
;; Author: Willem (generated with pi) ;; Author: Willem (generated with pi)
;; Version: 1.0.0 ;; Version: 2.0.0
;; Package-Requires: ((emacs "27.1") (websocket "1.13")) ;; Package-Requires: ((emacs "27.1"))
;; URL: https://github.com/lemonade-sdk/lemonade
;;; Commentary: ;;; Commentary:
;; Live speech-to-text dictation using Lemonade Server's OpenAI ;; Live speech-to-text dictation against a `whisper.cpp' server
;; Realtime-compatible WebSocket endpoint (/v1/realtime). ;; (`whisper-server', the `POST /inference' endpoint).
;; ;;
;; `live-dictate' toggles dictation in the current buffer: microphone audio ;; `live-dictate' toggles dictation in the current buffer: microphone audio
;; is captured with FFmpeg as 16kHz PCM16, streamed to the server over a ;; is captured with FFmpeg as 16 kHz mono PCM16, cut into utterances on the
;; WebSocket, and interim/final transcripts are inserted at point as you ;; client by a small energy-based VAD, and each utterance is posted to the
;; speak. Finalized utterances replace their interim preview. ;; server as a WAV file. Transcripts are inserted at point, in order.
;; ;;
;; Concurrency note: websocket.el can desync its frame parser if frames are ;; History: version 1 spoke the OpenAI realtime protocol over a WebSocket
;; sent from within its own network process filter (or any process filter). ;; (ws://host/v1/realtime). Only Lemonade-style servers implement that;
;; All sends are therefore queued to an outbox and flushed from a timer. ;; whisper.cpp answers 404 for it, hence the rewrite.
;;; Code: ;;; Code:
(require 'json) (require 'json)
(require 'cl-lib) (require 'cl-lib)
(require 'subr-x)
(defgroup live-dictate nil (defgroup live-dictate nil
"Live dictation via Lemonade's realtime transcription WebSocket." "Live dictation via a whisper.cpp server."
:group 'external) :group 'external)
(defcustom live-dictate-server-url "http://localhost:13305" (defcustom live-dictate-server-url "http://localhost:13305"
"Base URL of the Lemonade server (WS upgrade happens on /v1/realtime)." "Base URL of the whisper.cpp server (transcription via /inference)."
:type 'string :type 'string
:group 'live-dictate) :group 'live-dictate)
(defcustom live-dictate-model "Whisper-Large-v3-Turbo" (defcustom live-dictate-language "en"
"Realtime transcription model. Must support `realtime-transcription'." "Language passed to the server (`auto' to detect)."
:type 'string
:group 'live-dictate)
(defcustom live-dictate-prompt ""
"Optional initial prompt sent to the server (often empty)."
:type 'string :type 'string
:group 'live-dictate) :group 'live-dictate)
@@ -43,13 +48,29 @@
:type 'boolean :type 'boolean
:group 'live-dictate) :group 'live-dictate)
(defcustom live-dictate-stop-delay 2.0 (defcustom live-dictate-silence-threshold 2
"Seconds to wait after committing the buffer before closing the WebSocket." "Peak-amplitude threshold (0-127, on the high byte of each sample).
Above it the stream counts as speech; at or below it, as silence."
:type 'integer
:group 'live-dictate)
(defcustom live-dictate-silence-duration 0.7
"Seconds of silence that end an utterance."
:type 'number :type 'number
:group 'live-dictate) :group 'live-dictate)
(defcustom live-dictate-flush-interval 0.1 (defcustom live-dictate-min-utterance 0.3
"How often to flush queued audio to the WebSocket, in seconds." "Shortest utterance, in seconds, that is sent to the server."
:type 'number
:group 'live-dictate)
(defcustom live-dictate-max-utterance 15.0
"Longest utterance, in seconds, before it is cut and sent."
:type 'number
:group 'live-dictate)
(defcustom live-dictate-preroll 0.3
"Seconds of audio kept from before speech is detected."
:type 'number :type 'number
:group 'live-dictate) :group 'live-dictate)
@@ -77,19 +98,29 @@
:type 'boolean :type 'boolean
:group 'live-dictate) :group 'live-dictate)
(defvar live-dictate--ws nil) (defconst live-dictate--sample-rate 16000)
(defconst live-dictate--bytes-per-sample 2)
(defconst live-dictate--pcm-buffer " *live-dictate-pcm*")
(defconst live-dictate--stderr-buffer " *live-dictate-stderr*")
(defvar live-dictate--ffmpeg nil) (defvar live-dictate--ffmpeg nil)
(defvar live-dictate--active nil) (defvar live-dictate--active nil)
(defvar live-dictate--outbox nil)
(defvar live-dictate--flush-timer nil)
(defvar live-dictate--stop-timer nil)
(defvar live-dictate--target-buffer nil) (defvar live-dictate--target-buffer nil)
(defvar live-dictate--marker nil) (defvar live-dictate--marker nil)
(defvar live-dictate--interim-start nil)
(defvar live-dictate--interim-end nil) ;; Audio bookkeeping: the work buffer holds PCM from
(defvar live-dictate--chunk-count 0) ;; `live-dictate--buf-start' up to `live-dictate--total' (both in samples).
(defvar live-dictate--chunk-bytes 0) (defvar live-dictate--buf-start 0)
(defvar live-dictate--stderr-buffer " *live-dictate-stderr*") (defvar live-dictate--total 0)
(defvar live-dictate--speech-start nil)
(defvar live-dictate--silence 0)
(defvar live-dictate--max-peak 0)
(defvar live-dictate--warned-silence nil)
;; Transcription pipeline: utterances queue up, one curl request at a time,
;; so transcripts are inserted in the order they were spoken.
(defvar live-dictate--queue nil)
(defvar live-dictate--busy nil)
(defvar live-dictate--mode-line-indicator (defvar live-dictate--mode-line-indicator
(propertize " 🎙" 'face 'font-lock-warning-face)) (propertize " 🎙" 'face 'font-lock-warning-face))
@@ -98,38 +129,216 @@
(when live-dictate-debug (when live-dictate-debug
(message "live-dictate: %s" (apply #'format fmt args)))) (message "live-dictate: %s" (apply #'format fmt args))))
(defun live-dictate--ws-url () (defun live-dictate--samples (seconds)
(format "ws://%s/v1/realtime?model=%s" (round (* seconds live-dictate--sample-rate)))
(replace-regexp-in-string "^https?://" "" live-dictate-server-url)
(url-hexify-string live-dictate-model)))
(defun live-dictate--queue-send (payload) ;;; Audio capture
"Queue JSON-able PAYLOAD for sending. Safe from any context."
(push payload live-dictate--outbox))
(defun live-dictate--flush-outbox () (defun live-dictate--peak (chunk)
"Send all queued payloads. Runs from a timer, never inside process filters." "Peak amplitude of raw PCM16 CHUNK, measured on the high byte."
(when live-dictate--outbox (let ((i 0)
(if (and live-dictate--ws (websocket-openp live-dictate--ws)) (n (length chunk))
(let ((queue (nreverse live-dictate--outbox))) (peak 0))
(setq live-dictate--outbox nil) (while (< i n)
(live-dictate--dbg "flush: %d payload(s), first is %s" (let ((v (aref chunk i)))
(length queue) (when (> v 127) (setq v (- 256 v)))
(alist-get 'type (car queue))) (when (> v peak) (setq peak v)))
(catch 'dead (setq i (+ i 2)))
(dolist (payload queue) peak))
(condition-case err
(websocket-send-text live-dictate--ws (json-encode payload)) (defun live-dictate--drop-before (sample-pos)
(error "Discard buffered audio before SAMPLE-POS."
(message "live-dictate: send failed: %s" err) (let ((pos (max sample-pos live-dictate--buf-start)))
(live-dictate--cleanup) (when (and (> pos live-dictate--buf-start)
(throw 'dead nil)))))) (buffer-live-p (get-buffer live-dictate--pcm-buffer)))
(live-dictate--dbg "flush withheld: %d queued, ws=%s openp=%s status=%s" (with-current-buffer live-dictate--pcm-buffer
(length live-dictate--outbox) (let ((bytes (* live-dictate--bytes-per-sample
(and live-dictate--ws t) (- pos live-dictate--buf-start))))
(and live-dictate--ws (websocket-openp live-dictate--ws)) (delete-region (point-min)
(and live-dictate--ws (min (point-max) (+ (point-min) bytes)))))
(process-status (websocket-conn live-dictate--ws))))))) (setq live-dictate--buf-start pos))))
(defun live-dictate--slice (from to)
"Return raw PCM bytes buffered between sample positions FROM and TO."
(let ((offset (* live-dictate--bytes-per-sample (- from live-dictate--buf-start)))
(len (* live-dictate--bytes-per-sample (- to from))))
(with-current-buffer live-dictate--pcm-buffer
(let ((beg (+ (point-min) offset)))
(buffer-substring-no-properties beg (min (point-max) (+ beg len)))))))
(defun live-dictate--filter (_proc chunk)
"Buffer CHUNK, run the VAD, and flush complete utterances."
(when (and live-dictate--active (> (length chunk) 1))
(let ((peak (live-dictate--peak chunk))
(nsamples (/ (length chunk) live-dictate--bytes-per-sample)))
(with-current-buffer (get-buffer-create live-dictate--pcm-buffer)
(set-buffer-multibyte nil)
(goto-char (point-max))
(insert chunk))
(setq live-dictate--total (+ live-dictate--total nsamples)
live-dictate--max-peak (max live-dictate--max-peak peak))
;; all-zero input means the OS is muting us, not that the room is quiet
(when (and (not live-dictate--warned-silence)
(zerop live-dictate--max-peak)
(>= live-dictate--total (live-dictate--samples 4)))
(setq live-dictate--warned-silence t)
(message "live-dictate: microphone is delivering silence -- check \
the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'"))
(if (> peak live-dictate-silence-threshold)
(progn
(unless live-dictate--speech-start
(setq live-dictate--speech-start
(max live-dictate--buf-start
(- live-dictate--total nsamples
(live-dictate--samples live-dictate-preroll)))))
(setq live-dictate--silence 0))
(when live-dictate--speech-start
(setq live-dictate--silence (+ live-dictate--silence nsamples))))
(unless live-dictate--speech-start
(live-dictate--drop-before
(- live-dictate--total (live-dictate--samples live-dictate-preroll))))
(live-dictate--maybe-flush))))
(defun live-dictate--maybe-flush (&optional force)
"Send the current utterance if it looks finished, or if FORCE."
(when live-dictate--speech-start
(let ((length (- live-dictate--total live-dictate--speech-start)))
(when (or force
(and (>= live-dictate--silence
(live-dictate--samples live-dictate-silence-duration))
(>= length (live-dictate--samples live-dictate-min-utterance)))
(>= length (live-dictate--samples live-dictate-max-utterance)))
(live-dictate--flush-utterance)))))
(defun live-dictate--flush-utterance ()
"Cut the current utterance out of the buffer and queue it for transcription."
(let* ((start live-dictate--speech-start)
(end live-dictate--total)
(pcm (live-dictate--slice start end)))
(setq live-dictate--speech-start nil
live-dictate--silence 0)
(live-dictate--drop-before end)
(if (>= (length pcm) (* live-dictate--bytes-per-sample
(live-dictate--samples live-dictate-min-utterance)))
(progn
(live-dictate--dbg "flush: %.2fs (%d bytes)"
(/ (float (- end start)) live-dictate--sample-rate)
(length pcm))
(setq live-dictate--queue
(nconc live-dictate--queue (list (live-dictate--wav pcm))))
(live-dictate--pump))
(live-dictate--dbg "discarding short utterance (%d bytes)" (length pcm)))))
;;; WAV encoding
(defun live-dictate--le16 (n)
(unibyte-string (logand n 255) (logand (ash n -8) 255)))
(defun live-dictate--le32 (n)
(unibyte-string (logand n 255)
(logand (ash n -8) 255)
(logand (ash n -16) 255)
(logand (ash n -24) 255)))
(defun live-dictate--wav (pcm)
"Wrap raw PCM16 mono audio PCM in a WAV container."
(let ((n (length pcm)))
;; every literal and helper here is ASCII/unibyte, so `concat' stays unibyte
(concat "RIFF" (live-dictate--le32 (+ 36 n)) "WAVE"
"fmt " (live-dictate--le32 16)
(live-dictate--le16 1) ; PCM
(live-dictate--le16 1) ; mono
(live-dictate--le32 live-dictate--sample-rate)
(live-dictate--le32 (* live-dictate--sample-rate
live-dictate--bytes-per-sample))
(live-dictate--le16 live-dictate--bytes-per-sample)
(live-dictate--le16 16) ; bits
"data" (live-dictate--le32 n)
pcm)))
;;; Transcription
(defun live-dictate--pump ()
"Start the next queued transcription, if any."
(unless live-dictate--busy
(if live-dictate--queue
(let ((wav (pop live-dictate--queue)))
(setq live-dictate--busy t)
(live-dictate--transcribe wav))
(unless live-dictate--active
(live-dictate--cleanup)))))
(defun live-dictate--transcribe (wav)
"Post WAV to the server and insert the transcript when it comes back."
(let ((file (make-temp-file "live-dictate-" nil ".wav"))
(out (generate-new-buffer " *live-dictate-curl*"))
(url (concat (string-trim-right live-dictate-server-url "/") "/inference")))
(with-temp-file file
(set-buffer-multibyte nil)
(insert wav))
(live-dictate--dbg "POST %s (%d bytes)" url (length wav))
(make-process
:name "live-dictate-curl"
:buffer out
:noquery t
:coding 'binary
:command (append (list "curl" "-sS" "-m" "180")
(list "-F" (concat "file=@" file)
"-F" "response_format=json"
"-F" (concat "language=" live-dictate-language)
"-F" "temperature=0.0")
(unless (string-empty-p live-dictate-prompt)
(list "-F" (concat "prompt=" live-dictate-prompt)))
(list url))
:sentinel (lambda (proc event)
(when (memq (process-status proc) '(exit signal))
(live-dictate--transcribed out file event))))))
(defun live-dictate--transcribed (out file event)
"Handle a finished transcription: insert its text, then continue."
(unwind-protect
(let ((body (with-current-buffer out
(decode-coding-string
(buffer-substring-no-properties (point-min) (point-max))
'utf-8))))
(if (string-match-p "finished" event)
(condition-case _
(let ((text (alist-get 'text (json-read-from-string body))))
(when (stringp text)
(live-dictate--dbg "-> %S" text)
(live-dictate--insert text)))
(error
(message "live-dictate: unparsable reply: %s" (string-trim body))))
(message "live-dictate: transcription failed (%s): %s"
(string-trim event) (string-trim body))))
(when (buffer-live-p out) (kill-buffer out))
(ignore-errors (delete-file file))
(setq live-dictate--busy nil)
(live-dictate--pump)))
;;; Insertion
(defun live-dictate--insert (text)
"Insert TEXT at the dictation marker in the target buffer."
(let ((text (string-trim text)))
(when (and (not (string-empty-p text))
(buffer-live-p live-dictate--target-buffer)
(markerp live-dictate--marker)
(marker-position live-dictate--marker))
(with-current-buffer live-dictate--target-buffer
(let ((inhibit-read-only t))
(save-excursion
(goto-char (marker-position live-dictate--marker))
;; keep utterances (and text already typed) separated
(unless (or (bobp) (memq (char-before) '(?\s ?\n ?\t ?\()))
(insert " "))
(insert text)
(set-marker live-dictate--marker (point)))
(when (and live-dictate-follow-cursor
(eq (current-buffer) (window-buffer (selected-window))))
(goto-char (marker-position live-dictate--marker))))))))
;;; Mode line
(defun live-dictate--mode-line (show) (defun live-dictate--mode-line (show)
(when show (when show
@@ -139,202 +348,99 @@
(remove (list t live-dictate--mode-line-indicator) global-mode-string)) (remove (list t live-dictate--mode-line-indicator) global-mode-string))
(force-mode-line-update t)) (force-mode-line-update t))
(defun live-dictate--clear-interim () ;;; Lifecycle
"Drop the interim region markers without touching text."
(setq live-dictate--interim-start nil
live-dictate--interim-end nil))
(defun live-dictate--insert (text) (defvar live-dictate--cleanup-timer nil)
"Insert TEXT into the target buffer at the marker, replacing any interim text."
(when (buffer-live-p live-dictate--target-buffer)
(with-current-buffer live-dictate--target-buffer
(let (inhibit-read-only)
(save-excursion
(cond
((and live-dictate--interim-start live-dictate--interim-end)
;; deltas carry the full interim text: replace the whole region
(delete-region live-dictate--interim-start live-dictate--interim-end)
(goto-char live-dictate--interim-start)
(insert text)
(set-marker live-dictate--interim-end (point)))
(t
(goto-char live-dictate--marker)
(setq live-dictate--interim-start (point-marker))
(insert text)
(setq live-dictate--interim-end (point-marker)))))
(when live-dictate-follow-cursor
(goto-char (marker-position live-dictate--interim-end)))))))
(defun live-dictate--handle-message (payload)
(let* ((msg (condition-case _ (json-read-from-string payload)
(error nil)))
(type (and msg (alist-get 'type msg))))
(live-dictate--dbg "<- %s%s" (or type "(unparsed)")
(let ((d (alist-get 'delta msg)))
(if (stringp d) (concat " | " d) "")))
(pcase type
("conversation.item.input_audio_transcription.delta"
(let ((delta (alist-get 'delta msg)))
(when (and (stringp delta) (not (equal delta "")))
(live-dictate--insert delta))))
("conversation.item.input_audio_transcription.completed"
(let ((transcript (alist-get 'transcript msg)))
(when (stringp transcript)
;; replace the interim preview with the final transcript
(live-dictate--insert (string-trim transcript))
(with-current-buffer live-dictate--target-buffer
(let (inhibit-read-only)
(save-excursion
(goto-char (marker-position live-dictate--interim-end))
(insert " ")
(set-marker live-dictate--interim-end (point))))
(set-marker live-dictate--marker (marker-position live-dictate--interim-end))
(live-dictate--clear-interim)))))
("error"
(message "live-dictate server error: %s"
(or (alist-get 'message (alist-get 'error msg)) payload)))
(_ nil))))
(defun live-dictate--on-message (_ws frame)
(when (eq (websocket-frame-opcode frame) 'text)
(live-dictate--handle-message (websocket-frame-payload frame))))
(defun live-dictate--audio-filter (_proc chunk)
"Queue raw PCM16 CHUNK from FFmpeg for sending."
(setq live-dictate--chunk-count (1+ live-dictate--chunk-count)
live-dictate--chunk-bytes (+ live-dictate--chunk-bytes (length chunk)))
(when (zerop (mod live-dictate--chunk-count 100))
(live-dictate--dbg "audio: %d chunks, %d bytes so far"
live-dictate--chunk-count live-dictate--chunk-bytes))
(live-dictate--queue-send
`((type . "input_audio_buffer.append")
(audio . ,(base64-encode-string chunk 'nolinebreaks)))))
(defun live-dictate--on-open (_ws)
(live-dictate--dbg "ws open")
(condition-case err
(progn
(live-dictate--queue-send
`((type . "session.update")
(session . ((model . ,live-dictate-model)))))
;; start flush timer (sending must not happen inside filter callbacks)
(when live-dictate--flush-timer (cancel-timer live-dictate--flush-timer))
(setq live-dictate--flush-timer
(run-with-timer live-dictate-flush-interval
live-dictate-flush-interval
#'live-dictate--flush-outbox))
(unless live-dictate--ffmpeg
(setq live-dictate--ffmpeg
(make-process
:name "live-dictate-ffmpeg"
:command `("ffmpeg" "-nostdin" "-hide_banner" "-loglevel" "error"
"-f" ,live-dictate-ffmpeg-input-format
"-i" ,live-dictate-ffmpeg-input-device
"-ac" "1" "-ar" "16000" "-f" "s16le" "pipe:1")
:connection-type 'pipe
:filter #'live-dictate--audio-filter
:stderr (get-buffer-create live-dictate--stderr-buffer)
:sentinel (lambda (_proc event)
(when (and live-dictate--active
(not (string-prefix-p "finished" event)))
(message "live-dictate: FFmpeg stopped (%s)"
(string-trim event)))))))
(live-dictate--dbg "on-open done"))
(error
(message "live-dictate: ERROR in on-open (was being swallowed): %S" err))))
(defun live-dictate--on-close (_ws)
(live-dictate--dbg "ws closed")
(setq live-dictate--ws nil))
(defun live-dictate--on-error (_ws _type err)
(message "live-dictate WebSocket error: %s" err)
(live-dictate--cleanup))
(defun live-dictate--cleanup () (defun live-dictate--cleanup ()
"Tear down all processes and state." "Tear down all processes and state."
(setq live-dictate--active nil) ; keep the ffmpeg sentinel quiet (setq live-dictate--active nil
(when live-dictate--stop-timer live-dictate--queue nil
(cancel-timer live-dictate--stop-timer) live-dictate--busy nil
(setq live-dictate--stop-timer nil)) live-dictate--speech-start nil
(when live-dictate--flush-timer live-dictate--silence 0
(cancel-timer live-dictate--flush-timer) live-dictate--buf-start 0
(setq live-dictate--flush-timer nil)) live-dictate--total 0
live-dictate--max-peak 0
live-dictate--warned-silence nil)
(when (process-live-p live-dictate--ffmpeg) (when (process-live-p live-dictate--ffmpeg)
(delete-process live-dictate--ffmpeg)) (delete-process live-dictate--ffmpeg))
(setq live-dictate--ffmpeg nil) (setq live-dictate--ffmpeg nil)
(when (and live-dictate--ws (websocket-openp live-dictate--ws)) (when (buffer-live-p (get-buffer live-dictate--pcm-buffer))
(websocket-close live-dictate--ws)) (kill-buffer live-dictate--pcm-buffer))
(setq live-dictate--ws nil
live-dictate--outbox nil)
(live-dictate--clear-interim)
(when (markerp live-dictate--marker) (when (markerp live-dictate--marker)
(set-marker live-dictate--marker nil)) (set-marker live-dictate--marker nil))
(setq live-dictate--marker nil (setq live-dictate--marker nil
live-dictate--target-buffer nil) live-dictate--target-buffer nil)
(live-dictate--mode-line nil)) (live-dictate--mode-line nil))
(defun live-dictate--load-model () (defun live-dictate--start-capture ()
"Ask the server to load the transcription model, like the official clients do." (setq live-dictate--ffmpeg
(condition-case err (make-process
(let ((url-request-method "POST") :name "live-dictate-ffmpeg"
(url-request-extra-headers '(("Content-Type" . "application/json"))) :command `("ffmpeg" "-nostdin" "-hide_banner" "-loglevel" "error"
(url-request-data (json-encode `((model_name . ,live-dictate-model))))) "-f" ,live-dictate-ffmpeg-input-format
(with-timeout (20 (message "live-dictate: /load preflight timed out, continuing")) "-i" ,live-dictate-ffmpeg-input-device
(url-retrieve-synchronously "-ac" "1" "-ar" ,(number-to-string live-dictate--sample-rate)
(concat live-dictate-server-url "/api/v1/load") "-f" "s16le" "pipe:1")
nil nil 20) :connection-type 'pipe
(live-dictate--dbg "model load preflight done"))) :coding 'binary
(error (message "live-dictate: /load preflight failed: %s (continuing)" err)))) :noquery t
:filter #'live-dictate--filter
:stderr (get-buffer-create live-dictate--stderr-buffer)
:sentinel (lambda (_proc event)
(when (and live-dictate--active
(not (string-prefix-p "finished" event)))
(message "live-dictate: FFmpeg stopped (%s)"
(string-trim event))
(live-dictate--stop))))))
(defun live-dictate--stop () (defun live-dictate--stop ()
"Stop dictation: commit remaining audio, then close." "Stop dictation: send whatever is left, then clean up when it is done."
(interactive)
(setq live-dictate--active nil) ; before killing ffmpeg, so the sentinel stays quiet (setq live-dictate--active nil) ; before killing ffmpeg, so the sentinel stays quiet
(when (process-live-p live-dictate--ffmpeg) (when (process-live-p live-dictate--ffmpeg)
(delete-process live-dictate--ffmpeg)) (delete-process live-dictate--ffmpeg))
(setq live-dictate--ffmpeg nil) (setq live-dictate--ffmpeg nil)
(live-dictate--queue-send '((type . "input_audio_buffer.commit"))) (live-dictate--maybe-flush t)
(live-dictate--flush-outbox) (if (or live-dictate--busy live-dictate--queue)
(setq live-dictate--stop-timer (message "live-dictate: finishing transcription...")
(run-with-timer live-dictate-stop-delay nil (live-dictate--cleanup)
(lambda () (message "live-dictate: stopped")))
(live-dictate--cleanup)
(message "live-dictate: stopped")))))
;;;###autoload ;;;###autoload
(defun live-dictate () (defun live-dictate ()
"Toggle live dictation in the current buffer. "Toggle live dictation in the current buffer.
While active, speech is transcribed continuously via Lemonade's realtime While active, speech is transcribed by a whisper.cpp server and the text is
endpoint and text is inserted at point as it arrives. Run again to stop." inserted at point as each utterance completes. Run again to stop."
(interactive) (interactive)
(if live-dictate--active (if live-dictate--active
(live-dictate--stop) (live-dictate--stop)
(unless (require 'websocket nil t)
(user-error "live-dictate needs the `websocket' package (run `doom sync')"))
(when live-dictate-debug
(setq websocket-debug t ; frames -> *websocket ...debug* buffer
websocket-callback-debug-on-error t)) ; surface swallowed callback errors
(unless (and live-dictate-ffmpeg-input-format live-dictate-ffmpeg-input-device) (unless (and live-dictate-ffmpeg-input-format live-dictate-ffmpeg-input-device)
(user-error "live-dictate: set live-dictate-ffmpeg-input-format/-device")) (user-error "live-dictate: set live-dictate-ffmpeg-input-format/-device"))
(unless (executable-find "ffmpeg") (unless (executable-find "ffmpeg")
(user-error "live-dictate: FFmpeg not found in PATH")) (user-error "live-dictate: FFmpeg not found in PATH"))
(unless (executable-find "curl")
(user-error "live-dictate: curl not found in PATH"))
(when buffer-read-only (when buffer-read-only
(user-error "Buffer is read-only, can't dictate here")) (user-error "Buffer is read-only, can't dictate here"))
(setq live-dictate--active t (setq live-dictate--active t
live-dictate--target-buffer (current-buffer) live-dictate--target-buffer (current-buffer)
live-dictate--marker (copy-marker (point)) live-dictate--marker (copy-marker (point))
live-dictate--chunk-count 0 live-dictate--queue nil
live-dictate--chunk-bytes 0 live-dictate--busy nil
live-dictate--outbox nil) live-dictate--speech-start nil
live-dictate--silence 0
live-dictate--buf-start 0
live-dictate--total 0
live-dictate--max-peak 0
live-dictate--warned-silence nil)
(with-current-buffer (get-buffer-create live-dictate--pcm-buffer)
(erase-buffer)
(set-buffer-multibyte nil))
(live-dictate--mode-line t) (live-dictate--mode-line t)
(live-dictate--load-model) (live-dictate--start-capture)
(setq live-dictate--ws (message "live-dictate: listening (%s)" live-dictate-server-url)))
(websocket-open (live-dictate--ws-url)
:on-open #'live-dictate--on-open
:on-message #'live-dictate--on-message
:on-close #'live-dictate--on-close
:on-error #'live-dictate--on-error))
(message "live-dictate: connecting to %s..." live-dictate-server-url)))
(provide 'live-dictate) (provide 'live-dictate)
;;; live-dictate.el ends here ;;; live-dictate.el ends here
+5 -3
View File
@@ -31,9 +31,11 @@
(package! mastodon) (package! mastodon)
(package! pi-coding-agent (package! pi-coding-agent
:recipe (:host github :repo "dnouri/pi-coding-agent")) :recipe (:host github :repo "dnouri/pi-coding-agent"))
;; speech-to-text: `whisper' is used by config-linux.el, and `websocket' is a ;; speech-to-text: `whisper' is used by config-linux.el (and by
;; hard dependency of lisp/live-dictate.el -- it is what makes streaming ;; config-mac.el against a local whisper.cpp server). lisp/live-dictate.el
;; dictation possible. ;; no longer needs `websocket': it POSTs utterances to whisper.cpp's
;; /inference endpoint, so `websocket' is only kept because whisper.el pulls
;; it in transitively.
(package! whisper (package! whisper
:recipe (:host github :repo "natrys/whisper.el")) :recipe (:host github :repo "natrys/whisper.el"))
(package! websocket) (package! websocket)