Phone-FA-EN-AR-Dataset / DatasetRecorder /datasetRecorderGUI.py
mah92's picture
Upload 5 files
35d0f94 verified
# Besm ALLAH
# Code for recording audio dataset, reads a txt file placed nearby. The txt file is assumed to have a single column with normalized text
# pip install PyQt5 sounddevice soundfile numpy
# sudo apt-get install libportaudio2
import sys
import os
import re
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
QPushButton, QLabel, QHBoxLayout, QLineEdit)
from PyQt5.QtCore import Qt, QTimer
import sounddevice as sd
import soundfile as sf
import numpy as np
import glob
class VoiceRecorderApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Voice Recorder")
self.setGeometry(100, 100, 800, 600) # Increased window size
# Recording variables
self.is_recording = False
self.recording = None
self.fs = 44100
self.current_number = 0
self.lines = []
# Create wav directory if it doesn't exist
os.makedirs("wav", exist_ok=True)
self.init_ui()
self.load_text_file()
self.find_next_available_number()
def init_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout()
# Button row
button_row = QHBoxLayout()
# Record button (now wider)
self.record_btn = QPushButton("🎤 Start Recording (Space)")
self.record_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
font-size: 16px;
padding: 15px 30px;
min-width: 200px;
}
""")
self.record_btn.clicked.connect(self.toggle_recording)
button_row.addWidget(self.record_btn)
# Recording indicator
self.recording_indicator = QLabel()
self.recording_indicator.setFixedSize(40, 40)
button_row.addWidget(self.recording_indicator)
# Stop button
self.stop_btn = QPushButton("⏹ Stop & Save (Space)")
self.stop_btn.setStyleSheet("""
QPushButton {
background-color: #2196F3;
color: white;
font-size: 16px;
padding: 15px 30px;
min-width: 200px;
}
QPushButton:disabled {
background-color: #cccccc;
}
""")
self.stop_btn.clicked.connect(self.stop_recording)
self.stop_btn.setEnabled(False)
button_row.addWidget(self.stop_btn)
# Skip button
self.skip_btn = QPushButton("⏭ Skip (S)")
self.skip_btn.setStyleSheet("""
QPushButton {
background-color: #FF9800;
color: white;
font-size: 16px;
padding: 15px 30px;
min-width: 200px;
}
QPushButton:disabled {
background-color: #cccccc;
}
""")
self.skip_btn.clicked.connect(self.skip_recording)
self.skip_btn.setEnabled(False)
button_row.addWidget(self.skip_btn)
# Cancel button
self.cancel_btn = QPushButton("✖ Cancel (ESC)")
self.cancel_btn.setStyleSheet("""
QPushButton {
background-color: #f44336;
color: white;
font-size: 16px;
padding: 15px 30px;
min-width: 200px;
}
QPushButton:disabled {
background-color: #cccccc;
}
""")
self.cancel_btn.clicked.connect(self.cancel_recording)
self.cancel_btn.setEnabled(False)
button_row.addWidget(self.cancel_btn)
layout.addLayout(button_row)
# Status label
self.status_label = QLabel("Ready to record (Press Space to start)")
self.status_label.setStyleSheet("font-size: 16px;")
layout.addWidget(self.status_label)
# Current number display (moved below buttons)
counter_row = QHBoxLayout()
counter_label = QLabel("Current #:")
counter_label.setStyleSheet("font-size: 18px;")
self.counter_display = QLineEdit("0000")
self.counter_display.setReadOnly(True)
self.counter_display.setStyleSheet("""
QLineEdit {
font-size: 24px;
font-weight: bold;
border: 2px solid #ccc;
padding: 10px;
min-width: 100px;
max-width: 100px;
}
""")
self.counter_display.setAlignment(Qt.AlignCenter)
counter_row.addWidget(counter_label)
counter_row.addWidget(self.counter_display)
counter_row.addStretch()
layout.addLayout(counter_row)
# Text display with larger font
self.file_label = QLabel()
self.file_label.setStyleSheet("""
QLabel {
font-size: 36px;
padding: 20px;
border: 2px solid #ddd;
background-color: #f9f9f9;
min-height: 200px;
qproperty-alignment: 'AlignTop | AlignRight';
}
""")
self.file_label.setWordWrap(True)
layout.addWidget(self.file_label)
central_widget.setLayout(layout)
# Keyboard shortcuts
self.record_btn.setShortcut("Space")
self.stop_btn.setShortcut("Space")
self.skip_btn.setShortcut("S")
self.cancel_btn.setShortcut("Escape")
def process_text_with_directions(self, text):
"""
Process text to automatically insert line breaks at script changes.
Returns formatted text with RTL/LTR markers and the overall direction.
"""
if not text:
return "", Qt.LeftToRight
# Split text into segments by script
segments = []
current_script = None
current_segment = []
for char in text:
# Determine script for current character
if '\u0600' <= char <= '\u06FF' or '\u0750' <= char <= '\u077F':
char_script = 'rtl'
elif char.isalpha():
char_script = 'ltr'
else:
char_script = current_script # Non-letters inherit current script
# Start new segment if script changes
if char_script != current_script and current_segment:
segments.append((''.join(current_segment), current_script))
current_segment = []
current_script = char_script
current_segment.append(char)
# Add the last segment
if current_segment:
segments.append((''.join(current_segment), current_script))
# Determine overall direction
overall_direction = Qt.RightToLeft if any(s[1] == 'rtl' for s in segments) else Qt.LeftToRight
# Format segments with proper direction markers
formatted_lines = []
for segment, script in segments:
if script == 'rtl':
formatted_lines.append("\u202B" + segment + "\u202C") # RTL embedding
else:
formatted_lines.append("\u202A" + segment + "\u202C") # LTR embedding
return '\n'.join(formatted_lines), overall_direction
def load_text_file(self):
"""Load text file and prepare lines"""
try:
txt_files = glob.glob('*.txt')
if not txt_files:
self.status_label.setText("No .txt file found in directory")
return
with open(txt_files[0], 'r', encoding='utf-8') as f:
raw_lines = [line.strip() for line in f.readlines() if line.strip()]
if not raw_lines:
self.status_label.setText("Text file is empty")
self.record_btn.setEnabled(False)
return
# Process each line for proper direction handling
self.lines = []
for line in raw_lines:
processed_line, _ = self.process_text_with_directions(line)
self.lines.append(processed_line)
except Exception as e:
self.status_label.setText(f"Error reading file: {str(e)}")
def find_next_available_number(self):
"""Find the next available WAV file number, considering gaps"""
existing_files = glob.glob('wav/*.wav')
existing_numbers = []
for f in existing_files:
try:
num = int(os.path.splitext(os.path.basename(f))[0])
existing_numbers.append(num)
except ValueError:
continue
if not existing_numbers:
self.current_number = 1
else:
max_num = max(existing_numbers)
all_numbers = set(range(1, max_num + 1))
missing = sorted(all_numbers - set(existing_numbers))
if missing:
self.current_number = missing[0] # Use first gap
else:
self.current_number = max_num + 1 # No gaps, use next number
self.update_display()
def update_display(self):
"""Update counter and display processed text"""
self.counter_display.setText(f"{self.current_number:04d}")
line_index = self.current_number - 1
if line_index < len(self.lines):
display_text = self.lines[line_index]
# Determine overall direction for alignment
if any('\u202B' in part for part in display_text.split('\n')):
self.file_label.setLayoutDirection(Qt.RightToLeft)
self.file_label.setAlignment(Qt.AlignRight | Qt.AlignTop)
else:
self.file_label.setLayoutDirection(Qt.LeftToRight)
self.file_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
self.file_label.setText(display_text)
else:
self.file_label.setText("No text available for this number")
def toggle_recording(self):
if self.is_recording:
self.stop_recording()
else:
self.start_recording()
def start_recording(self):
self.is_recording = True
self.recording = []
# Update UI
self.record_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.skip_btn.setEnabled(True)
self.cancel_btn.setEnabled(True)
self.status_label.setText("Recording... (Space=Stop, S=Skip, ESC=Cancel)")
self.status_label.setStyleSheet("color: red; font-size: 12px;")
# Show recording indicator
self.recording_indicator.setStyleSheet("background-color: red; border-radius: 15px;")
self.indicator_animation()
# Start recording
def callback(indata, frames, time, status):
if self.is_recording:
self.recording.append(indata.copy())
self.stream = sd.InputStream(
samplerate=self.fs,
channels=1,
callback=callback,
dtype='float32'
)
self.stream.start()
def indicator_animation(self):
if self.is_recording:
current_color = self.recording_indicator.styleSheet()
new_color = "background-color: darkred; border-radius: 15px;" if "red" in current_color else "background-color: red; border-radius: 15px;"
self.recording_indicator.setStyleSheet(new_color)
QTimer.singleShot(500, self.indicator_animation)
def stop_recording(self):
self.is_recording = False
if hasattr(self, 'stream'):
self.stream.stop()
self.stream.close()
# Save recording
if len(self.recording) > 0:
recording_array = np.concatenate(self.recording, axis=0)
wav_path = f"wav/{self.current_number:04d}.wav"
sf.write(wav_path, recording_array, self.fs)
# Find next available number
self.find_next_available_number()
# Update UI
self.reset_ui()
self.status_label.setText("Recording saved")
self.status_label.setStyleSheet("color: green; font-size: 12px;")
self.recording_indicator.setStyleSheet("")
def skip_recording(self):
"""Skip current recording by saving empty WAV file"""
self.is_recording = False
if hasattr(self, 'stream'):
self.stream.stop()
self.stream.close()
# Save empty WAV file
empty_array = np.zeros(0, dtype='float32')
wav_path = f"wav/{self.current_number:04d}.wav"
sf.write(wav_path, empty_array, self.fs)
# Find next available number
self.find_next_available_number()
# Update UI
self.reset_ui()
self.status_label.setText("Recording skipped (empty file saved)")
self.status_label.setStyleSheet("color: orange; font-size: 12px;")
self.recording_indicator.setStyleSheet("")
def cancel_recording(self):
self.is_recording = False
if hasattr(self, 'stream'):
self.stream.stop()
self.stream.close()
# Update UI
self.reset_ui()
self.status_label.setText("Recording canceled")
self.status_label.setStyleSheet("color: orange; font-size: 12px;")
self.recording_indicator.setStyleSheet("")
def reset_ui(self):
self.record_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.skip_btn.setEnabled(False)
self.cancel_btn.setEnabled(False)
if __name__ == "__main__":
app = QApplication(sys.argv)
recorder = VoiceRecorderApp()
recorder.show()
sys.exit(app.exec_())