diff --git a/AGENTS.md b/AGENTS.md index 771005c..c0d0142 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ This file provides context for LLM coding agents working on this Doom Emacs conf ## Repository Overview -This is a [Doom Emacs](https://github.com/doomemacs/doomemacs) configuration at `~/.doom.d/`. The Doom framework lives in `~/.emacs.d/` (managed via straight.el). This repo only contains user configuration: +This is a [Doom Emacs](https://github.com/doomemacs/doomemacs) configuration at `~/.config/doom/`. The Doom framework lives in `~/.config/emacs/` (managed via straight.el). This repo only contains user configuration: - `init.el` — Doom module declarations (what features to enable) - `config.el` — Main user configuration (editor settings, keybindings, org, latex, gptel, etc.) diff --git a/README.org b/README.org index 97ad511..fd1d736 100644 --- a/README.org +++ b/README.org @@ -26,11 +26,9 @@ Do not run =doom sync= until the root =init.el= symlink exists: Doom can regenerate an empty module list if it is missing. The script links either =mac/init.el= or =linux/init.el= as the root =init.el= based on the host OS. -The expected installed location is =~/.doom.d= (also Doom's normal user -configuration directory in this setup). Several shared configuration paths -assume that location. The staging/publication checkout is not a standalone -=DOOMDIR= just because it exists at another path; adapting the hard-coded -load paths and personal directories would be needed to run it elsewhere. +The expected installed location is =~/.config/doom=. Paths inside the config +resolve against =doom-user-dir=, so a checkout at another location works as +well; personal directories (org notes, blog checkouts) are home-relative. Configuration is split as follows: diff --git a/config-linux.el b/config-linux.el index 2eee02f..72acc46 100644 --- a/config-linux.el +++ b/config-linux.el @@ -9,6 +9,17 @@ ;; checkouts in unusual places) belong in config-local.el, which is ;; gitignored -- see config-local.example.el. +;;; Where the notes live +;; +;; Owned per machine (config.el loads this file before org and org-roam, so +;; these are in place in time). Linux keeps them on the local disk, next to +;; everything else under ~/Documents; ~/MyDocuments on the mac is inside +;; iCloud, which is not where these notes belong. Override in +;; config-local.el if a checkout moves. +(setq org-directory "~/Documents/qwan/essays/willem" + org-default-notes-file (expand-file-name "notes.org" org-directory) + org-roam-directory org-directory) + ;; Elixir language server. The shared config.el deliberately does not ;; configure this: a single value cannot be right on both machines, and ;; pointing eglot at a binary that may not exist is worse than leaving it at @@ -48,6 +59,7 @@ ;; so these autoloads exist on a fresh install. (add-load-path! "lisp") (autoload #'live-dictate "live-dictate" nil t) +(autoload #'live-dictate-reload "live-dictate" nil t) (use-package! whisper :commands (whisper-run whisper-file whisper-select-language) @@ -68,4 +80,26 @@ whisper-translate nil ; t would POST to /translations instead whisper-return-cursor 'end)) +;; live-dictate talks to the same Lemonade server. Lemonade only serves the +;; OpenAI-compatible endpoint (/v1/audio/transcriptions), not whisper.cpp's +;; /inference, and it rejects requests that do not name a model it has +;; loaded -- so point it at the whisper model Lemonade actually serves. If +;; the endpoint ever disappears, live-dictate falls back to /inference and +;; says so instead of silently dropping the transcript. +(with-eval-after-load 'live-dictate + (setopt live-dictate-server-url "http://localhost:13305" + live-dictate-openai-model "Whisper-Large-v3-Turbo" + live-dictate-debug nil)) + +;; `require' keeps the first copy of a library it reads, so edits to +;; lisp/live-dictate.el are invisible until Emacs restarts -- `doom/reload' +;; reloads config.el but not the library. Drop and re-read it afterwards; +;; the `with-eval-after-load' settings above then run again. By hand: +;; `M-x live-dictate-reload'. +(add-hook 'doom-after-reload-hook + (defun live-dictate--reload-after-doom-reload () + "Re-read lisp/live-dictate.el if it has been loaded." + (when (featurep 'live-dictate) + (live-dictate-reload)))) + ;;; config-linux.el ends here diff --git a/config-mac.el b/config-mac.el index 277dee7..0392c35 100644 --- a/config-mac.el +++ b/config-mac.el @@ -5,6 +5,17 @@ ;; home for anything with a macOS path, macOS binary, or macOS-hosted ;; backend. It is no longer a pristine vendor copy -- treat it as ours. +;;; Where the notes live +;; +;; Owned per machine (config.el loads this file before org and org-roam, so +;; these are in place in time). Linux uses ~/Documents; on the mac the +;; notes sit in ~/MyDocuments, which is iCloud-synced -- fine for now, but +;; the private notes should move out of iCloud and this value with them. +;; Override in config-local.el if the notes live somewhere else. +(setq org-directory "~/MyDocuments/qwan/essays/willem" + org-default-notes-file (expand-file-name "notes.org" org-directory) + org-roam-directory org-directory) + ;; Enable tool use in gptel (setq gptel-use-tools t) @@ -261,6 +272,7 @@ Returns answer with org-roam links to sources." ;; one as a WAV, so no WebSocket or Lemonade server is needed. (add-load-path! "lisp") (autoload #'live-dictate "live-dictate" nil t) +(autoload #'live-dictate-reload "live-dictate" nil t) (use-package! whisper :commands (whisper-run whisper-file whisper-select-language) @@ -289,4 +301,14 @@ Returns answer with org-roam links to sources." (with-eval-after-load 'live-dictate (setopt live-dictate-debug nil)) +;; `require' keeps the first copy of a library it reads, so edits to +;; lisp/live-dictate.el are invisible until Emacs restarts -- `doom/reload' +;; reloads config.el but not the library. Drop and re-read it afterwards. +;; By hand: `M-x live-dictate-reload'. +(add-hook 'doom-after-reload-hook + (defun live-dictate--reload-after-doom-reload () + "Re-read lisp/live-dictate.el if it has been loaded." + (when (featurep 'live-dictate) + (live-dictate-reload)))) + ;;; config-mac.el ends here diff --git a/config.el b/config.el index fc27b20..0df7356 100644 --- a/config.el +++ b/config.el @@ -7,6 +7,15 @@ ;; Some functionality uses this to identify you, e.g. GPG configuration, email ;; clients, file templates and snippets. (setq user-full-name "Willem van den Ende") + +;; Load the machine's own configuration first: config-mac.el and +;; config-linux.el own anything with a platform path, binary or backend -- +;; including where the notes live (`org-directory'/`org-roam-directory'), +;; which has to be in place before org and org-roam load below. +;; config-local.el still loads last and wins over everything. +(pcase system-type + ('darwin (load! "config-mac.el" doom-user-dir t)) + ('gnu/linux (load! "config-linux.el" doom-user-dir t))) ;; Doom exposes five (optional) variables for controlling fonts in Doom. Here ;; are the three important ones: ;; @@ -35,10 +44,10 @@ (setq org-superstar-headline-bullets-list '("⁖" "◉" "○" "✸" "✿")) (setq org-startup-with-inline-images t) ;; org-roam customizations -;; If you use `org' and don't want your org files in the default location below, -;; change `org-directory'. It must be set before org loads! -(setq org-directory "~/MyDocuments/qwan/essays/willem") -(setq org-roam-directory "~/MyDocuments/qwan/essays/willem") +;; Where the notes live is machine-specific and is set by config-mac.el / +;; config-linux.el (config-local.el can override it). Set it there rather +;; than here: `org-default-notes-file' is computed from `org-directory' when +;; org loads, which happens below. ; (define-key org-roam-mode-map [mouse-1] #'org-roam-visit-thing) ;; `+roam` makes org-roam a module dependency, so this is normally a no-op. @@ -301,26 +310,25 @@ ;; craft of emacs -(add-load-path! "~/.doom.d/coe-xx") +;; Local packages live next to this file; resolve them against `doom-user-dir' +;; so the same config works on macOS (~/.config/doom) and Linux. +(add-load-path! (expand-file-name "coe-xx" doom-user-dir)) (require 'coe-xx) (require 'coe-demo) -(add-load-path! "~/.doom.d/mostalive") +(add-load-path! (expand-file-name "mostalive" doom-user-dir)) (require 'my-org-roam) (require 'journelly-convert-entry-to-org-roam) -(add-load-path! "~/.doom.d/qwan") +(add-load-path! (expand-file-name "qwan" doom-user-dir)) (require 'qwan-blog) (require 'qwan-refactor) (require 'qwan-dictation) (require 'qwan-markdown-dnd) (require 'org-roam-export-blog) -;; Blog export targets. Both paths are home-relative, so one setting works -;; on macOS (/Users/willem) and Linux (/home/willem). Override per machine -;; in config-mac.el / config-linux.el if a checkout lives elsewhere. -(setq org-roam-export-blog-firehose-root "~/dev/elixir/firehose" - org-roam-export-jekyll-root "~/MyDocuments/qwan/sites/qwaneu.github.io") +;; Blog export targets are machine-specific (config-mac.el / config-linux.el +;; own them) because the checkouts sit in different places per OS. ;; Toggle inline previews (images) of org links — SPC m l p in org buffers (map! :after org @@ -343,11 +351,6 @@ :init (defalias 'pi 'pi-coding-agent) ;; :custom pi-coding-agent-executable '("devcontainer" "exec" "pi")) ) -;; Load machine-specific configuration (gptel backends, etc.) -;; Each file only applies on its own platform. -(pcase system-type - ('darwin (load! "config-mac.el" doom-user-dir t)) - ('gnu/linux (load! "config-linux.el" doom-user-dir t))) ;; org-roam v1 port to v2, insert node without opening buffer diff --git a/lisp/live-dictate.el b/lisp/live-dictate.el index aa3525a..657245c 100644 --- a/lisp/live-dictate.el +++ b/lisp/live-dictate.el @@ -6,17 +6,27 @@ ;;; Commentary: -;; Live speech-to-text dictation against a `whisper.cpp' server -;; (`whisper-server', the `POST /inference' endpoint). +;; 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. +;; 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: @@ -30,7 +40,27 @@ :group 'external) (defcustom live-dictate-server-url "http://localhost:13305" - "Base URL of the whisper.cpp server (transcription via /inference)." + "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) @@ -141,6 +171,8 @@ Only used on darwin, where avfoundation indices shift as devices come and go." ;; 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)) @@ -200,13 +232,16 @@ Only used on darwin, where avfoundation indices shift as devices come and go." (concat ":" (number-to-string (car chosen)))))))))) (defun live-dictate--peak (chunk) - "Peak amplitude of raw PCM16 CHUNK, measured on the high byte." - (let ((i 0) + "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))) - (when (> v 127) (setq v (- 256 v))) + (let* ((v (aref chunk i)) + (v (abs (if (> v 127) (- v 256) v)))) (when (> v peak) (setq peak v))) (setq i (+ i 2))) peak)) @@ -333,53 +368,147 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (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")) - (out (generate-new-buffer " *live-dictate-curl*")) - (url (concat (string-trim-right live-dictate-server-url "/") "/inference"))) + (let ((file (make-temp-file "live-dictate-" nil ".wav"))) (with-temp-file file (set-buffer-multibyte nil) (insert wav)) - (live-dictate--dbg "POST %s (%d bytes)" url (length 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 (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)) + :command (live-dictate--curl-args api file) :sentinel (lambda (proc event) (when (memq (process-status proc) '(exit signal)) - (live-dictate--transcribed out file event)))))) + (live-dictate--transcribed out file apis 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)))) +(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)) - (ignore-errors (delete-file file)) - (setq live-dictate--busy nil) - (live-dictate--pump))) + (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 @@ -464,6 +593,26 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (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) @@ -472,10 +621,11 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (delete-process live-dictate--ffmpeg)) (setq live-dictate--ffmpeg nil) (live-dictate--maybe-flush t) - (if (or live-dictate--busy live-dictate--queue) - (message "live-dictate: finishing transcription...") - (live-dictate--cleanup) - (message "live-dictate: stopped"))) + (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 () @@ -485,20 +635,27 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (live-dictate--stop) (message "live-dictate: not running"))) -(defun live-dictate--level (device) - "Record two seconds from DEVICE and return FFmpeg's max volume, or nil." +(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 - (call-process "ffmpeg" nil t nil "-hide_banner" "-loglevel" "info" - "-f" live-dictate-ffmpeg-input-format "-i" device - "-t" "2" "-ac" "1" "-ar" "16000" "-af" "volumedetect" - "-f" "null" "-") - (goto-char (point-min)) - (when (re-search-forward "max_volume: \\(-?[0-9.]+ dB\\)" nil t) - (match-string 1)))) + (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 whisper.cpp server and the microphone, and say what is wrong." + "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))) @@ -509,18 +666,40 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (mapconcat (lambda (d) (format "[%d] %s" (car d) (cdr d))) devices ", "))) (message "live-dictate: selected device %s" device) - (let ((level (and device (live-dictate--level 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 level) + ((null peak) (message "live-dictate: could not record from %s" device)) - ((string-prefix-p "-91" level) + ((zerop peak) (message (concat "live-dictate: %s delivers digital silence -- grant " "Microphone access to Emacs in System Settings > " - "Privacy & Security > Microphone, then retry") + "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 (max volume %s)" - device level)))))) + (message "live-dictate: %s is delivering audio (peak %d over 3s, threshold %d)" + device peak live-dictate-silence-threshold)))))) ;;;###autoload (defun live-dictate () diff --git a/mostalive/my-org-roam.el b/mostalive/my-org-roam.el index 7f98315..900d8f3 100644 --- a/mostalive/my-org-roam.el +++ b/mostalive/my-org-roam.el @@ -11,25 +11,87 @@ (apply #'org-roam-node-insert args))) -;; make sure that org-timer works and org-pomodoro therefore. Limit the number of agenda files searched -;; plus a utility function for flattening, since that is not part of the standard library of emacs - -(defun org-roam-collect-org-agenda-files () - (interactive) - (setq org-agenda-files (collect-org-agenda-files-))) +;; Make sure that org-timer works and org-pomodoro therefore, by limiting the +;; number of agenda files searched to the 20 most recent 2023 daily notes. +;; +;; This used to go through org-roam's database (`org-roam-db-query'), which is a +;; startup trap: Doom advises `org-roam-db-query' to run `org-roam-db-sync' the +;; first time it is called in a session (see `+org-roam-try-init-db-a'), and +;; `org-roam-db-sync' re-hashes every org file under `org-roam-directory' -- +;; 8000+ files here -- synchronously, before the first frame is drawn, so Emacs +;; looks hung (blank screen). Listing a single directory gives the same answer +;; for this query and is effectively free, so never touch the DB at startup. (defun collect-org-agenda-files- () - (seq-map - 'car - (org-roam-db-query - [:select - [file] - :from files - :where (like file "%daily\/2023%") - :order-by (desc file) - :limit 20]))) + "Return the 20 most recent `daily/2023-*.org' notes, newest first." + (seq-take + (sort (file-expand-wildcards + (expand-file-name "daily/2023-*.org" org-roam-directory) + t) + #'string>) + 20)) -(setq org-agenda-files (collect-org-agenda-files-)) +(defun org-roam-collect-org-agenda-files () + "Refresh `org-agenda-files' from org-roam's notes directory." + (interactive) + (let ((files (collect-org-agenda-files-))) + (if files + (setq org-agenda-files files) + (message "my-org-roam: no daily/2023-*.org notes found under %s" + org-roam-directory)))) + +;; Cheap enough to run at load time; safe if the notes directory is missing. +(condition-case err + (when (bound-and-true-p org-roam-directory) + (org-roam-collect-org-agenda-files)) + (error (message "my-org-roam: could not set org-agenda-files: %S" err))) + + +;;; Don't let org-roam freeze startup +;; +;; Doom turns the *first* `org-roam-db-query' of a session into a full +;; `org-roam-db-sync' (see `+org-roam-try-init-db-a'), and that sync SHA1s +;; every note under `org-roam-directory'. With ~8.4k notes here that is five +;; seconds of frozen Emacs, usually while the first frame is still being drawn +;; -- the busy cursor at startup. The database already exists by then, so +;; drop the advice before the first frame and resync at idle instead, and only +;; when a note is actually newer than the database: one `stat' per note is an +;; order of magnitude cheaper than hashing them all. + +(defun my/org-roam-db-stale-p () + "Non-nil when some note under `org-roam-directory' is newer than the DB." + (let* ((db (expand-file-name org-roam-db-location)) + (db-time (and (file-exists-p db) + (float-time (file-attribute-modification-time + (file-attributes db)))))) + (or (null db-time) + (seq-some (lambda (file) + (> (float-time (file-attribute-modification-time + (file-attributes file))) + db-time)) + (directory-files-recursively org-roam-directory "\\.org\\'"))))) + +(defun my/org-roam-sync-when-stale () + "Sync the org-roam database at idle, if any note changed behind our back. +Changes made from Emacs are already handled incrementally by +`org-roam-db-autosync-mode', so normally this does nothing." + (when (and (featurep 'org-roam) + (bound-and-true-p org-roam-directory) + (file-directory-p (expand-file-name org-roam-directory))) + (if (my/org-roam-db-stale-p) + (progn + (message "org-roam: notes changed on disk, syncing database (Emacs \ +may pause)...") + (org-roam-db-sync) + (message "org-roam: database synced")) + (message "org-roam: database is up to date")))) + +(defun my/org-roam-defer-db-sync () + "Take the full DB sync off the startup path; see `my/org-roam-sync-when-stale'." + (ignore-errors (advice-remove 'org-roam-db-query #'+org-roam-try-init-db-a)) + (run-with-idle-timer 10 nil #'my/org-roam-sync-when-stale)) + +(add-hook 'after-init-hook #'my/org-roam-defer-db-sync) (defun open-today-log () diff --git a/qwan/org-roam-export-blog-test.el b/qwan/org-roam-export-blog-test.el index 2d80939..4a42d82 100644 --- a/qwan/org-roam-export-blog-test.el +++ b/qwan/org-roam-export-blog-test.el @@ -3,7 +3,7 @@ ;;; Commentary: ;; Run with: -;; emacs --batch -Q -l org -l ox-md -L ~/.doom.d/qwan \ +;; emacs --batch -Q -l org -l ox-md -L ~/.config/doom/qwan \ ;; -l org-roam-export-blog.el -l org-roam-export-blog-test.el \ ;; -f ert-run-tests-batch-and-exit ;;