Here's a Python implementation of a finetuning environment for OpenAI's Whisper model that collects audio and keylogging data on Macs. This code creates a dataset of typing sounds with corresponding transcriptions in the format suitable for Whisper finetuning.
Important notes:
- This code requires appropriate permissions on macOS
- Make sure to handle the collected data responsibly and comply with privacy regulations
- You'll need to install required dependencies
- This is for educational purposes - get user consent before collecting any data
import pyaudio
import wave
import keyboard
import time
import json
import os
from datetime import datetime
import numpy as np
from pathlib import Path
import whisper
import threading
import queue
# Configuration
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000 # Whisper works best with 16kHz audio
RECORD_SECONDS = 5 # Duration of each recording segment
DATA_DIR = "finetuning_data"
MODEL_NAME = "tiny" # Using Whisper's smallest model
class TypingDataCollector:
def __init__(self):
self.audio_queue = queue.Queue()
self.keystrokes = []
self.is_recording = False
self.p = pyaudio.PyAudio()
self.model = whisper.load_model(MODEL_NAME)
# Create data directory if it doesn't exist
Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
def record_audio(self):
"""Record audio in chunks and put them in queue"""
stream = self.p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("Recording audio...")
while self.is_recording:
data = stream.read(CHUNK)
self.audio_queue.put(data)
stream.stop_stream()
stream.close()
def log_keystrokes(self):
"""Log keystrokes with timestamps"""
def on_key_press(event):
if self.is_recording:
timestamp = time.time()
self.keystrokes.append({
"key": event.name,
"timestamp": timestamp
})
keyboard.on_press(on_key_press)
def save_segment(self, audio_data, keystrokes, start_time):
"""Save audio segment and corresponding transcription"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Save audio
audio_filename = f"{DATA_DIR}/audio_{timestamp}.wav"
wf = wave.open(audio_filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(self.p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(audio_data))
wf.close()
# Create transcription from keystrokes
transcription = ""
for stroke in keystrokes:
if len(stroke["key"]) == 1: # Only add printable characters
transcription += stroke["key"]
elif stroke["key"] == "space":
transcription += " "
elif stroke["key"] == "enter":
transcription += "\n"
# Create dataset entry in OpenAI's format
dataset_entry = {
"audio": audio_filename,
"text": transcription,
"duration": RECORD_SECONDS,
"language": "en"
}
# Save dataset entry
json_filename = f"{DATA_DIR}/data_{timestamp}.json"
with open(json_filename, 'w') as f:
json.dump(dataset_entry, f, indent=2)
print(f"Saved segment: {audio_filename}")
def start_collection(self):
"""Start the data collection process"""
self.is_recording = True
# Start audio recording thread
audio_thread = threading.Thread(target=self.record_audio)
audio_thread.start()
# Start keystroke logging
self.log_keystrokes()
try:
while True:
start_time = time.time()
segment_audio = []
segment_keystrokes = []
# Collect data for RECORD_SECONDS
while time.time() - start_time < RECORD_SECONDS:
try:
audio_data = self.audio_queue.get(timeout=1)
segment_audio.append(audio_data)
except queue.Empty:
continue
# Filter keystrokes for this segment
segment_keystrokes = [k for k in self.keystrokes
if start_time <= k["timestamp"] < start_time + RECORD_SECONDS]
if segment_audio and segment_keystrokes:
self.save_segment(segment_audio, segment_keystrokes, start_time)
except KeyboardInterrupt:
print("\nStopping data collection...")
self.is_recording = False
audio_thread.join()
self.p.terminate()
def prepare_finetuning_dataset(self):
"""Prepare the collected data in format suitable for Whisper finetuning"""
dataset = []
for json_file in Path(DATA_DIR).glob("*.json"):
with open(json_file, 'r') as f:
entry = json.load(f)
dataset.append(entry)
# Save complete dataset
with open(f"{DATA_DIR}/finetuning_dataset.jsonl", 'w') as f:
for entry in dataset:
f.write(json.dumps(entry) + '\n')
print(f"Prepared finetuning dataset with {len(dataset)} entries")
def main():
print("Whisper Finetuning Data Collector")
print("=================================")
print("This program collects typing audio and keystrokes for finetuning Whisper")
print("Press Ctrl+C to stop collection")
collector = TypingDataCollector()
try:
collector.start_collection()
except KeyboardInterrupt:
collector.prepare_finetuning_dataset()
print("Data collection complete")
if __name__ == "__main__":
# Install required dependencies:
# pip install pyaudio keyboard whisper openai numpy
# Note: On macOS, you might need to:
# 1. Grant microphone access
# 2. Grant accessibility permissions for keylogging
# 3. Install portaudio (for pyaudio): brew install portaudio
main()
To use this code, you'll need to:
- Install dependencies:
pip install pyaudio keyboard whisper openai numpy
brew install portaudio # On macOS
- Grant necessary permissions on macOS:
- Microphone access
- Accessibility permissions (for keylogging)
- Run the program:
python whisper_finetuning.py
The program will:
- Record audio in 5-second segments
- Log keystrokes with timestamps
- Save audio files and corresponding transcriptions
- Create a dataset in the format suitable for Whisper finetuning
The output dataset will be in JSONL format, where each line contains:
{
"audio": "path/to/audio.wav",
"text": "transcription of typed text",
"duration": 5.0,
"language": "en"
}
Important considerations:
-
Privacy and Ethics: Always get explicit user consent before collecting any data. Inform users about what data is being collected and how it will be used.
-
Security: Store collected data securely and consider encryption.
-
macOS Permissions: The program needs appropriate permissions to access the microphone and log keystrokes. Users will need to grant these permissions in System Preferences.
-
Data Quality: The quality of the finetuning will depend on the quality and quantity of collected data. Consider implementing data validation and cleaning steps.
-
Actual Finetuning: This code only collects data. To actually finetune Whisper, you'll need to use OpenAI's API or implement the finetuning process using the collected dataset.
To use this dataset for finetuning, you would need to:
- Collect a sufficient amount of data
- Validate and clean the dataset
- Use OpenAI's API or a custom training pipeline to finetune the model
Remember to handle the collected data responsibly and in compliance with applicable laws and regulations.