Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Hold a hotkey, speak, release — the transcribed text is typed wherever your cu
- **Local** offline — `parakeet-primeline` (German fine-tune of `nvidia/parakeet-tdt-0.6b-v3`, int8 ONNX via [sherpa-onnx](https://github.com/k2-fsa/sherpa-onnx)). CPU-only, ~50 ms decode for 2 s audio at 4 threads. No network, no API key.
- Optional minimum-hold threshold to ignore accidental modifier presses
- API keys stored locally in `~/.config/dictate/config.json` (mode 600)
- **Wayland-compatible**: uses `evdev` for key capture and `ydotool` for typing, falls back to `pynput`/`xdotool` on X11
- **Wayland-compatible**: uses `evdev` for key capture and `wtype`/`ydotool` for typing, falls back to `pynput`/`xdotool` on X11
- **Windows / macOS**: `pip install PyQt6 sounddevice pynput requests numpy` and run `python gui.py`; hotkeys and typing go through `pynput`. Pair it with the Yorik provider and the machine needs no model.

## Requirements
Expand Down Expand Up @@ -72,7 +72,7 @@ Attribution (CC-BY-4.0): [primeline](https://huggingface.co/flozen1981/parakeet-

## Wayland notes

On Wayland (GNOME Mutter in particular) the compositor does not forward global key events to XWayland, so `pynput`'s X-based listener sees nothing. Dictate works around this by reading `/dev/input/event*` directly via `evdev`. The `install.sh` script sets this up. Typing likewise uses `ydotool` (via `/dev/uinput`) because `xdotool` cannot type into native Wayland windows.
On Wayland (GNOME Mutter in particular) the compositor does not forward global key events to XWayland, so `pynput`'s X-based listener sees nothing. Dictate works around this by reading `/dev/input/event*` directly via `evdev`. The `install.sh` script sets this up. Typing uses `wtype` (layout-correct, KDE/wlroots) and falls back to `ydotool` (via `/dev/uinput`, US-QWERTY only) because `xdotool` cannot type into native Wayland windows.

If a hotkey silently does nothing after install, the two things to check are:

Expand Down
4 changes: 3 additions & 1 deletion WAYLAND_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ Between 00:13 and 01:16 there was **no Xorg NVIDIA module installed**. Any GDM r

**Fix:** use `ydotool` instead, which writes to `/dev/uinput`. That is a kernel interface below both X and Wayland, so any focused window receives the keystrokes. Ubuntu 24.04's `ydotool` 0.1.8 works standalone (no `ydotoold` daemon needed), just warns about missing daemon. `/dev/uinput` is accessible when the user is in the `input` group (the ACL is granted automatically by `systemd-logind`).

`core.type_text` tries `ydotool` first and falls back to `xdotool` if the binary is missing.
`core.type_text` tries `wtype` first, then `ydotool`, then `xdotool`.

**Layout caveat (TASK-001):** `wtype` works on KDE Plasma and wlroots but not on GNOME Mutter (no virtual-keyboard protocol). On GNOME, `ydotool` sends US-QWERTY key positions and the compositor applies the active layout, so QWERTZ gets Y/Z swapped and umlauts are lost. `core.type_text` therefore types through `ydotool` with a Swiss German (`ch`) key-position table when GNOME's *active* input source is `ch` (table from `/usr/share/X11/xkb/symbols/ch`). Other GNOME layouts still use plain `ydotool` and keep the problem.

## Bug 3 — `sd.InputStream.stop()` freezes the Qt main thread

Expand Down
20 changes: 20 additions & 0 deletions _done/TASK-001-BUG-WAYLAND-Umlaute-Layout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# TASK-001-BUG: Wayland-Typing verliert Umlaute/ß und vertauscht Y/Z

## Verstanden
Diktat-Vorschau im GUI zeigt korrekten Text (ä/ö/ü/ß, Y/Z). Beim Tippen in
fremde Fenster (Konsole) fehlen Umlaute und ß, Y und Z sind vertauscht.

Ursache: `core.type_text` nutzt unter Wayland zuerst `ydotool`. `ydotool`
schreibt rohe US-QWERTY-Scancodes via `/dev/uinput` und kennt das XKB-Layout
nicht → QWERTZ-Layout falsch, Nicht-ASCII nicht tippbar.

## Plan
1. Unter Wayland zuerst `wtype` (Virtual-Keyboard-Protokoll, sendet Keysyms → layout-korrekt).
2. Fallback auf `ydotool`, dann `xdotool` (nur wenn wtype fehlt/nicht unterstützt).
3. `wtype` in `install.sh` und Doku aufnehmen.

## DoD
- [x] Code kompiliert (`python -m py_compile core.py`)
- [x] Reihenfolge wtype → ydotool → xdotool, Fallback bei wtype-Fehler
- [x] install.sh / README / WAYLAND_NOTES aktualisiert
- [x] Manueller Test (GNOME, Layout ch, App neu gestartet): "Übung Zürich Yak ä ö" → korrekt (ß wird als "ss" getippt)
134 changes: 121 additions & 13 deletions core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import logging
import logging.handlers
import re
import subprocess
import threading
import wave
Expand Down Expand Up @@ -187,6 +188,93 @@ def notify(msg, urgency="normal", timeout_ms=1500):
pass


# Swiss German (XKB "ch") on top of evdev keycodes, taken from
# /usr/share/X11/xkb/symbols/ch. ydotool injects *physical key positions* as
# on a US keyboard; the compositor applies the active layout. So "y" must be
# sent as KEY_Z (44) and "z" as KEY_Y (21). Value: (keycode, mods, dead) with
# mods "" / "S" (Shift) / "A" (AltGr) / "C" (CapsLock toggle); dead=True means a dead key that needs a
# following Space to yield the bare accent character.
_CH_KEYS = {}
_US_LETTER_CODES = dict(zip("abcdefghijklmnopqrstuvwxyz", [
30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38, 50,
49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 44, 21]))
for _c, _k in _US_LETTER_CODES.items():
_CH_KEYS[_c] = (_k, "", False)
_CH_KEYS[_c.upper()] = (_k, "S", False)
_CH_KEYS.update({
"§": (41, "", False), "°": (41, "S", False),
"1": (2, "", False), "+": (2, "S", False),
"2": (3, "", False), '"': (3, "S", False), "@": (3, "A", False),
"3": (4, "", False), "*": (4, "S", False), "#": (4, "A", False),
"4": (5, "", False), "ç": (5, "S", False),
"5": (6, "", False), "%": (6, "S", False),
"6": (7, "", False), "&": (7, "S", False), "¬": (7, "A", False),
"7": (8, "", False), "/": (8, "S", False), "|": (8, "A", False),
"8": (9, "", False), "(": (9, "S", False), "¢": (9, "A", False),
"9": (10, "", False), ")": (10, "S", False),
"0": (11, "", False), "=": (11, "S", False),
"'": (12, "", False), "?": (12, "S", False), "´": (12, "A", True),
"^": (13, "", True), "`": (13, "S", True), "~": (13, "A", True),
"ü": (26, "", False), "è": (26, "S", False), "[": (26, "A", False),
"¨": (27, "", True), "!": (27, "S", False), "]": (27, "A", False),
"ö": (39, "", False), "é": (39, "S", False),
"ä": (40, "", False), "à": (40, "S", False), "{": (40, "A", False),
"$": (43, "", False), "£": (43, "S", False), "}": (43, "A", False),
"<": (86, "", False), ">": (86, "S", False), "\\": (86, "A", False),
",": (51, "", False), ";": (51, "S", False),
".": (52, "", False), ":": (52, "S", False),
"-": (53, "", False), "_": (53, "S", False),
" ": (57, "", False), "\n": (28, "", False), "\t": (15, "", False),
"€": (18, "A", False),
# Capital umlauts: no direct key on Swiss German; CapsLock turns ü/ö/ä into Ü/Ö/Ä.
"Ü": (26, "C", False), "Ö": (39, "C", False), "Ä": (40, "C", False),
})
_MOD_CODES = {"S": 42, "A": 100} # KEY_LEFTSHIFT, KEY_RIGHTALT
_KEY_SPACE = 57


def _ch_key_args(text):
"""ydotool key arguments ("code:state") that type `text` on a Swiss German
layout. Characters without a key position are skipped with a warning."""
args = []
text = text.replace("ß", "ss") # Swiss German has no ß key; "ss" is the Swiss spelling
for ch in text:
if ch == "\r":
continue
entry = _CH_KEYS.get(ch)
if entry is None:
log.warning("no Swiss German key for %r — skipped", ch)
continue
code, mods, dead = entry
if mods == "C":
args += ["58:1", "58:0", f"{code}:1", f"{code}:0", "58:1", "58:0"]
continue
mod_code = _MOD_CODES.get(mods)
if mod_code:
args.append(f"{mod_code}:1")
args += [f"{code}:1", f"{code}:0"]
if mod_code:
args.append(f"{mod_code}:0")
if dead:
args += [f"{_KEY_SPACE}:1", f"{_KEY_SPACE}:0"]
return args


def _gnome_active_layout():
"""XKB layout name of GNOME's *active* input source (e.g. 'de', 'ch'), or ''."""
try:
def get(key):
return subprocess.run(
["gsettings", "get", "org.gnome.desktop.input-sources", key],
capture_output=True, text=True, timeout=2,
).stdout
sources = re.findall(r"\('xkb', '([^']+)'\)", get("sources"))
idx = int(get("current").split()[-1]) # "uint32 0" -> 0
return sources[idx].split("+")[0] if idx < len(sources) else ""
except (FileNotFoundError, subprocess.TimeoutExpired, IndexError, ValueError):
return ""


def type_text(text):
if not text:
return
Expand All @@ -203,23 +291,43 @@ def type_text(text):
keyboard.Controller().type(text)
return
on_x11 = os.environ.get("XDG_SESSION_TYPE") == "x11"
tools = ["xdotool", "ydotool"] if on_x11 else ["ydotool", "xdotool"]
# Wayland: wtype speaks the virtual-keyboard protocol and sends keysyms,
# so umlauts, ß and QWERTZ come out right. ydotool only sends raw US-QWERTY
# scancodes (wrong Y/Z, no umlauts) and is kept purely as a fallback.
tools = ["xdotool", "ydotool"] if on_x11 else ["wtype", "ydotool", "xdotool"]
commands = {
"wtype": ["wtype", "--", text],
"xdotool": ["xdotool", "type", "--delay", "0", "--", text],
"ydotool": ["ydotool", "type", "--key-delay", "0", "--", text],
}
if not on_x11 and _gnome_active_layout() == "ch":
# ydotool with Swiss German key positions: correct umlauts and Y/Z on QWERTZ.
args = _ch_key_args(text)
if args:
try:
subprocess.run(["ydotool", "key", *args], check=False, stderr=subprocess.DEVNULL)
except FileNotFoundError:
log.error("ydotool not installed — text not typed")
notify("Typing failed (ydotool not installed)", urgency="critical", timeout_ms=5000)
return
for tool in tools:
try:
if tool == "xdotool":
r = subprocess.run(["xdotool", "type", "--delay", "0", "--", text], check=False)
else:
r = subprocess.run(
["ydotool", "type", "--key-delay", "0", "--", text],
check=False,
stderr=subprocess.DEVNULL,
)
if r.returncode != 0:
log.error("%s exited with %s — text not typed", tool, r.returncode)
notify(f"Typing failed ({tool} exit {r.returncode})", urgency="critical", timeout_ms=5000)
return
r = subprocess.run(
commands[tool],
check=False,
stderr=subprocess.DEVNULL if tool != "xdotool" else None,
)
except FileNotFoundError:
continue
if r.returncode != 0 and tool == "wtype":
# Compositor without virtual-keyboard support (e.g. GNOME): nothing
# was typed, so try the next tool.
log.warning("wtype exited with %s — falling back", r.returncode)
continue
if r.returncode != 0:
log.error("%s exited with %s — text not typed", tool, r.returncode)
notify(f"Typing failed ({tool} exit {r.returncode})", urgency="critical", timeout_ms=5000)
return


class Recorder:
Expand Down
5 changes: 3 additions & 2 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ echo
echo "[1/4] Installing system packages (needs sudo)..."
sudo apt-get update -qq
# xdotool: X11 typing fallback
# ydotool: /dev/uinput typing, works in native Wayland windows
# wtype: layout-aware Wayland typing (umlauts, ß, QWERTZ); needs virtual-keyboard support (KDE, wlroots)
# ydotool: /dev/uinput typing fallback (US-QWERTY only), works in native Wayland windows
# python3-evdev: /dev/input/event* reader, works on Wayland where pynput is blind
# libportaudio2: runtime library for the sounddevice wheel (missing on a fresh Ubuntu desktop)
sudo apt-get install -y \
xdotool ydotool libnotify-bin python3-pip libxcb-cursor0 python3-evdev libportaudio2
xdotool wtype ydotool libnotify-bin python3-pip libxcb-cursor0 python3-evdev libportaudio2

echo
echo "[2/4] Installing Python packages..."
Expand Down