-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwhispypy-daemon.py
More file actions
1401 lines (1204 loc) · 50.3 KB
/
whispypy-daemon.py
File metadata and controls
1401 lines (1204 loc) · 50.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import configparser
from contextlib import contextmanager
import importlib.util
import json
import logging
import os
from pathlib import Path
import shutil
import signal
import struct
import subprocess
import sys
import tempfile
import time
from typing import Any, Generator, Optional, Union
import wave
import numpy as np
import whisper
# Audio file constants
BEEP_START_FILENAME = "BEEPTimer_Montre_numerique_bip_2_ID_2255_LS.wav"
BEEP_COMPLETE_FILENAME = "BEEPTimer_Montre_numerique_bip_1_ID_2254_LS.wav"
# Audio recording constants
SAMPLE_RATE = 16000 # Hz - Whisper's expected sample rate
CHANNELS = 1 # Mono audio
AUDIO_FORMAT = "f32" # 32-bit float format for PipeWire
FLOAT32_BYTE_SIZE = 4 # Size of f32 in bytes
# Timing and validation constants
DEVICE_TEST_DURATION = 1.0 # seconds - Duration for device validation test
# File paths (will be replaced with proper temp files)
TEMP_AUDIO_FILENAME = "whispy_recording" # Base filename for temporary audio (extension will be added based on engine)
# Terminal detection constants
TERMINAL_KEYWORDS = [
"term",
"konsole",
"kitty",
"alacritty",
"ghostty",
"wezterm",
"foot",
"gnome-terminal",
"xterm",
"urxvt",
"st",
] # Common terminal identifiers for window class/title matching
# State files for external indicators (e.g., Waybar)
RECORDING_STATE_FILE = Path("/tmp/whispypy_recording")
READY_STATE_FILE = Path("/tmp/whispypy_ready")
DEFAULT_SHERPA_ONNX_PARAKEET_INT8_MODEL = (
"sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8"
)
def _auto_onnx_threads() -> int:
cpu_count = os.cpu_count() or 1
return max(1, min(4, cpu_count // 2))
def _whispypy_cache_dir() -> Path:
xdg_cache_home = os.environ.get("XDG_CACHE_HOME")
base = Path(xdg_cache_home) if xdg_cache_home else (Path.home() / ".cache")
return base / "whispypy"
def _is_valid_parakeet_onnx_dir(model_dir: Path) -> bool:
return all(
(model_dir / name).is_file()
for name in ("encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt")
)
def ensure_sherpa_onnx_parakeet_model_dir(
model_id: str,
cache_dir: Optional[Union[str, Path]] = None,
) -> Path:
"""Ensure the sherpa-onnx model bundle exists locally; download if missing."""
models_root = (
Path(cache_dir) if cache_dir is not None else _whispypy_cache_dir()
) / "models"
models_root.mkdir(parents=True, exist_ok=True)
expected_dir = models_root / model_id
if _is_valid_parakeet_onnx_dir(expected_dir):
return expected_dir
url = (
"https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/"
f"{model_id}.tar.bz2"
)
logging.info("Downloading sherpa-onnx model bundle from %s", url)
tmp_path: Optional[str] = None
try:
with tempfile.NamedTemporaryFile(suffix=".tar.bz2", delete=False) as tmp:
tmp_path = tmp.name
if shutil.which("curl"):
download_cmd = [
"curl",
"-L",
"-f",
"-o",
tmp_path,
url,
]
elif shutil.which("wget"):
download_cmd = [
"wget",
"-O",
tmp_path,
url,
]
else:
raise RuntimeError(
"Auto-download requires either 'curl' or 'wget' to be installed. "
"Install one of them, or pass --parakeet-onnx-dir to point to a pre-downloaded bundle."
)
subprocess.run(
download_cmd,
check=True,
)
subprocess.run(
[
"tar",
"-xjf",
tmp_path,
"-C",
str(models_root),
],
check=True,
)
finally:
if tmp_path:
Path(tmp_path).unlink(missing_ok=True)
if _is_valid_parakeet_onnx_dir(expected_dir):
return expected_dir
# Some archives may not extract to the expected directory name.
candidates = [
p for p in models_root.iterdir() if p.is_dir() and _is_valid_parakeet_onnx_dir(p)
]
if len(candidates) == 1:
return candidates[0]
raise FileNotFoundError(
f"Downloaded model bundle but could not find required files under {models_root}. "
f"Expected {expected_dir} with encoder/decoder/joiner/tokens."
)
class SherpaOnnxParakeetInt8Transcriber:
def __init__(
self,
model_dir: Union[str, Path],
provider: str = "cpu",
num_threads: Optional[int] = None,
):
try:
import sherpa_onnx
except ImportError as e:
raise ImportError(
"sherpa-onnx is required for engine 'parakeet_onnx_int8'. "
"Install with the optional extra (to be added): whispypy[parakeet-onnx]"
) from e
self._sherpa_onnx = sherpa_onnx
self.model_dir = Path(model_dir)
encoder = self.model_dir / "encoder.int8.onnx"
decoder = self.model_dir / "decoder.int8.onnx"
joiner = self.model_dir / "joiner.int8.onnx"
tokens = self.model_dir / "tokens.txt"
missing = [
str(p)
for p in (encoder, decoder, joiner, tokens)
if not p.is_file()
]
if missing:
raise FileNotFoundError(
"Missing required Parakeet INT8 files in model dir. Missing: "
+ ", ".join(missing)
)
self.num_threads = num_threads if num_threads is not None else _auto_onnx_threads()
self.provider = provider
model_load_start = time.time()
kwargs: dict[str, Any] = dict(
encoder=str(encoder),
decoder=str(decoder),
joiner=str(joiner),
tokens=str(tokens),
num_threads=self.num_threads,
sample_rate=SAMPLE_RATE,
feature_dim=80,
decoding_method="greedy_search",
model_type="nemo_transducer",
debug=False,
)
# Provider support varies by sherpa-onnx version; try best-effort.
if self.provider in {"cpu", "cuda"}:
kwargs["provider"] = self.provider
try:
try:
self.recognizer = self._sherpa_onnx.OfflineRecognizer.from_transducer(
**kwargs
)
except TypeError:
# Older sherpa-onnx may not accept provider/model_type kwargs.
kwargs.pop("provider", None)
kwargs.pop("model_type", None)
self.recognizer = self._sherpa_onnx.OfflineRecognizer.from_transducer(
**kwargs
)
except Exception as e:
if self.provider == "cuda":
logging.warning(
"Failed to initialize sherpa-onnx with provider=cuda (%s); falling back to cpu",
e,
)
self.provider = "cpu"
kwargs["provider"] = "cpu"
try:
self.recognizer = self._sherpa_onnx.OfflineRecognizer.from_transducer(
**kwargs
)
except TypeError:
kwargs.pop("provider", None)
kwargs.pop("model_type", None)
self.recognizer = self._sherpa_onnx.OfflineRecognizer.from_transducer(
**kwargs
)
else:
raise
model_load_time = time.time() - model_load_start
logging.info(
"Sherpa-ONNX Parakeet INT8 model loaded in %.2f seconds (provider=%s, threads=%s)",
model_load_time,
self.provider,
self.num_threads,
)
def transcribe_wav(self, wav_path: Union[str, Path]) -> str:
stream = self.recognizer.create_stream()
with wave.open(str(wav_path)) as wf:
if wf.getnchannels() != 1:
raise ValueError(f"Expected mono wav, got channels={wf.getnchannels()}")
if wf.getsampwidth() != 2:
raise ValueError(
f"Expected 16-bit PCM wav, got sampwidth={wf.getsampwidth()} bytes"
)
num_frames = wf.getnframes()
pcm = wf.readframes(num_frames)
samples_i16 = np.frombuffer(pcm, dtype=np.int16)
samples_f32 = samples_i16.astype(np.float32) / 32768.0
sample_rate = wf.getframerate()
stream.accept_waveform(sample_rate, samples_f32)
self.recognizer.decode_streams([stream])
return str(stream.result.text).strip()
def get_config_file() -> Path:
"""Get the configuration file path following XDG Base Directory specification."""
xdg_config_home = os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
config_dir = Path(xdg_config_home) / "whispypy"
config_dir.mkdir(parents=True, exist_ok=True)
return config_dir / "config.conf"
# Configuration
CONFIG_FILE = get_config_file()
class ConfigManager:
"""Manages configuration file operations with cached config parsing."""
def __init__(self, config_file: Path = CONFIG_FILE):
self.config_file = config_file
self._config: Optional[configparser.ConfigParser] = None
self._config_mtime: Optional[float] = None
def _get_config(self) -> Optional[configparser.ConfigParser]:
"""Get cached config, reloading if file changed."""
if not self.config_file.exists():
self._config = None
self._config_mtime = None
return None
current_mtime = self.config_file.stat().st_mtime
if self._config is None or self._config_mtime != current_mtime:
self._config = configparser.ConfigParser()
self._config.read(self.config_file)
self._config_mtime = current_mtime
return self._config
def _invalidate_cache(self) -> None:
"""Invalidate cached config after writes."""
self._config = None
self._config_mtime = None
def _load_config_value(
self, key: str, log_msg: Optional[str] = None, log_level: str = "info"
) -> Optional[str]:
"""Generic method to load a config value."""
config = self._get_config()
if config is None:
return None
try:
value = config.get("DEFAULT", key, fallback=None)
if value and log_msg:
getattr(logging, log_level)(log_msg.format(value=value))
return value
except Exception as e:
logging.debug(f"Error reading {key} from config: {e}")
return None
def save_device(self, device: str) -> None:
"""Save device configuration to config file."""
config = self._get_config() or configparser.ConfigParser()
if "DEFAULT" not in config:
config.add_section("DEFAULT")
config.set("DEFAULT", "device", device)
with open(self.config_file, "w") as f:
config.write(f)
self._invalidate_cache()
logging.info(f"Device '{device}' saved to {self.config_file}")
def load_device(self) -> Optional[str]:
"""Load device configuration from config file."""
return self._load_config_value(
"device", "Using device from config: {value}", "info"
)
def load_dotool_layout(self) -> Optional[str]:
"""Load DOTOOL_XKB_LAYOUT configuration from config file."""
return self._load_config_value(
"dotool_xkb_layout", "Using dotool XKB layout from config: {value}", "debug"
)
def load_dotool_variant(self) -> Optional[str]:
"""Load DOTOOL_XKB_VARIANT configuration from config file."""
return self._load_config_value(
"dotool_xkb_variant", "Using dotool XKB variant from config: {value}", "debug"
)
def validate_config(self) -> bool:
"""Validate configuration file format and values."""
config = self._get_config()
if config is None:
return True # No config file is valid (will use defaults)
try:
# Check if DEFAULT section exists
if "DEFAULT" not in config:
logging.warning("Configuration file missing DEFAULT section")
return False
# Validate device if present
device = config.get("DEFAULT", "device", fallback=None)
if device:
# Basic validation - device name should not be empty
if not device.strip():
logging.warning("Device name in config is empty")
return False
# Validate device name format (basic checks)
if len(device.strip()) < 3:
logging.warning("Device name appears too short, may be invalid")
return False
# Validate other audio-related settings if present
# Validate sample_rate if present
sample_rate_value = config.get("DEFAULT", "sample_rate", fallback=None)
if sample_rate_value is not None:
try:
sample_rate = int(sample_rate_value)
valid_sample_rates = [8000, 16000, 22050, 44100, 48000]
if sample_rate not in valid_sample_rates:
logging.warning(
f"Invalid sample_rate value '{sample_rate}'. "
f"Valid values: {valid_sample_rates}"
)
return False
except ValueError:
logging.warning(
f"Invalid sample_rate value '{sample_rate_value}' - not an integer"
)
return False
# Validate channels if present
channels_value = config.get("DEFAULT", "channels", fallback=None)
if channels_value is not None:
try:
channels = int(channels_value)
valid_channels = [1, 2]
if channels not in valid_channels:
logging.warning(
f"Invalid channels value '{channels}'. "
f"Valid values: {valid_channels}"
)
return False
except ValueError:
logging.warning(
f"Invalid channels value '{channels_value}' - not an integer"
)
return False
# Validate audio_format if present
audio_format_value = config.get("DEFAULT", "audio_format", fallback=None)
if audio_format_value is not None:
audio_format = audio_format_value.strip()
valid_formats = ["f32", "s16", "s24", "s32"]
if audio_format not in valid_formats:
logging.warning(
f"Invalid audio_format value '{audio_format}'. "
f"Valid values: {valid_formats}"
)
return False
# Validate dotool_xkb_layout if present
dotool_layout_value = config.get(
"DEFAULT", "dotool_xkb_layout", fallback=None
)
if dotool_layout_value is not None:
dotool_layout = dotool_layout_value.strip()
if not dotool_layout:
logging.warning("dotool_xkb_layout value is empty")
return False
# Validate dotool_xkb_variant if present
dotool_variant_value = config.get(
"DEFAULT", "dotool_xkb_variant", fallback=None
)
if dotool_variant_value is not None:
dotool_variant = dotool_variant_value.strip()
if not dotool_variant:
logging.warning("dotool_xkb_variant value is empty")
return False
logging.debug("Configuration validation successful")
return True
except Exception as e:
logging.error(f"Configuration validation failed: {e}")
return False
def load_audio_f32(filepath: Union[str, Path]) -> np.ndarray:
"""Load audio file as float32 samples."""
with open(filepath, "rb") as f:
data = f.read()
# Convert bytes to float32
num_floats = len(data) // FLOAT32_BYTE_SIZE
floats = struct.unpack(f"<{num_floats}f", data)
return np.array(floats, dtype=np.float32)
def load_audio_s16_as_f32(filepath: Union[str, Path]) -> np.ndarray:
"""Load 16-bit PCM audio and convert to float32 samples in [-1, 1]."""
with open(filepath, "rb") as f:
data = f.read()
num_samples = len(data) // 2
if num_samples == 0:
return np.array([], dtype=np.float32)
ints = struct.unpack(f"<{num_samples}h", data)
floats = np.asarray(ints, dtype=np.float32) / 32768.0
return floats
def _play_beep_file(filename: str, beep_type: str) -> None:
"""Play a beep sound file with fallback options.
Args:
filename: The beep sound filename (from the assets directory)
beep_type: Description of the beep type for logging (e.g., "start", "completion")
"""
# Construct path to beep sound file
beep_file = Path(__file__).parent / "assets" / filename
if not beep_file.exists():
logging.debug(f"Beep file not found: {beep_file}")
_try_terminal_beep_fallback(beep_type)
return
# Audio players to try, in order of preference
audio_players = [
"aplay", # ALSA player
"paplay", # PulseAudio player
"pw-play", # PipeWire player
]
for player in audio_players:
if _try_audio_player(player, str(beep_file), beep_type):
return
# All audio players failed, try terminal beep
_try_terminal_beep_fallback(beep_type)
def _try_audio_player(player: str, audio_file: str, beep_type: str) -> bool:
"""Try to play audio with a specific player.
Returns:
bool: True if successful, False otherwise
"""
try:
result = subprocess.run(
[player, audio_file],
capture_output=True,
text=True,
timeout=10, # 10 second timeout
check=False, # Don't raise exception on non-zero exit
)
if result.returncode == 0:
logging.debug(f"{beep_type.capitalize()} beep played via {player}")
return True
else:
# Log the actual error for debugging
error_parts = [f"exit code {result.returncode}"]
if result.stderr.strip():
error_parts.append(f"stderr: {result.stderr.strip()}")
logging.debug(f"{player} failed: {', '.join(error_parts)}")
return False
except subprocess.TimeoutExpired:
logging.debug(f"{player} timed out after 10 seconds")
return False
except FileNotFoundError:
logging.debug(f"{player} command not found")
return False
except PermissionError:
logging.debug(f"{player} permission denied")
return False
except Exception as e:
logging.debug(f"{player} failed with exception: {e}")
return False
def _try_terminal_beep_fallback(beep_type: str) -> None:
"""Try to play terminal beep as fallback."""
try:
result = subprocess.run(
["printf", "\\a"], capture_output=True, text=True, timeout=5, check=False
)
if result.returncode == 0:
logging.debug(f"{beep_type.capitalize()} beep played via printf (fallback)")
else:
logging.debug(f"Terminal beep failed with exit code {result.returncode}")
logging.debug(f"Could not play {beep_type} beep")
except Exception as e:
logging.debug(f"Terminal beep failed with exception: {e}")
logging.debug(f"Could not play {beep_type} beep")
def play_start_beep() -> None:
"""Play a start beep sound to indicate recording is starting."""
_play_beep_file(BEEP_START_FILENAME, "start")
def play_completion_beep() -> None:
"""Play a completion beep sound to indicate transcription is ready."""
_play_beep_file(BEEP_COMPLETE_FILENAME, "completion")
def copy_to_clipboard(text: str) -> bool:
"""Copy text to clipboard using the appropriate tool for the current display server."""
# Check if we're on Wayland
if os.getenv("WAYLAND_DISPLAY"):
# Use wl-copy for Wayland
try:
subprocess.run(["wl-copy", text], check=True)
logging.info("Text copied to clipboard (wl-copy)")
return True
except (subprocess.CalledProcessError, FileNotFoundError) as e:
logging.warning(f"wl-copy failed: {e}")
# Check if we're on X11
if os.getenv("DISPLAY"):
# Try xclip first (more common)
try:
subprocess.run(
["xclip", "-selection", "clipboard"], input=text, text=True, check=True
)
logging.info("Text copied to clipboard (xclip)")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
# Fallback to xsel
try:
subprocess.run(
["xsel", "--clipboard", "--input"],
input=text,
text=True,
check=True,
)
logging.info("Text copied to clipboard (xsel)")
return True
except (subprocess.CalledProcessError, FileNotFoundError) as e:
logging.warning(f"X11 clipboard tools failed: {e}")
# Fallback: try to detect clipboard tools
clipboard_tools = [
(["xclip", "-selection", "clipboard"], True), # input via stdin
(["xsel", "--clipboard", "--input"], True), # input via stdin
(["wl-copy"], False), # text as argument
]
for cmd, use_stdin in clipboard_tools:
try:
if use_stdin:
subprocess.run(cmd, input=text, text=True, check=True)
else:
subprocess.run(cmd + [text], check=True)
tool_name = cmd[0]
logging.info(f"Text copied to clipboard ({tool_name})")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
continue
logging.error("Failed to copy to clipboard: no suitable clipboard tool found")
return False
def _detect_terminal_window() -> bool:
"""Detect if the focused window is a terminal application.
Returns True if terminal detected, False otherwise (including on detection failure).
"""
# Try Wayland (Hyprland) detection first
if os.getenv("WAYLAND_DISPLAY"):
try:
result = subprocess.run(
["hyprctl", "activewindow", "-j"],
capture_output=True,
text=True,
check=True
)
window_info = json.loads(result.stdout)
window_class = window_info.get("class", "").lower()
window_title = window_info.get("title", "").lower()
is_terminal = any(
keyword in window_class or keyword in window_title
for keyword in TERMINAL_KEYWORDS
)
logging.debug(f"Window class: {window_class}, is_terminal: {is_terminal}")
return is_terminal
except (subprocess.CalledProcessError, FileNotFoundError, json.JSONDecodeError):
pass
# Try X11 detection
if os.getenv("DISPLAY"):
try:
result = subprocess.run(
["xdotool", "getactivewindow", "getwindowclassname"],
capture_output=True,
text=True,
check=True,
)
window_class = result.stdout.strip().lower()
window_title = ""
try:
title_result = subprocess.run(
["xdotool", "getactivewindow", "getwindowname"],
capture_output=True,
text=True,
check=True,
)
window_title = title_result.stdout.strip().lower()
except (subprocess.CalledProcessError, FileNotFoundError):
pass
is_terminal = any(
keyword in window_class or keyword in window_title
for keyword in TERMINAL_KEYWORDS
)
logging.debug(f"Window class: {window_class}, is_terminal: {is_terminal}")
return is_terminal
except (subprocess.CalledProcessError, FileNotFoundError):
pass
logging.debug("Could not detect window type, defaulting to GUI paste")
return False
def paste_from_clipboard() -> bool:
"""Paste text from clipboard using the appropriate tool for the current display server."""
# Check if we're on Wayland
if os.getenv("WAYLAND_DISPLAY"):
logging.debug("Detected Wayland display server for pasting")
is_terminal = _detect_terminal_window()
# Use wtype for Wayland (simulates typing)
# Use Ctrl+Shift+V for terminals, Ctrl+V for GUI apps
try:
if is_terminal:
logging.debug("Attempting to paste using wtype with Ctrl+Shift+V (terminal)")
subprocess.run(["wtype", "-M", "ctrl", "-M", "shift", "v"], check=True)
logging.info("Pasted from clipboard (wtype with Ctrl+Shift+V)")
else:
logging.debug("Attempting to paste using wtype with Ctrl+V (GUI)")
subprocess.run(["wtype", "-M", "ctrl", "v"], check=True)
logging.info("Pasted from clipboard (wtype with Ctrl+V)")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
pass
# If wtype failed, try ydotool
try:
# Add small delay before paste to let window manager settle
time.sleep(0.1)
# Use key codes: 29 is left ctrl, 42 is left shift, 47 is v
# Format: "keycode:state" where :1 = key down, :0 = key up
if is_terminal:
logging.debug("Attempting to paste using ydotool with Ctrl+Shift+V (terminal)")
subprocess.run(["ydotool", "key", "29:1", "42:1", "47:1", "47:0", "42:0", "29:0"], check=True)
logging.info("Pasted from clipboard (ydotool with Ctrl+Shift+V)")
else:
logging.debug("Attempting to paste using ydotool with Ctrl+V (GUI)")
subprocess.run(["ydotool", "key", "29:1", "47:1", "47:0", "29:0"], check=True)
logging.info("Pasted from clipboard (ydotool with Ctrl+V)")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
# Final fallback: try wl-paste + dotool with layout settings
try:
logging.debug(
"Attempting to paste using dotool with layout settings"
)
# Load dotool configuration
config_manager = ConfigManager()
dotool_layout = config_manager.load_dotool_layout()
dotool_variant = config_manager.load_dotool_variant()
# Build command with optional environment variables
env_vars = []
if dotool_layout:
env_vars.append(f"DOTOOL_XKB_LAYOUT={dotool_layout}")
if dotool_variant:
env_vars.append(f"DOTOOL_XKB_VARIANT={dotool_variant}")
env_prefix = " ".join(env_vars)
if env_prefix:
command = f"wl-paste | sed 's/^/type /' | {env_prefix} dotool"
else:
command = "wl-paste | sed 's/^/type /' | dotool"
subprocess.run(
command,
shell=True,
check=True,
)
logging.info("Pasted from clipboard (dotool)")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
pass
# Check if we're on X11
if os.getenv("DISPLAY"):
is_terminal = _detect_terminal_window()
# Use xdotool for X11 - Ctrl+Shift+V for terminals, Ctrl+V for GUI apps
try:
if is_terminal:
logging.debug("Attempting to paste using xdotool with Ctrl+Shift+V (terminal)")
subprocess.run(["xdotool", "key", "ctrl+shift+v"], check=True)
logging.info("Pasted from clipboard (xdotool with Ctrl+Shift+V)")
else:
logging.debug("Attempting to paste using xdotool with Ctrl+V (GUI)")
subprocess.run(["xdotool", "key", "ctrl+v"], check=True)
logging.info("Pasted from clipboard (xdotool with Ctrl+V)")
return True
except (subprocess.CalledProcessError, FileNotFoundError) as e:
logging.warning(f"xdotool failed: {e}")
# Fallback: try all available paste tools
time.sleep(0.1)
paste_tools = [
["xdotool", "key", "ctrl+v"], # X11
["wtype", "-M", "ctrl", "v"], # Wayland
["ydotool", "key", "29:1", "47:1", "47:0", "29:0"], # Wayland alternative (ctrl+v)
]
for cmd in paste_tools:
try:
subprocess.run(cmd, check=True)
tool_name = cmd[0]
logging.info(f"Pasted from clipboard ({tool_name})")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
continue
logging.error("Failed to paste from clipboard: no suitable paste tool found")
logging.error("Available tools: xdotool (X11), wtype/ydotool (Wayland)")
return False
@contextmanager
def managed_subprocess(
args: list[str],
) -> Generator[subprocess.Popen[bytes], None, None]:
"""Context manager for subprocess handling with proper cleanup."""
proc = None
try:
proc = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
yield proc
finally:
if proc:
proc.terminate()
proc.wait()
class WhispypyDaemon:
"""Signal-controlled audio transcription daemon using OpenAI Whisper or NVIDIA Parakeet."""
def __init__(
self,
model_path: str,
device_name: str,
engine: str = "whisper",
parakeet_onnx_dir: Optional[str] = None,
parakeet_onnx_model_id: str = DEFAULT_SHERPA_ONNX_PARAKEET_INT8_MODEL,
parakeet_onnx_cache_dir: Optional[str] = None,
onnx_provider: str = "cpu",
onnx_threads: Optional[int] = None,
keep_audio: bool = False,
autopaste: bool = False,
):
self.model_path = model_path
self.device_name = device_name
self.engine = engine
self.parakeet_onnx_dir = parakeet_onnx_dir
self.parakeet_onnx_model_id = parakeet_onnx_model_id
self.parakeet_onnx_cache_dir = parakeet_onnx_cache_dir
self.onnx_provider = onnx_provider
self.onnx_threads = onnx_threads
self.keep_audio = keep_audio
self.autopaste = autopaste
# Create temporary file for audio recording with appropriate extension
audio_extension = ".wav" if engine in {"parakeet", "parakeet_onnx_int8"} else ".au"
self.temp_audio_file = Path(tempfile.gettempdir()) / (
TEMP_AUDIO_FILENAME + audio_extension
)
# State
self.recording = False
self.running = True
self.pw_record_proc: Optional[subprocess.Popen[bytes]] = None
# Model attribute - will be assigned in load methods
self.model: Any = None
# Load the appropriate model
if self.engine == "whisper":
self._load_whisper_model()
elif self.engine == "parakeet":
self._load_parakeet_model()
elif self.engine == "parakeet_onnx_int8":
self._load_parakeet_onnx_int8_model()
else:
raise ValueError(f"Unsupported engine: {self.engine}")
# Setup signal handlers
signal.signal(signal.SIGINT, self._handle_sigint)
signal.signal(signal.SIGUSR2, self._handle_sigusr2)
def _load_whisper_model(self) -> None:
"""Load Whisper model."""
logging.info(f"Loading Whisper model from {self.model_path}...")
model_load_start = time.time()
self.model = whisper.load_model(self.model_path)
model_load_time = time.time() - model_load_start
logging.info(f"Whisper model loaded in {model_load_time:.2f} seconds")
def _load_parakeet_model(self) -> None:
"""Load Parakeet model."""
try:
import nemo.collections.asr as nemo_asr
except ImportError:
raise ImportError(
"Parakeet (NeMo) is not available. Please see README for installation instructions."
)
logging.info(f"Loading Parakeet model from {self.model_path}...")
model_load_start = time.time()
self.model = nemo_asr.models.ASRModel.from_pretrained(
model_name=self.model_path
)
model_load_time = time.time() - model_load_start
logging.info(f"Parakeet model loaded in {model_load_time:.2f} seconds")
def _load_parakeet_onnx_int8_model(self) -> None:
"""Load Parakeet INT8 model via sherpa-onnx."""
if not self.parakeet_onnx_dir:
self.parakeet_onnx_dir = str(
ensure_sherpa_onnx_parakeet_model_dir(
model_id=self.parakeet_onnx_model_id,
cache_dir=self.parakeet_onnx_cache_dir,
)
)
self.model = SherpaOnnxParakeetInt8Transcriber(
model_dir=self.parakeet_onnx_dir,
provider=self.onnx_provider,
num_threads=self.onnx_threads,
)
def _is_alsa_device(self) -> bool:
"""Return True if device_name looks like a raw ALSA device."""
return self.device_name.startswith(("hw:", "plughw:"))
def _get_alsa_device(self) -> str:
"""Get ALSA device name, converting hw: to plughw: for format conversion."""
if self.device_name.startswith("hw:"):
return self.device_name.replace("hw:", "plughw:", 1)
return self.device_name
def validate_device(self) -> bool:
"""Validate that the audio device exists and is accessible."""
try:
# Test device by attempting a very short recording
audio_extension = (
".wav" if self.engine in {"parakeet", "parakeet_onnx_int8"} else ".au"
)
with tempfile.NamedTemporaryFile(
suffix=audio_extension, delete=False
) as test_file:
test_file_path = test_file.name
if self._is_alsa_device():
# ALSA: use arecord with the same device transformation as recording
with managed_subprocess(
[
"arecord",
"-D", self._get_alsa_device(),
"-f", "S16_LE",
"-r", str(SAMPLE_RATE),
"-c", str(CHANNELS),
"-t", "raw",
test_file_path,
]
) as _:
time.sleep(DEVICE_TEST_DURATION)
else:
# PipeWire: use pw-record
pw_format = AUDIO_FORMAT
if self.engine == "parakeet_onnx_int8":
pw_format = "s16"
with managed_subprocess(
[
"pw-record",
f"--target={self.device_name}",
f"--format={pw_format}",
f"--rate={SAMPLE_RATE}",
f"--channels={CHANNELS}",
test_file_path,
]
) as _:
# Let it record for the test duration then it will be terminated
time.sleep(DEVICE_TEST_DURATION)
size = Path(test_file_path).stat().st_size
# Clean up test file
Path(test_file_path).unlink(missing_ok=True)
if size == 0:
logging.debug("Device validation produced empty audio file")
return False