Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
8017 lines (7082 loc) · 382 KB
/
Copy pathmain.py
File metadata and controls
8017 lines (7082 loc) · 382 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
import os
import sys
# Capture every print/warning/traceback from the very first import: the
# packaged exe is --windowed (no stdout), so modules/system/debug_console tees all
# output into debug.log next to the exe and can mirror it to a live console
# window. Must run before the heavy imports below — some of them print
# warnings worth keeping.
from modules.system import debug_console
debug_console.install()
# The packaged app has no console, so every ffmpeg, ffprobe or yt-dlp it starts
# would flash up a console window of its own. Before anything starts one.
from modules.system import hidden_subprocess
hidden_subprocess.install()
# A frozen build starts every multiprocessing child — the object-detection
# workers, their Manager, the thumbnail decoder — by re-running this exe, and
# the child becomes a child only when it reaches freeze_support(). Left at the
# bottom of the file, each one first loaded everything below: cv2, Qt,
# OpenVINO, transformers, the assistant. Object detection starts six of them;
# on a Mac that filled the memory until the machine had to be restarted.
# Here a child costs the log tee and nothing else. In the parent (and in any
# run from source) this is a no-op.
if __name__ == "__main__":
import multiprocessing
multiprocessing.freeze_support()
# Every relative path in the app — `./cache` above all — resolves against the
# working directory, and a packaged app does not get to choose what that is.
# macOS starts an .app in `/`, which is read-only, so the first cache write
# failed with "[Errno 30] Read-only file system: 'cache'". Do this before
# anything opens a file.
from modules.system.app_paths import use_writable_cwd
print(f"📂 Working directory: {use_writable_cwd()}")
# Before torch is imported: an operator Metal lacks then runs on the processor
# instead of failing the model that needed it. A no-op off macOS.
from modules.system import mps_device
mps_device.enable_cpu_fallback()
# Interface size, if the user set one. Qt reads QT_SCALE_FACTOR when the
# QApplication is constructed and never again, so this has to happen before the
# Qt imports below — on a 55" 4K panel the OS scale is right for a television
# and far too large for an app at desk distance.
from modules.system import ui_scale
ui_scale.apply()
# A Hugging Face mirror, if the user set one. huggingface_hub reads
# HF_ENDPOINT once, when it is first imported, and transformers below imports it.
from modules.system import hf_mirror
hf_mirror.apply()
# Progress reporting for the launch itself. Imported here, before the heavy
# imports below, because in a frozen build *they* are the slow part — several
# seconds of decompressing and initialising cv2/OpenVINO/transformers before
# any window can exist. The bootloader's splash covers that stretch with the
# logo; these stage() calls are what make a slow launch readable afterwards in
# debug.log, and they would drive the splash text too if the build ever moves
# to a .spec (see modules/system/startup_splash.py on why the CLI flag cannot).
# This module deliberately pulls in no Qt, so it cannot disturb the import
# order below, which matters on Windows.
from modules.system import startup_splash
from modules.system import compute_backend
from modules.media import video_decode
startup_splash.stage("Loading the video engine…")
import cv2
import json
import subprocess
import threading
import time
import yaml
import multiprocessing
from PySide6.QtWidgets import (
QApplication, QCompleter, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QFileDialog, QLineEdit, QSpinBox, QDoubleSpinBox,
QGroupBox, QTextEdit, QFormLayout, QProgressBar, QCheckBox,
QComboBox, QTabWidget, QListWidget, QSplitter, QStackedWidget,
QDialog, QDialogButtonBox, QAbstractItemView,
QTableWidget, QTableWidgetItem, QHeaderView, QScrollArea,
QGridLayout, QSlider, QSizePolicy, QToolButton, QMenu,
)
from PySide6.QtCore import Qt, QThread, Signal, QTimer, QMetaObject, Q_ARG, Slot, QStringListModel
from modules import i18n
from modules.i18n import content_language
# Translate QLabel/QPushButton/… text at the Qt boundary so the chosen UI
# language covers the whole surface, not only hand-wrapped call sites.
i18n.install_qt_hooks()
from downloader import download_videos_with_immediate_processing, extract_video_links, DownloadError, reset_duration_method_cache
startup_splash.stage("Loading the assistant…")
from llm.llm_chat_widget import LLMChatWidget
from modules.media.video_cache import VideoAnalysisCache, CachedAnalysisData, build_analysis_cache_params
from modules.report import analysis_stats
from modules.ui import icons as _ui_icons, theme as _ui_theme
from modules.ui.main_menu import build_menu_bar
from modules.segments.simple_run import apply_simple_run
from modules.ui.simple_start import (
SimpleStartPage, persist_simple_start, simple_start_enabled,
)
# The five classes the expression scan can report. Imported for the Basic
# tab's picker; the module itself loads no model until something asks it to scan.
from modules.vision.face_emotions import EMOTION_LABELS
startup_splash.stage("Loading the detection runtime…")
try:
import openvino # registers OpenVINO's DLL dir on Windows
except Exception:
pass
from modules.system.app_paths import resource_path as _resource_path, data_file as _data_file, config_path
from version import __version__, __edition__
# --- Contact / support details shown in the About tab ---
SUPPORT_EMAIL = "przkreft@gmail.com"
WEBSITE_URL = "https://aseiel.github.io/VideoHighlighter-site/"
DISCORD_URL = "https://discord.gg/cUPJqPAMmm"
REPO_URL = "https://github.com/Aseiel/VideoHighlighter"
# User-editable config: lives next to the exe when frozen (so saves persist),
# seeded from the bundled default; just the project-root file when run from source.
CONFIG_FILE = config_path("config.yaml")
# Whisper codes the transcript and subtitle language boxes offer: every
# interface language's (modules/i18n/content_language.WHISPER) and a few more.
TRANSCRIPT_LANGUAGES = ["auto", "en", "zh", "es", "pt", "fr", "ja", "de", "ko", "id",
"tr", "it", "pl", "vi", "nl", "ru"]
YOLO_OBJECTS_LABELS_FILE = _resource_path("yolo_objects_labels.json")
# Suggestions for the action field. SigLIP2 scores any action by name; this
# list is what the field offers as you type (Kinetics-700-2020, CC BY 4.0).
KINETICS_700_LABELS_FILE = _resource_path("kinetics_700_labels.json")
# The analysis cache still records a sample rate; actions no longer read it.
ACTION_SAMPLE_RATE = 5
class LabelSelectorDialog(QDialog):
"""Dialog with search/filter and multi-select for labels."""
def __init__(self, title, labels, current_selection=None, parent=None):
super().__init__(parent)
self.setWindowTitle(title)
self.setMinimumSize(480, 520)
self.all_labels = sorted(labels)
self.current_selection = set(current_selection or [])
layout = QVBoxLayout()
search_layout = QHBoxLayout()
search_layout.addWidget(QLabel("Filter:"))
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Type to filter labels...")
self.search_input.textChanged.connect(self._filter_labels)
search_layout.addWidget(self.search_input)
layout.addLayout(search_layout)
self.info_label = QLabel(f"{len(self.all_labels)} labels available")
self.info_label.setStyleSheet("color: #666; font-size: 9pt;")
layout.addWidget(self.info_label)
self.label_list = QListWidget()
self.label_list.setSelectionMode(QAbstractItemView.MultiSelection)
self._populate_list(self.all_labels)
layout.addWidget(self.label_list)
quick_layout = QHBoxLayout()
select_all_btn = QPushButton("Select All Visible")
select_all_btn.clicked.connect(self._select_all_visible)
deselect_all_btn = QPushButton("Deselect All")
deselect_all_btn.clicked.connect(self._deselect_all)
quick_layout.addWidget(select_all_btn)
quick_layout.addWidget(deselect_all_btn)
quick_layout.addStretch()
layout.addLayout(quick_layout)
self.selection_label = QLabel("0 selected")
self.selection_label.setStyleSheet("font-weight: bold; color: #2f81f7;")
layout.addWidget(self.selection_label)
self.label_list.itemSelectionChanged.connect(self._update_selection_count)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.setLayout(layout)
self._preselect_current()
def _populate_list(self, labels):
self.label_list.clear()
for label in labels:
self.label_list.addItem(label)
def _preselect_current(self):
for i in range(self.label_list.count()):
item = self.label_list.item(i)
if item.text() in self.current_selection:
item.setSelected(True)
self._update_selection_count()
def _filter_labels(self, text):
text = text.strip().lower()
filtered = [l for l in self.all_labels if text in l.lower()] if text else self.all_labels
self._populate_list(filtered)
self.info_label.setText(f"{len(filtered)} of {len(self.all_labels)} labels shown")
self._preselect_current()
def _select_all_visible(self):
for i in range(self.label_list.count()):
self.label_list.item(i).setSelected(True)
self._update_selection_count()
def _deselect_all(self):
self.label_list.clearSelection()
self._update_selection_count()
def _update_selection_count(self):
self.selection_label.setText(f"{len(self.label_list.selectedItems())} selected")
def get_selected_labels(self):
return [item.text() for item in self.label_list.selectedItems()]
class NoAnalysisWarningDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("No Analysis Data")
self.setFixedWidth(420)
layout = QVBoxLayout()
icon_label = QLabel("⚠️")
icon_label.setStyleSheet("font-size: 32px;")
icon_label.setAlignment(Qt.AlignCenter)
layout.addWidget(icon_label)
msg = QLabel(
"No analysis cache found for this video.\n\n"
"You can still use the timeline viewer to seek through\n"
"the video and chat with the LLM — but motion, audio,\n"
"object and action signals won't be available.\n\n"
"Run the pipeline first to get full signal data."
)
msg.setWordWrap(True)
msg.setAlignment(Qt.AlignCenter)
layout.addWidget(msg)
self.dont_show_chk = QCheckBox("Don't show this warning again")
self.dont_show_chk.setStyleSheet("color: #666;")
layout.addWidget(self.dont_show_chk)
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttons.button(QDialogButtonBox.Ok).setText("Open Anyway")
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
self.setLayout(layout)
class MultiCompleter(QCompleter):
"""QCompleter that works on comma-separated fields, completing only the current token.
Matches labels where any word starts with the typed text."""
def __init__(self, labels=None, parent=None):
super().__init__(parent)
self._all_labels = labels or []
self._source_model = QStringListModel(self._all_labels)
self.setModel(self._source_model)
self.setCaseSensitivity(Qt.CaseInsensitive)
self.setFilterMode(Qt.MatchContains)
def setLabels(self, labels):
"""Update the full label list."""
self._all_labels = labels
self._source_model.setStringList(labels)
def pathFromIndex(self, index):
completion = super().pathFromIndex(index)
widget = self.widget()
if not widget:
return completion
text = widget.text()
cursor = widget.cursorPosition()
before = text[:cursor]
last_comma = before.rfind(",")
prefix = text[:last_comma + 1] + " " if last_comma >= 0 else ""
after_cursor = text[cursor:]
next_comma = after_cursor.find(",")
suffix = after_cursor[next_comma:] if next_comma >= 0 else ""
return prefix + completion + suffix
def splitPath(self, path):
widget = self.widget()
if not widget:
return [path.strip()]
cursor = widget.cursorPosition()
before = path[:cursor]
last_comma = before.rfind(",")
current_token = before[last_comma + 1:].strip().lower()
# Filter: any word in label starts with typed text
if current_token:
filtered = [l for l in self._all_labels
if any(w.startswith(current_token) for w in l.lower().split())]
else:
filtered = self._all_labels
self._source_model.setStringList(filtered)
return [current_token]
class DownloadWorker(QThread):
"""
Worker thread for downloading videos (with optional immediate processing after each file).
Emits signals for:
- progress updates
- logging
- finished list of downloaded paths
- cancellation
- individual video processed (when immediate processing is active)
"""
finished = Signal(list) # List of downloaded file paths
progress = Signal(int, int, str, str) # current, total, status, message
log = Signal(str) # log messages
cancelled = Signal() # emitted when cancelled
video_processed = Signal(str, dict) # filepath, processing result dict
add_to_file_list = Signal(str) # emits filepath to be added
def __init__(self, url, save_dir, pattern, time_range=None, download_full=True,
use_percentages=False, immediate_processing=False, max_concurrent=1,
process_callback=None, video_urls=None):
super().__init__()
self.url = url
self.save_dir = save_dir
self.pattern = pattern
self.time_range = time_range # (start, end) seconds or percentages
self.download_full = download_full
self.use_percentages = use_percentages
self.immediate_processing = immediate_processing
self.max_concurrent = max_concurrent
self.process_callback = process_callback # called after each download if immediate_processing
self.video_urls = video_urls # explicit selection from the picker (skips scrape)
self._cancelled = False
self._is_running = False
self._download_results = [] # store all download metadata
def run(self):
try:
self._is_running = True
self.log.emit(f"🚀 Starting download from: {self.url}")
def log_fn(message):
self.log.emit(message)
def progress_fn(current, total, status, message):
self.progress.emit(current, total, status, message)
# Wraps the GUI-supplied callback. Emits video_processed so the GUI
# can react per file. Only used when immediate_processing is on
# AND a real callback was provided; otherwise the downloader runs
# without per-video processing.
def wrapped_process_callback(filepath, metadata):
if self._cancelled:
return {'cancelled': True}
self.log.emit(f"🔧 Processing: {os.path.basename(filepath)}")
try:
result = self.process_callback(filepath, metadata)
self.log.emit(f"✅ Processed: {os.path.basename(filepath)}")
self.video_processed.emit(filepath, result)
return result
except Exception as e:
self.log.emit(f"❌ Processing failed: {e}")
return {'error': str(e)}
callback = (wrapped_process_callback
if (self.immediate_processing and self.process_callback)
else None)
results = download_videos_with_immediate_processing(
search_url=self.url,
save_dir=self.save_dir,
pattern=self.pattern,
log_fn=log_fn,
progress_fn=progress_fn,
process_callback=callback,
cancel_flag=self,
time_range=self.time_range,
download_full=self.download_full,
use_percentages=self.use_percentages,
max_workers=self.max_concurrent,
video_urls=self.video_urls,
)
# Collect downloaded files
downloaded_files = []
for result in results:
if result.get('success') and result.get('filepath'):
downloaded_files.append(result['filepath'])
self._download_results.append(result)
if self._cancelled:
self.log.emit("⏹️ Download was cancelled")
self.cancelled.emit()
self.finished.emit([])
else:
self.finished.emit(downloaded_files)
except Exception as e:
self.log.emit(f"❌ Download thread error: {e}")
import traceback
self.log.emit(traceback.format_exc())
self.finished.emit([])
finally:
self._is_running = False
def cancel(self):
"""Request cancellation – called from GUI.
Non-blocking: just trip the flag and return. run() unwinds and emits
cancelled/finished, which drive the UI cleanup. (Previously this called
self.wait()/terminate() on the GUI thread, which froze the UI and — on
timeout — killed the thread before it could emit its signals, leaving the
Download button stuck disabled. force_download_cleanup is the safety net
for a worker genuinely stuck in a non-cancellable subprocess.)"""
if self._is_running:
self.log.emit("⏹️ Cancellation requested - stopping download...")
self._cancelled = True
def is_cancelled(self):
"""Public method used by downloader module to check cancellation"""
return self._cancelled
def is_set(self):
"""Compatibility alias – matches threading.Event.is_set()"""
return self._cancelled
class DetectionPreviewWindow(QWidget):
"""Standalone window showing live detection frames during processing.
Supports pause (freezes the pipeline) and rewind (scrub back through a ring
buffer of recently shown frames).
"""
closed = Signal()
BUFFER_SIZE = 250 # rewind history (~30s at 8 fps); ~125MB of pixmaps
def __init__(self, parent=None):
super().__init__(parent)
from collections import deque
self.setWindowTitle("🔍 Live Detection Preview")
self.setMinimumSize(560, 400)
self.resize(720, 540)
self._frames = deque(maxlen=self.BUFFER_SIZE) # (pixmap, caption)
self._paused = False
self._view_index = -1 # -1 = follow live (latest)
layout = QVBoxLayout(self)
layout.setContentsMargins(6, 6, 6, 6)
self.image_label = QLabel("Waiting for the detection stage (objects / actions)…")
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setStyleSheet(
"QLabel { background:#101010; color:#8c8c8c; border:1px solid #333; }"
)
layout.addWidget(self.image_label, 1)
self.caption = QLabel("")
self.caption.setStyleSheet("color:#9aa; font-size:10pt;")
self.caption.setAlignment(Qt.AlignCenter)
layout.addWidget(self.caption)
# ── Controls: pause/resume, step, scrub slider ──
controls = QHBoxLayout()
self.pause_btn = QPushButton("⏸ Freeze")
self.pause_btn.setFixedWidth(90)
self.pause_btn.setToolTip("Freeze the preview to inspect a frame.\n"
"Processing keeps running in the background.")
self.pause_btn.clicked.connect(self._toggle_pause)
controls.addWidget(self.pause_btn)
self.prev_btn = QPushButton("◀")
self.prev_btn.setFixedWidth(36)
self.prev_btn.clicked.connect(lambda: self._step(-1))
controls.addWidget(self.prev_btn)
self.scrub = QSlider(Qt.Horizontal)
self.scrub.setMinimum(0)
self.scrub.setMaximum(0)
self.scrub.sliderPressed.connect(self._on_scrub_pressed)
self.scrub.valueChanged.connect(self._on_scrub_moved)
controls.addWidget(self.scrub, 1)
self.next_btn = QPushButton("▶")
self.next_btn.setFixedWidth(36)
self.next_btn.clicked.connect(lambda: self._step(1))
controls.addWidget(self.next_btn)
self.live_btn = QPushButton("⏭ Live")
self.live_btn.setFixedWidth(70)
self.live_btn.setToolTip("Jump back to the live frame and resume following")
self.live_btn.clicked.connect(self._go_live)
controls.addWidget(self.live_btn)
layout.addLayout(controls)
self._update_controls_enabled()
# ── public: called from the GUI when a new frame arrives ──
def set_frame(self, pixmap, caption=""):
# Background processing keeps feeding frames even while frozen.
was_full = len(self._frames) == self._frames.maxlen
self._frames.append((pixmap, caption))
# If frozen and the buffer just dropped its oldest frame, shift the view
# index down by one so we keep looking at the SAME content.
if self._paused and was_full and self._view_index > 0:
self._view_index -= 1
self.scrub.blockSignals(True)
self.scrub.setMaximum(len(self._frames) - 1)
self.scrub.setValue(self._view_index if self._paused else len(self._frames) - 1)
self.scrub.blockSignals(False)
if not self._paused:
self._view_index = len(self._frames) - 1
self._render_current()
self._update_controls_enabled()
# ── internals ──
def _render_current(self):
if not self._frames:
return
idx = self._view_index if self._view_index >= 0 else len(self._frames) - 1
idx = max(0, min(idx, len(self._frames) - 1))
pix, cap = self._frames[idx]
self.image_label.setPixmap(
pix.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
)
live_tag = " • LIVE" if (not self._paused and idx == len(self._frames) - 1) else \
f" • frozen {idx + 1}/{len(self._frames)}"
self.caption.setText((cap or "") + live_tag)
def _toggle_pause(self):
self._paused = not self._paused
self.pause_btn.setText("▶ Resume" if self._paused else "⏸ Freeze")
if not self._paused:
# Un-freeze → follow live again
self._view_index = len(self._frames) - 1
self._render_current()
self._update_controls_enabled()
def _on_scrub_pressed(self):
# Touching the slider implies you want to review → auto-pause
if not self._paused:
self._toggle_pause()
def _on_scrub_moved(self, value):
if self._paused:
self._view_index = value
self._render_current()
def _step(self, delta):
if not self._paused:
self._toggle_pause()
self._view_index = max(0, min(self._view_index + delta, len(self._frames) - 1))
self.scrub.blockSignals(True)
self.scrub.setValue(self._view_index)
self.scrub.blockSignals(False)
self._render_current()
def _go_live(self):
if self._paused:
self._toggle_pause() # resume → follows live
else:
self._view_index = len(self._frames) - 1
self._render_current()
def _update_controls_enabled(self):
has = len(self._frames) > 0
self.prev_btn.setEnabled(has)
self.next_btn.setEnabled(has)
self.scrub.setEnabled(has)
def closeEvent(self, event):
self.closed.emit()
super().closeEvent(event)
class Worker(QThread):
finished = Signal(object)
progress = Signal(int, int, str, str)
log = Signal(str)
cancelled = Signal()
preview = Signal(object, object, int) # frame_bgr (ndarray), boxes (list), sec
timeline_requested = Signal(str, object) # video_path, analysis_data
def __init__(self, video_path, gui_config=None):
super().__init__()
self.video_path = video_path
self.gui_config = gui_config
self._cancel_flag = threading.Event()
self._pause_event = threading.Event()
self._pause_event.set() # starts unpaused
self._is_running = False
self.preview_enabled = False
def pause(self):
self._pause_event.clear()
def resume(self):
self._pause_event.set()
def is_paused(self):
return not self._pause_event.is_set()
def run(self):
from pipeline import run_highlighter
try:
self._is_running = True
def pausing_progress(cur, tot, task, det):
self._pause_event.wait() # blocks while paused
if not self._cancel_flag.is_set():
self.progress.emit(cur, tot, task, det)
# Check if single or multiple files
if isinstance(self.video_path, list):
self.log.emit(f"🚀 Starting batch processing of {len(self.video_path)} videos...")
else:
self.log.emit("🚀 Starting video highlighter pipeline...")
# Gate the preview emit on the live flag, checked per call so the
# checkbox works mid-run. (The detector only builds/resizes a frame
# ~8x/sec, negligible next to inference.)
def preview_gate(frame, boxes, sec):
if self.preview_enabled and not self._cancel_flag.is_set():
self.preview.emit(frame, boxes, sec)
output = run_highlighter(
self.video_path,
gui_config=self.gui_config,
log_fn=self.log.emit,
progress_fn=pausing_progress,
cancel_flag=self._cancel_flag,
preview_fn=preview_gate,
# Qt widgets may only be built on the main thread; emitting
# hands the request off to the GUI's reuse-aware handler.
timeline_fn=lambda path, data: self.timeline_requested.emit(str(path), data),
)
if self._cancel_flag.is_set():
self.log.emit("⏹️ Pipeline was cancelled")
self.cancelled.emit()
self.finished.emit("")
else:
self.finished.emit(output or "")
except Exception as e:
self.log.emit(f"❌ Worker error: {e}")
import traceback
self.log.emit(f"Full traceback: {traceback.format_exc()}")
self.finished.emit("")
finally:
self._is_running = False
def cancel(self):
"""Non-blocking: trip the flag and return. run() stops at the pipeline's
next check and emits cancelled/finished, which clean up the UI.
Never terminate(). Whisper on the processor checks the flag once per
30 s window, which can take longer than any grace period; killing the
thread inside PyTorch left the model and its threads in memory, and the
next run then exhausted memory and crashed the process in ntdll."""
if self._is_running:
self.log.emit("⏹️ Cancellation requested - stopping pipeline...")
self._cancel_flag.set()
def is_cancelled(self):
return self._cancel_flag.is_set()
class SignalRunWorker(QThread):
"""Run ONE analysis signal on demand over a list of videos, folding each
result into that video's cache (leaving the other signals intact).
This is the main-window twin of the timeline viewer's "Analyze" panel: same
engine (`modules.report.analysis_ondemand`), same fold-into-cache behaviour, just
looped over the whole file list instead of one loaded video. It never cuts
highlights — it only produces the standalone `.srt`/`.txt` (subtitles /
transcript) and/or warms the cache for a later highlight run or the viewer.
"""
finished = Signal(str) # short summary, or "" on hard error
progress = Signal(int, int, str, str) # current, total, task, message
log = Signal(str)
cancelled = Signal()
preview = Signal(object, object, int) # frame_bgr (ndarray), boxes, sec
def __init__(self, kind, video_paths, params=None):
super().__init__()
self.kind = kind
self.video_paths = list(video_paths)
self.params = params or {}
self._cancel_flag = threading.Event()
self._is_running = False
self.preview_enabled = False
def run(self):
from modules.report import analysis_ondemand as aod
self._is_running = True
n = len(self.video_paths)
done = 0
try:
self.log.emit(f"🚀 {self.kind.title()} on demand over {n} video(s)...")
for i, vp in enumerate(self.video_paths):
if self._cancel_flag.is_set():
break
name = os.path.basename(vp)
self.log.emit(f"▶️ {self.kind} [{i+1}/{n}]: {name}")
def progress(cur, tot, task, det, _i=i, _name=name):
frac = (cur / tot) if tot else 0.0
overall = int(((_i + frac) / n) * 100)
self.progress.emit(overall, 100, self.kind.title(), f"{_name}: {det}")
try:
patch = self._run_one(aod, vp, progress)
except aod._Cancelled:
break
except Exception as e:
self.log.emit(f"❌ {name}: {e}")
continue
if patch:
aod.merge_into_cache(vp, patch, log=self.log.emit)
done += 1
if self._cancel_flag.is_set():
self.log.emit("⏹️ On-demand run cancelled")
self.cancelled.emit()
self.finished.emit("")
else:
self.done = done
self.finished.emit(f"{self.kind.title()}: {done}/{n} done")
except Exception as e:
import traceback
self.log.emit(f"❌ {self.kind} run error: {e}")
self.log.emit(traceback.format_exc())
self.finished.emit("")
finally:
self._is_running = False
def _run_one(self, aod, video_path, progress):
"""Dispatch to the matching on-demand runner and shape the cache patch.
Mirrors the timeline viewer's per-kind cache keys."""
c = self._cancel_flag
p = self.params
# An on-demand object/action run detects over the whole video exactly as
# the pipeline's stage does — same detector, same length — so it feeds
# the preview window from the same checkbox. Without this the window
# opened and stayed on its placeholder for the entire run, which is the
# one place the wait is longest and the reassurance worth most.
# Checked per call so the checkbox still works mid-run.
def preview_fn(frame, boxes, sec):
if self.preview_enabled and not self._cancel_flag.is_set():
self.preview.emit(frame, boxes, sec)
if self.kind == "shots":
return aod.run_shots(video_path, progress=progress, cancel=c, log=self.log.emit)
if self.kind == "motion":
# merge_into_cache keeps frame-accurate shots over these cuts.
return aod.run_motion(video_path, progress=progress, cancel=c, log=self.log.emit)
if self.kind == "audio":
return aod.run_audio(video_path, progress=progress, cancel=c, log=self.log.emit)
if self.kind == "objects":
# The patch form, so the boxes are cached too: they are what the
# composition rules and the overlay read, and a pass that dropped
# them had to be run again in full to get them.
classes = p.get("objects") or []
patch = aod.run_objects_patch(video_path, classes, progress=progress,
cancel=c, log=self.log.emit,
preview_fn=preview_fn)
patch["object_bboxes"] = aod.fold_object_boxes(
video_path, patch["object_bboxes"], classes)
return patch
if self.kind == "composition":
# Applying the rules is milliseconds, but fetching what they read
# need not be: a rule naming a class the cache lacks starts a
# detection pass here, and one naming a vocal signal decodes the
# audio. Both report and both are interruptible, so the run looks
# like every other on-demand run rather than a frozen window.
def detect_fn(classes, progress=None, cancel=None):
return aod.run_objects_patch(
video_path, classes, progress=progress,
cancel=cancel if cancel is not None else c,
log=self.log.emit, preview_fn=preview_fn)
return aod.run_composition(video_path, progress=progress, cancel=c,
detect_fn=detect_fn, log=self.log.emit)
if self.kind == "actions":
result = aod.run_actions(video_path, interesting_actions=p.get("actions") or [],
progress=progress, cancel=c, log=self.log.emit,
preview_fn=preview_fn)
return {"actions": result, "actions_all": result}
if self.kind == "transcript":
result = aod.run_transcript(video_path, language=p.get("language"),
progress=progress, cancel=c, log=self.log.emit)
return {"transcript": result}
if self.kind == "subtitles":
result = aod.run_subtitles(video_path, language=p.get("language"),
source_lang=p.get("source_lang"),
target_lang=p.get("target_lang"),
reuse_cached=p.get("reuse_cached", True),
snap_to_shots=bool(p.get("snap_to_shots")),
progress=progress, cancel=c, log=self.log.emit)
return {"transcript": result}
raise ValueError(f"unknown signal kind: {self.kind}")
def cancel(self):
if self._is_running:
self.log.emit("⏹️ Cancellation requested — finishing current video...")
self._cancel_flag.set()
def is_cancelled(self):
return self._cancel_flag.is_set()
class FaceScanWorker(QThread):
"""Offline identity pass over a video to populate the face bank with everyone
who appears, so they show up in the Avoid list (the 'dry run')."""
log = Signal(str)
done = Signal(int) # identity count after scan, or -1 on error
def __init__(self, video_path, db_path):
super().__init__()
self.video_path = video_path
self.db_path = db_path
def run(self):
try:
from video_ai_editor.face_identity import FaceIdentityBank
from modules.segments.compute_forbidden import build_tracking_model, tag_entries
bank = FaceIdentityBank(db_path=self.db_path)
model = build_tracking_model("n", log_fn=self.log.emit)
self.log.emit(f"🔍 Scanning {os.path.basename(self.video_path)} for faces…")
# tag_entries caches the per-frame tagging so the pipeline's avoid step
# reuses this same pass instead of re-running face recognition.
tag_entries(
self.video_path, bank,
yolo_model=model,
model_size="n",
face_every=15,
vid_stride=3,
save_bank=True,
log_fn=self.log.emit,
)
self.done.emit(len(bank))
except Exception as e:
self.log.emit(f"❌ Face scan failed: {e}")
self.done.emit(-1)
class UpdateCheckWorker(QThread):
"""Ask the update manifest whether a newer build exists.
Off the GUI thread because a network round trip on it would freeze the
window for the whole timeout on a bad connection — at the exact moment the
user is trying to start work. Nothing here touches a widget; the answer
travels back as a signal, and silence means "nothing to say".
"""
found = Signal(object) # modules.update.update_check.UpdateInfo
nothing = Signal(str) # only for an explicit "check now": why it found nothing
def __init__(self, force=False, parent=None):
super().__init__(parent)
self.force = force
def run(self):
try:
from modules.update import update_check
info = update_check.check_for_update(force=self.force)
except Exception as e:
# An update check must never be the reason anything goes wrong.
print(f"update_check: check failed ({type(e).__name__}: {e})")
if self.force:
self.nothing.emit("Could not check right now.")
return
if info:
self.found.emit(info)
elif self.force:
# The automatic check says nothing when there is nothing; a user who
# pressed a button is owed an answer either way.
self.nothing.emit(f"You're on the latest version ({__version__}).")
class UpdateInstallWorker(QThread):
"""Download and install a release, off the GUI thread.
All the logic lives in modules/update/update_install; this only marshals progress
and the result back to the window.
"""
progress = Signal(str, int, int, str) # phase, done, total, detail
finished_with = Signal(object) # update_install.InstallResult
def __init__(self, manifest_url, root, parent=None):
super().__init__(parent)
self.manifest_url = manifest_url
self.root = root
self._cancel = False
def cancel(self):
self._cancel = True
def run(self):
from modules.update import update_install
try:
result = update_install.install_update(
self.manifest_url, self.root,
progress=lambda *a: self.progress.emit(*a),
should_cancel=lambda: self._cancel,
)
except Exception as e:
print(f"update_install: unexpected failure ({type(e).__name__}: {e})")
result = update_install.InstallResult(
ok=False, message=f"The update failed: {e}")
self.finished_with.emit(result)
class RangeSlider(QWidget):
"""Single slider with two handles for selecting a range"""
startChanged = Signal(int)
endChanged = Signal(int)
def __init__(self, minimum=0, maximum=100, parent=None):
super().__init__(parent)
self._min = minimum
self._max = maximum
self._start = minimum
self._end = maximum
self._dragging = None # 'start', 'end', or None
self.setFixedHeight(32)
self.setMinimumWidth(200)
self.setCursor(Qt.PointingHandCursor)
def start(self):
return self._start
def end(self):
return self._end
def setStart(self, val):
val = max(self._min, min(val, self._end - 1))
if val != self._start:
self._start = val
self.startChanged.emit(val)
self.update()
def setEnd(self, val):
val = min(self._max, max(val, self._start + 1))
if val != self._end:
self._end = val
self.endChanged.emit(val)
self.update()
def setRangeValues(self, start, end):
"""Set both handles at once.
setStart()/setEnd() clamp against the *current* opposite handle, so
calling them in sequence fails when the whole window moves past the old
range (e.g. switching from 'first 5min' to 'last 5min' clamps the new
start to the old end). Setting both together avoids that cross-clamp.
"""
start = max(self._min, min(int(start), self._max))
end = max(self._min, min(int(end), self._max))
if start > end:
start, end = end, start
if end <= start:
end = min(self._max, start + 1)
changed_start = (start != self._start)
changed_end = (end != self._end)
self._start = start
self._end = end
if changed_start:
self.startChanged.emit(start)
if changed_end:
self.endChanged.emit(end)
if changed_start or changed_end:
self.update()
def setRange(self, minimum, maximum):
self._min = minimum
self._max = maximum
self._start = max(self._start, minimum)
self._end = min(self._end, maximum)
self.update()
def _val_to_x(self, val):
inset = 8
w = self.width() - 2 * inset
if self._max == self._min:
return inset