-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey_presser_gui.py
More file actions
1063 lines (875 loc) · 44.6 KB
/
key_presser_gui.py
File metadata and controls
1063 lines (875 loc) · 44.6 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
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import pyautogui
import time
import threading
import pygame
import os
import subprocess
import sounddevice as sd
import soundfile as sf
import numpy as np
# Import CoreAudio virtual mic creator
try:
from coreaudio_virtual_mic import CoreAudioVirtualMic
COREAUDIO_AVAILABLE = True
except ImportError:
COREAUDIO_AVAILABLE = False
class KeyPresserGUI:
def __init__(self, root):
self.root = root
self.root.title("Key Presser & Voice Dictation Timer")
self.root.geometry("700x800")
self.root.resizable(True, True)
self.root.minsize(700, 800)
# Apply modern styling
style = ttk.Style()
style.theme_use('aqua' if os.name == 'posix' else 'clam')
self.is_running = False
self.audio_file_path = None
self.virtual_mic_enabled = False
self.blackhole_device = None
self.audio_stream = None
self.audio_data = None
self.audio_samplerate = None
self.stop_audio_flag = False
self.audio_stop_time = None
self.first_text_time = None
self.last_text_time = None
self.initial_text_length = 0
self.key_press_start_time = None
self.key_release_time = None
# Initialize pygame mixer for audio playback
pygame.mixer.init()
# Detect BlackHole installation
self.detect_blackhole()
# Configure root window grid
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
# Create notebook for tabs
self.notebook = ttk.Notebook(root)
self.notebook.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=5, pady=5)
# Create main frame with better spacing
main_frame = ttk.Frame(self.notebook, padding="20")
self.notebook.add(main_frame, text="Single Run")
# Configure column weights for better layout
main_frame.columnconfigure(0, weight=0)
main_frame.columnconfigure(1, weight=1)
row = 0
# ===== KEY PRESS SECTION =====
section_label = ttk.Label(main_frame, text="⌨️ Key Press Configuration",
font=("TkDefaultFont", 12, "bold"))
section_label.grid(row=row, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
row += 1
# Key input
ttk.Label(main_frame, text="Key to press:", font=("TkDefaultFont", 10)).grid(
row=row, column=0, sticky=tk.W, pady=8, padx=(15, 10))
self.key_entry = ttk.Entry(main_frame, width=35, font=("TkDefaultFont", 10))
self.key_entry.grid(row=row, column=1, pady=8, sticky=(tk.W, tk.E))
row += 1
# Mode selection
ttk.Label(main_frame, text="Mode:", font=("TkDefaultFont", 10)).grid(
row=row, column=0, sticky=tk.W, pady=8, padx=(15, 10))
self.mode_var = tk.StringVar(value="hold")
mode_frame = ttk.Frame(main_frame)
mode_frame.grid(row=row, column=1, sticky=tk.W, pady=8)
ttk.Radiobutton(mode_frame, text="Press and hold", variable=self.mode_var,
value="hold").pack(anchor=tk.W, pady=2)
ttk.Radiobutton(mode_frame, text="Wait then press", variable=self.mode_var,
value="wait").pack(anchor=tk.W, pady=2)
row += 1
# Duration input
ttk.Label(main_frame, text="Duration (seconds):", font=("TkDefaultFont", 10)).grid(
row=row, column=0, sticky=tk.W, pady=8, padx=(15, 10))
self.duration_entry = ttk.Entry(main_frame, width=35, font=("TkDefaultFont", 10))
self.duration_entry.grid(row=row, column=1, pady=8, sticky=(tk.W, tk.E))
row += 1
# Separator
ttk.Separator(main_frame, orient='horizontal').grid(
row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=20)
row += 1
# ===== AUDIO SECTION =====
section_label = ttk.Label(main_frame, text="🎵 Audio Configuration",
font=("TkDefaultFont", 12, "bold"))
section_label.grid(row=row, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
row += 1
# Audio file section
ttk.Label(main_frame, text="Audio File:", font=("TkDefaultFont", 10)).grid(
row=row, column=0, sticky=tk.W, pady=8, padx=(15, 10))
audio_frame = ttk.Frame(main_frame)
audio_frame.grid(row=row, column=1, sticky=(tk.W, tk.E), pady=8)
self.audio_label = ttk.Label(audio_frame, text="No file selected",
foreground="gray", font=("TkDefaultFont", 9))
self.audio_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Button(audio_frame, text="Browse...", command=self.browse_audio,
width=12).pack(side=tk.LEFT, padx=(10, 0))
row += 1
# Enable audio checkbox
self.enable_audio_var = tk.BooleanVar(value=False)
self.enable_audio_check = ttk.Checkbutton(
main_frame, text="Play audio simultaneously with key press",
variable=self.enable_audio_var)
self.enable_audio_check.grid(row=row, column=0, columnspan=2, pady=8, padx=(15, 15), sticky=tk.W)
row += 1
# Virtual Microphone section
vm_container = ttk.Frame(main_frame)
vm_container.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=8, padx=(15, 15))
ttk.Label(vm_container, text="Virtual Mic:", font=("TkDefaultFont", 10)).pack(side=tk.LEFT)
self.vm_status_label = ttk.Label(vm_container, text="", font=("TkDefaultFont", 9))
self.vm_status_label.pack(side=tk.LEFT, padx=(10, 0))
self.vm_toggle_button = ttk.Button(vm_container, text="Enable",
command=self.toggle_virtual_mic, width=12)
self.vm_toggle_button.pack(side=tk.LEFT, padx=(10, 0))
row += 1
# Update virtual mic status
self.update_vm_status()
# Separator
ttk.Separator(main_frame, orient='horizontal').grid(
row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=20)
row += 1
# ===== DICTATION SECTION =====
section_label = ttk.Label(main_frame, text="🎤 Dictation Output & Timing",
font=("TkDefaultFont", 12, "bold"))
section_label.grid(row=row, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
row += 1
# Dictation text box
dictation_container = ttk.LabelFrame(main_frame, text="Click here to start • Voice dictation will appear here",
padding="10")
dictation_container.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E),
pady=8, padx=(15, 15))
# Text area with scrollbar
text_frame = ttk.Frame(dictation_container)
text_frame.pack(fill=tk.BOTH, expand=True)
self.dictation_text = tk.Text(text_frame, height=5, wrap=tk.WORD,
font=("TkDefaultFont", 10), relief=tk.SOLID,
borderwidth=1, highlightthickness=1)
self.dictation_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Bind multiple events to catch all text changes
self.dictation_text.bind('<KeyRelease>', self.on_dictation_text_change)
self.dictation_text.bind('<<Modified>>', self.on_dictation_modified)
self.dictation_text.bind('<Button-1>', self.on_dictation_click)
scrollbar = ttk.Scrollbar(text_frame, orient=tk.VERTICAL,
command=self.dictation_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.dictation_text.config(yscrollcommand=scrollbar.set)
# Clear button below the text box
button_frame = ttk.Frame(dictation_container)
button_frame.pack(fill=tk.X, pady=(10, 0))
self.clear_button = ttk.Button(button_frame, text="🗑️ Clear", command=self.clear_dictation, width=15)
self.clear_button.pack(side=tk.RIGHT)
row += 1
# Timing metrics in a nice frame
timing_frame = ttk.LabelFrame(main_frame, text="Timing Metrics", padding="10")
timing_frame.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E),
pady=8, padx=(15, 15))
self.timing_label = ttk.Label(timing_frame, text="Waiting for dictation...",
foreground="#666666", font=("TkDefaultFont", 9))
self.timing_label.pack(fill=tk.X)
row += 1
# Separator
ttk.Separator(main_frame, orient='horizontal').grid(
row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=20)
row += 1
# Status label
self.status_label = ttk.Label(main_frame, text="⚫ Ready - Click on dictation box to start", foreground="#28a745",
font=("TkDefaultFont", 11, "bold"))
self.status_label.grid(row=row, column=0, columnspan=2, pady=(10, 15))
row += 1
# Execute button (hidden by default, keeping for backwards compatibility)
self.execute_button = ttk.Button(main_frame, text="▶ Execute", command=self.execute)
# Not gridding it - button is now hidden since we trigger on click
# Set default values
self.key_entry.insert(0, "fn")
self.duration_entry.insert(0, "2")
# Automatically set up virtual microphone on startup
if COREAUDIO_AVAILABLE:
threading.Thread(target=self.auto_setup_virtual_mic, daemon=True).start()
# Create batch tab
self.create_batch_tab()
def create_batch_tab(self):
"""Create the batch execution tab."""
# Create batch frame
batch_frame = ttk.Frame(self.notebook, padding="20")
self.notebook.add(batch_frame, text="Batch Run")
# Configure column weights
batch_frame.columnconfigure(0, weight=0)
batch_frame.columnconfigure(1, weight=1)
row = 0
# ===== BATCH CONFIGURATION SECTION =====
section_label = ttk.Label(batch_frame, text="🔄 Batch Configuration",
font=("TkDefaultFont", 12, "bold"))
section_label.grid(row=row, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
row += 1
# Number of runs
ttk.Label(batch_frame, text="Number of runs:", font=("TkDefaultFont", 10)).grid(
row=row, column=0, sticky=tk.W, pady=8, padx=(15, 10))
self.batch_count_entry = ttk.Entry(batch_frame, width=35, font=("TkDefaultFont", 10))
self.batch_count_entry.insert(0, "5")
self.batch_count_entry.grid(row=row, column=1, pady=8, sticky=(tk.W, tk.E))
row += 1
# Interval between runs
ttk.Label(batch_frame, text="Interval (seconds):", font=("TkDefaultFont", 10)).grid(
row=row, column=0, sticky=tk.W, pady=8, padx=(15, 10))
self.batch_interval_entry = ttk.Entry(batch_frame, width=35, font=("TkDefaultFont", 10))
self.batch_interval_entry.insert(0, "1")
self.batch_interval_entry.grid(row=row, column=1, pady=8, sticky=(tk.W, tk.E))
row += 1
# Note about configuration
note_label = ttk.Label(batch_frame,
text="Note: Batch will use configuration from Single Run tab",
font=("TkDefaultFont", 9), foreground="#666666")
note_label.grid(row=row, column=0, columnspan=2, pady=8, padx=(15, 15), sticky=tk.W)
row += 1
# Separator
ttk.Separator(batch_frame, orient='horizontal').grid(
row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=20)
row += 1
# ===== BATCH RESULTS SECTION =====
section_label = ttk.Label(batch_frame, text="📊 Results",
font=("TkDefaultFont", 12, "bold"))
section_label.grid(row=row, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
row += 1
# Results text box with scrollbar
results_container = ttk.LabelFrame(batch_frame, text="Batch Results", padding="10")
results_container.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S),
pady=8, padx=(15, 15))
# Configure row to expand
batch_frame.rowconfigure(row, weight=1)
text_frame = ttk.Frame(results_container)
text_frame.pack(fill=tk.BOTH, expand=True)
self.batch_results_text = tk.Text(text_frame, height=30, wrap=tk.WORD,
font=("Courier", 10), relief=tk.SOLID,
borderwidth=1, state='disabled')
self.batch_results_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar = ttk.Scrollbar(text_frame, orient=tk.VERTICAL,
command=self.batch_results_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.batch_results_text.config(yscrollcommand=scrollbar.set)
row += 1
# Clear and copy buttons below the results container
button_frame = ttk.Frame(batch_frame)
button_frame.grid(row=row, column=0, columnspan=2, pady=(5, 8), padx=(15, 15), sticky=tk.E)
ttk.Button(button_frame, text="📋 Copy Results",
command=self.copy_batch_results, width=15).pack(side=tk.LEFT, padx=(0, 5))
ttk.Button(button_frame, text="🗑️ Clear Results",
command=self.clear_batch_results, width=15).pack(side=tk.LEFT)
row += 1
# Separator
ttk.Separator(batch_frame, orient='horizontal').grid(
row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=20)
row += 1
# ===== BATCH TRIGGER SECTION =====
section_label = ttk.Label(batch_frame, text="🎤 Batch Trigger",
font=("TkDefaultFont", 12, "bold"))
section_label.grid(row=row, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
row += 1
# Trigger text box
trigger_container = ttk.LabelFrame(batch_frame, text="Click here to start batch execution",
padding="10")
trigger_container.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E),
pady=8, padx=(15, 15))
# Text area with scrollbar
trigger_text_frame = ttk.Frame(trigger_container)
trigger_text_frame.pack(fill=tk.BOTH, expand=True)
self.batch_trigger_text = tk.Text(trigger_text_frame, height=3, wrap=tk.WORD,
font=("TkDefaultFont", 10), relief=tk.SOLID,
borderwidth=1, highlightthickness=1)
self.batch_trigger_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Bind click event to start batch
self.batch_trigger_text.bind('<Button-1>', self.on_batch_trigger_click)
# Bind text change events to track timing
self.batch_trigger_text.bind('<KeyRelease>', self.on_dictation_text_change)
self.batch_trigger_text.bind('<<Modified>>', self.on_dictation_modified)
trigger_scrollbar = ttk.Scrollbar(trigger_text_frame, orient=tk.VERTICAL,
command=self.batch_trigger_text.yview)
trigger_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.batch_trigger_text.config(yscrollcommand=trigger_scrollbar.set)
# Clear trigger button
trigger_button_frame = ttk.Frame(trigger_container)
trigger_button_frame.pack(fill=tk.X, pady=(10, 0))
ttk.Button(trigger_button_frame, text="🗑️ Clear",
command=self.clear_batch_trigger, width=15).pack(side=tk.RIGHT)
row += 1
# Separator
ttk.Separator(batch_frame, orient='horizontal').grid(
row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=20)
row += 1
# Batch status
self.batch_status_label = ttk.Label(batch_frame, text="⚫ Ready - Click on trigger box to start",
foreground="#28a745",
font=("TkDefaultFont", 11, "bold"))
self.batch_status_label.grid(row=row, column=0, columnspan=2, pady=(10, 15))
row += 1
# Stop batch button (initially hidden)
self.stop_batch_button = ttk.Button(batch_frame, text="⏹ Stop Batch",
command=self.stop_batch_execution,
style='Accent.TButton')
self.stop_batch_button.grid(row=row, column=0, columnspan=2, pady=10)
self.stop_batch_button.grid_remove() # Hide initially
# Batch execution state
self.batch_running = False
self.batch_stop_requested = False
self.batch_results = []
def clear_batch_trigger(self):
"""Clear the batch trigger text box."""
self.batch_trigger_text.delete("1.0", tk.END)
def on_batch_trigger_click(self, event=None):
"""Handle click on batch trigger text box to start batch execution."""
# Only start if not already running
if not self.batch_running and not self.is_running:
self.execute_batch()
return None
def stop_batch_execution(self):
"""Stop the batch execution."""
self.batch_stop_requested = True
self.update_batch_status("Stopping batch...", "orange")
self.stop_batch_button.grid_remove()
def copy_batch_results(self):
"""Copy the batch results to clipboard."""
results_text = self.batch_results_text.get("1.0", tk.END).strip()
if results_text:
self.root.clipboard_clear()
self.root.clipboard_append(results_text)
self.update_batch_status("Results copied to clipboard", "green")
# Reset status after 2 seconds
self.root.after(2000, lambda: self.update_batch_status("Ready - Click on trigger box to start", "#28a745"))
else:
messagebox.showinfo("No Results", "No batch results to copy")
def clear_batch_results(self):
"""Clear the batch results display."""
self.batch_results_text.config(state='normal')
self.batch_results_text.delete("1.0", tk.END)
self.batch_results_text.config(state='disabled')
self.batch_results = []
def update_batch_status(self, message, color="blue"):
"""Update the batch tab status label."""
icon = "⚫"
if color in ["green", "#28a745"]:
icon = "✓"
elif color == "red":
icon = "✗"
elif color in ["blue", "orange"]:
icon = "▶"
self.batch_status_label.config(text=f"{icon} {message}", foreground=color)
def append_batch_result(self, text):
"""Append text to the batch results display."""
self.batch_results_text.config(state='normal')
self.batch_results_text.insert(tk.END, text + "\n")
self.batch_results_text.see(tk.END)
self.batch_results_text.config(state='disabled')
def execute_batch(self):
"""Execute batch runs with the specified configuration."""
if self.batch_running or self.is_running:
messagebox.showwarning("Warning", "Operation already in progress")
return
# Validate batch parameters
try:
batch_count = int(self.batch_count_entry.get())
if batch_count <= 0:
messagebox.showerror("Error", "Number of runs must be positive")
return
except ValueError:
messagebox.showerror("Error", "Invalid number of runs")
return
try:
batch_interval = float(self.batch_interval_entry.get())
if batch_interval < 0:
messagebox.showerror("Error", "Interval must be non-negative")
return
except ValueError:
messagebox.showerror("Error", "Invalid interval value")
return
# Validate single run configuration
key = self.key_entry.get().strip()
if not key:
messagebox.showerror("Error", "Please enter a key in the Single Run tab")
return
try:
duration = float(self.duration_entry.get())
if duration <= 0:
messagebox.showerror("Error", "Duration must be positive")
return
except ValueError:
messagebox.showerror("Error", "Invalid duration value in Single Run tab")
return
mode = self.mode_var.get()
enable_audio = self.enable_audio_var.get()
if enable_audio and not self.audio_file_path:
messagebox.showerror("Error", "Please select an audio file or disable audio playback")
return
# Clear previous results
self.clear_batch_results()
# Reset stop flag and show stop button
self.batch_stop_requested = False
self.stop_batch_button.grid()
# Run batch in separate thread
thread = threading.Thread(target=self.perform_batch_runs,
args=(batch_count, batch_interval, key, duration, mode, enable_audio))
thread.daemon = True
thread.start()
def perform_batch_runs(self, batch_count, batch_interval, key, duration, mode, enable_audio):
"""Perform multiple runs and collect timing data."""
self.batch_running = True
self.batch_results = []
try:
self.append_batch_result("=" * 60)
self.append_batch_result(f"BATCH EXECUTION STARTED")
self.append_batch_result(f"Configuration: Key='{key}', Duration={duration}s, Mode={mode}")
self.append_batch_result(f"Runs: {batch_count}, Interval: {batch_interval}s")
self.append_batch_result("=" * 60)
self.append_batch_result("")
for i in range(batch_count):
# Check if stop was requested
if self.batch_stop_requested:
self.append_batch_result(f"\nBatch stopped by user after {i} runs")
self.append_batch_result("=" * 60)
break
self.update_batch_status(f"Running {i+1}/{batch_count}...", "blue")
# Clear batch trigger text box before each run
self.batch_trigger_text.delete("1.0", tk.END)
# Reset timing for this run
self.reset_timing_metrics()
# Record start time
run_start_time = time.time()
# Perform the action
self.is_running = True
try:
if mode == "hold":
if enable_audio:
self.play_audio()
self.key_press_start_time = time.time()
pyautogui.keyDown(key)
time.sleep(duration)
pyautogui.keyUp(key)
self.key_release_time = time.time()
if enable_audio:
self.stop_audio()
else: # wait mode
time.sleep(duration)
if enable_audio:
self.play_audio()
self.key_press_start_time = time.time()
pyautogui.press(key)
self.key_release_time = time.time()
if enable_audio:
self.stop_audio()
# Wait to collect timing data from dictation
# Monitor for text changes for up to 5 seconds
wait_start = time.time()
last_check_time = self.last_text_time
while time.time() - wait_start < 5:
time.sleep(0.2)
# If text stopped changing for 1 second, we're done
if self.last_text_time and self.last_text_time == last_check_time:
if time.time() - self.last_text_time > 1:
break
last_check_time = self.last_text_time
# Record results
run_end_time = time.time()
total_run_time = run_end_time - run_start_time
result = {
'run': i + 1,
'total_time': total_run_time,
'key_press_start': self.key_press_start_time,
'key_release': self.key_release_time,
'first_text_time': self.first_text_time,
'last_text_time': self.last_text_time
}
# Calculate timing metrics
time_to_first = None
time_to_last = None
dictation_duration = None
end_to_end = None
if self.key_release_time and self.first_text_time:
time_to_first = self.first_text_time - self.key_release_time
result['time_to_first'] = time_to_first
if self.key_release_time and self.last_text_time:
time_to_last = self.last_text_time - self.key_release_time
result['time_to_last'] = time_to_last
if self.first_text_time and self.last_text_time:
dictation_duration = self.last_text_time - self.first_text_time
result['dictation_duration'] = dictation_duration
if self.key_press_start_time and self.last_text_time:
end_to_end = self.last_text_time - self.key_press_start_time
result['end_to_end'] = end_to_end
self.batch_results.append(result)
# Display result
self.append_batch_result(f"Run #{i+1}:")
if time_to_first is not None:
self.append_batch_result(f" Time to first text: {time_to_first:.3f}s")
if time_to_last is not None:
self.append_batch_result(f" Time to last text: {time_to_last:.3f}s")
if dictation_duration is not None:
self.append_batch_result(f" Dictation duration: {dictation_duration:.3f}s")
if end_to_end is not None:
self.append_batch_result(f" End-to-end time: {end_to_end:.3f}s")
if time_to_first is None and time_to_last is None:
self.append_batch_result(f" No dictation detected")
self.append_batch_result("")
except Exception as e:
self.append_batch_result(f"Run #{i+1}: ERROR - {str(e)}")
self.append_batch_result("")
finally:
self.is_running = False
if enable_audio:
self.stop_audio()
# Wait interval before next run (except after last run)
if i < batch_count - 1:
self.update_batch_status(f"Waiting {batch_interval}s before next run...", "orange")
time.sleep(batch_interval)
# Calculate and display summary statistics
self.append_batch_result("=" * 60)
self.append_batch_result("SUMMARY STATISTICS")
self.append_batch_result("=" * 60)
if self.batch_results:
# Calculate averages
times_to_first = [r['time_to_first'] for r in self.batch_results if 'time_to_first' in r]
times_to_last = [r['time_to_last'] for r in self.batch_results if 'time_to_last' in r]
dictation_durations = [r['dictation_duration'] for r in self.batch_results if 'dictation_duration' in r]
end_to_ends = [r['end_to_end'] for r in self.batch_results if 'end_to_end' in r]
if times_to_first:
avg_first = sum(times_to_first) / len(times_to_first)
min_first = min(times_to_first)
max_first = max(times_to_first)
self.append_batch_result(f"Time to first text:")
self.append_batch_result(f" Average: {avg_first:.3f}s")
self.append_batch_result(f" Min: {min_first:.3f}s")
self.append_batch_result(f" Max: {max_first:.3f}s")
self.append_batch_result("")
if times_to_last:
avg_last = sum(times_to_last) / len(times_to_last)
min_last = min(times_to_last)
max_last = max(times_to_last)
self.append_batch_result(f"Time to last text:")
self.append_batch_result(f" Average: {avg_last:.3f}s")
self.append_batch_result(f" Min: {min_last:.3f}s")
self.append_batch_result(f" Max: {max_last:.3f}s")
self.append_batch_result("")
if dictation_durations:
avg_duration = sum(dictation_durations) / len(dictation_durations)
min_duration = min(dictation_durations)
max_duration = max(dictation_durations)
self.append_batch_result(f"Dictation duration:")
self.append_batch_result(f" Average: {avg_duration:.3f}s")
self.append_batch_result(f" Min: {min_duration:.3f}s")
self.append_batch_result(f" Max: {max_duration:.3f}s")
self.append_batch_result("")
if end_to_ends:
avg_e2e = sum(end_to_ends) / len(end_to_ends)
min_e2e = min(end_to_ends)
max_e2e = max(end_to_ends)
self.append_batch_result(f"End-to-end time:")
self.append_batch_result(f" Average: {avg_e2e:.3f}s")
self.append_batch_result(f" Min: {min_e2e:.3f}s")
self.append_batch_result(f" Max: {max_e2e:.3f}s")
self.append_batch_result("")
successful_runs = len([r for r in self.batch_results if 'time_to_first' in r])
self.append_batch_result(f"Successful runs with dictation: {successful_runs}/{batch_count}")
self.append_batch_result("=" * 60)
self.update_batch_status("Batch completed", "green")
except Exception as e:
self.append_batch_result(f"BATCH ERROR: {str(e)}")
self.update_batch_status(f"Error: {str(e)}", "red")
finally:
self.batch_running = False
self.stop_batch_button.grid_remove()
if self.batch_stop_requested:
self.update_batch_status("Batch stopped", "orange")
def auto_setup_virtual_mic(self):
"""Automatically create virtual microphone device on startup."""
try:
vm = CoreAudioVirtualMic()
# Check if device already exists
if vm.device_exists():
self.root.after(0, lambda: self.update_status(
"✓ Virtual microphone detected", "green"))
else:
# Show status
self.root.after(0, lambda: self.update_status(
"Creating virtual microphone...", "orange"))
# Create the device
success = vm.setup()
if success:
# Re-detect devices
time.sleep(2)
self.root.after(0, self.detect_blackhole)
self.root.after(0, self.update_vm_status)
self.root.after(0, lambda: self.update_status(
"✓ Virtual microphone ready!", "green"))
else:
self.root.after(0, lambda: self.update_status(
"Ready - Virtual mic setup pending", "orange"))
except Exception as e:
print(f"Auto setup error: {e}")
# Don't show error to user as this runs in background
def detect_blackhole(self):
"""Detect if BlackHole is installed on the system."""
try:
devices = sd.query_devices()
for i, device in enumerate(devices):
if 'BlackHole' in device['name'] and device['max_output_channels'] > 0:
self.blackhole_device = i
return
self.blackhole_device = None
except Exception as e:
print(f"Error detecting BlackHole: {e}")
self.blackhole_device = None
def update_vm_status(self):
"""Update the virtual microphone status display."""
if self.blackhole_device is None:
self.vm_status_label.config(text="BlackHole not detected", foreground="red")
self.vm_toggle_button.config(state="disabled")
else:
if self.virtual_mic_enabled:
self.vm_status_label.config(text="Enabled", foreground="green")
self.vm_toggle_button.config(text="Disable")
else:
self.vm_status_label.config(text="Disabled", foreground="orange")
self.vm_toggle_button.config(text="Enable")
def clear_dictation(self):
"""Clear the dictation text box and reset timing metrics."""
self.dictation_text.delete("1.0", tk.END)
self.reset_timing_metrics()
def on_dictation_click(self, event=None):
"""Handle click on dictation text box to start the process."""
# Only start if not already running
if not self.is_running:
self.execute()
# Return 'break' to prevent default text widget behavior if needed, or None to allow normal click behavior
return None
def on_dictation_modified(self, event=None):
"""Handle the <<Modified>> event which fires on any text change including paste."""
# Determine which text widget triggered the event
widget = event.widget if event else self.dictation_text
if hasattr(widget, 'edit_modified') and widget.edit_modified():
# Reset the modified flag
widget.edit_modified(False)
# Call the text change handler
self.on_dictation_text_change(event)
def on_dictation_text_change(self, event=None):
"""Track timing when text is input into the dictation box or batch trigger box."""
current_time = time.time()
# Determine which text widget to read from
if event and hasattr(event, 'widget'):
widget = event.widget
else:
widget = self.dictation_text
current_text = widget.get("1.0", tk.END).strip()
current_length = len(current_text)
# Only track if key has been released (we're in a dictation session)
if self.key_release_time is None:
return
# Check if this is the first text input
if current_length > self.initial_text_length and self.first_text_time is None:
self.first_text_time = current_time
time_to_first = self.first_text_time - self.key_release_time
self.timing_label.config(text=f"⏱️ First text detected: {time_to_first:.3f}s", foreground="#007ACC")
# Update last text time whenever text changes
if current_length > self.initial_text_length:
self.last_text_time = current_time
# Calculate all metrics if we have both first and last text times
if self.first_text_time is not None:
time_to_first = self.first_text_time - self.key_release_time
time_to_last = self.last_text_time - self.key_release_time
total_dictation_time = self.last_text_time - self.first_text_time
# Calculate end-to-end time from key press start to last text
end_to_end_time = None
if self.key_press_start_time is not None:
end_to_end_time = self.last_text_time - self.key_press_start_time
timing_text = f"⏱️ First: {time_to_first:.3f}s • Last: {time_to_last:.3f}s • Duration: {total_dictation_time:.3f}s"
if end_to_end_time is not None:
timing_text += f" • End-to-End: {end_to_end_time:.3f}s"
self.timing_label.config(text=timing_text, foreground="#2E7D32")
def reset_timing_metrics(self):
"""Reset timing metrics for a new dictation session."""
self.audio_stop_time = None
self.first_text_time = None
self.last_text_time = None
self.key_press_start_time = None
self.key_release_time = None
# Use batch trigger text length if in batch mode, otherwise use dictation text
if self.batch_running:
self.initial_text_length = len(self.batch_trigger_text.get("1.0", tk.END).strip())
else:
self.initial_text_length = len(self.dictation_text.get("1.0", tk.END).strip())
self.timing_label.config(text="Waiting for dictation...", foreground="#666666")
def toggle_virtual_mic(self):
"""Toggle virtual microphone routing on/off."""
if self.blackhole_device is None:
messagebox.showerror("Error",
"BlackHole not detected. Please install BlackHole:\nbrew install blackhole-2ch")
return
self.virtual_mic_enabled = not self.virtual_mic_enabled
self.update_vm_status()
if self.virtual_mic_enabled:
# Initialize pygame mixer with BlackHole output
try:
pygame.mixer.quit()
# Note: pygame doesn't support selecting output device directly
# Audio will play through default output
# User needs to configure system to route audio to BlackHole
pygame.mixer.init()
messagebox.showinfo("Virtual Microphone",
"Virtual microphone enabled.\n\n"
"Note: You may need to configure your system audio settings to route "
"Python audio output to BlackHole in Audio MIDI Setup.\n\n"
"Other apps can now select BlackHole as their microphone input.")
except Exception as e:
messagebox.showerror("Error", f"Failed to enable virtual microphone: {e}")
self.virtual_mic_enabled = False
self.update_vm_status()
else:
# Reset to default output
pygame.mixer.quit()
pygame.mixer.init()
def browse_audio(self):
"""Open file dialog to select audio file."""
file_path = filedialog.askopenfilename(
title="Select Audio File",
filetypes=[
("Audio Files", "*.mp3 *.wav *.ogg *.flac"),
("MP3 Files", "*.mp3"),
("WAV Files", "*.wav"),
("OGG Files", "*.ogg"),
("FLAC Files", "*.flac"),
("All Files", "*.*")
]
)
if file_path:
self.audio_file_path = file_path
filename = os.path.basename(file_path)
self.audio_label.config(text=filename, foreground="black")
self.enable_audio_var.set(True)
def execute(self):
if self.is_running:
messagebox.showwarning("Warning", "Operation already in progress")
return
key = self.key_entry.get().strip()
if not key:
messagebox.showerror("Error", "Please enter a key")
return
try:
duration = float(self.duration_entry.get())
if duration <= 0:
messagebox.showerror("Error", "Duration must be positive")
return
except ValueError:
messagebox.showerror("Error", "Invalid duration value")
return
mode = self.mode_var.get()
# Check if audio is enabled
enable_audio = self.enable_audio_var.get()
if enable_audio and not self.audio_file_path:
messagebox.showerror("Error", "Please select an audio file or disable audio playback")
return
# Reset timing metrics for new session
self.reset_timing_metrics()
# Run in separate thread to avoid freezing GUI
thread = threading.Thread(target=self.perform_action, args=(key, duration, mode, enable_audio))
thread.daemon = True
thread.start()
def play_audio(self):
"""Play the selected audio file through virtual microphone (BlackHole)."""
if self.audio_file_path:
try:
# Load audio file
self.audio_data, self.audio_samplerate = sf.read(self.audio_file_path)
# Ensure audio is in the right format
if len(self.audio_data.shape) == 1:
# Mono audio, convert to stereo for compatibility
self.audio_data = np.column_stack((self.audio_data, self.audio_data))
self.stop_audio_flag = False
# Play through BlackHole if enabled, otherwise default device
device = self.blackhole_device if self.virtual_mic_enabled else None
def audio_callback(outdata, frames, time_info, status):
if self.stop_audio_flag:
raise sd.CallbackStop()
chunk = self.audio_data[:frames]
if len(chunk) < frames:
outdata[:len(chunk)] = chunk
outdata[len(chunk):] = 0
raise sd.CallbackStop()
else:
outdata[:] = chunk
self.audio_data = self.audio_data[frames:]
self.audio_stream = sd.OutputStream(
device=device,
samplerate=self.audio_samplerate,
channels=2,
callback=audio_callback
)
self.audio_stream.start()
except Exception as e:
self.update_status(f"Audio error: {str(e)}", "red")
def stop_audio(self):
"""Stop audio playback immediately."""
self.stop_audio_flag = True
if self.audio_stream:
try:
self.audio_stream.stop()
self.audio_stream.close()
self.audio_stream = None
except:
pass
# Mark the time when audio stopped to start tracking dictation timing
self.audio_stop_time = time.time()
def perform_action(self, key, duration, mode, enable_audio):
self.is_running = True
self.execute_button.config(state="disabled")
try:
if mode == "hold":
self.update_status(f"Pressing and holding '{key}' for {duration}s...")
# Start audio if enabled
if enable_audio:
self.play_audio()