Datasets:
File size: 14,160 Bytes
35d0f94 |
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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
# 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_()) |