forked from Magnussmari/whisperSSTis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlauncher.py
1359 lines (1126 loc) · 52 KB
/
launcher.py
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import webbrowser
import torch
import sounddevice as sd
import numpy as np
import threading
from datetime import datetime
import tempfile
import soundfile as sf
from transformers import WhisperProcessor, WhisperForConditionalGeneration
from scipy import signal
import logging # Add at the top with other imports
import queue
import wave
import yt_dlp
import time
import psutil # Add to imports at top
import pyttsx3
# Add after imports, before class definition
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
class WhisperSSTLauncher:
def __init__(self):
self.root = tk.Tk()
self.root.title("WhisperSST.is")
self.root.geometry("1280x1024")
# Initialize variables first
self.model = None
self.processor = None
self.recording = False
self.audio_stream = None
self.current_text = ""
self.audio_buffer = []
self.buffer_duration = 3
self.target_sample_rate = 16000 # What Whisper expects
self.device_sample_rate = 48000 # Default device rate
self.full_recording = [] # Add this to store the complete recording
# Initialize device variables before setup_record_tab
self.devices, self.default_device = self.get_audio_devices()
self.device_var = tk.StringVar(self.root) # Initialize with root
self.device_var.set(self.default_device) # Set initial value
self.device_menu = None
# Add these new variables
self.last_recording = None # To store the last recording
self.is_playing = False
self.playback_thread = None
# Initialize TTS
try:
self.tts_engine = pyttsx3.init()
# Get all available voices
voices = self.tts_engine.getProperty('voices')
# Try to find Icelandic voice
icelandic_voice = None
for voice in voices:
# Check for Icelandic identifiers in voice name or ID
if any(identifier in voice.name.lower() for identifier in ['icelandic', 'íslenska', 'is-is', 'islensku']):
icelandic_voice = voice
break
# Set Icelandic voice if found, otherwise use default
if icelandic_voice:
self.tts_engine.setProperty('voice', icelandic_voice.id)
logging.info(f"Using Icelandic voice: {icelandic_voice.name}")
else:
logging.warning("No Icelandic voice found, using default voice")
# Set initial properties
self.tts_engine.setProperty('rate', 150) # Speed
self.tts_engine.setProperty('volume', 1.0) # Volume
self.tts_ready = True
except Exception as e:
logging.error(f"Failed to load TTS: {e}")
self.tts_ready = False
# Rest of initialization
try:
self.root.iconbitmap("whisper_icon.ico")
except:
pass
style = ttk.Style()
style.configure("TButton", padding=10)
# Main container
self.main_frame = ttk.Frame(self.root, padding="20")
self.main_frame.pack(fill=tk.BOTH, expand=True)
# Title
title_label = ttk.Label(
self.main_frame,
text="WhisperSST.is",
font=("Helvetica", 20, "bold")
)
title_label.pack(pady=10)
# Subtitle
subtitle_label = ttk.Label(
self.main_frame,
text="Icelandic Speech Recognition",
font=("Helvetica", 12)
)
subtitle_label.pack(pady=5)
# Notebook for tabs
self.notebook = ttk.Notebook(self.main_frame)
self.notebook.pack(fill=tk.BOTH, expand=True, pady=10)
# Create tabs
self.record_tab = ttk.Frame(self.notebook)
self.upload_tab = ttk.Frame(self.notebook)
self.youtube_tab = ttk.Frame(self.notebook) # Add new tab
self.notebook.add(self.record_tab, text="🎤 Record Audio")
self.notebook.add(self.upload_tab, text="📁 Upload Audio")
self.notebook.add(self.youtube_tab, text="▶️ YouTube") # Add new tab
# Setup recording tab
self.setup_record_tab()
# Setup upload tab
self.setup_upload_tab()
# Setup YouTube tab
self.setup_youtube_tab() # Add new setup
# Status bar with system info
status_frame = ttk.Frame(self.main_frame)
status_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=5)
# Device info
device_info = "🖥️ GPU (CUDA)" if torch.cuda.is_available() else "💻 CPU"
if torch.cuda.is_available():
device_info += f" - {torch.cuda.get_device_name(0)}"
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3 # Convert to GB
device_info += f" ({gpu_memory:.1f}GB)"
# System memory
system_memory = psutil.virtual_memory().total / (1024**3) # Convert to GB
device_info += f" | 💾 RAM: {system_memory:.1f}GB"
self.device_label = ttk.Label(
status_frame,
text=device_info,
font=("Helvetica", 9)
)
self.device_label.pack(side=tk.LEFT, padx=10)
# Add memory usage monitoring
self.memory_label = ttk.Label(
status_frame,
text="",
font=("Helvetica", 9)
)
self.memory_label.pack(side=tk.LEFT, padx=10)
# Status label (for model loading etc)
self.status_label = ttk.Label(
status_frame,
text="Loading model...",
font=("Helvetica", 9)
)
self.status_label.pack(side=tk.RIGHT, padx=10)
# Start memory monitoring
self.update_memory_usage()
# Progress bar for model loading
self.progress = ttk.Progressbar(
self.main_frame,
mode='indeterminate',
length=300
)
# Show progress bar immediately
self.progress.pack(pady=5)
self.progress.start()
# Load model in background
self.load_model_async()
def setup_record_tab(self):
"""Setup the recording tab interface."""
# Device selection
device_frame = ttk.LabelFrame(self.record_tab, text="Audio Device", padding=10)
device_frame.pack(fill=tk.X, padx=10, pady=5)
# Create device menu only if we have devices
if self.devices:
self.device_menu = ttk.OptionMenu(
device_frame,
self.device_var,
self.default_device,
*self.devices.keys()
)
self.device_menu.pack(fill=tk.X)
else:
# Show error if no devices found
ttk.Label(device_frame, text="No audio input devices found").pack()
# Recording controls
control_frame = ttk.Frame(self.record_tab, padding=10)
control_frame.pack(fill=tk.X, padx=10, pady=5)
# Use tk.Button instead of ttk.Button for recording
self.record_btn = tk.Button(
control_frame,
text="Start Recording",
command=self.toggle_recording,
state="disabled", # Start disabled
relief="raised",
bg="#f0f0f0", # Light gray - default button color
padx=10,
pady=5
)
self.record_btn.pack(pady=10)
# Add playback controls
playback_frame = ttk.Frame(self.record_tab, padding=10)
playback_frame.pack(fill=tk.X, padx=10, pady=5)
self.playback_btn = tk.Button(
playback_frame,
text="Play Last Recording",
command=self.toggle_playback,
state="disabled",
relief="raised",
bg="#f0f0f0",
padx=10,
pady=5
)
self.playback_btn.pack(pady=5)
# Transcription display
self.transcription_text = tk.Text(
self.record_tab,
height=10,
wrap=tk.WORD,
font=("Helvetica", 11)
)
self.transcription_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
# Add TTS controls
tts_frame = ttk.LabelFrame(self.record_tab, text="Text-to-Speech", padding=10)
tts_frame.pack(fill=tk.X, padx=10, pady=5)
# Add controls
self.setup_tts_controls(tts_frame)
# Speak button
self.tts_btn = ttk.Button(
tts_frame,
text="🔊 Speak Text",
command=self.speak_text,
state="disabled" if not self.tts_ready else "normal"
)
self.tts_btn.pack(pady=5)
def setup_upload_tab(self):
"""Setup the file upload tab interface."""
upload_frame = ttk.Frame(self.upload_tab, padding=10)
upload_frame.pack(fill=tk.BOTH, expand=True)
upload_btn = ttk.Button(
upload_frame,
text="Choose Audio File",
command=self.choose_file
)
upload_btn.pack(pady=10)
self.file_label = ttk.Label(
upload_frame,
text="No file selected",
font=("Helvetica", 9)
)
self.file_label.pack(pady=5)
self.upload_text = tk.Text(
upload_frame,
height=10,
wrap=tk.WORD,
font=("Helvetica", 11)
)
self.upload_text.pack(fill=tk.BOTH, expand=True, pady=5)
def setup_youtube_tab(self):
"""Setup the YouTube tab interface."""
# Main container
youtube_frame = ttk.Frame(self.youtube_tab, padding=10)
youtube_frame.pack(fill=tk.BOTH, expand=True)
# URL input
url_frame = ttk.Frame(youtube_frame)
url_frame.pack(fill=tk.X, pady=5)
ttk.Label(url_frame, text="YouTube URL:").pack(side=tk.LEFT, padx=5)
self.url_var = tk.StringVar()
url_entry = ttk.Entry(url_frame, textvariable=self.url_var, width=50)
url_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Video title label
self.video_title_label = ttk.Label(
youtube_frame,
text="",
font=("Helvetica", 10, "italic"),
wraplength=500 # Wrap long titles
)
self.video_title_label.pack(pady=5)
# Process button
self.youtube_btn = ttk.Button(
youtube_frame,
text="Process Video",
command=self.process_youtube
)
self.youtube_btn.pack(pady=10)
# Progress frame
self.progress_frame = ttk.LabelFrame(youtube_frame, text="Progress", padding=10)
self.progress_frame.pack(fill=tk.X, pady=5)
# Download progress
ttk.Label(self.progress_frame, text="Download:").pack(anchor=tk.W)
self.download_progress = ttk.Progressbar(
self.progress_frame,
mode='determinate',
length=300
)
self.download_progress.pack(fill=tk.X, pady=2)
# Processing progress
ttk.Label(self.progress_frame, text="Processing:").pack(anchor=tk.W)
self.processing_progress = ttk.Progressbar(
self.progress_frame,
mode='indeterminate',
length=300
)
self.processing_progress.pack(fill=tk.X, pady=2)
# Status label
self.youtube_status = ttk.Label(
youtube_frame,
text="Ready",
font=("Helvetica", 9)
)
self.youtube_status.pack(pady=5)
# Transcription display
self.youtube_text = tk.Text(
youtube_frame,
height=10,
wrap=tk.WORD,
font=("Helvetica", 11)
)
self.youtube_text.pack(fill=tk.BOTH, expand=True, pady=5)
# Add TTS button to YouTube tab
tts_frame = ttk.LabelFrame(youtube_frame, text="Text-to-Speech", padding=10)
tts_frame.pack(fill=tk.X, pady=5)
# Add controls
self.setup_tts_controls(tts_frame)
self.youtube_tts_btn = ttk.Button(
tts_frame,
text="🔊 Speak Text",
command=lambda: self.speak_text(source='youtube'),
state="disabled" if not self.tts_ready else "normal"
)
self.youtube_tts_btn.pack(pady=5)
def get_audio_devices(self):
"""Get available audio input devices."""
devices = {}
try:
# Get default input device
default_device = sd.default.device[0]
logging.info(f"System default input device index: {default_device}")
# Get all devices first
all_devices = sd.query_devices()
logging.info(f"All available devices: {all_devices}")
# Get default device info
default_info = all_devices[default_device]
logging.info(f"Default device info: {default_info}")
# Create consistent key for default device
default_name = default_info.get('name', 'default')
default_key = f"Default - {default_name} (ID: {default_device})"
devices[default_key] = default_device
logging.info(f"Added default device with key: {default_key}")
# Add other input devices
for i, dev in enumerate(all_devices):
if dev['max_input_channels'] > 0 and i != default_device:
name = f"{dev['name']} (ID: {i})"
devices[name] = i
logging.info(f"Added additional device: {name}")
logging.info(f"Final devices dictionary: {devices}")
logging.info(f"Default key: {default_key}")
except Exception as e:
logging.error(f"Error getting audio devices: {e}", exc_info=True)
default_key = "Default System Device"
devices[default_key] = None
return devices, default_key
def load_model_async(self):
"""Load the Whisper model in a background thread."""
def load():
try:
model_name = "carlosdanielhernandezmena/whisper-large-icelandic-10k-steps-1000h"
self.processor = WhisperProcessor.from_pretrained(model_name)
device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = WhisperForConditionalGeneration.from_pretrained(model_name).to(device)
self.root.after(0, self.model_loaded)
except Exception as e:
self.root.after(0, lambda: self.show_error(f"Failed to load model: {str(e)}"))
thread = threading.Thread(target=load)
thread.daemon = True
thread.start()
def model_loaded(self):
"""Called when model is loaded successfully."""
self.progress.stop()
self.progress.pack_forget()
self.status_label.config(text="Model loaded - Ready")
self.record_btn.config(state="normal") # Enable button when model is loaded
def toggle_recording(self):
"""Toggle audio recording on/off."""
if not self.recording:
self.start_recording()
else:
self.stop_recording()
def start_recording(self):
"""Start audio recording."""
if not self.model:
self.show_error("Please wait for the model to load")
return
if not self.devices:
self.show_error("No audio input devices available")
return
try:
selected_device = self.device_var.get()
if not selected_device:
self.show_error("No audio device selected")
return
logging.info(f"Selected device: {selected_device}")
logging.info(f"Available devices: {self.devices}")
if selected_device not in self.devices:
logging.error(f"Selected device '{selected_device}' not found in devices dictionary")
raise KeyError(f"Device '{selected_device}' not found")
device_id = self.devices[selected_device]
logging.info(f"Device ID: {device_id}")
if device_id is None:
device_id = sd.default.device[0]
logging.info(f"Using system default device ID: {device_id}")
# Log device details
device_info = sd.query_devices(device_id)
logging.info(f"Device details: {device_info}")
self.recording = True
self.full_recording = [] # Reset full recording buffer
self.record_btn.config(
text="Stop Recording",
bg="#ff0000",
activebackground="#cc0000"
)
self.transcription_text.delete(1.0, tk.END)
self.current_text = ""
logging.info("Starting recording thread")
self.record_thread = threading.Thread(target=self.record_audio)
self.record_thread.daemon = True
self.record_thread.start()
except Exception as e:
logging.error(f"Failed to start recording: {e}", exc_info=True)
self.show_error(f"Failed to start recording: {str(e)}")
def stop_recording(self):
"""Stop audio recording and process the complete recording."""
self.recording = False
self.record_btn.config(
text="Processing...",
state="disabled"
)
# Process the complete recording
if self.audio_buffer:
try:
# Concatenate all audio data
audio_data = np.concatenate(self.audio_buffer)
# Store for playback
self.last_recording = {
'data': audio_data.copy(),
'sample_rate': self.device_sample_rate
}
# Enable playback button
self.playback_btn.config(state="normal")
# Prepare audio for processing
audio_data = audio_data.flatten()
audio_data = audio_data.astype(np.float32)
# Resample if needed
if self.device_sample_rate != self.target_sample_rate:
logging.info(f"Resampling from {self.device_sample_rate} to {self.target_sample_rate}")
audio_data = self.resample_audio(
audio_data,
self.device_sample_rate,
self.target_sample_rate
)
# Process in separate thread
process_thread = threading.Thread(
target=self.process_audio,
args=(audio_data,)
)
process_thread.daemon = True
process_thread.start()
except Exception as e:
logging.error(f"Error processing recording: {e}")
self.show_error("Error processing recording")
finally:
# Clear the buffer
self.audio_buffer = []
# Reset button state
self.record_btn.config(
text="Start Recording",
bg="#f0f0f0",
activebackground="#e0e0e0",
state="normal"
)
def record_audio(self):
"""Record and process audio in real-time."""
try:
selected_device = self.device_var.get()
logging.info(f"Recording thread - Selected device: {selected_device}")
device_id = self.devices[selected_device]
logging.info(f"Recording thread - Device ID: {device_id}")
if device_id is None:
device_id = sd.default.device[0]
logging.info(f"Recording thread - Using system default device ID: {device_id}")
# Get device info and its supported sample rate
device_info = sd.query_devices(device_id)
self.device_sample_rate = int(device_info['default_samplerate'])
logging.info(f"Using device sample rate: {self.device_sample_rate}")
self.audio_buffer = []
logging.info(f"Starting InputStream with device {device_id}, sample rate {self.device_sample_rate}")
with sd.InputStream(
device=device_id,
channels=1,
samplerate=self.device_sample_rate, # Use device's native rate
blocksize=int(self.device_sample_rate * 0.5), # 0.5 second chunks
callback=self.audio_callback
) as stream:
logging.info("Audio stream started successfully")
while self.recording:
sd.sleep(100)
except Exception as e:
error_msg = str(e) # Capture error message
self.root.after(0, lambda: self.show_error(f"Recording error: {error_msg}"))
def audio_callback(self, indata, frames, time, status):
"""Process recorded audio chunks."""
if status:
logging.warning(f"Audio callback status: {status}")
if self.recording:
try:
# Only store the audio data, don't process
self.audio_buffer.append(indata.copy())
except Exception as e:
logging.error(f"Error in audio callback: {e}")
self.recording = False
def process_audio(self, audio_data):
"""Process audio data and update transcription."""
try:
logging.info("Starting audio processing")
self.status_label.config(text="Processing audio...")
# Ensure audio data is in the right format
audio_data = audio_data.astype(np.float32)
# Normalize if needed
if np.abs(audio_data).max() > 1.0:
audio_data = audio_data / np.abs(audio_data).max()
logging.info(f"Processing audio of shape: {audio_data.shape}")
# Convert audio to features
input_features = self.processor(
audio_data,
sampling_rate=self.target_sample_rate,
return_tensors="pt"
).input_features.to(self.model.device)
# Generate transcription with Icelandic language
predicted_ids = self.model.generate(
input_features,
language="<|is|>",
task="transcribe"
)
transcription = self.processor.batch_decode(
predicted_ids,
skip_special_tokens=True
)[0]
logging.info(f"Transcription result: {transcription}")
# Update UI in main thread
if transcription.strip():
self.root.after(0, lambda: self.update_transcription(transcription))
self.root.after(0, lambda: self.status_label.config(text="Ready"))
except Exception as e:
logging.error(f"Error in process_audio: {e}", exc_info=True)
self.root.after(0, lambda: self.status_label.config(text="Error processing audio"))
self.root.after(0, lambda: self.show_error(f"Processing error: {str(e)}"))
def process_text_formatting(self, text):
"""Process text to add proper capitalization and periods."""
# Initial cleanup
text = text.strip()
if not text:
return text
# Common Icelandic abbreviations to preserve
abbreviations = ['hr.', 'dr.', 'pr.', 'sr.', 't.d.', 'o.s.frv.', 'þ.e.', 'þ.e.a.s.']
# Split into potential sentences (keeping abbreviations intact)
raw_sentences = []
current = []
words = text.split()
for i, word in enumerate(words):
current.append(word)
# Check if this word ends a sentence
ends_sentence = False
# Check if word is not an abbreviation
if word not in abbreviations:
# Check for sentence endings
if (i == len(words) - 1 or # Last word
word.endswith(('.', '!', '?')) or # Has ending punctuation
(len(word) > 1 and not word[-1].isalnum() and not word.endswith('.')) or # Non-period punctuation
# Next word starts with capital (unless it's "I" or "É")
(i < len(words) - 1 and words[i + 1][0].isupper() and
not words[i + 1].startswith(('I ', 'É'))) or
# Long pause indicated by multiple spaces or punctuation
(i < len(words) - 1 and (word.endswith(',') or word.endswith(';')))
):
ends_sentence = True
if ends_sentence:
sentence = ' '.join(current)
# Add period if no ending punctuation
if not sentence[-1] in '.!?':
sentence += '.'
raw_sentences.append(sentence)
current = []
# Handle any remaining words
if current:
sentence = ' '.join(current)
if not sentence[-1] in '.!?':
sentence += '.'
raw_sentences.append(sentence)
# Process each sentence
processed_sentences = []
for sentence in raw_sentences:
# Capitalize first letter if it's a letter
if sentence and sentence[0].isalpha():
sentence = sentence[0].upper() + sentence[1:]
# Fix spacing around punctuation
sentence = sentence.replace(' ,', ',')
sentence = sentence.replace(' .', '.')
sentence = sentence.replace(' !', '!')
sentence = sentence.replace(' ?', '?')
sentence = sentence.replace(' :', ':')
sentence = sentence.replace(' ;', ';')
# Add proper spacing after punctuation
for punct in ['.', ',', '!', '?', ':', ';']:
sentence = sentence.replace(f"{punct}", f"{punct} ")
# Clean up multiple spaces
sentence = ' '.join(sentence.split())
processed_sentences.append(sentence)
# Join sentences with proper spacing
final_text = ' '.join(processed_sentences)
# Final cleanup of any double spaces
final_text = ' '.join(final_text.split())
return final_text
def update_transcription(self, text):
"""Update the transcription display smoothly."""
logging.info(f"Updating transcription with: {text}")
# Process text formatting
text = self.process_text_formatting(text)
# Clean up the text
text = text.strip()
# If this is a continuation of previous text, append it
if text.lower().startswith(self.current_text.lower()):
new_part = text[len(self.current_text):].strip()
if new_part:
self.transcription_text.insert(tk.END, new_part + " ")
self.current_text = text
else:
# If it's new text, add it on a new line
if self.current_text: # If there was previous text
self.transcription_text.insert(tk.END, "\n")
self.transcription_text.insert(tk.END, text + " ")
self.current_text = text
self.transcription_text.see(tk.END)
def choose_file(self):
"""Open file chooser dialog."""
file_path = filedialog.askopenfilename(
filetypes=[
("Audio Files", "*.wav *.mp3 *.m4a *.flac"),
("All Files", "*.*")
]
)
if file_path:
self.process_file(file_path)
def process_file(self, file_path):
"""Process an audio file."""
if not self.model:
self.show_error("Please wait for the model to load")
return
self.file_label.config(text=os.path.basename(file_path))
self.status_label.config(text="Processing audio file...")
self.progress.pack(pady=5)
self.progress.start()
def process():
try:
# Load and process audio file
audio_data, sr = sf.read(file_path)
if sr != 16000:
# Resample if needed
audio_data = self.resample_audio(audio_data, sr, 16000)
# Process audio
input_features = self.processor(
audio_data,
sampling_rate=16000,
return_tensors="pt"
).input_features.to(self.model.device) # Move to same device as model
# Generate transcription with Icelandic language
predicted_ids = self.model.generate(
input_features,
language="<|is|>", # Specify Icelandic
task="transcribe"
)
transcription = self.processor.batch_decode(
predicted_ids,
skip_special_tokens=True
)[0]
# Update UI in main thread
self.root.after(0, lambda: self.file_processed(transcription))
except Exception as e:
error_msg = str(e)
self.root.after(0, lambda: self.show_error(f"Failed to process file: {error_msg}"))
thread = threading.Thread(target=process)
thread.daemon = True
thread.start()
def file_processed(self, transcription):
"""Called when file processing is complete."""
self.progress.stop()
self.progress.pack_forget()
self.status_label.config(text="File processed")
# Process text formatting
formatted_text = self.process_text_formatting(transcription)
# Update text widget
self.upload_text.delete(1.0, tk.END)
self.upload_text.insert(tk.END, formatted_text)
self.current_text = "" # Reset current text
def resample_audio(self, audio_data, orig_sr, target_sr):
"""Resample audio to target sample rate."""
# Calculate resampling ratio
ratio = target_sr / orig_sr
output_length = int(len(audio_data) * ratio)
# Use scipy's resample function
return signal.resample(audio_data, output_length)
def show_error(self, message):
"""Show error message."""
messagebox.showerror("Error", message)
self.status_label.config(text="Error occurred")
self.progress.stop()
self.progress.pack_forget()
def on_device_change(self, *args):
"""Handle device selection changes."""
logging.info(f"Device changed to: {self.device_var.get()}")
logging.info(f"Current devices: {self.devices}")
def refresh_devices(self):
"""Refresh the list of audio devices."""
try:
# Get updated devices
self.devices, new_default = self.get_audio_devices()
if self.device_menu is None:
logging.warning("Device menu not initialized")
return
# Update the OptionMenu
menu = self.device_menu['menu']
menu.delete(0, 'end')
for device in self.devices.keys():
menu.add_command(
label=device,
command=lambda d=device: self.device_var.set(d)
)
# Set to default if current selection is not available
current = self.device_var.get()
if current not in self.devices:
self.device_var.set(new_default)
logging.info(f"Devices refreshed: {self.devices}")
except Exception as e:
logging.error(f"Error refreshing devices: {e}", exc_info=True)
def toggle_playback(self):
"""Toggle playback of last recording."""
if not self.last_recording:
return
if self.is_playing:
self.stop_playback()
else:
self.start_playback()
def start_playback(self):
"""Start playing the last recording."""
if not self.last_recording:
return
try:
self.is_playing = True
self.playback_btn.config(
text="Stop Playback",
bg="#4CAF50", # Green
activebackground="#45a049"
)
# Start playback in a separate thread
self.playback_thread = threading.Thread(target=self.play_audio)
self.playback_thread.daemon = True
self.playback_thread.start()
except Exception as e:
logging.error(f"Error starting playback: {e}")
self.show_error("Failed to start playback")
self.stop_playback()
def stop_playback(self):
"""Stop the audio playback."""
self.is_playing = False
self.playback_btn.config(
text="Play Last Recording",
bg="#f0f0f0",
activebackground="#e0e0e0"
)
def play_audio(self):
"""Play the audio data."""
try:
# Create a stream for playback
with sd.OutputStream(
channels=1,
samplerate=self.last_recording['sample_rate'],
callback=self.playback_callback
) as stream:
while self.is_playing:
sd.sleep(100)
except Exception as e:
logging.error(f"Playback error: {e}")
self.root.after(0, self.stop_playback)
def playback_callback(self, outdata, frames, time, status):
"""Callback for audio playback."""
if status:
logging.warning(f"Playback status: {status}")
try:
if self.is_playing and self.last_recording:
# Get the data to play
data = self.last_recording['data']
if len(data) > 0:
# Copy data to output buffer
if len(data) >= len(outdata):
outdata[:] = data[:len(outdata)]
self.last_recording['data'] = data[len(outdata):]
else:
outdata[:len(data)] = data
outdata[len(data):] = 0
self.last_recording['data'] = np.array([])
# Stop when we're done
self.root.after(0, self.stop_playback)
except Exception as e:
logging.error(f"Error in playback callback: {e}")
self.root.after(0, self.stop_playback)
def process_youtube(self):
"""Process YouTube video URL."""
url = self.url_var.get().strip()
if not url:
self.show_error("Please enter a YouTube URL")
return
if not self.model:
self.show_error("Please wait for the model to load")
return
# Disable button while processing
self.youtube_btn.config(state="disabled")
self.youtube_status.config(text="Starting download...")
self.download_progress['value'] = 0
self.processing_progress.stop()
# Start processing in background
thread = threading.Thread(target=self.download_and_process_youtube)
thread.daemon = True
thread.start()
def download_and_process_youtube(self):
"""Download and process YouTube video."""
try:
with tempfile.TemporaryDirectory() as temp_dir: