-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecorder.py
More file actions
executable file
·305 lines (266 loc) · 10.9 KB
/
Copy pathrecorder.py
File metadata and controls
executable file
·305 lines (266 loc) · 10.9 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
#!/usr/bin/env python3
"""
recorder.py – Hotkey-triggered audio recorder with forced language (pt/en).
Controls:
Ctrl+Shift+Alt+R → Start / Stop recording
Ctrl+Shift+Alt+L → Switch language between Portuguese and English
Ctrl+Shift+Alt+Q → Quit gracefully
Ctrl+C → Also quits (terminal only)
Requirements:
pip install faster-whisper sounddevice pynput python-xlib pyperclip numpy
pip install nvidia-cublas-cu12 nvidia-cudnn-cu12
"""
# ── 0. CUDA path fix ──────────────────────────────────────────────────────────
import os
import sys
import threading
def _setup_cuda():
script_dir = os.path.dirname(os.path.abspath(__file__))
venv_dir = os.path.join(script_dir, ".venv")
if not os.path.isdir(venv_dir):
print("⚠️ Pasta .venv não encontrada.")
return
extra = []
for lib_dir in ("lib", "lib64"):
site_pkgs = os.path.join(venv_dir, lib_dir, "python3.13/site-packages")
cublas = os.path.join(site_pkgs, "nvidia/cublas/lib")
cudnn = os.path.join(site_pkgs, "nvidia/cudnn/lib")
if os.path.isdir(cublas):
extra.append(cublas)
if os.path.isdir(cudnn):
extra.append(cudnn)
if not extra:
print("⚠️ Bibliotecas CUDA não encontradas.")
else:
os.environ["LD_LIBRARY_PATH"] = ":".join(extra) + ":" + os.environ.get("LD_LIBRARY_PATH", "")
print(f"🔧 CUDA libs: {', '.join(extra)}")
_setup_cuda()
# ── 0.5 Forçar carga da libcublas ─────────────────────────────────────────────
import ctypes
def _force_load_cublas():
for path in os.environ.get("LD_LIBRARY_PATH", "").split(":"):
lib_path = os.path.join(path, "libcublas.so.12")
if os.path.exists(lib_path):
try:
ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL)
print(f"✅ libcublas carregada de {lib_path}")
return
except Exception as e:
print(f"⚠️ Falha ao carregar {lib_path}: {e}")
print("⚠️ libcublas.so.12 não encontrada ou não pôde ser carregada")
_force_load_cublas()
# ── 1. Imports ────────────────────────────────────────────────────────────────
import numpy as np
import sounddevice as sd
import pyperclip
from pynput import keyboard as kb
from faster_whisper import WhisperModel
# ── 2. Configurações globais ─────────────────────────────────────────────────
SAMPLE_RATE = 16_000
TRIGGER_VK = 82 # tecla R
LANG_VK = 76 # tecla L
QUIT_VK = 81 # tecla Q
# Controle do idioma atual (pt ou en)
current_lang = "pt"
lang_lock = threading.Lock()
# ── 3. Beeps (enhanced with more events) ────────────────────────────────────
def _beep(freq, dur=0.18, vol=0.35):
t = np.linspace(0, dur, int(SAMPLE_RATE * dur), endpoint=False)
wave = (vol * np.sin(2 * np.pi * freq * t)).astype(np.float32)
fl = int(SAMPLE_RATE * 0.03)
wave[-fl:] *= np.linspace(1.0, 0.0, fl)
sd.play(wave, samplerate=SAMPLE_RATE)
sd.wait()
def play_startup_beep():
_beep(800, 0.15)
def play_init_complete_beep():
_beep(1200, 0.15)
def play_transcription_success_beep():
_beep(1000, 0.20)
def play_shutdown_beep():
_beep(600, 0.20)
def play_start():
_beep(660, 0.12)
_beep(880, 0.15)
def play_stop():
_beep(880, 0.12)
_beep(440, 0.20)
def play_language_switch(new_lang):
# Inglês: bipe agudo; Português: bipe grave
if new_lang == "en":
_beep(1200, 0.10)
else:
_beep(400, 0.15)
# ── 4. Whisper model (medium, GPU int8) ─────────────────────────────────────
play_startup_beep()
print("⏳ Carregando modelo Whisper medium (GPU int8) …")
model = WhisperModel("medium", device="cuda", compute_type="int8")
print("✅ Modelo carregado.")
play_init_complete_beep() # second beep – initialization complete
# ── 5. Gravador (recorder) ──────────────────────────────────────────────────
class Recorder:
def __init__(self):
self._chunks = []
self._stream = None
self.recording = False
self._lock = threading.Lock()
def _cb(self, indata, frames, t, status):
if status:
print(f"[áudio] {status}", file=sys.stderr)
with self._lock:
if self.recording:
self._chunks.append(indata.copy())
def start(self):
if self.recording:
return
with self._lock:
self._chunks.clear()
self.recording = True
self._stream = sd.InputStream(
samplerate=SAMPLE_RATE, channels=1, dtype="float32", callback=self._cb
)
self._stream.start()
print("🔴 Gravando …")
def stop(self):
if not self.recording:
return np.array([], dtype=np.float32)
with self._lock:
self.recording = False
if self._stream:
self._stream.stop()
self._stream.close()
self._stream = None
with self._lock:
if not self._chunks:
return np.array([], dtype=np.float32)
audio = np.concatenate(self._chunks, axis=0).flatten()
print(f"⏹️ Parado. {len(audio)/SAMPLE_RATE:.1f}s capturados.")
return audio
# ── 6. Transcrição com idioma forçado ───────────────────────────────────────
def transcribe(audio):
if audio.size == 0:
return ""
# Pega o idioma atual com lock
with lang_lock:
lang = current_lang
lang_name = "Português" if lang == "pt" else "English"
print(f"🧠 Transcrevendo em {lang_name} (tradução forçada) …")
segments, info = model.transcribe(
audio,
beam_size=5,
task="transcribe",
language=lang,
condition_on_previous_text=False,
)
texts = []
for seg in segments:
print(f" {seg.text.strip()}")
texts.append(seg.text.strip())
print(f"\n📋 Idioma forçado: {lang_name}")
return " ".join(texts)
# ── 7. Hotkey listeners (modified for Alt modifier and new quit hotkey) ─────
def _is_ctrl(k):
return k in (kb.Key.ctrl, kb.Key.ctrl_l, kb.Key.ctrl_r)
def _is_shift(k):
return k in (kb.Key.shift, kb.Key.shift_l, kb.Key.shift_r)
def _is_alt(k):
return k in (kb.Key.alt, kb.Key.alt_l, kb.Key.alt_r)
def _is_r(k):
return isinstance(k, kb.KeyCode) and k.vk == TRIGGER_VK
def _is_l(k):
return isinstance(k, kb.KeyCode) and k.vk == LANG_VK
def _is_q(k):
return isinstance(k, kb.KeyCode) and k.vk == QUIT_VK
def start_hotkey_listeners(trigger_event, shutdown_event):
ctrl_held = shift_held = alt_held = False
r_triggered = False
l_triggered = False
q_triggered = False
def on_press(key):
nonlocal ctrl_held, shift_held, alt_held, r_triggered, l_triggered, q_triggered
if _is_ctrl(key):
ctrl_held = True
elif _is_shift(key):
shift_held = True
elif _is_alt(key):
alt_held = True
elif _is_r(key) and not r_triggered:
r_triggered = True
if ctrl_held and shift_held and alt_held:
trigger_event.set()
elif _is_l(key) and not l_triggered:
l_triggered = True
if ctrl_held and shift_held and alt_held:
with lang_lock:
global current_lang
current_lang = "en" if current_lang == "pt" else "pt"
new_lang = current_lang
lang_name = "English" if new_lang == "en" else "Português"
print(f"\n🔁 Idioma alterado para: {lang_name}")
play_language_switch(new_lang)
elif _is_q(key) and not q_triggered:
q_triggered = True
if ctrl_held and shift_held and alt_held:
shutdown_event.set()
def on_release(key):
nonlocal ctrl_held, shift_held, alt_held, r_triggered, l_triggered, q_triggered
if _is_ctrl(key):
ctrl_held = False
elif _is_shift(key):
shift_held = False
elif _is_alt(key):
alt_held = False
elif _is_r(key):
r_triggered = False
elif _is_l(key):
l_triggered = False
elif _is_q(key):
q_triggered = False
listener = kb.Listener(on_press=on_press, on_release=on_release)
listener.daemon = True
listener.start()
return listener
# ── 8. Main (with shutdown handling and new beeps) ──────────────────────────
def main():
# First beep – program started
recorder = Recorder()
trigger = threading.Event()
shutdown_event = threading.Event()
print("⌨️ Hotkey: Ctrl+Shift+Alt+R → iniciar / parar gravação")
print("⌨️ Hotkey: Ctrl+Shift+Alt+L → alternar idioma (Português ↔ English)")
print("⌨️ Hotkey: Ctrl+Shift+Alt+Q → sair gracefully")
print("⌨️ Sair também com Ctrl+C no terminal\n")
start_hotkey_listeners(trigger, shutdown_event)
try:
while not shutdown_event.is_set():
# Wait for recording trigger with a short timeout so we can check shutdown_event
trigger.wait(timeout=0.2)
if trigger.is_set():
trigger.clear()
if not recorder.recording:
play_start()
recorder.start()
else:
play_stop()
audio = recorder.stop()
if audio.size == 0:
print("⚠️ Nenhum áudio capturado.\n")
continue
text = transcribe(audio)
if not text:
print("⚠️ Transcrição vazia.\n")
continue
pyperclip.copy(text)
play_transcription_success_beep() # success beep
print(f"\n✅ Copiado:\n{'-'*60}\n{text}\n{'-'*60}\n")
except KeyboardInterrupt:
print("\n👋 Encerrando via Ctrl+C …")
finally:
# Graceful shutdown
if recorder.recording:
recorder.stop()
play_shutdown_beep()
print("Programa encerrado.")
sys.exit(0)
if __name__ == "__main__":
main()