Please create a python implementation of a finetuning environment for openai whisper's smallest model. The program should collect data from users on macs using built in audio and keylogging to create a dataset of key typing sounds to output. It should be in the format openai uses for their speech to text data.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Whisper Fine-Tuning Environment for Keystroke Audio
Below is a Python implementation for collecting keystroke audio data to fine-tune OpenAI's Whisper model. This implementation uses PyAudio for audio recording and pynput for keylogging on macOS.
python
import os
import json
import time
import wave
import pyaudio
from pynput import keyboard
from datetime import datetime
from typing import List, Dict, Optional
class KeystrokeAudioRecorder:
def __init__(self, output_dir: str = "keystroke_dataset", sample_rate: int = 16000, chunk_size: int = 1024):
"""
Initialize the keystroke audio recorder.
Args:
output_dir: Directory to save the recorded data
sample_rate: Audio sample rate (Whisper uses 16kHz)
chunk_size: Audio chunk size for recording
"""
self.output_dir = output_dir
self.sample_rate = sample_rate
self.chunk_size = chunk_size
self.audio = pyaudio.PyAudio()
self.is_recording = False
self.current_recording = None
self.current_key = None
self.recording_start_time = None
self.dataset = []
# Create output directory if it doesn't exist
os.makedirs(self.output_dir, exist_ok=True)
# Initialize keyboard listener
self.keyboard_listener = keyboard.Listener(
on_press=self._on_press,
on_release=self._on_release
)
def start(self):
"""Start the recording and keylogging process."""
print("Starting keystroke audio recorder...")
self.keyboard_listener.start()
self.keyboard_listener.join()
def _on_press(self, key):
"""Callback for when a key is pressed."""
try:
key_char = key.char
except AttributeError:
key_char = str(key).replace("Key.", "")
# Skip modifier keys
if key_char in ['ctrl', 'cmd', 'shift', 'alt', 'caps_lock']:
return
print(f"Key pressed: {key_char}")
self.current_key = key_char
self._start_recording()
def _on_release(self, key):
"""Callback for when a key is released."""
if self.is_recording:
self._stop_recording()
def _start_recording(self):
"""Start audio recording."""
if self.is_recording:
return
self.is_recording = True
self.recording_start_time = time.time()
# Open audio stream
self.current_recording = {
"audio_frames": [],
"key": self.current_key,
"start_time": self.recording_start_time
}
stream = self.audio.open(
format=pyaudio.paInt16,
channels=1,
rate=self.sample_rate,
input=True,
frames_per_buffer=self.chunk_size,
stream_callback=self._audio_callback
)
self.current_recording["stream"] = stream
stream.start_stream()
def _stop_recording(self):
"""Stop audio recording and save the data."""
if not self.is_recording:
return
self.is_recording = False
recording = self.current_recording
stream = recording["stream"]
# Stop the audio stream
stream.stop_stream()
stream.close()
# Calculate duration
duration = time.time() - recording["start_time"]
# Save audio to WAV file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{timestamp}_{recording['key']}.wav"
filepath = os.path.join(self.output_dir, filename)
wf = wave.open(filepath, 'wb')
wf.setnchannels(1)
wf.setsampwidth(self.audio.get_sample_size(pyaudio.paInt16))
wf.setframerate(self.sample_rate)
wf.writeframes(b''.join(recording["audio_frames"]))
wf.close()
# Create dataset entry in Whisper format
dataset_entry = {
"audio": {
"path": filepath,
"array": None, # Will be loaded later
"sampling_rate": self.sample_rate
},
"text": recording["key"],
"duration": duration
}
self.dataset.append(dataset_entry)
print(f"Saved recording for key '{recording['key']}' to {filepath}")
self.current_recording = None
def _audio_callback(self, in_data, frame_count, time_info, status):
"""Callback for audio stream data."""
if self.is_recording and self.current_recording:
self.current_recording["audio_frames"].append(in_data)
return (in_data, pyaudio.paContinue)
def save_dataset(self, output_file: str = "keystroke_dataset.json"):
"""Save the collected dataset to a JSON file in Whisper format."""
output_path = os.path.join(self.output_dir, output_file)
# Convert dataset to Whisper format
whisper_dataset = {
"version": "1.0",
"data": self.dataset
}
with open(output_path, 'w') as f:
json.dump(whisper_dataset, f, indent=2)
print(f"Dataset saved to {output_path}")
def cleanup(self):
"""Clean up resources."""
self.audio.terminate()
if self.keyboard_listener:
self.keyboard_listener.stop()
def main():
# Initialize the recorder
recorder = KeystrokeAudioRecorder()
try:
print("Keystroke audio recorder started. Press keys to record their sounds.")
print("Press Ctrl+C to stop recording and save the dataset.")
# Start recording
recorder.start()
except KeyboardInterrupt:
print("\nStopping recording...")
finally:
# Save dataset and clean up
recorder.save_dataset()
recorder.cleanup()
print("Recording session completed.")
if __name__ == "__main__":
main()
Important Notes:
Privacy and Security Considerations:
This program records audio and keystrokes, which may have privacy implications
Only use this on your own devices with your own data
Never collect data from others without explicit consent