-
Notifications
You must be signed in to change notification settings - Fork 785
/
gui.py
1470 lines (1120 loc) · 60.7 KB
/
gui.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 enum
import gettext
import json
import logging
import os
import platform
import sys
from datetime import datetime
from enum import auto
from typing import Dict, List, Optional, Tuple
import humanize
import sounddevice
from PyQt6 import QtGui
from PyQt6.QtCore import (QObject, Qt, QThread,
QTimer, QUrl, pyqtSignal, QModelIndex, QSize, QPoint,
QUrlQuery, QMetaObject, QEvent, QLocale)
from PyQt6.QtGui import (QAction, QCloseEvent, QDesktopServices, QIcon,
QKeySequence, QPixmap, QTextCursor, QValidator, QKeyEvent, QPainter, QColor)
from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PyQt6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialog,
QDialogButtonBox, QFileDialog, QLabel, QLineEdit,
QMainWindow, QMessageBox, QPlainTextEdit,
QProgressDialog, QPushButton, QVBoxLayout, QHBoxLayout, QMenu,
QWidget, QGroupBox, QToolBar, QTableWidget, QMenuBar, QFormLayout, QTableWidgetItem,
QHeaderView, QAbstractItemView, QListWidget, QListWidgetItem, QToolButton, QSizePolicy)
from whisper import tokenizer
from buzz.cache import TasksCache
from .__version__ import VERSION
from .model_loader import ModelLoader, WhisperModelSize, ModelType, TranscriptionModel
from .recording import RecordingAmplitudeListener
from .transcriber import (SUPPORTED_OUTPUT_FORMATS, FileTranscriptionOptions, OutputFormat,
Task,
get_default_output_file_path, segments_to_text, write_output, TranscriptionOptions,
FileTranscriberQueueWorker, FileTranscriptionTask, RecordingTranscriber, LOADED_WHISPER_DLL)
APP_NAME = 'Buzz'
def get_asset_path(path: str):
if getattr(sys, 'frozen', False):
return os.path.join(os.path.dirname(sys.executable), path)
return os.path.join(os.path.dirname(__file__), '..', path)
if 'LANG' not in os.environ:
language = str(QLocale().uiLanguages()[0]).replace("-", "_")
os.environ['LANG'] = language
locale_dir = get_asset_path('locale')
gettext.bindtextdomain('buzz', locale_dir)
translate = gettext.translation(APP_NAME, locale_dir, fallback=True)
_ = translate.gettext
def get_platform_styles(all_platform_styles: Dict[str, str]):
return all_platform_styles.get(platform.system(), '')
def file_paths_as_title(file_paths: List[str]):
return ', '.join([file_path_as_title(path) for path in file_paths])
def file_path_as_title(file_path: str):
return os.path.basename(file_path)
class FormLabel(QLabel):
def __init__(self, name: str, parent: Optional[QWidget], *args) -> None:
super().__init__(name, parent, *args)
self.setStyleSheet('QLabel { text-align: right; }')
self.setAlignment(Qt.AlignmentFlag(
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignRight))
class AudioDevicesComboBox(QComboBox):
"""AudioDevicesComboBox displays a list of available audio input devices"""
device_changed = pyqtSignal(int)
audio_devices: List[Tuple[int, str]]
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.audio_devices = self.get_audio_devices()
self.addItems([device[1] for device in self.audio_devices])
self.currentIndexChanged.connect(self.on_index_changed)
default_device_id = self.get_default_device_id()
if default_device_id != -1:
for i, device in enumerate(self.audio_devices):
if device[0] == default_device_id:
self.setCurrentIndex(i)
def get_audio_devices(self) -> List[Tuple[int, str]]:
try:
devices: sounddevice.DeviceList = sounddevice.query_devices()
return [(device.get('index'), device.get('name'))
for device in devices if device.get('max_input_channels') > 0]
except UnicodeDecodeError:
QMessageBox.critical(
self, '',
'An error occurred while loading your audio devices. Please check the application logs for more '
'information.')
return []
def on_index_changed(self, index: int):
self.device_changed.emit(self.audio_devices[index][0])
def get_default_device_id(self) -> Optional[int]:
default_system_device = sounddevice.default.device[0]
if default_system_device != -1:
return default_system_device
audio_devices = self.get_audio_devices()
if len(audio_devices) > 0:
return audio_devices[0][0]
return -1
class LanguagesComboBox(QComboBox):
"""LanguagesComboBox displays a list of languages available to use with Whisper"""
# language is a language key from whisper.tokenizer.LANGUAGES or '' for "detect language"
languageChanged = pyqtSignal(str)
def __init__(self, default_language: Optional[str], parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
whisper_languages = sorted(
[(lang, tokenizer.LANGUAGES[lang].title()) for lang in tokenizer.LANGUAGES], key=lambda lang: lang[1])
self.languages = [('', _('Detect Language'))] + whisper_languages
self.addItems([lang[1] for lang in self.languages])
self.currentIndexChanged.connect(self.on_index_changed)
default_language_key = default_language if default_language != '' else None
for i, lang in enumerate(self.languages):
if lang[0] == default_language_key:
self.setCurrentIndex(i)
def on_index_changed(self, index: int):
self.languageChanged.emit(self.languages[index][0])
class TasksComboBox(QComboBox):
"""TasksComboBox displays a list of tasks available to use with Whisper"""
taskChanged = pyqtSignal(Task)
def __init__(self, default_task: Task, parent: Optional[QWidget], *args) -> None:
super().__init__(parent, *args)
self.tasks = [i for i in Task]
self.addItems(map(lambda task: task.value.title(), self.tasks))
self.currentIndexChanged.connect(self.on_index_changed)
self.setCurrentText(default_task.value.title())
def on_index_changed(self, index: int):
self.taskChanged.emit(self.tasks[index])
class TextDisplayBox(QPlainTextEdit):
"""TextDisplayBox is a read-only textbox"""
def __init__(self, parent: Optional[QWidget], *args) -> None:
super().__init__(parent, *args)
self.setReadOnly(True)
class RecordButton(QPushButton):
def __init__(self, parent: Optional[QWidget]) -> None:
super().__init__(_("Record"), parent)
self.setDefault(True)
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
def set_stopped(self):
self.setText(_('Record'))
self.setDefault(True)
def set_recording(self):
self.setText(_('Stop'))
self.setDefault(False)
class DownloadModelProgressDialog(QProgressDialog):
start_time: datetime
def __init__(self, parent: Optional[QWidget], *args) -> None:
super().__init__(_('Downloading model (0%, unknown time remaining)'),
_('Cancel'), 0, 100, parent, *args)
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.start_time = datetime.now()
self.setFixedSize(self.size())
def set_fraction_completed(self, fraction_completed: float) -> None:
self.setValue(int(fraction_completed * self.maximum()))
if fraction_completed > 0.0:
time_spent = (datetime.now() - self.start_time).total_seconds()
time_left = (time_spent / fraction_completed) - time_spent
self.setLabelText(_('Downloading model') +
f' ({fraction_completed :.0%}, ' +
humanize.naturaldelta(time_left) + ')')
def show_model_download_error_dialog(parent: QWidget, error: str):
message = parent.tr(
'An error occurred while loading the Whisper model') + \
f": {error}{'' if error.endswith('.') else '.'}" + \
parent.tr("Please retry or check the application logs for more information.")
QMessageBox.critical(parent, '', message)
class FileTranscriberWidget(QWidget):
model_download_progress_dialog: Optional[DownloadModelProgressDialog] = None
model_loader: Optional[ModelLoader] = None
transcriber_thread: Optional[QThread] = None
file_transcription_options: FileTranscriptionOptions
transcription_options: TranscriptionOptions
is_transcribing = False
# (TranscriptionOptions, FileTranscriptionOptions, str)
triggered = pyqtSignal(tuple)
openai_access_token_changed = pyqtSignal(str)
def __init__(self, file_paths: List[str], openai_access_token: Optional[str] = None,
parent: Optional[QWidget] = None, flags: Qt.WindowType = Qt.WindowType.Widget) -> None:
super().__init__(parent, flags)
self.setWindowTitle(file_paths_as_title(file_paths))
self.file_paths = file_paths
self.transcription_options = TranscriptionOptions(openai_access_token=openai_access_token)
self.file_transcription_options = FileTranscriptionOptions(
file_paths=self.file_paths)
layout = QVBoxLayout(self)
transcription_options_group_box = TranscriptionOptionsGroupBox(
default_transcription_options=self.transcription_options, parent=self)
transcription_options_group_box.transcription_options_changed.connect(
self.on_transcription_options_changed)
self.word_level_timings_checkbox = QCheckBox(_('Word-level timings'))
self.word_level_timings_checkbox.stateChanged.connect(
self.on_word_level_timings_changed)
file_transcription_layout = QFormLayout()
file_transcription_layout.addRow('', self.word_level_timings_checkbox)
self.run_button = QPushButton(_('Run'), self)
self.run_button.setDefault(True)
self.run_button.clicked.connect(self.on_click_run)
layout.addWidget(transcription_options_group_box)
layout.addLayout(file_transcription_layout)
layout.addWidget(self.run_button, 0, Qt.AlignmentFlag.AlignRight)
self.setLayout(layout)
self.setFixedSize(self.sizeHint())
def on_transcription_options_changed(self, transcription_options: TranscriptionOptions):
self.transcription_options = transcription_options
self.word_level_timings_checkbox.setDisabled(
self.transcription_options.model.model_type == ModelType.HUGGING_FACE or self.transcription_options.model.model_type == ModelType.OPEN_AI_WHISPER_API)
if self.transcription_options.openai_access_token is not None:
self.openai_access_token_changed.emit(self.transcription_options.openai_access_token)
def on_click_run(self):
self.run_button.setDisabled(True)
self.transcriber_thread = QThread()
self.model_loader = ModelLoader(model=self.transcription_options.model)
self.model_loader.moveToThread(self.transcriber_thread)
self.transcriber_thread.started.connect(self.model_loader.run)
self.model_loader.finished.connect(
self.transcriber_thread.quit)
self.model_loader.progress.connect(self.on_download_model_progress)
self.model_loader.error.connect(self.on_download_model_error)
self.model_loader.error.connect(self.model_loader.deleteLater)
self.model_loader.finished.connect(self.on_model_loaded)
self.model_loader.finished.connect(self.model_loader.deleteLater)
self.transcriber_thread.finished.connect(
self.transcriber_thread.deleteLater)
self.transcriber_thread.start()
def on_model_loaded(self, model_path: str):
self.reset_transcriber_controls()
self.triggered.emit((self.transcription_options,
self.file_transcription_options, model_path))
self.close()
def on_download_model_progress(self, progress: Tuple[float, float]):
(current_size, total_size) = progress
if self.model_download_progress_dialog is None:
self.model_download_progress_dialog = DownloadModelProgressDialog(parent=self)
self.model_download_progress_dialog.canceled.connect(
self.on_cancel_model_progress_dialog)
if self.model_download_progress_dialog is not None:
self.model_download_progress_dialog.set_fraction_completed(fraction_completed=current_size / total_size)
def on_download_model_error(self, error: str):
self.reset_model_download()
show_model_download_error_dialog(self, error)
self.reset_transcriber_controls()
def reset_transcriber_controls(self):
self.run_button.setDisabled(False)
def on_cancel_model_progress_dialog(self):
if self.model_loader is not None:
self.model_loader.stop()
self.reset_model_download()
def reset_model_download(self):
if self.model_download_progress_dialog is not None:
self.model_download_progress_dialog.close()
self.model_download_progress_dialog = None
def on_word_level_timings_changed(self, value: int):
self.transcription_options.word_level_timings = value == Qt.CheckState.Checked.value
def closeEvent(self, event: QtGui.QCloseEvent) -> None:
if self.transcriber_thread is not None:
self.transcriber_thread.wait()
super().closeEvent(event)
class TranscriptionViewerWidget(QWidget):
transcription_task: FileTranscriptionTask
def __init__(
self, transcription_task: FileTranscriptionTask,
open_transcription_output=True,
parent: Optional['QWidget'] = None,
flags: Qt.WindowType = Qt.WindowType.Widget,
) -> None:
super().__init__(parent, flags)
self.transcription_task = transcription_task
self.open_transcription_output = open_transcription_output
self.setMinimumWidth(500)
self.setMinimumHeight(500)
self.setWindowTitle(file_path_as_title(transcription_task.file_path))
layout = QVBoxLayout(self)
self.text_box = TextDisplayBox(self)
text = segments_to_text(transcription_task.segments)
self.text_box.setPlainText(text)
layout.addWidget(self.text_box)
buttons_layout = QHBoxLayout()
buttons_layout.addStretch()
menu = QMenu()
actions = [QAction(text=output_format.value.upper(), parent=self)
for output_format in OutputFormat]
menu.addActions(actions)
menu.triggered.connect(self.on_menu_triggered)
export_button = QPushButton(self)
export_button.setText(_('Export'))
export_button.setMenu(menu)
buttons_layout.addWidget(export_button)
layout.addLayout(buttons_layout)
self.setLayout(layout)
def on_menu_triggered(self, action: QAction):
output_format = OutputFormat[action.text()]
default_path = get_default_output_file_path(
task=self.transcription_task.transcription_options.task,
input_file_path=self.transcription_task.file_path,
output_format=output_format)
(output_file_path, nil) = QFileDialog.getSaveFileName(self, _('Save File'), default_path,
_('Text files') + f' (*.{output_format.value})')
if output_file_path == '':
return
write_output(path=output_file_path, segments=self.transcription_task.segments, output_format=output_format)
class AdvancedSettingsButton(QPushButton):
def __init__(self, parent: Optional[QWidget]) -> None:
super().__init__('Advanced...', parent)
class AudioMeterWidget(QWidget):
current_amplitude: float
BAR_WIDTH = 2
BAR_MARGIN = 1
BAR_INACTIVE_COLOR: QColor
BAR_ACTIVE_COLOR: QColor
# Factor by which the amplitude is scaled to make the changes more visible
DIFF_MULTIPLIER_FACTOR = 10
SMOOTHING_FACTOR = 0.95
def __init__(self, parent: Optional[QWidget] = None):
super().__init__(parent)
self.setMinimumWidth(10)
self.setFixedHeight(16)
# Extra padding to fix layout
self.PADDING_TOP = 3
self.current_amplitude = 0.0
self.MINIMUM_AMPLITUDE = 0.00005 # minimum amplitude to show the first bar
self.AMPLITUDE_SCALE_FACTOR = 15 # scale the amplitudes such that 1/AMPLITUDE_SCALE_FACTOR will show all bars
if self.palette().window().color().black() > 127:
self.BAR_INACTIVE_COLOR = QColor('#555')
self.BAR_ACTIVE_COLOR = QColor('#999')
else:
self.BAR_INACTIVE_COLOR = QColor('#BBB')
self.BAR_ACTIVE_COLOR = QColor('#555')
def paintEvent(self, event: QtGui.QPaintEvent) -> None:
painter = QPainter(self)
painter.setPen(Qt.PenStyle.NoPen)
rect = self.rect()
center_x = rect.center().x()
num_bars_in_half = int((rect.width() / 2) / (self.BAR_MARGIN + self.BAR_WIDTH))
for i in range(num_bars_in_half):
is_bar_active = ((self.current_amplitude - self.MINIMUM_AMPLITUDE) * self.AMPLITUDE_SCALE_FACTOR) > (
i / num_bars_in_half)
painter.setBrush(self.BAR_ACTIVE_COLOR if is_bar_active else self.BAR_INACTIVE_COLOR)
# draw to left
painter.drawRect(center_x - ((i + 1) * (self.BAR_MARGIN + self.BAR_WIDTH)), rect.top() + self.PADDING_TOP,
self.BAR_WIDTH,
rect.height() - self.PADDING_TOP)
# draw to right
painter.drawRect(center_x + (self.BAR_MARGIN + (i * (self.BAR_MARGIN + self.BAR_WIDTH))),
rect.top() + self.PADDING_TOP,
self.BAR_WIDTH, rect.height() - self.PADDING_TOP)
def update_amplitude(self, amplitude: float):
self.current_amplitude = max(amplitude, self.current_amplitude * self.SMOOTHING_FACTOR)
self.repaint()
class RecordingTranscriberWidget(QWidget):
current_status: 'RecordingStatus'
transcription_options: TranscriptionOptions
selected_device_id: Optional[int]
model_download_progress_dialog: Optional[DownloadModelProgressDialog] = None
transcriber: Optional[RecordingTranscriber] = None
model_loader: Optional[ModelLoader] = None
transcription_thread: Optional[QThread] = None
recording_amplitude_listener: Optional[RecordingAmplitudeListener] = None
device_sample_rate: Optional[int] = None
class RecordingStatus(enum.Enum):
STOPPED = auto()
RECORDING = auto()
def __init__(self, parent: Optional[QWidget] = None, flags: Optional[Qt.WindowType] = None) -> None:
super().__init__(parent)
if flags is not None:
self.setWindowFlags(flags)
layout = QVBoxLayout(self)
self.current_status = self.RecordingStatus.STOPPED
self.setWindowTitle(_('Live Recording'))
self.transcription_options = TranscriptionOptions(
model=TranscriptionModel(model_type=ModelType.WHISPER_CPP if LOADED_WHISPER_DLL else ModelType.WHISPER,
whisper_model_size=WhisperModelSize.TINY))
self.audio_devices_combo_box = AudioDevicesComboBox(self)
self.audio_devices_combo_box.device_changed.connect(
self.on_device_changed)
self.selected_device_id = self.audio_devices_combo_box.get_default_device_id()
self.record_button = RecordButton(self)
self.record_button.clicked.connect(self.on_record_button_clicked)
self.text_box = TextDisplayBox(self)
self.text_box.setPlaceholderText(_('Click Record to begin...'))
transcription_options_group_box = TranscriptionOptionsGroupBox(
default_transcription_options=self.transcription_options,
# Live transcription with OpenAI Whisper API not implemented
model_types=[model_type for model_type in ModelType if model_type is not ModelType.OPEN_AI_WHISPER_API],
parent=self)
transcription_options_group_box.transcription_options_changed.connect(
self.on_transcription_options_changed)
recording_options_layout = QFormLayout()
recording_options_layout.addRow(
_('Microphone:'), self.audio_devices_combo_box)
self.audio_meter_widget = AudioMeterWidget(self)
record_button_layout = QHBoxLayout()
record_button_layout.addWidget(self.audio_meter_widget)
record_button_layout.addWidget(self.record_button)
layout.addWidget(transcription_options_group_box)
layout.addLayout(recording_options_layout)
layout.addLayout(record_button_layout)
layout.addWidget(self.text_box)
self.setLayout(layout)
self.setFixedSize(self.sizeHint())
self.reset_recording_amplitude_listener()
def on_transcription_options_changed(self, transcription_options: TranscriptionOptions):
self.transcription_options = transcription_options
def on_device_changed(self, device_id: int):
self.selected_device_id = device_id
self.reset_recording_amplitude_listener()
def reset_recording_amplitude_listener(self):
if self.recording_amplitude_listener is not None:
self.recording_amplitude_listener.stop_recording()
# Listening to audio will fail if there are no input devices
if self.selected_device_id is None or self.selected_device_id == -1:
return
# Get the device sample rate before starting the listener as the PortAudio function
# fails if you try to get the device's settings while recording is in progress.
self.device_sample_rate = RecordingTranscriber.get_device_sample_rate(self.selected_device_id)
self.recording_amplitude_listener = RecordingAmplitudeListener(input_device_index=self.selected_device_id,
parent=self)
self.recording_amplitude_listener.amplitude_changed.connect(self.on_recording_amplitude_changed)
self.recording_amplitude_listener.start_recording()
def on_record_button_clicked(self):
if self.current_status == self.RecordingStatus.STOPPED:
self.start_recording()
self.current_status = self.RecordingStatus.RECORDING
self.record_button.set_recording()
else: # RecordingStatus.RECORDING
self.stop_recording()
self.set_recording_status_stopped()
def start_recording(self):
self.record_button.setDisabled(True)
self.transcription_thread = QThread()
self.model_loader = ModelLoader(model=self.transcription_options.model)
self.transcriber = RecordingTranscriber(input_device_index=self.selected_device_id,
sample_rate=self.device_sample_rate,
transcription_options=self.transcription_options)
self.model_loader.moveToThread(self.transcription_thread)
self.transcriber.moveToThread(self.transcription_thread)
self.transcription_thread.started.connect(self.model_loader.run)
self.transcription_thread.finished.connect(
self.transcription_thread.deleteLater)
self.model_loader.finished.connect(self.reset_recording_controls)
self.model_loader.finished.connect(self.transcriber.start)
self.model_loader.finished.connect(self.model_loader.deleteLater)
self.model_loader.progress.connect(
self.on_download_model_progress)
self.model_loader.error.connect(self.on_download_model_error)
self.transcriber.transcription.connect(self.on_next_transcription)
self.transcriber.finished.connect(self.on_transcriber_finished)
self.transcriber.finished.connect(self.transcription_thread.quit)
self.transcriber.finished.connect(self.transcriber.deleteLater)
self.transcriber.error.connect(self.on_transcriber_error)
self.transcriber.error.connect(self.transcription_thread.quit)
self.transcriber.error.connect(self.transcriber.deleteLater)
self.transcription_thread.start()
def on_download_model_progress(self, progress: Tuple[float, float]):
(current_size, total_size) = progress
if self.model_download_progress_dialog is None:
self.model_download_progress_dialog = DownloadModelProgressDialog(parent=self)
self.model_download_progress_dialog.canceled.connect(
self.on_cancel_model_progress_dialog)
if self.model_download_progress_dialog is not None:
self.model_download_progress_dialog.set_fraction_completed(fraction_completed=current_size / total_size)
def set_recording_status_stopped(self):
self.record_button.set_stopped()
self.current_status = self.RecordingStatus.STOPPED
def on_download_model_error(self, error: str):
self.reset_model_download()
show_model_download_error_dialog(self, error)
self.stop_recording()
self.set_recording_status_stopped()
self.record_button.setDisabled(False)
def on_next_transcription(self, text: str):
text = text.strip()
if len(text) > 0:
self.text_box.moveCursor(QTextCursor.MoveOperation.End)
if len(self.text_box.toPlainText()) > 0:
self.text_box.insertPlainText('\n\n')
self.text_box.insertPlainText(text)
self.text_box.moveCursor(QTextCursor.MoveOperation.End)
def stop_recording(self):
if self.transcriber is not None:
self.transcriber.stop_recording()
# Disable record button until the transcription is actually stopped in the background
self.record_button.setDisabled(True)
def on_transcriber_finished(self):
self.reset_record_button()
def on_transcriber_error(self, error: str):
self.reset_record_button()
self.set_recording_status_stopped()
QMessageBox.critical(
self, '',
_('An error occurred while starting a new recording:') + error + '. ' +
_('Please check your audio devices or check the application logs for more information.'))
def on_cancel_model_progress_dialog(self):
if self.model_loader is not None:
self.model_loader.stop()
self.reset_model_download()
self.set_recording_status_stopped()
self.record_button.setDisabled(False)
def reset_model_download(self):
if self.model_download_progress_dialog is not None:
self.model_download_progress_dialog.close()
self.model_download_progress_dialog = None
def reset_recording_controls(self):
# Clear text box placeholder because the first chunk takes a while to process
self.text_box.setPlaceholderText('')
self.reset_record_button()
if self.model_download_progress_dialog is not None:
self.model_download_progress_dialog.close()
self.model_download_progress_dialog = None
def reset_record_button(self):
self.record_button.setEnabled(True)
def on_recording_amplitude_changed(self, amplitude: float):
self.audio_meter_widget.update_amplitude(amplitude)
def closeEvent(self, event: QCloseEvent) -> None:
self.stop_recording()
if self.recording_amplitude_listener is not None:
self.recording_amplitude_listener.stop_recording()
self.recording_amplitude_listener.deleteLater()
return super().closeEvent(event)
BUZZ_ICON_PATH = get_asset_path('assets/buzz.ico')
BUZZ_LARGE_ICON_PATH = get_asset_path('assets/buzz-icon-1024.png')
RECORD_ICON_PATH = get_asset_path('assets/mic_FILL0_wght700_GRAD0_opsz48.svg')
EXPAND_ICON_PATH = get_asset_path('assets/open_in_full_FILL0_wght700_GRAD0_opsz48.svg')
ADD_ICON_PATH = get_asset_path('assets/add_FILL0_wght700_GRAD0_opsz48.svg')
TRASH_ICON_PATH = get_asset_path('assets/delete_FILL0_wght700_GRAD0_opsz48.svg')
CANCEL_ICON_PATH = get_asset_path('assets/cancel_FILL0_wght700_GRAD0_opsz48.svg')
class AboutDialog(QDialog):
GITHUB_API_LATEST_RELEASE_URL = 'https://api.github.com/repos/chidiwilliams/buzz/releases/latest'
GITHUB_LATEST_RELEASE_URL = 'https://github.com/chidiwilliams/buzz/releases/latest'
def __init__(self, network_access_manager: Optional[QNetworkAccessManager] = None,
parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.setFixedSize(200, 250)
self.setWindowIcon(QIcon(BUZZ_ICON_PATH))
self.setWindowTitle(f'{_("About")} {APP_NAME}')
if network_access_manager is None:
network_access_manager = QNetworkAccessManager()
self.network_access_manager = network_access_manager
self.network_access_manager.finished.connect(self.on_latest_release_reply)
layout = QVBoxLayout(self)
image_label = QLabel()
pixmap = QPixmap(BUZZ_LARGE_ICON_PATH).scaled(
80, 80, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
image_label.setPixmap(pixmap)
image_label.setAlignment(Qt.AlignmentFlag(
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter))
buzz_label = QLabel(APP_NAME)
buzz_label.setAlignment(Qt.AlignmentFlag(
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter))
buzz_label_font = QtGui.QFont()
buzz_label_font.setBold(True)
buzz_label_font.setPointSize(20)
buzz_label.setFont(buzz_label_font)
version_label = QLabel(f"{_('Version')} {VERSION}")
version_label.setAlignment(Qt.AlignmentFlag(
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter))
self.check_updates_button = QPushButton(_('Check for updates'), self)
self.check_updates_button.clicked.connect(self.on_click_check_for_updates)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton(
QDialogButtonBox.StandardButton.Close), self)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(image_label)
layout.addWidget(buzz_label)
layout.addWidget(version_label)
layout.addWidget(self.check_updates_button)
layout.addWidget(button_box)
self.setLayout(layout)
def on_click_check_for_updates(self):
url = QUrl(self.GITHUB_API_LATEST_RELEASE_URL)
self.network_access_manager.get(QNetworkRequest(url))
self.check_updates_button.setDisabled(True)
def on_latest_release_reply(self, reply: QNetworkReply):
if reply.error() == QNetworkReply.NetworkError.NoError:
response = json.loads(reply.readAll().data())
tag_name = response.get('name')
if self.is_version_lower(VERSION, tag_name[1:]):
QDesktopServices.openUrl(QUrl(self.GITHUB_LATEST_RELEASE_URL))
else:
QMessageBox.information(self, '', _("You're up to date!"))
self.check_updates_button.setEnabled(True)
@staticmethod
def is_version_lower(version_a: str, version_b: str):
return version_a.replace('.', '') < version_b.replace('.', '')
class TranscriptionTasksTableWidget(QTableWidget):
TASK_ID_COLUMN_INDEX = 0
FILE_NAME_COLUMN_INDEX = 1
STATUS_COLUMN_INDEX = 2
def __init__(self, parent: Optional[QWidget] = None):
super().__init__(parent)
self.setRowCount(0)
self.setAlternatingRowColors(True)
self.setColumnCount(3)
self.setColumnHidden(0, True)
self.verticalHeader().hide()
self.setHorizontalHeaderLabels([_('ID'), _('File Name'), _('Status')])
self.horizontalHeader().setMinimumSectionSize(160)
self.horizontalHeader().setSectionResizeMode(self.FILE_NAME_COLUMN_INDEX,
QHeaderView.ResizeMode.Stretch)
self.setSelectionBehavior(
QAbstractItemView.SelectionBehavior.SelectRows)
def upsert_task(self, task: FileTranscriptionTask):
task_row_index = self.task_row_index(task.id)
if task_row_index is None:
self.insertRow(self.rowCount())
row_index = self.rowCount() - 1
task_id_widget_item = QTableWidgetItem(str(task.id))
self.setItem(row_index, self.TASK_ID_COLUMN_INDEX,
task_id_widget_item)
file_name_widget_item = QTableWidgetItem(
os.path.basename(task.file_path))
file_name_widget_item.setFlags(
file_name_widget_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
self.setItem(row_index, self.FILE_NAME_COLUMN_INDEX,
file_name_widget_item)
status_widget_item = QTableWidgetItem(
task.status.value.title() if task.status is not None else '')
status_widget_item.setFlags(
status_widget_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
self.setItem(row_index, self.STATUS_COLUMN_INDEX,
status_widget_item)
else:
status_widget = self.item(task_row_index, self.STATUS_COLUMN_INDEX)
if task.status == FileTranscriptionTask.Status.IN_PROGRESS:
status_widget.setText(
f'{_("In Progress")} ({task.fraction_completed :.0%})')
elif task.status == FileTranscriptionTask.Status.COMPLETED:
status_widget.setText(_('Completed'))
elif task.status == FileTranscriptionTask.Status.FAILED:
status_widget.setText(f'{_("Failed")} ({task.error})')
elif task.status == FileTranscriptionTask.Status.CANCELED:
status_widget.setText(_('Canceled'))
def clear_task(self, task_id: int):
task_row_index = self.task_row_index(task_id)
if task_row_index is not None:
self.removeRow(task_row_index)
def task_row_index(self, task_id: int) -> int | None:
table_items_matching_task_id = [item for item in self.findItems(str(task_id), Qt.MatchFlag.MatchExactly) if
item.column() == self.TASK_ID_COLUMN_INDEX]
if len(table_items_matching_task_id) == 0:
return None
return table_items_matching_task_id[0].row()
@staticmethod
def find_task_id(index: QModelIndex):
sibling_index = index.siblingAtColumn(TranscriptionTasksTableWidget.TASK_ID_COLUMN_INDEX).data()
return int(sibling_index) if sibling_index is not None else None
class MainWindowToolbar(QToolBar):
new_transcription_action_triggered: pyqtSignal
open_transcript_action_triggered: pyqtSignal
clear_history_action_triggered: pyqtSignal
ICON_LIGHT_THEME_BACKGROUND = '#555'
ICON_DARK_THEME_BACKGROUND = '#AAA'
def __init__(self, parent: Optional[QWidget]):
super().__init__(parent)
record_action = QAction(self.load_icon(RECORD_ICON_PATH), _('Record'), self)
record_action.triggered.connect(self.on_record_action_triggered)
new_transcription_action = QAction(
self.load_icon(ADD_ICON_PATH), _('New Transcription'), self)
self.new_transcription_action_triggered = new_transcription_action.triggered
self.open_transcript_action = QAction(self.load_icon(EXPAND_ICON_PATH),
_('Open Transcript'), self)
self.open_transcript_action_triggered = self.open_transcript_action.triggered
self.open_transcript_action.setDisabled(True)
self.stop_transcription_action = QAction(self.load_icon(CANCEL_ICON_PATH), _('Cancel Transcription'), self)
self.stop_transcription_action_triggered = self.stop_transcription_action.triggered
self.stop_transcription_action.setDisabled(True)
self.clear_history_action = QAction(self.load_icon(TRASH_ICON_PATH), _('Clear History'), self)
self.clear_history_action_triggered = self.clear_history_action.triggered
self.clear_history_action.setDisabled(True)
self.addAction(record_action)
self.addSeparator()
self.addAction(new_transcription_action)
self.addAction(self.open_transcript_action)
self.addAction(self.stop_transcription_action)
self.addAction(self.clear_history_action)
self.setMovable(False)
self.setIconSize(QSize(18, 18))
self.setStyleSheet('QToolButton{margin: 6px 3px;}')
for action in self.actions():
widget = self.widgetForAction(action)
if isinstance(widget, QToolButton):
widget.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
# Fix spacing issue on Mac
if platform.system() == 'Darwin':
self.widgetForAction(self.actions()[0]).setStyleSheet(
'QToolButton { margin-left: 9px; margin-right: 1px; }')
def load_icon(self, file_path: str):
is_dark_theme = self.palette().window().color().black() > 127
return self.load_icon_with_color(file_path,
self.ICON_DARK_THEME_BACKGROUND if is_dark_theme else self.ICON_LIGHT_THEME_BACKGROUND)
@staticmethod
def load_icon_with_color(file_path: str, color: str):
"""Adapted from https://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt"""
pixmap = QPixmap(file_path)
painter = QPainter(pixmap)
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceIn)
painter.fillRect(pixmap.rect(), QColor(color))
painter.end()
return QIcon(pixmap)
def on_record_action_triggered(self):
recording_transcriber_window = RecordingTranscriberWidget(self, flags=Qt.WindowType.Window)
recording_transcriber_window.show()
def set_stop_transcription_action_enabled(self, enabled: bool):
self.stop_transcription_action.setEnabled(enabled)
def set_open_transcript_action_enabled(self, enabled: bool):
self.open_transcript_action.setEnabled(enabled)
def set_clear_history_action_enabled(self, enabled: bool):
self.clear_history_action.setEnabled(enabled)
class MainWindow(QMainWindow):
table_widget: TranscriptionTasksTableWidget
tasks: Dict[int, 'FileTranscriptionTask']
tasks_changed = pyqtSignal()
openai_access_token: Optional[str] = None
def __init__(self, tasks_cache=TasksCache()):
super().__init__(flags=Qt.WindowType.Window)
self.setWindowTitle(APP_NAME)
self.setWindowIcon(QIcon(BUZZ_ICON_PATH))
self.setMinimumSize(450, 400)
self.tasks_cache = tasks_cache
self.tasks = {}
self.tasks_changed.connect(self.on_tasks_changed)
self.toolbar = MainWindowToolbar(self)
self.toolbar.new_transcription_action_triggered.connect(self.on_new_transcription_action_triggered)
self.toolbar.open_transcript_action_triggered.connect(self.on_open_transcript_action_triggered)
self.toolbar.clear_history_action_triggered.connect(self.on_clear_history_action_triggered)
self.toolbar.stop_transcription_action_triggered.connect(self.on_stop_transcription_action_triggered)
self.addToolBar(self.toolbar)
self.setUnifiedTitleAndToolBarOnMac(True)
menu_bar = MenuBar(self)
menu_bar.import_action_triggered.connect(
self.on_new_transcription_action_triggered)
self.setMenuBar(menu_bar)
self.table_widget = TranscriptionTasksTableWidget(self)
self.table_widget.doubleClicked.connect(self.on_table_double_clicked)
self.table_widget.itemSelectionChanged.connect(
self.on_table_selection_changed)
self.setCentralWidget(self.table_widget)
# Start transcriber thread
self.transcriber_thread = QThread()
self.transcriber_worker = FileTranscriberQueueWorker()
self.transcriber_worker.moveToThread(self.transcriber_thread)
self.transcriber_worker.task_updated.connect(
self.update_task_table_row)
self.transcriber_worker.completed.connect(self.transcriber_thread.quit)
self.transcriber_thread.started.connect(self.transcriber_worker.run)
self.transcriber_thread.finished.connect(
self.transcriber_thread.deleteLater)
self.transcriber_thread.start()
self.load_tasks_from_cache()
def on_file_transcriber_triggered(self, options: Tuple[TranscriptionOptions, FileTranscriptionOptions, str]):
transcription_options, file_transcription_options, model_path = options
for file_path in file_transcription_options.file_paths:
task = FileTranscriptionTask(
file_path, transcription_options, file_transcription_options, model_path)
self.transcriber_worker.add_task(task)
def update_task_table_row(self, task: FileTranscriptionTask):
self.table_widget.upsert_task(task)
self.tasks[task.id] = task
self.tasks_changed.emit()
@staticmethod
def task_completed_or_errored(task: FileTranscriptionTask):
return task.status == FileTranscriptionTask.Status.COMPLETED or \
task.status == FileTranscriptionTask.Status.FAILED
def on_clear_history_action_triggered(self):
selected_rows = self.table_widget.selectionModel().selectedRows()