Files
dotemacs/lisp/live-dictate.el
T
Willem van den Ende 0b267d04c5 fix(linux): port startup and dictation fixes from the private working copy
Fixes that only existed on the Linux machine (unpushed commit and
uncommitted work there), without which a fresh clone breaks on Linux:

- config.el resolved coe-xx/mostalive/qwan against ~/.doom.d, but the
  config lives at ~/.config/doom, so (require 'coe-xx) aborted startup
  with "Cannot open load file". Resolve them against doom-user-dir.

- lisp/live-dictate.el only spoke whisper.cpp's POST /inference, which
  Lemonade (the Linux transcription server) does not serve -- every
  utterance came back as a not_found object and was dropped silently.
  It now auto-detects between /inference and the OpenAI-compatible
  /v1/audio/transcriptions endpoint, remembers which one answered,
  reports unusable replies, reads the VAD peak from the high byte of
  little-endian PCM16 (the low byte made silence look like speech),
  prints the peak level on stop, and gains M-x live-dictate-reload,
  wired into doom-after-reload-hook on both OSes.

- config.el hardcoded the macOS org-directory (~/MyDocuments, inside
  iCloud). Where the notes live is now owned by config-linux.el
  (~/Documents) and config-mac.el (~/MyDocuments), and the OS leaf
  loads before org and org-roam load below instead of after them.
  Blog export targets stay in the OS files, where they belong.

- mostalive/my-org-roam.el: compute org-agenda-files by listing the
  daily/ directory instead of org-roam-db-query at load time, and
  defer the full org-roam DB sync to idle time. Doom advises the first
  DB query of a session into a full org-roam-db-sync, which SHA1s all
  ~8.4k notes before the first frame is drawn (blank-screen startup).

Also correct the ~/.doom.d paths in AGENTS.md, the export-test header
and README that the sanitization base predated the fix for.
2026-11-27 17:57:37 +01:00

743 lines
31 KiB
EmacsLisp

;;; live-dictate.el --- Live dictation via a whisper.cpp server -*- lexical-binding: t; -*-
;; Author: Willem (generated with pi)
;; Version: 2.0.0
;; Package-Requires: ((emacs "27.1"))
;;; Commentary:
;; Live speech-to-text dictation against a local transcription server.
;;
;; `live-dictate' toggles dictation in the current buffer: microphone audio
;; is captured with FFmpeg as 16 kHz mono PCM16, cut into utterances on the
;; client by a small energy-based VAD, and each utterance is posted to the
;; server as a WAV file. Transcripts are inserted at point, in order.
;;
;; Two HTTP dialects are supported, because the two machines serve
;; different ones (see `live-dictate-server-api'):
;; `inference' whisper.cpp's native POST /inference
;; `openai' POST /v1/audio/transcriptions (Lemonade, LocalAI, ...)
;; With the default `auto', the dialect that fits the OS is tried first, the
;; other one is tried if the reply carries no `text' field, and whichever
;; worked is remembered. Either way a reply we cannot use is reported in
;; the echo area -- a lost transcript is never silent.
;;
;; History: version 1 spoke the OpenAI realtime protocol over a WebSocket
;; (ws://host/v1/realtime). Only Lemonade-style servers implement that;
;; whisper.cpp answers 404 for it, hence the rewrite. Version 2 posted only
;; to /inference, which Lemonade does not serve, so on Linux every utterance
;; came back as a `not_found' object and was dropped without a word.
;;; Code:
(require 'json)
(require 'cl-lib)
(require 'seq)
(require 'subr-x)
(defgroup live-dictate nil
"Live dictation via a whisper.cpp server."
:group 'external)
(defcustom live-dictate-server-url "http://localhost:13305"
"Base URL of the transcription server."
:type 'string
:group 'live-dictate)
(defcustom live-dictate-server-api 'auto
"Which HTTP API `live-dictate-server-url' speaks.
`inference' is whisper.cpp's native POST /inference, the endpoint
`whisper-server' serves. `openai' is the OpenAI-compatible POST
/v1/audio/transcriptions, served by Lemonade, LocalAI and friends.
`auto' tries the style that suits this OS, falls back to the other one if
the reply carries no `text', and remembers which one answered, so the
wrong guess costs one request per session at most."
:type '(choice (const :tag "Detect automatically" auto)
(const :tag "whisper.cpp /inference" inference)
(const :tag "OpenAI /v1/audio/transcriptions" openai))
:group 'live-dictate)
(defcustom live-dictate-openai-model "whisper-1"
"Model name sent to an OpenAI-compatible server.
Servers that route to a single loaded model ignore it; Lemonade wants the
exact id it serves (e.g. \"Whisper-Large-v3-Turbo\")."
:type 'string
:group 'live-dictate)
(defcustom live-dictate-language "en"
"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
:group 'live-dictate)
(defcustom live-dictate-follow-cursor t
"Whether point follows the incoming transcription."
:type 'boolean
:group 'live-dictate)
(defcustom live-dictate-silence-threshold 2
"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
:group 'live-dictate)
(defcustom live-dictate-min-utterance 0.3
"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
:group 'live-dictate)
(defcustom live-dictate-ffmpeg-input-format
(pcase system-type
('gnu/linux (if (or (executable-find "pulseaudio") (executable-find "pipewire-pulse"))
"pulse" "alsa"))
('darwin "avfoundation")
('windows-nt "dshow")
(_ nil))
"Value passed to FFmpeg's `-f' flag to record audio."
:type '(choice string (const nil))
:group 'live-dictate)
(defcustom live-dictate-ffmpeg-input-device
(pcase system-type
('gnu/linux "default")
(_ nil))
"Value passed to FFmpeg's `-i' flag to record audio.
On darwin, nil (the default) means: pick the device by name, using
`live-dictate-device-name-pattern'. A string is either a literal FFmpeg
device (e.g. \":2\") or a regexp matched against the device names."
:type '(choice string (const nil))
:group 'live-dictate)
(defcustom live-dictate-device-name-pattern
(pcase system-type
('darwin "MacBook.*Microphone\\|Built-in Microphone")
(_ nil))
"Regexp matching the input device to prefer when the device is not pinned.
Only used on darwin, where avfoundation indices shift as devices come and go."
:type '(choice regexp (const nil))
:group 'live-dictate)
(defcustom live-dictate-ignore-device-name
"Teams Audio\\|Loopback\\|BlackHole\\|Aggregate\\|Soundflower"
"Regexp matching virtual/loopback devices that never carry microphone audio."
:type '(choice regexp (const nil))
:group 'live-dictate)
(defcustom live-dictate-debug nil
"Verbose logging to *Messages*."
:type 'boolean
:group 'live-dictate)
(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--active nil)
(defvar live-dictate--target-buffer nil)
(defvar live-dictate--marker nil)
;; Audio bookkeeping: the work buffer holds PCM from
;; `live-dictate--buf-start' up to `live-dictate--total' (both in samples).
(defvar live-dictate--buf-start 0)
(defvar live-dictate--total 0)
(defvar live-dictate--device nil)
(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--api nil
"API style (`inference' or `openai') that last produced a transcript.")
(defvar live-dictate--mode-line-indicator
(propertize " 🎙" 'face 'font-lock-warning-face))
(defun live-dictate--dbg (fmt &rest args)
(when live-dictate-debug
(message "live-dictate: %s" (apply #'format fmt args))))
(defun live-dictate--samples (seconds)
(round (* seconds live-dictate--sample-rate)))
;;; Audio capture
(defun live-dictate--avfoundation-audio-devices ()
"Return an alist of (INDEX . NAME) for AVFoundation audio inputs."
(with-temp-buffer
(call-process "ffmpeg" nil t nil "-hide_banner"
"-f" "avfoundation" "-list_devices" "true" "-i" "")
(goto-char (point-min))
(when (re-search-forward "AVFoundation audio devices:" nil t)
(let (devices)
(while (re-search-forward "\\[\\([0-9]+\\)\\] \\(.+?\\)[ \t]*$" nil t)
(push (cons (string-to-number (match-string 1)) (match-string 2))
devices))
(nreverse devices)))))
(defun live-dictate--resolve-input-device ()
"Work out the FFmpeg `-i' value for the configured input device."
(if (not (eq system-type 'darwin))
live-dictate-ffmpeg-input-device
(let ((want live-dictate-ffmpeg-input-device))
(if (and (stringp want) (string-match-p "\\`:[0-9]+\\'" want))
want ; explicitly pinned index
(let* ((devices (live-dictate--avfoundation-audio-devices))
(virtual-p
(lambda (dev)
(and live-dictate-ignore-device-name
(string-match-p live-dictate-ignore-device-name (cdr dev)))))
(named (and (stringp want)
(seq-find (lambda (dev) (string-match-p want (cdr dev)))
devices)))
(preferred (and live-dictate-device-name-pattern
(seq-find (lambda (dev)
(and (string-match-p
live-dictate-device-name-pattern
(cdr dev))
(not (funcall virtual-p dev))))
devices)))
(fallback (seq-find (lambda (dev) (not (funcall virtual-p dev))) devices))
(chosen (or named preferred fallback (car devices))))
(cond
((null chosen)
(live-dictate--dbg "no avfoundation audio devices found")
nil)
(t
(live-dictate--dbg "audio device %d: %s" (car chosen) (cdr chosen))
(concat ":" (number-to-string (car chosen))))))))))
(defun live-dictate--peak (chunk)
"Peak amplitude of raw PCM16 CHUNK, measured on the high byte.
The capture is little-endian, so the high byte is the odd one. Reading
the low byte instead (as an earlier version did) makes the dither of a
silent microphone look like speech, and the VAD never sees silence."
(let ((i 1)
(n (length chunk))
(peak 0))
(while (< i n)
(let* ((v (aref chunk i))
(v (abs (if (> v 127) (- v 256) v))))
(when (> v peak) (setq peak v)))
(setq i (+ i 2)))
peak))
(defun live-dictate--drop-before (sample-pos)
"Discard buffered audio before SAMPLE-POS."
(let ((pos (max sample-pos live-dictate--buf-start)))
(when (and (> pos live-dictate--buf-start)
(buffer-live-p (get-buffer live-dictate--pcm-buffer)))
(with-current-buffer live-dictate--pcm-buffer
(let ((bytes (* live-dictate--bytes-per-sample
(- pos live-dictate--buf-start))))
(delete-region (point-min)
(min (point-max) (+ (point-min) bytes)))))
(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--endpoint (api)
"Return the URL for API style API (`inference' or `openai')."
(let ((base (string-trim-right live-dictate-server-url "/")))
(pcase api
('inference (concat base "/inference"))
('openai (concat base "/v1/audio/transcriptions")))))
(defun live-dictate--api-candidates ()
"Return the API styles to try, most likely first.
The style that worked before is tried first; after that, `inference' on
darwin (whisper.cpp) and `openai' elsewhere (Lemonade et al.)."
(if (memq live-dictate-server-api '(inference openai))
(list live-dictate-server-api)
(let ((first (or live-dictate--api
(if (eq system-type 'darwin) 'inference 'openai))))
(if (eq first 'inference)
(list 'inference 'openai)
(list 'openai 'inference)))))
(defun live-dictate--curl-args (api file)
"Return the curl command line posting FILE to the API style API."
(append
(list "curl" "-sS" "-m" "180")
(list "-F" (concat "file=@" file)
"-F" "response_format=json"
"-F" (concat "language=" live-dictate-language))
(pcase api
('inference (list "-F" "temperature=0.0"))
('openai (list "-F" (concat "model=" live-dictate-openai-model))))
(unless (string-empty-p live-dictate-prompt)
(list "-F" (concat "prompt=" live-dictate-prompt)))
(list (live-dictate--endpoint api))))
(defun live-dictate--probe (api)
"Probe the API style API.
Return (STATUS . OKP) where STATUS is the HTTP status the server replies
with, and OKP is non-nil when the reply actually carried a `text' field --
so a 200 that is really an error is not mistaken for success."
(let* ((wav (make-temp-file "live-dictate-probe-" nil ".wav"))
(out (make-temp-file "live-dictate-probe-out-"))
(status nil))
(unwind-protect
(progn
(with-temp-file wav
(set-buffer-multibyte nil)
(insert (live-dictate--wav
(make-string (* live-dictate--bytes-per-sample 1600) 0))))
(setq status
(string-trim
(with-output-to-string
(apply #'call-process "curl" nil standard-output nil
(append
(cdr (butlast (live-dictate--curl-args api wav) 1))
(list "-o" out "-w" "%{http_code}"
(live-dictate--endpoint api)))))))
(unless (string-match-p "\\`[0-9][0-9][0-9]\\'" status)
(setq status nil))
(cons status
(and (file-exists-p out)
(with-temp-buffer
(insert-file-contents out)
(goto-char (point-min))
(search-forward "\"text\"" nil t)))))
(ignore-errors (delete-file wav))
(ignore-errors (delete-file out)))))
(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")))
(with-temp-file file
(set-buffer-multibyte nil)
(insert wav))
(live-dictate--post file (live-dictate--api-candidates))))
(defun live-dictate--post (file apis)
"POST FILE to the server, trying the API styles in APIS in order."
(let ((api (car apis))
(out (generate-new-buffer " *live-dictate-curl*")))
(live-dictate--dbg "POST %s (%s)" (live-dictate--endpoint api) api)
(make-process
:name "live-dictate-curl"
:buffer out
:noquery t
:coding 'binary
:command (live-dictate--curl-args api file)
:sentinel (lambda (proc event)
(when (memq (process-status proc) '(exit signal))
(live-dictate--transcribed out file apis event))))))
(defun live-dictate--reply (out event)
"Return (TEXT . PROBLEM) parsed from curl's OUT and EVENT.
TEXT is the transcript when the reply is usable; otherwise it is nil and
PROBLEM says what came back, so a failure is reported instead of ignored."
(let ((body (string-trim
(decode-coding-string
(with-current-buffer out
(buffer-substring-no-properties (point-min) (point-max)))
'utf-8))))
(if (not (string-match-p "finished" event))
(cons nil (format "%s %s" (string-trim event) body))
(condition-case nil
(let* ((json (json-read-from-string body))
(text (alist-get 'text json))
(err (alist-get 'error json)))
(cond
((stringp text) (cons text nil))
(err (cons nil (or (alist-get 'message err) body)))
(t (cons nil (format "no `text' in reply: %s" body)))))
(error (cons nil (format "unparsable reply: %s" body)))))))
(defun live-dictate--transcribed (out file apis event)
"Handle a finished transcription of FILE; APIS are the styles left to try."
(let* ((api (car apis))
(reply (live-dictate--reply out event))
(text (car reply))
(problem (cdr reply)))
(when (buffer-live-p out) (kill-buffer out))
(cond
((stringp text)
(unless (eq api live-dictate--api)
(setq live-dictate--api api)
(message "live-dictate: server speaks %s (%s)"
api (live-dictate--endpoint api)))
(live-dictate--dbg "-> %S" text)
(live-dictate--insert text)
(live-dictate--finish file))
((cdr apis)
;; The reply was well formed but had no text -- wrong endpoint, most
;; likely. Try the other API style before giving up.
(live-dictate--dbg "%s failed (%s), trying %s" api problem (cadr apis))
(live-dictate--post file (cdr apis)))
(t
(message "live-dictate: transcription failed via %s: %s"
(live-dictate--endpoint api) problem)
(live-dictate--finish file)))))
(defun live-dictate--finish (file)
"Clean up after FILE has been transcribed, and start the next request."
(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)
(when show
(cl-pushnew (list t live-dictate--mode-line-indicator)
global-mode-string :test #'equal))
(setq global-mode-string
(remove (list t live-dictate--mode-line-indicator) global-mode-string))
(force-mode-line-update t))
;;; Lifecycle
(defvar live-dictate--cleanup-timer nil)
(defun live-dictate--cleanup ()
"Tear down all processes and state."
(setq live-dictate--active nil
live-dictate--queue nil
live-dictate--busy 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)
(when (process-live-p live-dictate--ffmpeg)
(delete-process live-dictate--ffmpeg))
(setq live-dictate--ffmpeg nil)
(when (buffer-live-p (get-buffer live-dictate--pcm-buffer))
(kill-buffer live-dictate--pcm-buffer))
(when (markerp live-dictate--marker)
(set-marker live-dictate--marker nil))
(setq live-dictate--marker nil
live-dictate--target-buffer nil)
(live-dictate--mode-line nil))
(defun live-dictate--start-capture ()
(let ((device (live-dictate--resolve-input-device)))
(unless device
(user-error "live-dictate: no usable audio input device"))
(setq live-dictate--device device
live-dictate--ffmpeg
(make-process
:name "live-dictate-ffmpeg"
:command `("ffmpeg" "-nostdin" "-hide_banner" "-loglevel" "error"
"-f" ,live-dictate-ffmpeg-input-format
"-i" ,device
"-ac" "1" "-ar" ,(number-to-string live-dictate--sample-rate)
"-f" "s16le" "pipe:1")
:connection-type 'pipe
:coding 'binary
: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-reload ()
"Read this library from disk again, picking up edits without a restart.
`require' keeps the first version of a library it loads, so editing this
file has no effect until the feature is dropped and read again. The
`with-eval-after-load' settings in config-linux.el / config-mac.el run
again as part of the load."
(interactive)
(cond
((and (boundp 'live-dictate--active) live-dictate--active)
(user-error "live-dictate: stop dictation before reloading it"))
((and (boundp 'live-dictate--busy) live-dictate--busy)
(user-error "live-dictate: wait for the pending transcription"))
(t
(let ((file (or (locate-library "live-dictate")
(user-error "live-dictate: library not on `load-path'"))))
(when (featurep 'live-dictate)
(unload-feature 'live-dictate t))
(load file nil t)
(message "live-dictate: reloaded from %s" file)))))
(defun live-dictate--stop ()
"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
(when (process-live-p live-dictate--ffmpeg)
(delete-process live-dictate--ffmpeg))
(setq live-dictate--ffmpeg nil)
(live-dictate--maybe-flush t)
(let ((peak live-dictate--max-peak))
(if (or live-dictate--busy live-dictate--queue)
(message "live-dictate: finishing transcription (peak level %d)..." peak)
(live-dictate--cleanup)
(message "live-dictate: stopped (peak level %d)" peak))))
;;;###autoload
(defun live-dictate-stop ()
"Stop live dictation; anything already spoken is still transcribed."
(interactive)
(if live-dictate--active
(live-dictate--stop)
(message "live-dictate: not running")))
(defun live-dictate--measure-peak (device seconds)
"Record SECONDS from DEVICE and return the peak as the VAD measures it.
Returns nil when FFmpeg could not record at all."
(with-temp-buffer
(set-buffer-multibyte nil)
(let ((coding-system-for-read 'binary)
(coding-system-for-write 'binary))
(apply #'call-process "ffmpeg" nil (current-buffer) nil
(list "-nostdin" "-hide_banner" "-loglevel" "error"
"-f" live-dictate-ffmpeg-input-format
"-i" device
"-t" (number-to-string seconds)
"-ac" "1" "-ar" (number-to-string live-dictate--sample-rate)
"-f" "s16le" "pipe:1")))
(let ((pcm (buffer-string)))
(when (> (length pcm) 1)
(live-dictate--peak pcm)))))
;;;###autoload
(defun live-dictate-diagnose ()
"Check the transcription server and the microphone, and say what is wrong."
(interactive)
(let ((devices (and (eq system-type 'darwin)
(live-dictate--avfoundation-audio-devices)))
(device (live-dictate--resolve-input-device)))
(message "live-dictate: server %s" live-dictate-server-url)
(when devices
(message "live-dictate: devices %s"
(mapconcat (lambda (d) (format "[%d] %s" (car d) (cdr d)))
devices ", ")))
(message "live-dictate: selected device %s" device)
;; Which endpoint does the server actually answer?
(let* ((ok (cl-remove-if-not
(lambda (api)
(let* ((probe (live-dictate--probe api))
(status (car probe)))
(message "live-dictate: %-9s %s -> HTTP %s%s"
api (live-dictate--endpoint api)
(or status "no reply")
(if (cdr probe) "" " (no text field)"))
(cdr probe)))
'(inference openai))))
(message "live-dictate: usable endpoint: %s"
(if ok (mapconcat (lambda (a) (format "%s" a)) ok " and ")
"none -- is the server running with a model loaded?"))
(when ok
(setq live-dictate--api (car ok))))
;; Is the microphone delivering anything the VAD would call speech?
(let ((peak (and device (live-dictate--measure-peak device 3))))
(cond
((null peak)
(message "live-dictate: could not record from %s" device))
((zerop peak)
(message (concat "live-dictate: %s delivers digital silence -- grant "
"Microphone access to Emacs in System Settings > "
"Privacy & Security > Microphone (macOS), then retry")
device))
((<= peak live-dictate-silence-threshold)
(message (concat "live-dictate: %s is very quiet (peak %d over 3s, "
"speech needs > %d) -- raise the input level or "
"lower `live-dictate-silence-threshold'")
device peak live-dictate-silence-threshold))
(t
(message "live-dictate: %s is delivering audio (peak %d over 3s, threshold %d)"
device peak live-dictate-silence-threshold))))))
;;;###autoload
(defun live-dictate ()
"Toggle live dictation in the current buffer.
While active, speech is transcribed by a whisper.cpp server and the text is
inserted at point as each utterance completes. Run the same command again
\(or `live-dictate-stop', SPC A d) to stop; the microphone indicator in the
mode line shows when it is listening."
(interactive)
(if live-dictate--active
(live-dictate--stop)
(unless live-dictate-ffmpeg-input-format
(user-error "live-dictate: set live-dictate-ffmpeg-input-format"))
(unless (executable-find "ffmpeg")
(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
(user-error "Buffer is read-only, can't dictate here"))
(setq live-dictate--active t
live-dictate--target-buffer (current-buffer)
live-dictate--marker (copy-marker (point))
live-dictate--queue nil
live-dictate--busy 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--start-capture)
(message "live-dictate: listening (%s via device %s; SPC A d to stop)"
live-dictate-server-url live-dictate--device)))
(provide 'live-dictate)
;;; live-dictate.el ends here