Repository navigation
Expand file tree
/
Copy patheditor.py
More file actions
4602 lines (3929 loc) · 193 KB
/
Copy patheditor.py
File metadata and controls
4602 lines (3929 loc) · 193 KB
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
"""Main SRT/transcript editor window for CapsQual."""
import sys
import re
import json
import os
import math
import tempfile
import webbrowser
from pathlib import Path
from datetime import datetime
from collections import deque
import queue
import string
import copy
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,
QTextEdit, QListWidget, QPushButton, QWidget, QLabel,
QFileDialog, QMessageBox, QSpinBox, QShortcut, QFrame,
QInputDialog, QLineEdit, QDialog, QDialogButtonBox,
QGridLayout, QPlainTextEdit, QCheckBox, QTabWidget, QRadioButton,
QSlider, QProgressBar, QMenuBar, QMenu, QAction, QFontDialog,
QGroupBox, QScrollArea, QSizePolicy, QComboBox, QStackedWidget, QStyle, QSplashScreen,
QAbstractSpinBox
)
from PyQt5.QtCore import Qt, QTimer, QUrl, pyqtSignal, QPoint, QRect, QElapsedTimer, QThread, QSize, QRegularExpression, QSettings, QEvent
from PyQt5.QtGui import QFont, QKeySequence, QColor, QPalette, QTextCharFormat, QTextCursor, QIcon, QPixmap
from utils import resource_path, logger
from generators import (
time_to_seconds, time_to_ms, format_timestamp, get_timestamp_width,
format_srt_time,
replace_indent_placeholders, generate_gat2_text, generate_dresing_pehl_text,
generate_tiq_text, generate_srt_text, generate_transcript_text,
_build_ordered_segments, _group_into_turns, _tokenize_with_pauses,
_tokenize_cjk_with_pauses, _wrap_text as wrap_text, estimate_missing_timestamps,
_ms_to_time as ms_to_time
)
from export import (
build_html_content, write_html_file, write_srt_file, write_txt_file,
write_docx_file
)
from transcript import Transcript
from parsers import parse_srt, parse_text, parse_tsv, parse_json, parse_vtt
from highlighting import FormattingMarkerHighlighter
from audio_players import VlcAudioPlayer
from dialogs import (
TextSelectionDialog, BlockSplitDialog, EnhancedSymbolDialog, CommentDialog,
RichEditDialog, EditTimestampsDialog, SettingsDialog, ProjectMemoDialog, JsonImportDialog,
UnassignedSegmentsDialog, ExportPreviewDialog, SearchDialog, JumpToTimeDialog,
EnhancedPlacementDialog, PlacementDialog, InsertPausesDialog, ShortcutsDialog
)
from widgets import SpeedKnob, WaveformViewer, CollapsibleSplitter, CollapsibleSplitterHandle
# Widgets where Ctrl+Left/Right is used for text editing (word navigation /
# selection). When one of these has focus, the waveform shortcuts must NOT
# fire — otherwise typing would nudge markers instead of moving the caret.
_TEXT_EDIT_WIDGETS = (
QLineEdit, QPlainTextEdit, QTextEdit, QAbstractSpinBox, QComboBox,
)
def _is_editable_text_widget(widget):
"""True if ``widget`` is a text-input control where Ctrl+arrow means
word navigation/selection (i.e. the user can type into it)."""
if not isinstance(widget, _TEXT_EDIT_WIDGETS):
return False
# Read-only multi-line displays (e.g. the transcript) are not being
# edited, so the waveform shortcuts should still work there.
if isinstance(widget, (QTextEdit, QPlainTextEdit)):
return not widget.isReadOnly()
return True
class SRTEditor(QMainWindow):
# Constant for placeholder character (visible in viewer)
INDENT_PLACEHOLDER = '␣' # U+2423 OPEN BOX — kept for backward compat
# ── transcript-backed properties ──────────────────────────
@property
def srt_blocks(self):
return self.transcript.blocks
@srt_blocks.setter
def srt_blocks(self, value):
self.transcript.blocks = value
@property
def speakers(self):
return self.transcript.speakers
@speakers.setter
def speakers(self, value):
self.transcript.speakers = value
@property
def cjk_mode(self):
return self.transcript.cjk_mode
@cjk_mode.setter
def cjk_mode(self, value):
self.transcript.cjk_mode = value
@property
def file_has_timestamps(self):
return self.transcript.file_has_timestamps
@file_has_timestamps.setter
def file_has_timestamps(self, value):
self.transcript.file_has_timestamps = value
def __init__(self, splash=None):
super().__init__()
self.splash = splash
self.transcript = Transcript()
self.current_block_index = 0
# App-level event filter so the waveform marker shortcuts work from
# anywhere in the window (not only when the waveform has focus), while
# leaving Ctrl+Left/Right text editing intact. Qt auto-removes the
# filter when this window is destroyed.
app = QApplication.instance()
if app is not None:
app.installEventFilter(self)
self.recent_files = []
self.max_recent = 10
self.load_recent_files()
self.undo_stack = []
self.redo_stack = []
self.max_undo = 100
self.context_blocks = 5
self.current_file_path = None
self.timestamp_style = "curly"
self.custom_timestamp_pattern = "{HH:mm:ss}"
self.audio_file_path = None
self.project_name = ""
self.project_memo = ""
self.text_display_font = QFont("Arial", 12)
self.has_unsaved_changes = False
# Load theme from global preferences (QSettings), not from projects
theme_settings = QSettings('CapsQual', 'Preferences')
self.current_theme = theme_settings.value('viewer_theme', 'light')
# Set initial theme palette so all widgets inherit theme colours
QApplication.instance().setPalette(
self._dark_palette() if self.current_theme == "dark" else self._light_palette()
)
# Set up speaker colour palette based on loaded theme (before init_ui creates widgets)
if self.current_theme == "dark":
self.speaker_color_palette = [
QColor(80, 120, 160), # Steel blue
QColor(170, 80, 80), # Brick red
QColor(75, 155, 75), # Forest green
QColor(170, 170, 80), # Olive yellow
QColor(130, 80, 170), # Amethyst
QColor(175, 110, 60), # Burnt orange
QColor(65, 130, 130), # Teal
QColor(170, 80, 120) # Rose
]
else:
self.speaker_color_palette = [
QColor(220, 240, 255), # Light blue
QColor(255, 220, 220), # Light red
QColor(220, 255, 220), # Light green
QColor(255, 255, 200), # Light yellow
QColor(230, 200, 255), # Light purple
QColor(255, 200, 150), # Light orange
QColor(200, 230, 230), # Light cyan
QColor(255, 210, 230) # Light pink
]
# Initialize speaker colors from palette
self.speaker_colors = self.speaker_color_palette[:4]
self.playback_speed = 1.0
self.segment_sync_buffer = 0
self.original_audio_duration = 0
self.last_symbol_category = 0
# VLC audio player
self.audio_player = None
self.is_playing = False
self.auto_sync_enabled = False
self.auto_pause_enabled = False
# Timer for UI updates
self.ui_update_timer = QTimer()
self.ui_update_timer.timeout.connect(self.update_ui)
self.ui_update_timer.start(50)
self.update_splash("Creating user interface...")
self.init_ui()
self.setAcceptDrops(True)
# Fix up export button style for dark theme (init_ui hardcodes light)
if self.current_theme == "dark" and hasattr(self, 'btn_quick_export'):
self.btn_quick_export.setStyleSheet("""
QPushButton {
background-color: #1e7230;
padding: 2px 7px;
font-size: 12px;
font-weight: bold;
color: white;
border: 0px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #2d9e45;
}
""")
def time_label_clicked(self, event):
self.jump_to_time()
def update_splash(self, message):
"""Update splash screen message if splash exists."""
if self.splash:
self.splash.showMessage(message, Qt.AlignBottom | Qt.AlignCenter, Qt.black)
QApplication.processEvents() # ensure UI updates
self.marker_pattern = re.compile(r'(#@[BIU]|#@/[BIU])')
self.punctuation_set = set(string.punctuation + ",。!?;:“”‘’()【】《》……——·")
def _apply_to_text_ignoring_markers(self, text, func):
"""Apply function `func` to all non‑marker parts of `text`, leaving markers unchanged."""
parts = []
last_end = 0
for m in self.marker_pattern.finditer(text):
start, end = m.span()
if start > last_end:
# Apply func to the non‑marker part
parts.append(func(text[last_end:start]))
parts.append(m.group()) # marker remains unchanged
last_end = end
if last_end < len(text):
parts.append(func(text[last_end:]))
return ''.join(parts)
def strip_punctuation(self):
"""Remove all punctuation marks from the transcript text (ignoring formatting markers)."""
if not self.srt_blocks:
return
reply = QMessageBox.warning(
self,
"Strip Punctuation",
"This will remove all punctuation marks from the transcript text.\n\n"
"Are you sure you want to continue?",
QMessageBox.Yes | QMessageBox.No
)
if reply != QMessageBox.Yes:
return
self.push_undo()
def remove_punct(s):
return ''.join(ch for ch in s if ch not in self.punctuation_set)
for block in self.srt_blocks:
block['raw_text'] = self._apply_to_text_ignoring_markers(block['raw_text'], remove_punct)
block['text'] = block['raw_text']
self.update_display()
self.mark_unsaved_changes()
def convert_to_lowercase(self):
"""Convert all transcript text to lowercase (ignoring formatting markers)."""
if not self.srt_blocks:
return
reply = QMessageBox.warning(
self,
"Convert to Lowercase",
"This will convert the entire transcript text to lowercase.\n\n"
"For non Latin‑based transcripts, this may have no effect.\n\n"
"Are you sure you want to continue?",
QMessageBox.Yes | QMessageBox.No
)
if reply != QMessageBox.Yes:
return
self.push_undo()
for block in self.srt_blocks:
block['raw_text'] = self._apply_to_text_ignoring_markers(block['raw_text'], str.lower)
block['text'] = block['raw_text']
self.update_display()
self.mark_unsaved_changes()
def init_ui(self):
self.setWindowTitle("CapsQual 1.6.3 - Subtitle-to-Transcript Workstation")
# Get the screen geometry (available space, excluding taskbars/docks)
screen = QApplication.primaryScreen()
screen_geom = screen.availableGeometry()
screen_width = screen_geom.width()
screen_height = screen_geom.height()
# Set a reasonable initial size (e.g., 80% of width, 90% of height)
init_width = int(screen_width * 0.8)
init_height = int(screen_height * 0.9)
self.resize(init_width, init_height)
# Set a minimum size that is still usable
self.setMinimumSize(800, 560)
# Center the window on the screen
self.move((screen_width - init_width) // 2, (screen_height - init_height) // 2)
# Now show the window (do not call showMaximized unless desired)
self.show()
self.setWindowIcon(QIcon(resource_path('images/logo.ico')))
# Create menu bar
self.update_splash("Creating menu bar...")
self.create_menu_bar()
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QHBoxLayout(central_widget)
# Left panel - Context display
left_panel = QVBoxLayout()
# Current block info display
self.current_info_label = QLabel("No block selected")
self.current_info_label.setStyleSheet("""
QLabel {
background-color: palette(window);
color: palette(windowtext);
padding: 10px;
border: 2px solid palette(mid);
border-radius: 5px;
font-weight: bold;
}
""")
left_panel.addWidget(self.current_info_label)
# Main content display label
context_label = QLabel("Transcript Content:")
context_label.setFont(QFont("Arial", 10, QFont.Bold))
left_panel.addWidget(context_label)
# Main text display
self.text_display = QTextEdit()
self.text_display.setReadOnly(True)
self.text_display.setFont(self.text_display_font)
self.text_display.setStyleSheet("""
QTextEdit {
background-color: palette(base);
color: palette(text);
border: 2px solid palette(mid);
border-radius: 5px;
padding: 10px;
}
""")
self.text_display.setMinimumWidth(150) # allow it to shrink
self.text_display.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) # horizontal scroll if needed
self.text_display.setAcceptDrops(False) # let drops propagate to parent window
left_panel.addWidget(self.text_display)
self.highlighter = FormattingMarkerHighlighter(self.text_display.document())
# ── Waveform viewer ──────────────────────────────────────
waveform_label = QLabel("Waveform:")
waveform_label.setFont(QFont("Arial", 10, QFont.Bold))
left_panel.addWidget(waveform_label)
self.waveform_viewer = WaveformViewer()
self.waveform_viewer.set_theme(self.current_theme)
self.waveform_viewer.segment_start_changed.connect(self._on_waveform_start_changed)
self.waveform_viewer.segment_end_changed.connect(self._on_waveform_end_changed)
self.waveform_viewer.drag_started.connect(self._on_waveform_drag_started)
self.waveform_viewer.seek_requested.connect(self._on_waveform_seek)
left_panel.addWidget(self.waveform_viewer)
# Navigation buttons
nav_layout = QHBoxLayout()
self.btn_prev = QPushButton("← Previous (P)")
self.btn_prev.clicked.connect(self.previous_block)
self.lbl_current = QLabel("Current: -/-")
self.btn_next = QPushButton("Next (N) →")
self.btn_next.clicked.connect(self.next_block)
nav_layout.addWidget(self.btn_prev)
nav_layout.addWidget(self.lbl_current)
nav_layout.addWidget(self.btn_next)
left_panel.addLayout(nav_layout)
# Right panel - Controls
right_panel = QVBoxLayout()
# ----- Speaker Assignment group -----
speaker_group = QGroupBox("Speakers")
speaker_group.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
speaker_group_layout = QVBoxLayout()
speaker_group_layout.setSpacing(2)
speaker_group_layout.setContentsMargins(0, 0, 0, 0)
# Header with +/- buttons and count (centered)
header_layout = QHBoxLayout()
header_layout.addStretch()
# Minus button
self.btn_remove_speaker = QPushButton("−")
self.btn_remove_speaker.setFixedSize(25, 25)
self.btn_remove_speaker.setStyleSheet("""
QPushButton {
border-radius: 12px;
font-size: 16px;
font-weight: bold;
padding: 0px;
}
""")
self.btn_remove_speaker.clicked.connect(self.decrease_speaker_count)
header_layout.addWidget(self.btn_remove_speaker)
# Speaker count display
self.speaker_count_label = QLabel("4")
self.speaker_count_label.setFixedSize(40, 28)
self.speaker_count_label.setAlignment(Qt.AlignCenter)
self.speaker_count_label.setStyleSheet("""
QLabel {
font-size: 14px;
font-weight: bold;
}
""")
header_layout.addWidget(self.speaker_count_label)
# Plus button
self.btn_add_speaker = QPushButton("+")
self.btn_add_speaker.setFixedSize(25, 25)
self.btn_add_speaker.setStyleSheet(self.btn_remove_speaker.styleSheet())
self.btn_add_speaker.clicked.connect(self.increase_speaker_count)
header_layout.addWidget(self.btn_add_speaker)
header_layout.addStretch()
speaker_group_layout.addLayout(header_layout)
# Speaker container (list of speaker widgets)
self.speaker_container = QWidget()
self.speaker_layout = QVBoxLayout(self.speaker_container)
self.speaker_layout.setSpacing(2)
self.speaker_layout.setContentsMargins(0, 0, 0, 0)
self.create_speaker_widgets()
# Wrap speaker container in a scroll area
speaker_scroll = QScrollArea()
speaker_scroll.setWidgetResizable(True)
speaker_scroll.setWidget(self.speaker_container)
speaker_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
speaker_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
speaker_scroll.setMinimumHeight(70)
speaker_scroll.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # allow expansion
speaker_scroll.setFrameShape(QScrollArea.NoFrame) # removes the border
speaker_scroll.setStyleSheet("QScrollArea { border: none; }") # extra safety
speaker_group_layout.addWidget(speaker_scroll)
speaker_group.setLayout(speaker_group_layout)
right_panel.addWidget(speaker_group)
# Audio controls group
audio_group = QGroupBox("Audio Controls")
audio_group.setMaximumHeight(240)
audio_layout = QVBoxLayout()
audio_layout.setSpacing(2)
audio_layout.setContentsMargins(3, 3, 3, 3)
# Audio file info
self.audio_info_label = QLabel("No audio loaded")
self.audio_info_label.setStyleSheet("""
QLabel {
padding: 0px;
border-radius: 3px;
font-size: 11px;
}
""")
self.audio_info_label.setMinimumWidth(170)
audio_layout.addWidget(self.audio_info_label)
# Audio progress bar
self.audio_progress = QSlider(Qt.Horizontal)
self.audio_progress.setEnabled(False)
self.audio_progress.sliderMoved.connect(self.seek_audio)
self.audio_progress.setStyleSheet("""
QSlider {
padding: 0px;
margin: 0px;
}
""")
audio_layout.addWidget(self.audio_progress)
# Time display
time_layout = QHBoxLayout()
self.time_label = QLabel("00:00 / 00:00")
self.time_label.setAlignment(Qt.AlignCenter)
self.time_label.setCursor(Qt.PointingHandCursor)
self.time_label.setToolTip("Click to jump to time (Ctrl+J)")
self.time_label.mousePressEvent = self.time_label_clicked
audio_button_font = QFont("Segoe UI Symbol")
self.btn_play_segment = QPushButton("Play from segment (Shift+Enter)")
self.btn_play_segment.clicked.connect(self.play_from_current_segment)
self.btn_play_segment.setEnabled(False) # initially disabled until audio loaded
self.btn_play_segment.setToolTip("Play audio from the start of the current segment")
time_layout.addWidget(self.time_label)
time_layout.addWidget(self.btn_play_segment)
audio_layout.addLayout(time_layout)
# Audio controls
audio_controls_layout = QHBoxLayout()
audio_controls_layout.setSpacing(15)
self.btn_load_audio = QPushButton("Load Audio")
self.btn_load_audio.clicked.connect(self.load_audio_file)
self.btn_rewind = QPushButton("⏪ (PgUp)")
self.btn_rewind.clicked.connect(self.rewind_audio)
self.btn_rewind.setFont(audio_button_font)
self.btn_rewind.setEnabled(False)
self.btn_play = QPushButton("▶ (End)")
self.btn_play.clicked.connect(self.toggle_playback)
self.btn_play.setFont(audio_button_font)
self.btn_play.setEnabled(False)
self.btn_forward = QPushButton("⏩ (PgDn)")
self.btn_forward.clicked.connect(self.forward_audio)
self.btn_forward.setFont(audio_button_font)
self.btn_forward.setEnabled(False)
audio_controls_layout.addWidget(self.btn_load_audio)
audio_controls_layout.addWidget(self.btn_rewind)
audio_controls_layout.addWidget(self.btn_play)
audio_controls_layout.addWidget(self.btn_forward)
audio_layout.addLayout(audio_controls_layout)
# Auto-sync and Autopause checkboxes
sync_layout = QHBoxLayout()
self.auto_sync_check = QCheckBox("Auto-sync to transcript")
self.auto_sync_check.setEnabled(False)
self.auto_sync_check.setChecked(False)
self.auto_sync_check.toggled.connect(self.toggle_auto_sync)
self.auto_pause_check = QCheckBox("Pause during editing")
self.auto_pause_check.setEnabled(False)
self.auto_pause_check.setChecked(False)
self.auto_pause_check.toggled.connect(self.toggle_auto_pause)
sync_layout.addWidget(self.auto_sync_check)
sync_layout.addWidget(self.auto_pause_check)
sync_layout.addStretch()
audio_layout.addLayout(sync_layout)
# Speed control
speed_layout = QHBoxLayout()
speed_layout.setSpacing(15)
speed_layout.addWidget(QLabel("Playback Speed:"))
self.speed_slower_btn = QPushButton("-")
self.speed_slower_btn.clicked.connect(lambda: self.speed_knob.set_value_direct(max(0.5, self.playback_speed - 0.1)))
self.speed_slower_btn.setFixedWidth(30)
speed_layout.addWidget(self.speed_slower_btn)
self.speed_knob = SpeedKnob()
self.speed_knob.valueChanged.connect(self.change_playback_speed)
#self.speed_knob.setMinimumHeight(40)
self.speed_knob.setMinimumSize(30, 30) # allow very small (will be drawn scaled)
# Create a container widget for the speed knob with a fixed height
knob_container = QWidget()
knob_container.setMinimumHeight(30)
knob_container.setMaximumHeight(60) # or whatever maximum height you want
knob_layout = QVBoxLayout(knob_container)
knob_layout.setContentsMargins(0, 0, 0, 0)
knob_layout.addWidget(self.speed_knob)
knob_layout.setAlignment(Qt.AlignCenter) # center the knob vertically
# Then add the container to speed_layout instead of the knob directly
speed_layout.addWidget(knob_container)
#audio_layout.addStretch()
self.speed_normal_btn = QPushButton("Reset")
self.speed_normal_btn.clicked.connect(lambda: self.speed_knob.set_value_direct(1.0))
self.speed_normal_btn.setFixedWidth(60)
self.speed_faster_btn = QPushButton("+")
self.speed_faster_btn.clicked.connect(lambda: self.speed_knob.set_value_direct(min(2.0, self.playback_speed + 0.1)))
self.speed_faster_btn.setFixedWidth(30)
speed_layout.addWidget(self.speed_faster_btn)
speed_layout.addWidget(self.speed_normal_btn)
# Add directly to audio_layout (no container)
audio_layout.addLayout(speed_layout)
audio_group.setLayout(audio_layout)
right_panel.addWidget(audio_group)
# Button panel (split, merge, edit, etc.)
button_panel = QGroupBox()
button_layout = QVBoxLayout()
# First row: Split, Merge, Edit
row1 = QHBoxLayout()
self.btn_split = QPushButton("Split (Space)")
self.btn_merge = QPushButton("Merge (Del)")
self.btn_edit = QPushButton("Edit (E)")
row1.addWidget(self.btn_split)
row1.addWidget(self.btn_merge)
row1.addWidget(self.btn_edit)
button_layout.addLayout(row1)
# Second row: Edit Timestamp, Unassign, Symbols
row2 = QHBoxLayout()
self.btn_edit_time = QPushButton("Edit Timestamp (T)")
self.btn_unassign = QPushButton("Unassign (U)")
self.btn_symbols = QPushButton("Symbols (*)")
row2.addWidget(self.btn_edit_time)
row2.addWidget(self.btn_unassign)
row2.addWidget(self.btn_symbols)
button_layout.addLayout(row2)
self.btn_split.clicked.connect(self.split_current_block)
self.btn_merge.clicked.connect(self.merge_with_next)
self.btn_edit.clicked.connect(self.edit_current_block)
self.btn_edit_time.clicked.connect(self.edit_current_timestamps)
self.btn_unassign.clicked.connect(self.unassign_current)
self.btn_symbols.clicked.connect(self.open_pause_dialog)
button_panel.setLayout(button_layout)
right_panel.addWidget(button_panel)
# Unassigned blocks with counter
self.unassigned_blocks_label = QLabel("Unassigned Segments (0/0):")
#self.unassigned_blocks_label.setFont(QFont("Arial", 12, QFont.Bold))
right_panel.addWidget(self.unassigned_blocks_label)
self.unassigned_list = QListWidget()
self.unassigned_list.setMinimumHeight(40)
self.unassigned_list.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
self.unassigned_list.itemDoubleClicked.connect(self.jump_to_block)
right_panel.addWidget(self.unassigned_list) # Give it stretch factor 1 to expand
# Button container (will stay at bottom)
button_container = QWidget()
button_layout = QVBoxLayout(button_container)
button_layout.setContentsMargins(0, 0, 0, 0)
button_layout.setSpacing(5)
self.btn_quick_export = QPushButton(" Export Transcript (Ctrl+Enter)")
self.btn_quick_export.clicked.connect(self.export_transcript)
svg_data = b'''<svg width="48" height="48" viewBox="0 0 600 500" xmlns="http://www.w3.org/2000/svg">
<path d="m171,183l-94,0l0,227l397,0l0,-50" fill="none" stroke="#ffffff" stroke-width="13" transform="matrix(0.951576, 0, 0, 0.792082, 22.341, 67.1476)"/>
<path d="m442.89,147.05l0.11,-76.05l114,118l-111,110l0,-69l-104.18,5.12c-29.52,4.98 -61.24,13.64 -106.76,43.52c-20.93,14.7 -31.06,17.82 -55.47,47c2.24,-13 10.61,-52.7 30.2,-83.17c35.09,-46.28 65.11,-63.01 74.11,-67.01c41.62,-30.5 165,-26.41 159,-28.41z" fill="none" stroke="#ffffff" stroke-width="13"/>
</svg>'''
pixmap = QPixmap()
pixmap.loadFromData(svg_data)
icon = QIcon(pixmap)
self.btn_quick_export.setIcon(icon)
self.btn_quick_export.setIconSize(QSize(32, 32))
self.btn_quick_export.setStyleSheet("""
QPushButton {
background-color: #124607;
padding: 2px 7px;
font-size: 12px;
font-weight: bold;
color: white;
border: 0px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #71906a;
}
""")
button_layout.addWidget(self.btn_quick_export)
right_panel.addWidget(button_container) # No stretch, stays at bottom
# Create left and right panel widgets
left_widget = QWidget()
left_widget.setLayout(left_panel)
right_widget = QWidget()
right_widget.setLayout(right_panel)
right_widget.setMinimumWidth(0)
right_widget.setMaximumWidth(450) # optional, adjust as needed
# Create custom splitter
splitter = CollapsibleSplitter(Qt.Horizontal, right_widget)
splitter.addWidget(left_widget)
splitter.addWidget(right_widget)
splitter.setSizes([800, 200]) # initial sizes
splitter.setHandleWidth(15) # wider handle for button
# Add splitter to central layout
layout.addWidget(splitter)
self.update_splash("Setting up shortcuts...")
self.setup_shortcuts()
# Apply initial theme QSS (buttons, scrollbars, group boxes, labels)
self._apply_theme_qss()
def preload_modules(self):
"""Preload heavy modules while splash is still visible."""
try:
import soundfile
import numpy
except ImportError:
pass
def load_recent_files(self):
settings = QSettings('CapsQual', 'RecentFiles')
size = settings.beginReadArray('recent')
self.recent_files = []
for i in range(size):
settings.setArrayIndex(i)
path = settings.value('path')
print(f"load_recent_files: index {i}, path={repr(path)}")
if path and os.path.exists(path):
self.recent_files.append(path)
else:
print(f" -> skipping (exists={os.path.exists(path) if path else False})")
settings.endArray()
print(f"Recent files after load: {self.recent_files}")
def save_recent_files(self):
"""Save recent files list to QSettings."""
settings = QSettings('CapsQual', 'RecentFiles')
settings.beginWriteArray('recent')
for i, path in enumerate(self.recent_files):
settings.setArrayIndex(i)
settings.setValue('path', path)
settings.endArray()
def add_to_recent(self, filepath):
print(f"add_to_recent: adding {repr(filepath)}")
if filepath in self.recent_files:
self.recent_files.remove(filepath)
self.recent_files.insert(0, filepath)
if len(self.recent_files) > self.max_recent:
self.recent_files.pop()
self.save_recent_files()
print(f"Recent files now: {self.recent_files}")
def update_recent_menu(self):
self.recent_menu.clear()
if not self.recent_files:
action = self.recent_menu.addAction("(empty)")
action.setEnabled(False)
else:
for path in self.recent_files:
name = os.path.basename(path)
action = self.recent_menu.addAction(name)
# Use lambda with default argument to capture path
action.triggered.connect(lambda checked, p=path: self.open_recent_file(p))
self.recent_menu.addSeparator()
clear_action = self.recent_menu.addAction("Clear Recent")
clear_action.triggered.connect(self.clear_recent)
def clear_recent(self):
"""Clear the recent files list."""
self.recent_files = []
self.save_recent_files()
self.update_recent_menu() # immediate update (menu is about to be shown anyway)
def open_recent_file(self, path):
"""Open a file from the recent list."""
if not os.path.exists(path):
QMessageBox.warning(self, "File Not Found",
f"The file '{path}' does not exist.\nIt will be removed from the recent list.")
self.recent_files.remove(path)
self.save_recent_files()
return
if self.check_unsaved_changes():
ext = os.path.splitext(path)[1].lower()
if ext in ('.capsqual', '.capsgat'):
self.load_project_from_path(path)
else:
# Non-project files are imported fresh — reset project-scoped state
# first, so stale metadata (name, memo, audio) doesn't leak from
# the previously open project.
self._reset_project_state()
self.load_file_from_path(path)
self.clear_unsaved_changes()
def push_undo(self):
"""Save current state before a modification."""
state = {
'blocks': copy.deepcopy(self.srt_blocks),
'current_index': self.current_block_index,
'speakers': self.speakers.copy()
}
self.undo_stack.append(state)
self.redo_stack.clear()
if len(self.undo_stack) > self.max_undo:
self.undo_stack.pop(0)
self.update_undo_redo_actions()
def _reset_project_state(self):
"""Clear project-scoped state for a fresh file import.
Resets everything NOT reloaded by load_file_from_path, so stale metadata
(project name, memo, audio) from a previous session does not leak when
opening a subtitle file from the recent-files list.
"""
# ── Project identity ────────────────────────────────────
self.project_name = ""
self.project_memo = ""
self.source_file = ""
# ── Audio ────────────────────────────────────────────────
if self.audio_player:
self.audio_player.cleanup()
self.audio_player = None
self.audio_file_path = None
self._clear_waveform_audio()
self.audio_info_label.setText("No audio loaded")
self.playback_speed = 1.0
self.speed_knob.value = 1.0
self.speed_knob.update()
self.speed_normal_btn.setText("1.0x")
self.original_audio_duration = 0
self.is_playing = False
self.auto_sync_enabled = False
self.auto_pause_enabled = False
self.auto_sync_check.setChecked(False)
self.auto_pause_check.setChecked(False)
self.auto_sync_check.setEnabled(False)
self.auto_pause_check.setEnabled(False)
self.audio_progress.setEnabled(False)
self.audio_progress.setValue(0)
self.time_label.setText("00:00 / 00:00")
self.btn_play.setEnabled(False)
self.btn_rewind.setEnabled(False)
self.btn_forward.setEnabled(False)
self.btn_play_segment.setEnabled(False)
self.update_speed_controls_state()
# ── Speakers ─────────────────────────────────────────────
self.speakers = ["A", "B", "C", "D"]
self.speaker_colors = self.speaker_color_palette[:4]
self.speaker_count_label.setText("4")
self.create_speaker_widgets()
self.setup_shortcuts()
# ── Metadata / flags ─────────────────────────────────────
self.cjk_mode = False
self.timestamp_style = "curly"
self.custom_timestamp_pattern = "{HH:mm:ss}"
self.file_has_timestamps = False
def undo(self):
if not self.undo_stack:
return
# push current state to redo
current = {
'blocks': copy.deepcopy(self.srt_blocks),
'current_index': self.current_block_index,
'speakers': self.speakers.copy()
}
self.redo_stack.append(current)
# restore previous state
prev = self.undo_stack.pop()
self._restore_state(prev)
self.update_undo_redo_actions()
def redo(self):
if not self.redo_stack:
return
# push current state to undo
current = {
'blocks': copy.deepcopy(self.srt_blocks),
'current_index': self.current_block_index,
'speakers': self.speakers.copy()
}
self.undo_stack.append(current)
# restore next state
next_state = self.redo_stack.pop()
self._restore_state(next_state)
self.update_undo_redo_actions()
def _restore_state(self, state):
"""Restore a saved state and refresh the UI."""
self.srt_blocks = state['blocks']
self.current_block_index = state['current_index']
self.speakers = state['speakers']
self.speaker_count_label.setText(str(len(self.speakers)))
self.update_display()
self.create_speaker_widgets()
self.setup_shortcuts()
self.update_speaker_buttons()
self.mark_unsaved_changes()
def update_undo_redo_actions(self):
"""Enable/disable Undo/Redo menu items based on stack emptiness."""
if hasattr(self, 'undo_action'):
self.undo_action.setEnabled(len(self.undo_stack) > 0)
if hasattr(self, 'redo_action'):
self.redo_action.setEnabled(len(self.redo_stack) > 0)
def insert_pauses_for_gaps(self):
if not self.srt_blocks or len(self.srt_blocks) < 2:
QMessageBox.information(self, "Cannot Insert Pauses",
"Need at least two segments to calculate gaps.")
return
# Check if we have timestamps
has_any_timestamp = any(block.get('start_time') for block in self.srt_blocks)
if not has_any_timestamp:
QMessageBox.warning(self, "No Timestamps",
"This transcript does not contain timestamp information.\n\n"
"Pause insertion requires start and end times for segments.")
return
dialog = InsertPausesDialog(self)
if dialog.exec_() != QDialog.Accepted:
return
settings = dialog.get_settings()
convention = settings['convention']
use_measured = settings['use_measured']
measured_threshold = settings['measured_threshold']
min_gap = settings['min_gap']
mode = settings['mode']
threshold = settings['threshold'] # used only if mode == "threshold"
self.push_undo()
blocks = self.srt_blocks
inserted_count = 0
# Work from last to first to avoid index shifting when inserting new blocks
for i in range(len(blocks) - 2, -1, -1):
current = blocks[i]
nxt = blocks[i+1]
# Get end time of current and start time of next
if not current.get('end_time') or not nxt.get('start_time'):
continue
end_sec = time_to_seconds(current['end_time'])
start_sec = time_to_seconds(nxt['start_time'])
gap = start_sec - end_sec
if gap < min_gap:
continue
# Generate pause symbol
symbol = self.gap_to_pause_symbol(gap, convention, use_measured, measured_threshold)
if not symbol:
continue
# Decide action based on mode
separate_this = False
if mode == "separate":
separate_this = True
elif mode == "attach":
separate_this = False
else: # threshold
separate_this = (gap >= threshold)
if separate_this:
# Insert a new pause block after current
new_block = {
'index': max(b['index'] for b in blocks) + 1,
'start_time': current['end_time'],
'end_time': nxt['start_time'],
'text': symbol,
'raw_text': symbol,
'speaker': None,
'is_turn_start': False,
'is_pause': True,
}
blocks.insert(i+1, new_block)
inserted_count += 1
else:
# Prepend symbol to the next block's text (no timestamp change)
if self.cjk_mode:
prefix = symbol
else:
# Add a space after the symbol unless the next block already starts with space