forked from jnjacobson/whispering-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
178 lines (143 loc) · 4.3 KB
/
Copy pathmain.py
File metadata and controls
178 lines (143 loc) · 4.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
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "sounddevice",
# "numpy",
# "openai",
# "pydub",
# "pynput",
# "pyperclip",
# "pyautogui",
# "python-dotenv",
# ]
# ///
import io
import threading
import argparse
import os
import sounddevice as sd
import numpy as np
from openai import OpenAI
from pydub import AudioSegment
from pynput import keyboard
import pyperclip
import pyautogui
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Parse command line arguments
parser = argparse.ArgumentParser(description='Speech to text recording tool')
parser.add_argument(
'--language',
'-l',
type=str,
default="de",
help='Language code for transcription (default: de)',
)
args = parser.parse_args()
# Recording parameters
LANGUAGE = args.language
HOTKEY = os.getenv("HOTKEY")
SAMPLE_RATE = 16000
CHANNELS = 1
MAX_RECORDING_SECONDS = 120
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Check if API key is set
if not OPENAI_API_KEY:
print("Error: OPENAI_API_KEY environment variable not set.")
exit(1)
# Display selected language
print(f"Using language: {LANGUAGE}")
client = OpenAI(api_key=OPENAI_API_KEY)
# Recording state class
class RecordingState:
def __init__(self):
self.is_recording = False
self.recorded_frames = []
self.timer = None
state = RecordingState()
def on_key_press():
"""Toggle recording state and handle transcription when recording stops."""
# Toggle recording state
state.is_recording = not state.is_recording
if state.is_recording:
print(f"Recording started... Press {HOTKEY} to stop.")
state.recorded_frames = [] # Clear previous recordings
state.timer = threading.Timer(MAX_RECORDING_SECONDS, on_key_press)
state.timer.start()
else:
print("Recording stopped. Transcribing...")
# Cancel the timer if manually stopped
if state.timer and state.timer.is_alive():
state.timer.cancel()
state.timer = None
transcribe_audio()
print("Press Ctrl+Alt+; to start recording again.")
def transcribe_audio():
"""Transcribe the recorded audio."""
try:
# Combine all recorded frames
if not state.recorded_frames:
return
audio_data = np.concatenate(state.recorded_frames)
# Convert to int16 for proper audio format
audio_int16 = (audio_data * np.iinfo(np.int16).max).astype(np.int16)
# Create an in-memory file-like object
byte_io = io.BytesIO()
# Create a temporary audio segment
AudioSegment(
audio_int16.tobytes(),
frame_rate=SAMPLE_RATE,
sample_width=2,
channels=CHANNELS,
).export(byte_io, format="wav")
byte_io.seek(0)
result = client.audio.transcriptions.create(
model="whisper-1",
file=("audio.wav", byte_io),
language=LANGUAGE,
)
# Save original clipboard content
original_clipboard = pyperclip.paste()
# Copy and paste transcription
pyperclip.copy(result.text)
pyautogui.hotkey('ctrl', 'v')
# Restore original clipboard content
pyperclip.copy(original_clipboard)
except Exception as e:
print(f"Error in transcription: {str(e)}")
def audio_callback(indata, frames, time_info, status):
"""Callback function to capture audio data."""
if status:
print(status)
if state.is_recording:
state.recorded_frames.append(indata.copy())
def setup_hotkey():
"""Set up the keyboard listener"""
hotkey = keyboard.HotKey(
keyboard.HotKey.parse(HOTKEY),
on_key_press
)
# Create a listener
with keyboard.Listener(
on_press=hotkey.press,
on_release=hotkey.release,
) as listener:
print(f"Ready. Press {HOTKEY} to start/stop recording.")
listener.join()
# Start capturing audio from the microphone in the background
stream = sd.InputStream(
callback=audio_callback,
channels=CHANNELS,
samplerate=SAMPLE_RATE,
)
stream.start()
# Setup and start the keyboard listener
try:
setup_hotkey()
except KeyboardInterrupt:
print("\nStopping the program...")
finally:
if stream.active:
stream.stop()
stream.close()