diff --git a/config.el b/config.el index 1659fe8..9a01cdb 100644 --- a/config.el +++ b/config.el @@ -138,6 +138,29 @@ :models '(mtplx-qwen38-27b-optimized-speed)) (set-default gptel-model 'mtplx-qwen38-27b-optimized-speed)) +;; Whisper speech-to-text via Lemonade server (OpenAI-compatible API) +(add-load-path! "lisp") +(autoload #'live-dictate "live-dictate" nil t) + +(use-package! whisper + :commands (whisper-run whisper-file whisper-select-language) + :init + (map! :leader + (:prefix ("A" . "+ai") + :desc "Whisper record/transcribe" "w" #'whisper-run + :desc "Whisper transcribe file" "W" #'whisper-file + :desc "Whisper select language" "l" #'whisper-select-language + :desc "Live dictate (streaming)" "d" #'live-dictate)) + :config + (setopt whisper-install-whispercpp nil ; no whisper.cpp needed, remote API only + whisper-server-mode 'openai ; use OpenAI-compatible transcription API + whisper-openai-api-baseurl "http://localhost:13305/" + whisper-openai-api-key "not-needed" ; Lemonade ignores auth, but whisper.el requires a non-nil key + whisper-openai-model "Whisper-Large-v3-Turbo" + whisper-language "en" + whisper-translate nil ; t would POST to /translations instead + whisper-return-cursor 'end)) + ;; elixir ;; inspiration https://medium.com/@victor.nascimento/elixir-emacs-development-2023-edition-1a6ccc40629 (use-package diff --git a/lisp/live-dictate.el b/lisp/live-dictate.el new file mode 100644 index 0000000..7e4add2 --- /dev/null +++ b/lisp/live-dictate.el @@ -0,0 +1,340 @@ +;;; live-dictate.el --- Live dictation via Lemonade realtime WebSocket -*- lexical-binding: t; -*- + +;; Author: Willem (generated with pi) +;; Version: 1.0.0 +;; Package-Requires: ((emacs "27.1") (websocket "1.13")) +;; URL: https://github.com/lemonade-sdk/lemonade + +;;; Commentary: + +;; Live speech-to-text dictation using Lemonade Server's OpenAI +;; Realtime-compatible WebSocket endpoint (/v1/realtime). +;; +;; `live-dictate' toggles dictation in the current buffer: microphone audio +;; is captured with FFmpeg as 16kHz PCM16, streamed to the server over a +;; WebSocket, and interim/final transcripts are inserted at point as you +;; speak. Finalized utterances replace their interim preview. +;; +;; Concurrency note: websocket.el can desync its frame parser if frames are +;; sent from within its own network process filter (or any process filter). +;; All sends are therefore queued to an outbox and flushed from a timer. + +;;; Code: + +(require 'json) +(require 'cl-lib) + +(defgroup live-dictate nil + "Live dictation via Lemonade's realtime transcription WebSocket." + :group 'external) + +(defcustom live-dictate-server-url "http://localhost:13305" + "Base URL of the Lemonade server (WS upgrade happens on /v1/realtime)." + :type 'string + :group 'live-dictate) + +(defcustom live-dictate-model "Whisper-Large-v3-Turbo" + "Realtime transcription model. Must support `realtime-transcription'." + :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-stop-delay 2.0 + "Seconds to wait after committing the buffer before closing the WebSocket." + :type 'number + :group 'live-dictate) + +(defcustom live-dictate-flush-interval 0.1 + "How often to flush queued audio to the WebSocket, in seconds." + :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." + :type '(choice string (const nil)) + :group 'live-dictate) + +(defcustom live-dictate-debug nil + "Verbose logging to *Messages*." + :type 'boolean + :group 'live-dictate) + +(defvar live-dictate--ws nil) +(defvar live-dictate--ffmpeg 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--marker nil) +(defvar live-dictate--interim-start nil) +(defvar live-dictate--interim-end nil) +(defvar live-dictate--chunk-count 0) +(defvar live-dictate--chunk-bytes 0) +(defvar live-dictate--stderr-buffer " *live-dictate-stderr*") + +(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--ws-url () + (format "ws://%s/v1/realtime?model=%s" + (replace-regexp-in-string "^https?://" "" live-dictate-server-url) + (url-hexify-string live-dictate-model))) + +(defun live-dictate--queue-send (payload) + "Queue JSON-able PAYLOAD for sending. Safe from any context." + (push payload live-dictate--outbox)) + +(defun live-dictate--flush-outbox () + "Send all queued payloads. Runs from a timer, never inside process filters." + (when live-dictate--outbox + (if (and live-dictate--ws (websocket-openp live-dictate--ws)) + (let ((queue (nreverse live-dictate--outbox))) + (setq live-dictate--outbox nil) + (live-dictate--dbg "flush: %d payload(s), first is %s" + (length queue) + (alist-get 'type (car queue))) + (catch 'dead + (dolist (payload queue) + (condition-case err + (websocket-send-text live-dictate--ws (json-encode payload)) + (error + (message "live-dictate: send failed: %s" err) + (live-dictate--cleanup) + (throw 'dead nil)))))) + (live-dictate--dbg "flush withheld: %d queued, ws=%s openp=%s status=%s" + (length live-dictate--outbox) + (and live-dictate--ws t) + (and live-dictate--ws (websocket-openp live-dictate--ws)) + (and live-dictate--ws + (process-status (websocket-conn live-dictate--ws))))))) + +(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)) + +(defun live-dictate--clear-interim () + "Drop the interim region markers without touching text." + (setq live-dictate--interim-start nil + live-dictate--interim-end nil)) + +(defun live-dictate--insert (text) + "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 () + "Tear down all processes and state." + (setq live-dictate--active nil) ; keep the ffmpeg sentinel quiet + (when live-dictate--stop-timer + (cancel-timer live-dictate--stop-timer) + (setq live-dictate--stop-timer nil)) + (when live-dictate--flush-timer + (cancel-timer live-dictate--flush-timer) + (setq live-dictate--flush-timer nil)) + (when (process-live-p live-dictate--ffmpeg) + (delete-process live-dictate--ffmpeg)) + (setq live-dictate--ffmpeg nil) + (when (and live-dictate--ws (websocket-openp live-dictate--ws)) + (websocket-close live-dictate--ws)) + (setq live-dictate--ws nil + live-dictate--outbox nil) + (live-dictate--clear-interim) + (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--load-model () + "Ask the server to load the transcription model, like the official clients do." + (condition-case err + (let ((url-request-method "POST") + (url-request-extra-headers '(("Content-Type" . "application/json"))) + (url-request-data (json-encode `((model_name . ,live-dictate-model))))) + (with-timeout (20 (message "live-dictate: /load preflight timed out, continuing")) + (url-retrieve-synchronously + (concat live-dictate-server-url "/api/v1/load") + nil nil 20) + (live-dictate--dbg "model load preflight done"))) + (error (message "live-dictate: /load preflight failed: %s (continuing)" err)))) + +(defun live-dictate--stop () + "Stop dictation: commit remaining audio, then close." + (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--queue-send '((type . "input_audio_buffer.commit"))) + (live-dictate--flush-outbox) + (setq live-dictate--stop-timer + (run-with-timer live-dictate-stop-delay nil + (lambda () + (live-dictate--cleanup) + (message "live-dictate: stopped"))))) + +;;;###autoload +(defun live-dictate () + "Toggle live dictation in the current buffer. +While active, speech is transcribed continuously via Lemonade's realtime +endpoint and text is inserted at point as it arrives. Run again to stop." + (interactive) + (if live-dictate--active + (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) + (user-error "live-dictate: set live-dictate-ffmpeg-input-format/-device")) + (unless (executable-find "ffmpeg") + (user-error "live-dictate: FFmpeg 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--chunk-count 0 + live-dictate--chunk-bytes 0 + live-dictate--outbox nil) + (live-dictate--mode-line t) + (live-dictate--load-model) + (setq live-dictate--ws + (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) +;;; live-dictate.el ends here diff --git a/packages.el b/packages.el index 5fc46e4..d9da753 100644 --- a/packages.el +++ b/packages.el @@ -49,3 +49,8 @@ ;; ...Or *all* packages (NOT RECOMMENDED; will likely break things) ;; (unpin! t) +(package! whisper + :recipe (:host github :repo "natrys/whisper.el")) + +(package! websocket) +