-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeakpaste.py
More file actions
1395 lines (1175 loc) · 54.5 KB
/
Copy pathspeakpaste.py
File metadata and controls
1395 lines (1175 loc) · 54.5 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
"""
SpeakPaste - Voice to Text
Hold Win+Alt to record, release to transcribe and paste.
Transcription engines (stt_engine):
google — Google Speech API (unofficial, free, no key) [default]
groq — Groq Whisper API (requires API key)
google-ext — Chrome extension + Offscreen Document (Chrome in background)
google-cloud — Google Cloud Speech-to-Text REST API (requires API key)
Prompt modes (prompt_mode):
off — paste raw transcript [default]
gemini-lite — transcript → Gemini Flash Lite → English prompt
gemini-flash — voice → Gemini Flash directly (bypasses transcription engine)
"""
import keyboard
import requests
import tempfile
import os
import sys
import threading
import datetime
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
if hasattr(sys.stderr, 'reconfigure'):
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
import time
import winreg
import ctypes
import json
import asyncio
import tkinter as tk
from tkinter import ttk, messagebox
from ctypes import wintypes
from queue import Queue, Empty
from collections import deque
import pystray
from PIL import Image, ImageDraw
# Get app directory (works for both script and exe)
if getattr(sys, 'frozen', False):
APP_DIR = os.path.dirname(sys.executable)
else:
APP_DIR = os.path.dirname(os.path.abspath(__file__))
VERSION = "1.8.0"
GITHUB_REPO = "mohammad-rj/speakpaste"
GITHUB_URL = f"https://github.com/{GITHUB_REPO}"
SETTINGS_FILE = os.path.join(APP_DIR, 'settings.json')
GROQ_API_URL = "https://api.groq.com/openai/v1/audio/transcriptions"
SAMPLE_RATE = 16000
CHANNELS = 1
GEMINI_DEFAULT_SYSTEM_PROMPT = (
"You are a voice-to-prompt converter inside a coding chatbot. "
"The user speaks conversationally (in any language) to describe what they want to code. "
"Your job: output ONLY the English prompt the user would type to an AI coding assistant. "
"Keep it close to the original intent — do not add features or details the user didn't mention. "
"If the request is short and simple, keep the output short and simple. "
"Output nothing else — no explanation, no 'here is your prompt', no quotes, just the prompt.\n\n"
"Examples:\n"
"Input: یه تابع بنویس که لیست رو sort کنه\n"
"Output: Write a function that sorts a list.\n\n"
"Input: میخوام بدونم چرا این کد کار نمیکنه\n"
"Output: Why is this code not working?\n\n"
"Input: یه کلاس پایتون برای مدیریت کاربر بنویس با login و logout\n"
"Output: Write a Python class for user management with login and logout methods."
)
_DEFAULTS = {
"stt_engine": "google",
"prompt_mode": "off",
"hotkey": "win+alt",
"language": "fa",
"mic_mode": "always",
"groq_api_key": "",
"model": "whisper-large-v3-turbo",
"google_cloud_api_key": "",
"ws_port": 9137,
"check_updates": True,
"gemini_api_key": "",
"gemini_system_prompt": GEMINI_DEFAULT_SYSTEM_PROMPT,
"lang_mode": "fixed",
"gemini_thinking_level": "LOW",
"gemini_media_resolution": "LOW",
}
# ─── Settings Load / Save ─────────────────────────────────────────────────────
def load_settings():
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
cfg = {**_DEFAULTS, **data}
# Migrate old engine + gemini_stt_engine fields to stt_engine + prompt_mode
if "stt_engine" not in data:
old_engine = data.get("engine", "google")
old_gemini_stt = data.get("gemini_stt_engine", "google")
if old_engine in ("gemini-lite", "gemini-flash"):
cfg["stt_engine"] = old_gemini_stt if old_engine == "gemini-lite" else "google"
cfg["prompt_mode"] = old_engine
else:
cfg["stt_engine"] = old_engine
cfg["prompt_mode"] = "off"
return cfg
except Exception:
pass
# Fallback: read from old .env
env_path = os.path.join(APP_DIR, '.env')
cfg = dict(_DEFAULTS)
if os.path.exists(env_path):
try:
from dotenv import dotenv_values
ev = dotenv_values(env_path)
old_engine = ev.get("ENGINE", "google")
if old_engine in ("gemini-lite", "gemini-flash"):
cfg["stt_engine"] = "google"
cfg["prompt_mode"] = old_engine
else:
cfg["stt_engine"] = old_engine
cfg["prompt_mode"] = "off"
if ev.get("HOTKEY"): cfg["hotkey"] = ev["HOTKEY"]
if ev.get("LANGUAGE"): cfg["language"] = ev["LANGUAGE"]
if ev.get("MIC_MODE"): cfg["mic_mode"] = ev["MIC_MODE"]
if ev.get("GROQ_API_KEY"): cfg["groq_api_key"] = ev["GROQ_API_KEY"]
if ev.get("MODEL"): cfg["model"] = ev["MODEL"]
if ev.get("WS_PORT"): cfg["ws_port"] = int(ev["WS_PORT"])
except Exception:
pass
return cfg
def save_settings(cfg):
with open(SETTINGS_FILE, 'w', encoding='utf-8') as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
# ─── Config (mutable globals) ─────────────────────────────────────────────────
_cfg = load_settings()
STT_ENGINE = _cfg["stt_engine"]
PROMPT_MODE = _cfg["prompt_mode"]
HOTKEY = _cfg["hotkey"]
LANGUAGE = _cfg["language"]
MIC_MODE = _cfg["mic_mode"]
GROQ_API_KEY = _cfg["groq_api_key"]
MODEL = _cfg["model"]
GOOGLE_CLOUD_API_KEY = _cfg["google_cloud_api_key"]
WS_PORT = _cfg["ws_port"]
CHECK_UPDATES = _cfg["check_updates"]
GEMINI_API_KEY = _cfg.get("gemini_api_key", "")
GEMINI_SYSTEM_PROMPT = _cfg.get("gemini_system_prompt", GEMINI_DEFAULT_SYSTEM_PROMPT)
LANG_MODE = _cfg.get("lang_mode", "fixed")
GEMINI_THINKING_LEVEL = _cfg.get("gemini_thinking_level", "LOW")
GEMINI_MEDIA_RESOLUTION = _cfg.get("gemini_media_resolution", "LOW")
_session_lang = LANGUAGE # language captured at hotkey press time
_last_stt = None # intermediate STT text captured inside _transcribe_gemini
_history = deque(maxlen=50)
_history_window = None
# ─── State ────────────────────────────────────────────────────────────────────
is_recording = False
is_hotkey_active = False
audio_queue = Queue()
logs = deque(maxlen=20)
tray_icon = None
audio_stream = None
running = True
_pre_roll_buf = deque()
_pre_roll_maxframes = int(SAMPLE_RATE * 0.5) # 500ms pre-roll
_ws_loop = None
_ws_clients = set()
_result_q = Queue()
_settings_window = None # only one open at a time
# ─── Windows Unicode Typing ───────────────────────────────────────────────────
user32 = ctypes.windll.user32
INPUT_KEYBOARD = 1
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_KEYUP = 0x0002
# ─── Keyboard Layout Detection ────────────────────────────────────────────────
_LANGID_TO_CODE = {
0x029: 'fa', # Persian / Farsi
0x009: 'en', # English
0x001: 'ar', # Arabic
0x01F: 'tr', # Turkish
0x007: 'de', # German
0x00C: 'fr', # French
0x019: 'ru', # Russian
0x016: 'pt', # Portuguese
0x00A: 'es', # Spanish
0x011: 'ja', # Japanese
0x012: 'ko', # Korean
0x004: 'zh', # Chinese
}
user32.GetKeyboardLayout.restype = ctypes.c_void_p
def get_keyboard_layout_language():
"""Return language code matching the currently active Windows keyboard layout."""
try:
hwnd = user32.GetForegroundWindow()
tid = user32.GetWindowThreadProcessId(hwnd, None)
hkl = user32.GetKeyboardLayout(tid)
langid = (hkl or 0) & 0xFFFF
primary = langid & 0x3FF
return _LANGID_TO_CODE.get(primary, LANGUAGE)
except Exception:
return LANGUAGE
def active_language():
"""Return the language to use: detected from keyboard layout or the fixed setting."""
if LANG_MODE == "keyboard":
return get_keyboard_layout_language()
return LANGUAGE
class KEYBDINPUT(ctypes.Structure):
_fields_ = [
("wVk", wintypes.WORD),
("wScan", wintypes.WORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.c_ulonglong),
]
class INPUT_UNION(ctypes.Union):
_fields_ = [("ki", KEYBDINPUT)]
class INPUT(ctypes.Structure):
_fields_ = [
("type", wintypes.DWORD),
("iu", INPUT_UNION),
("_pad", ctypes.c_ubyte * 8),
]
# ─── Logging / Tray Icon ──────────────────────────────────────────────────────
_log_last_t = [None] # [timestamp of last log] for elapsed calculation
def log(msg):
now = time.time()
dt = datetime.datetime.now()
ts = dt.strftime("%H:%M:%S.") + f"{dt.microsecond // 1000:03d}"
if _log_last_t[0] is not None:
line = f"[{ts}] +{now - _log_last_t[0]:.2f}s {msg}"
else:
line = f"[{ts}] {msg}"
_log_last_t[0] = now
print(line)
logs.append(line)
if tray_icon:
recent = list(logs)[-3:]
tray_icon.title = ("SpeakPaste\n" + "\n".join(l[:40] for l in recent))[:127]
def check_for_update():
"""Check GitHub for a newer release. Runs in background thread."""
try:
resp = requests.get(
f"https://api.github.com/repos/{GITHUB_REPO}/releases/latest",
timeout=8,
headers={"Accept": "application/vnd.github+json"},
)
if resp.status_code != 200:
return
latest = resp.json().get("tag_name", "").lstrip("v")
if not latest:
return
# Simple version compare: split by dot, compare as ints
def _ver(v):
try:
return tuple(int(x) for x in v.split('.'))
except Exception:
return (0,)
if _ver(latest) > _ver(VERSION):
log(f"Update available: v{latest} → {GITHUB_URL}/releases")
except Exception:
pass
def create_icon(state="idle"):
colors = {"idle": (100, 200, 100), "recording": (255, 80, 80), "waiting": (255, 180, 0)}
img = Image.new('RGB', (64, 64), color=(30, 30, 30))
draw = ImageDraw.Draw(img)
draw.ellipse([16, 16, 48, 48], fill=colors.get(state, colors["idle"]))
return img
# ─── Audio Recording ──────────────────────────────────────────────────────────
def _audio_callback(indata, frames, time_info, status):
chunk = indata.copy()
if is_recording:
audio_queue.put(chunk)
else:
_pre_roll_buf.append(chunk)
total = sum(c.shape[0] for c in _pre_roll_buf)
while total > _pre_roll_maxframes and _pre_roll_buf:
total -= _pre_roll_buf.popleft().shape[0]
def _start_recording():
global is_recording, audio_queue
if is_recording:
return
if MIC_MODE == "on_demand":
audio_stream.start()
is_recording = True
audio_queue = Queue()
for chunk in list(_pre_roll_buf):
audio_queue.put(chunk)
_pre_roll_buf.clear()
log("Recording...")
if tray_icon:
tray_icon.icon = create_icon("recording")
def _stop_recording():
global is_recording
if not is_recording:
return None
is_recording = False
if MIC_MODE == "on_demand":
audio_stream.stop()
if tray_icon:
tray_icon.icon = create_icon("waiting")
import numpy as np
import soundfile as sf
chunks = []
while not audio_queue.empty():
chunks.append(audio_queue.get())
if not chunks:
log("No audio captured")
if tray_icon:
tray_icon.icon = create_icon("idle")
return None
audio = np.concatenate(chunks, axis=0)
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
sf.write(tmp.name, audio, SAMPLE_RATE)
log(f"Recorded {len(audio) / SAMPLE_RATE:.1f}s")
return tmp.name
# ─── Gemini Models & Adapters ─────────────────────────────────────────────────
GEMINI_LITE_MODEL = "gemini-3.1-flash-lite-preview"
GEMINI_FLASH_MODEL = "gemini-3-flash-preview"
_THINKING_BUDGETS = {"MINIMAL": 512, "LOW": 1024, "MEDIUM": 4096, "HIGH": 8192}
def _thinking_budget(level):
return _THINKING_BUDGETS.get(level.upper(), 1024)
class GeminiAdapter:
"""Adapter for Google Gemini REST API (generateContent endpoint)."""
_BASE = "https://generativelanguage.googleapis.com/v1beta/models"
def get_url(self, model, api_key):
return f"{self._BASE}/{model}:generateContent?key={api_key}"
def get_headers(self):
return {"Content-Type": "application/json"}
def build_text_request(self, system_prompt, text, thinking_level="LOW", media_resolution="LOW"):
return {
"systemInstruction": {"parts": [{"text": system_prompt}]},
"contents": [{"parts": [{"text": text}]}],
"generationConfig": {
"thinkingConfig": {"thinkingBudget": _thinking_budget(thinking_level)},
"mediaResolution": f"MEDIA_RESOLUTION_{media_resolution}",
},
}
def build_audio_request(self, system_prompt, audio_b64, thinking_level="LOW", media_resolution="LOW"):
return {
"systemInstruction": {"parts": [{"text": system_prompt}]},
"contents": [{"parts": [
{"inlineData": {"mimeType": "audio/wav", "data": audio_b64}},
{"text": "Convert this voice recording into a professional English programming prompt."},
]}],
"generationConfig": {
"thinkingConfig": {"thinkingBudget": _thinking_budget(thinking_level)},
"mediaResolution": f"MEDIA_RESOLUTION_{media_resolution}",
},
}
def parse_response(self, data):
try:
return data["candidates"][0]["content"]["parts"][0]["text"].strip()
except (KeyError, IndexError, TypeError):
return None
PROVIDER_ADAPTERS = {
"gemini": GeminiAdapter(),
}
# ─── Transcription ────────────────────────────────────────────────────────────
def _transcribe_google_direct(audio_path):
log("Transcribing (Google)...")
try:
import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile(audio_path) as source:
audio = r.record(source)
text = r.recognize_google(audio, language=_session_lang)
log(f">> {text}")
return text
except Exception as e:
log(f"Google error: {e}")
return None
finally:
try:
os.unlink(audio_path)
except Exception:
pass
def _transcribe_google_cloud(audio_path):
"""Google Cloud Speech-to-Text REST API — official, requires API key."""
import base64
log("Transcribing (Google Cloud)...")
try:
with open(audio_path, 'rb') as f:
audio_b64 = base64.b64encode(f.read()).decode('utf-8')
# BCP-47: "fa" → "fa-IR", "en" → "en-US", already full codes pass through
lang = _session_lang if '-' in _session_lang else {
'fa': 'fa-IR', 'en': 'en-US', 'ar': 'ar-SA',
'tr': 'tr-TR', 'de': 'de-DE', 'fr': 'fr-FR',
}.get(_session_lang, _session_lang + '-' + _session_lang.upper())
resp = requests.post(
f"https://speech.googleapis.com/v1/speech:recognize?key={GOOGLE_CLOUD_API_KEY}",
json={
"config": {
"encoding": "LINEAR16",
"sampleRateHertz": SAMPLE_RATE,
"languageCode": lang,
"enableAutomaticPunctuation": True,
},
"audio": {"content": audio_b64},
},
)
if resp.status_code == 200:
results = resp.json().get("results", [])
if results:
text = results[0]["alternatives"][0]["transcript"].strip()
log(f">> {text}")
return text
log("Google Cloud: no speech detected")
return None
log(f"Google Cloud error {resp.status_code}: {resp.text[:120]}")
return None
except Exception as e:
log(f"Google Cloud error: {e}")
return None
finally:
try:
os.unlink(audio_path)
except Exception:
pass
def _transcribe_groq(audio_path):
log("Transcribing (Groq)...")
try:
with open(audio_path, 'rb') as f:
resp = requests.post(
GROQ_API_URL,
headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
files={"file": ("audio.wav", f, "audio/wav")},
data={"model": MODEL, "language": _session_lang, "response_format": "text"},
)
if resp.status_code == 200:
text = resp.text.strip()
log(f">> {text}")
return text
log(f"Groq API error {resp.status_code}")
return None
except Exception as e:
log(f"Groq error: {e}")
return None
finally:
try:
os.unlink(audio_path)
except Exception:
pass
def _gemini_lite_prompt(text):
"""Send transcribed text through Gemini Flash Lite to get a prompt. Returns prompted text or None."""
global _last_stt
if not GEMINI_API_KEY:
log("Gemini: API key not set — open Settings")
return None
_last_stt = text
log("Converting to prompt (Gemini Lite)...")
adapter = PROVIDER_ADAPTERS["gemini"]
try:
resp = requests.post(
adapter.get_url(GEMINI_LITE_MODEL, GEMINI_API_KEY),
headers=adapter.get_headers(),
json=adapter.build_text_request(GEMINI_SYSTEM_PROMPT, text,
GEMINI_THINKING_LEVEL, GEMINI_MEDIA_RESOLUTION),
timeout=30,
)
if resp.status_code == 200:
result = adapter.parse_response(resp.json())
if result:
log(f">> {result}")
return result
log("Gemini: empty response")
return None
log(f"Gemini error {resp.status_code}: {resp.text[:120]}")
return None
except Exception as e:
log(f"Gemini error: {e}")
return None
def _gemini_flash_prompt(wav_path):
"""Send audio directly to Gemini Flash to get a prompt. Returns prompted text or None."""
import base64
if not GEMINI_API_KEY:
log("Gemini: API key not set — open Settings")
try:
os.unlink(wav_path)
except Exception:
pass
return None
log("Converting voice to prompt (Gemini Flash)...")
adapter = PROVIDER_ADAPTERS["gemini"]
try:
with open(wav_path, "rb") as f:
audio_b64 = base64.b64encode(f.read()).decode("utf-8")
resp = requests.post(
adapter.get_url(GEMINI_FLASH_MODEL, GEMINI_API_KEY),
headers=adapter.get_headers(),
json=adapter.build_audio_request(GEMINI_SYSTEM_PROMPT, audio_b64,
GEMINI_THINKING_LEVEL, GEMINI_MEDIA_RESOLUTION),
timeout=30,
)
if resp.status_code == 200:
result = adapter.parse_response(resp.json())
if result:
log(f">> {result}")
return result
log("Gemini: empty response")
return None
log(f"Gemini error {resp.status_code}: {resp.text[:120]}")
return None
except Exception as e:
log(f"Gemini error: {e}")
return None
finally:
try:
os.unlink(wav_path)
except Exception:
pass
# ─── Google Extension (WebSocket) ─────────────────────────────────────────────
async def _ws_handler(websocket):
_ws_clients.add(websocket)
log("[Google-ext] Extension connected")
if tray_icon:
tray_icon.icon = create_icon("idle")
try:
async for raw in websocket:
try:
_result_q.put(json.loads(raw))
except json.JSONDecodeError:
pass
except Exception:
pass
finally:
_ws_clients.discard(websocket)
log("[Google-ext] Extension disconnected")
if tray_icon:
tray_icon.icon = create_icon("idle")
async def _ws_send(data):
if not _ws_clients:
return
msg = json.dumps(data)
await asyncio.gather(*[ws.send(msg) for ws in list(_ws_clients)], return_exceptions=True)
def _google_send(data):
if _ws_loop:
asyncio.run_coroutine_threadsafe(_ws_send(data), _ws_loop)
def _start_ws_server():
global _ws_loop
import websockets
_ws_loop = asyncio.new_event_loop()
asyncio.set_event_loop(_ws_loop)
async def _serve():
async with websockets.serve(_ws_handler, "localhost", WS_PORT):
log(f"[Google-ext] WebSocket ready on ws://localhost:{WS_PORT}")
await asyncio.Future()
_ws_loop.run_until_complete(_serve())
def _transcribe_google_ext():
while not _result_q.empty():
try:
_result_q.get_nowait()
except Empty:
break
if not _ws_clients:
log("[Google-ext] Extension not connected — install & reload Chrome")
if tray_icon:
tray_icon.icon = create_icon("idle")
return None
_google_send({"cmd": "stop"})
if tray_icon:
tray_icon.icon = create_icon("waiting")
try:
result = _result_q.get(timeout=10)
text = result.get("text", "").strip()
if result.get("error"):
log(f"[Google-ext] Error: {result['error']}")
return None
if text:
log(f">> {text}")
return text
return None
except Empty:
log("[Google-ext] Timeout")
return None
finally:
if tray_icon:
tray_icon.icon = create_icon("idle")
# ─── Text Injection ───────────────────────────────────────────────────────────
def _send_unicode_char(char_code):
down = INPUT()
down.type = INPUT_KEYBOARD
down.iu.ki.wScan = char_code
down.iu.ki.dwFlags = KEYEVENTF_UNICODE
up = INPUT()
up.type = INPUT_KEYBOARD
up.iu.ki.wScan = char_code
up.iu.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP
user32.SendInput(1, ctypes.byref(down), ctypes.sizeof(INPUT))
user32.SendInput(1, ctypes.byref(up), ctypes.sizeof(INPUT))
def type_text(text):
if not text:
return
keys = HOTKEY.split('+')
while any(keyboard.is_pressed(k) for k in keys):
time.sleep(0.05)
time.sleep(0.3)
for k in ['left windows', 'right windows', 'alt', 'ctrl', 'shift']:
try:
keyboard.release(k)
except Exception:
pass
for char in text:
_send_unicode_char(ord(char))
time.sleep(0.001)
log("Typed OK")
# ─── Hotkey Handlers ──────────────────────────────────────────────────────────
def on_hotkey_press():
global _session_lang
_log_last_t[0] = None # reset elapsed timer at start of each invocation
_session_lang = active_language()
if STT_ENGINE == "google-ext" and PROMPT_MODE != "gemini-flash":
if not _ws_clients:
log("[Google-ext] Extension not connected")
return
_google_send({"cmd": "start", "lang": _session_lang})
log("Listening (Google-ext)...")
if tray_icon:
tray_icon.icon = create_icon("recording")
else:
_start_recording()
def on_hotkey_release():
global _last_stt
_last_stt = None
if PROMPT_MODE == "gemini-flash":
# Bypass STT entirely — send audio straight to Gemini Flash
path = _stop_recording()
text = _gemini_flash_prompt(path) if path else None
elif STT_ENGINE == "google-ext":
raw = _transcribe_google_ext()
text = _gemini_lite_prompt(raw) if (raw and PROMPT_MODE == "gemini-lite") else raw
else:
path = _stop_recording()
if STT_ENGINE == "google":
raw = _transcribe_google_direct(path) if path else None
elif STT_ENGINE == "google-cloud":
raw = _transcribe_google_cloud(path) if path else None
else: # groq
raw = _transcribe_groq(path) if path else None
text = _gemini_lite_prompt(raw) if (raw and PROMPT_MODE == "gemini-lite") else raw
if text:
engine_label = STT_ENGINE if PROMPT_MODE == "off" else f"{STT_ENGINE}+{PROMPT_MODE}"
_history.appendleft({
"time": datetime.datetime.now().strftime("%H:%M:%S"),
"engine": engine_label,
"stt": _last_stt,
"output": text,
})
type_text(text)
if tray_icon:
tray_icon.icon = create_icon("idle")
def keyboard_listener():
global running, is_hotkey_active
keys = HOTKEY.split('+')
while running:
try:
pressed = all(keyboard.is_pressed(k) for k in keys)
if pressed and not is_hotkey_active:
is_hotkey_active = True
on_hotkey_press()
elif not pressed and is_hotkey_active:
is_hotkey_active = False
threading.Thread(target=on_hotkey_release, daemon=True).start()
except Exception:
pass
time.sleep(0.05)
# ─── Settings Window ──────────────────────────────────────────────────────────
def _apply_settings(new_cfg):
global STT_ENGINE, PROMPT_MODE, HOTKEY, LANGUAGE, MIC_MODE, GROQ_API_KEY, MODEL, WS_PORT, CHECK_UPDATES
global GEMINI_API_KEY, GEMINI_SYSTEM_PROMPT, LANG_MODE, GEMINI_THINKING_LEVEL, GEMINI_MEDIA_RESOLUTION
old_mic = MIC_MODE
old_engine = STT_ENGINE
STT_ENGINE = new_cfg["stt_engine"]
PROMPT_MODE = new_cfg["prompt_mode"]
HOTKEY = new_cfg["hotkey"]
LANGUAGE = new_cfg["language"]
GROQ_API_KEY = new_cfg["groq_api_key"]
MODEL = new_cfg["model"]
GOOGLE_CLOUD_API_KEY = new_cfg["google_cloud_api_key"]
WS_PORT = new_cfg["ws_port"]
MIC_MODE = new_cfg["mic_mode"]
CHECK_UPDATES = new_cfg["check_updates"]
GEMINI_API_KEY = new_cfg.get("gemini_api_key", "")
GEMINI_SYSTEM_PROMPT = new_cfg.get("gemini_system_prompt", GEMINI_DEFAULT_SYSTEM_PROMPT)
LANG_MODE = new_cfg.get("lang_mode", "fixed")
GEMINI_THINKING_LEVEL = new_cfg.get("gemini_thinking_level", "LOW")
GEMINI_MEDIA_RESOLUTION = new_cfg.get("gemini_media_resolution", "LOW")
# Apply mic mode change live
if audio_stream and old_mic != MIC_MODE:
if MIC_MODE == "on_demand":
try:
audio_stream.stop()
except Exception:
pass
else:
try:
audio_stream.start()
except Exception:
pass
save_settings(new_cfg)
log(f"Settings saved — stt={STT_ENGINE}, prompt={PROMPT_MODE}, mic={MIC_MODE}")
if old_engine != STT_ENGINE:
log("Engine changed — restart SpeakPaste to fully apply")
def open_settings(icon=None, item=None):
global _settings_window
if _settings_window and _settings_window.winfo_exists():
_settings_window.lift()
_settings_window.focus_force()
return
def _build():
global _settings_window
win = tk.Tk()
win.withdraw() # hide until fully built — prevents layout flash
win.title("SpeakPaste — Settings")
win.resizable(False, True)
win.configure(bg="#1e1e1e")
# ── Scrollable body ──────────────────────────────────────────────────
canvas = tk.Canvas(win, bg="#1e1e1e", highlightthickness=0, bd=0)
scrollbar = tk.Scrollbar(win, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
body = tk.Frame(canvas, bg="#1e1e1e", padx=20, pady=16)
body_id = canvas.create_window((0, 0), window=body, anchor="nw")
def _on_body_configure(e):
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfig(body_id, width=canvas.winfo_width())
body.bind("<Configure>", _on_body_configure)
canvas.bind("<Configure>", lambda e: canvas.itemconfig(body_id, width=e.width))
def _on_mousewheel(e):
canvas.yview_scroll(int(-1 * (e.delta / 120)), "units")
win.bind("<MouseWheel>", _on_mousewheel)
lbl_style = {"bg": "#1e1e1e", "fg": "#cccccc", "font": ("Segoe UI", 9)}
hdr_style = {"bg": "#1e1e1e", "fg": "#ffffff", "font": ("Segoe UI", 9, "bold")}
ent_style = {"bg": "#2d2d2d", "fg": "#ffffff", "insertbackground": "#ffffff",
"relief": "flat", "font": ("Segoe UI", 9)}
def section(text):
tk.Label(body, text=text, **hdr_style).pack(anchor="w", pady=(12, 2))
ttk.Separator(body).pack(fill="x", pady=(0, 6))
rb_cfg = dict(bg="#1e1e1e", fg="#cccccc", selectcolor="#2d2d2d",
activebackground="#1e1e1e", activeforeground="#ffffff",
font=("Segoe UI", 9))
# ── Transcription Engine ─────────────────────────────────────────────
section("Transcription Engine")
stt_var = tk.StringVar(value=STT_ENGINE)
stt_section = tk.Frame(body, bg="#1e1e1e")
stt_section.pack(fill="x")
stt_radios = []
for label, val in [
("Google — free, unofficial, no key", "google"),
("Google Cloud — official, API key required", "google-cloud"),
("Groq Whisper — API key required", "groq"),
("Google Extension — Chrome in background", "google-ext")]:
rb = tk.Radiobutton(stt_section, text=label, variable=stt_var, value=val, **rb_cfg)
rb.pack(anchor="w")
stt_radios.append(rb)
stt_extra = tk.Frame(stt_section, bg="#1e1e1e")
stt_extra.pack(fill="x")
# Groq sub-frame
groq_frame = tk.Frame(stt_extra, bg="#252525", padx=12, pady=6)
row3 = tk.Frame(groq_frame, bg="#252525")
row3.pack(fill="x", pady=2)
tk.Label(row3, text="API Key:", width=14, anchor="w",
bg="#252525", fg="#cccccc", font=("Segoe UI", 9)).pack(side="left")
key_var = tk.StringVar(value=GROQ_API_KEY)
tk.Entry(row3, textvariable=key_var, width=34, show="*",
**{**ent_style, "bg": "#333333"}).pack(side="left")
row4 = tk.Frame(groq_frame, bg="#252525")
row4.pack(fill="x", pady=2)
tk.Label(row4, text="Model:", width=14, anchor="w",
bg="#252525", fg="#cccccc", font=("Segoe UI", 9)).pack(side="left")
model_var = tk.StringVar(value=MODEL)
tk.Entry(row4, textvariable=model_var, width=34,
**{**ent_style, "bg": "#333333"}).pack(side="left")
# Google Cloud sub-frame
gcloud_frame = tk.Frame(stt_extra, bg="#252525", padx=12, pady=6)
row5 = tk.Frame(gcloud_frame, bg="#252525")
row5.pack(fill="x", pady=2)
tk.Label(row5, text="API Key:", width=14, anchor="w",
bg="#252525", fg="#cccccc", font=("Segoe UI", 9)).pack(side="left")
gcloud_key_var = tk.StringVar(value=GOOGLE_CLOUD_API_KEY)
tk.Entry(row5, textvariable=gcloud_key_var, width=34, show="*",
**{**ent_style, "bg": "#333333"}).pack(side="left")
tk.Label(gcloud_frame,
text="console.cloud.google.com → Speech-to-Text API → Credentials",
bg="#252525", fg="#666666", font=("Segoe UI", 8)).pack(anchor="w", pady=(2, 0))
def _refresh_stt_extra(*_):
eng = stt_var.get()
for child in stt_extra.winfo_children():
child.pack_forget()
if eng == "groq":
stt_extra.configure(bg="#252525")
groq_frame.pack(fill="x")
elif eng == "google-cloud":
stt_extra.configure(bg="#252525")
gcloud_frame.pack(fill="x")
else:
stt_extra.configure(bg="#1e1e1e")
stt_var.trace_add("write", _refresh_stt_extra)
_refresh_stt_extra()
# ── Prompt ───────────────────────────────────────────────────────────
section("Prompt")
prompt_var = tk.StringVar(value=PROMPT_MODE)
for label, val in [
("Off — paste raw transcript", "off"),
("Gemini Flash Lite — transcript \u2192 prompt", "gemini-lite"),
("Gemini Flash — voice \u2192 prompt directly (skips engine above)", "gemini-flash")]:
tk.Radiobutton(body, text=label, variable=prompt_var, value=val,
**rb_cfg).pack(anchor="w")
prompt_extra = tk.Frame(body, bg="#1e1e1e")
prompt_extra.pack(fill="x")
# Gemini config (API key + system prompt) — shared for both gemini modes
gemini_frame = tk.Frame(prompt_extra, bg="#252525", padx=12, pady=8)
row_gk = tk.Frame(gemini_frame, bg="#252525")
row_gk.pack(fill="x", pady=2)
tk.Label(row_gk, text="API Key:", width=14, anchor="w",
bg="#252525", fg="#cccccc", font=("Segoe UI", 9)).pack(side="left")
gemini_key_var = tk.StringVar(value=GEMINI_API_KEY)
tk.Entry(row_gk, textvariable=gemini_key_var, width=34, show="*",
**{**ent_style, "bg": "#333333"}).pack(side="left")
tk.Label(gemini_frame,
text="aistudio.google.com → Get API key",
bg="#252525", fg="#666666", font=("Segoe UI", 8)).pack(anchor="w", pady=(0, 6))
tk.Label(gemini_frame, text="System Prompt:", anchor="w",
bg="#252525", fg="#cccccc", font=("Segoe UI", 9)).pack(anchor="w", pady=(2, 2))
prompt_wrap = tk.Frame(gemini_frame, bg="#252525")
prompt_wrap.pack(fill="x")
gemini_prompt_text = tk.Text(
prompt_wrap, height=4, bg="#333333", fg="#ffffff",
insertbackground="#ffffff", relief="flat",
font=("Segoe UI", 9), wrap="word",
)
gemini_prompt_text.insert("1.0", GEMINI_SYSTEM_PROMPT)
gemini_prompt_text.pack(side="left", fill="x", expand=True)
prompt_sb = tk.Scrollbar(prompt_wrap, command=gemini_prompt_text.yview)
prompt_sb.pack(side="right", fill="y")
gemini_prompt_text.config(yscrollcommand=prompt_sb.set)
def _reset_prompt():
gemini_prompt_text.delete("1.0", "end")
gemini_prompt_text.insert("1.0", GEMINI_DEFAULT_SYSTEM_PROMPT)
tk.Button(gemini_frame, text="Reset to default", command=_reset_prompt,
bg="#3c3c3c", fg="#888888", relief="flat", font=("Segoe UI", 8),
activebackground="#4c4c4c", activeforeground="#cccccc").pack(anchor="e", pady=(4, 0))
# Quality settings — thinking level + media resolution
quality_frame = tk.Frame(gemini_frame, bg="#252525")
quality_frame.pack(fill="x", pady=(8, 0))
row_think = tk.Frame(quality_frame, bg="#252525")
row_think.pack(fill="x", pady=2)
tk.Label(row_think, text="Thinking level:", width=16, anchor="w",
bg="#252525", fg="#cccccc", font=("Segoe UI", 9)).pack(side="left")
thinking_var = tk.StringVar(value=GEMINI_THINKING_LEVEL)
om_think = tk.OptionMenu(row_think, thinking_var, "MINIMAL", "LOW", "MEDIUM", "HIGH")
om_think.config(bg="#333333", fg="#cccccc", activebackground="#444444",
activeforeground="#ffffff", highlightthickness=0,
relief="flat", font=("Segoe UI", 9))
om_think["menu"].config(bg="#333333", fg="#cccccc",
activebackground="#0078d4", activeforeground="#ffffff")