File size: 20,228 Bytes
0d35102
 
0729203
 
0d35102
 
 
c343e7a
 
0d35102
 
c343e7a
0d35102
 
 
 
 
 
 
 
54dde4f
0d35102
 
 
 
 
 
 
ebab963
 
 
 
0d35102
54dde4f
 
0d35102
 
 
 
 
54dde4f
0d35102
54dde4f
 
 
 
 
0d35102
 
 
 
 
 
 
 
 
 
 
 
c343e7a
 
54dde4f
c343e7a
 
 
 
 
 
 
 
54dde4f
c343e7a
 
 
 
 
 
 
 
ebab963
c343e7a
 
 
54dde4f
c343e7a
 
 
d0b93df
 
 
 
df02d45
 
 
 
0d35102
 
 
 
 
df02d45
54dde4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c343e7a
 
54dde4f
 
c343e7a
 
54dde4f
ebab963
 
 
 
54dde4f
c343e7a
 
54dde4f
 
 
 
 
 
 
ebab963
 
 
54dde4f
 
 
 
 
 
 
 
 
 
 
 
0d35102
 
 
07ef62b
 
 
 
54dde4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d35102
 
54dde4f
0d35102
 
 
 
54dde4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07ef62b
0d35102
07ef62b
 
 
0d35102
 
 
07ef62b
 
 
0d35102
 
 
54dde4f
 
07ef62b
 
54dde4f
 
 
0d35102
 
c022f02
c343e7a
 
 
54dde4f
07ef62b
 
 
 
54dde4f
c343e7a
 
54dde4f
 
 
 
 
 
 
 
 
 
 
 
 
c343e7a
 
 
ebab963
 
54dde4f
 
ebab963
54dde4f
ebab963
c343e7a
 
 
ebab963
 
54dde4f
 
c343e7a
 
54dde4f
 
0d35102
54dde4f
 
 
 
0d35102
c343e7a
 
 
 
 
54dde4f
c343e7a
ebab963
54dde4f
ebab963
 
 
0d35102
 
c343e7a
ebab963
 
d6d7b2c
 
54dde4f
 
 
 
 
 
d6d7b2c
 
 
 
 
 
 
c343e7a
 
 
 
ebab963
d6d7b2c
 
54dde4f
 
 
 
 
 
 
 
 
c343e7a
 
 
 
 
 
 
 
 
 
 
 
 
54dde4f
 
 
 
 
c343e7a
54dde4f
 
 
 
 
d6d7b2c
54dde4f
 
 
 
 
 
 
 
 
 
0d35102
 
ebab963
 
d0b93df
54dde4f
0d35102
 
54dde4f
 
 
 
 
 
 
 
 
 
 
 
 
 
0d35102
 
54dde4f
 
 
 
 
 
07ef62b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54dde4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d35102
 
 
 
 
 
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
import sys
import json
import numpy as np
import cv2
from pathlib import Path
from PIL import Image, ImageQt
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QPushButton, QSlider, QHBoxLayout, QVBoxLayout, QFileDialog, QListWidget, QSpinBox,
    QCheckBox
)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPixmap, QColor, QBrush, QImage

class LoopLabeler(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Video Loop Segment Labeler")
        self.resize(900, 600)
        self.data_dir = Path("data/loops")
        self.shots_dir = Path("data/shots")
        self.json_files = sorted(self.data_dir.glob("*.loop.json"))
        self.current_json = None
        self.frames = []
        self.loop_candidates = []
        self.current_candidate = 0
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_preview)
        self.preview_idx = 0
        # Initialize slider tracking variables
        self.current_start = 0
        self.current_end = 0
        self.is_dragging = False
        self.init_ui()
        # Load the first unannotated file if available
        self.load_first_unannotated()

    def init_ui(self):
        layout = QVBoxLayout()
        # File selector
        self.file_list = QListWidget()
        for i, f in enumerate(self.json_files):
            self.file_list.addItem(f.name)
            # Visual indicator for annotated files
            if self.is_annotated(f):
                item = self.file_list.item(i)
                if item:  # Ensure item exists
                    item.setForeground(QBrush(QColor(0, 120, 0)))  # Dark green text for annotated
        self.file_list.currentRowChanged.connect(self.on_file_selected)
        layout.addWidget(self.file_list)
        # Loop candidate selector
        self.candidate_spin = QSpinBox()
        self.candidate_spin.setMinimum(0)
        self.candidate_spin.valueChanged.connect(self.on_candidate_changed)
        layout.addWidget(QLabel("Loop candidate index:"))
        layout.addWidget(self.candidate_spin)
        # Preview
        self.preview_label = QLabel()
        self.preview_label.setFixedSize(320, 320)
        layout.addWidget(self.preview_label)
        # Custom number input fields instead of sliders
        # Using QSpinBox already imported at the top of the file
        
        # Create layout for start controls with label and spinbox
        start_layout = QHBoxLayout()
        start_layout.addWidget(QLabel("Start index"))
        self.start_spin = QSpinBox()
        self.start_spin.setMinimum(0)
        self.start_spin.setMaximum(9999)  # Will be updated with actual frame count
        start_layout.addWidget(self.start_spin)
        layout.addLayout(start_layout)
        
        # Create layout for end controls with label and spinbox
        end_layout = QHBoxLayout()
        end_layout.addWidget(QLabel("End index"))
        self.end_spin = QSpinBox()
        self.end_spin.setMinimum(0)
        self.end_spin.setMaximum(9999)  # Will be updated with actual frame count
        end_layout.addWidget(self.end_spin)
        layout.addLayout(end_layout)
        
        # Connect spinbox value changed signals
        self.start_spin.valueChanged.connect(self.on_range_changed)
        self.end_spin.valueChanged.connect(self.on_range_changed)
        
        # Keep track of current values
        self.current_start = 0
        self.current_end = 0
        # Loop checkbox
        self.loop_checkbox = QCheckBox("Is loop?")
        self.loop_checkbox.setChecked(True)
        layout.addWidget(self.loop_checkbox)
        # Revert button
        self.revert_btn = QPushButton("Revert to Detected")
        self.revert_btn.clicked.connect(self.revert_to_detected)
        layout.addWidget(self.revert_btn)
        # Save button
        self.save_btn = QPushButton("Save annotation")
        self.save_btn.clicked.connect(self.save_annotation)
        layout.addWidget(self.save_btn)
        self.setLayout(layout)
    def revert_to_detected(self):
        # Check if we have valid candidates and index
        if self.loop_candidates and 0 <= self.current_candidate < len(self.loop_candidates):
            candidate = self.loop_candidates[self.current_candidate]
            
            # Check if candidate has the required fields
            if "start" in candidate and "end" in candidate:
                # Get values from candidate
                start_value = int(candidate["start"])
                end_value = int(candidate["end"])
                
                # Ensure values are within valid range
                nframes = len(self.frames)
                start_value = max(0, min(start_value, nframes-1 if nframes > 0 else 0))
                end_value = max(0, min(end_value, nframes-1 if nframes > 0 else 0))
                
                # Block signals temporarily to avoid triggering callbacks
                self.start_spin.blockSignals(True)
                self.end_spin.blockSignals(True)
                
                # Set the values
                self.end_spin.setValue(end_value)
                self.start_spin.setValue(start_value)
                
                # Update our tracking variables
                self.current_start = start_value
                self.current_end = end_value
                
                # Re-enable signals
                self.start_spin.blockSignals(False)
                self.end_spin.blockSignals(False)
                
                # Mark as loop
                self.loop_checkbox.setChecked(True)
                
                # Reset preview
                self.preview_idx = 0
                
                # Make sure preview gets updated
                if not self.timer.isActive():
                    self.timer.start(40)
            else:
                print("Cannot revert: candidate missing start/end fields")
        else:
            print("Cannot revert: no valid loop candidate")
            # Set default values
            nframes = len(self.frames)
            self.start_slider.setValue(0)
            default_end = min(10, nframes-1) if nframes > 1 else 0
            self.end_slider.setValue(default_end)
            # Force update
            self.start_slider.update()
            self.end_slider.update()

    def load_json(self, json_path):
        self.current_json = json_path
        
        # Start with default loop state as true for new files
        self.loop_checkbox.setChecked(True)
        
        try:
            with open(json_path) as f:
                self.loop_candidates = json.load(f)
                
            # Validate loop_candidates is a list
            if not isinstance(self.loop_candidates, list):
                print(f"Warning: {json_path} does not contain a list of loop candidates")
                self.loop_candidates = []
                
        except (json.JSONDecodeError, FileNotFoundError, PermissionError) as e:
            print(f"Error loading JSON file {json_path}: {e}")
            self.loop_candidates = []
        
        # Update candidate spinner
        max_candidate = max(0, len(self.loop_candidates)-1)
        self.candidate_spin.setMaximum(max_candidate)
        self.current_candidate = 0
        self.candidate_spin.setValue(0)
        
        # Find corresponding webp
        stem = json_path.name.split(".")[0]
        webp_path = self.shots_dir / f"{stem}.webp"
        self.frames = []
        
        try:
            if webp_path.exists():
                with Image.open(webp_path) as im:
                    try:
                        while True:
                            self.frames.append(im.convert("RGB"))
                            im.seek(im.tell() + 1)
                    except EOFError:
                        pass
            else:
                print(f"Warning: WebP file not found: {webp_path}")
        except Exception as e:
            print(f"Error loading WebP file {webp_path}: {e}")
            
        # If no frames were loaded, ensure there's at least an empty frame
        if not self.frames:
            print(f"No frames found in {webp_path}")
            
        # First update the candidate from the loop detection data
        self.update_candidate()
        
        # Then check if we have human feedback data and override with that
        self.load_human_feedback()

    def on_file_selected(self, idx):
        if idx >= 0 and idx < len(self.json_files):
            # Reset checkbox to default state before loading new file
            # This will be overridden by load_human_feedback if necessary
            self.loop_checkbox.setChecked(True)
            self.load_json(self.json_files[idx])

    def on_candidate_changed(self, idx):
        if 0 <= idx < len(self.loop_candidates):
            self.current_candidate = idx
            # Default to assuming it is a loop when changing candidates
            self.loop_checkbox.setChecked(True)
            self.update_candidate()
        else:
            self.current_candidate = 0

    def update_candidate(self):
        nframes = len(self.frames)
        # Set both spin boxes to cover full range from 0 to N
        self.start_spin.setMaximum(nframes-1 if nframes > 0 else 0)
        self.end_spin.setMaximum(nframes-1 if nframes > 0 else 0)
        
        # Set default loop state to true when updating candidate
        # This will be overridden by load_human_feedback if human feedback exists
        self.loop_checkbox.setChecked(True)
        
        # Block signals temporarily to avoid triggering callbacks multiple times
        self.start_spin.blockSignals(True)
        self.end_spin.blockSignals(True)
        
        try:
            # Check if there are loop candidates and if the current index is valid
            if self.loop_candidates and self.current_candidate < len(self.loop_candidates):
                candidate = self.loop_candidates[self.current_candidate]
                # Check if candidate has the required keys
                if "start" in candidate and "end" in candidate:
                    start = int(candidate["start"])
                    end = int(candidate["end"])
                    # Make sure start/end are within valid range
                    start = max(0, min(start, nframes-1 if nframes > 0 else 0))
                    end = max(0, min(end, nframes-1 if nframes > 0 else 0))
                    
                    # Set spin box values and update our tracking variables
                    self.start_spin.setValue(start)
                    self.end_spin.setValue(end)
                    self.current_start = start
                    self.current_end = end
            else:
                # Default values if no candidates or invalid index
                start = 0
                default_end = min(10, nframes-1) if nframes > 1 else 0
                
                # Set spin box values and update our tracking variables
                self.start_spin.setValue(start)
                self.end_spin.setValue(default_end)
                self.current_start = start
                self.current_end = default_end
        finally:
            # Always re-enable signals
            self.start_spin.blockSignals(False)
            self.end_spin.blockSignals(False)
            
        # Reset animation
        self.preview_idx = 0
        
        # Make sure preview animation is running
        if not self.timer.isActive():
            self.timer.start(40)

    def on_range_changed(self):
        """Called when either spinbox value changes"""
        # Update our cached values
        self.current_start = self.start_spin.value()
        self.current_end = self.end_spin.value()
        
        # Reset animation index to give a smooth preview after changing range
        self.preview_idx = 0
        
        # Make sure preview is running
        if not self.timer.isActive():
            self.timer.start(40)

    def update_preview(self):
        # Get current values directly from spinboxes to ensure latest values
        start = self.current_start
        end = self.current_end
        
        # Handle case where end ≤ start by showing a single frame or appropriate range
        if self.frames and len(self.frames) > 0:
            # Make sure start and end are within valid ranges
            max_idx = len(self.frames) - 1
            start = max(0, min(start, max_idx))
            end = max(0, min(end, max_idx))
            
            if end <= start:
                # Show just the start frame when end <= start
                frame_idx = start
                frame = self.frames[frame_idx]
                show_progress = False
            else:
                # Normal case: show animation between start and end
                # The +1 is because we want to include both start and end frames
                range_size = end - start + 1
                frame_idx = start + (self.preview_idx % range_size)
                if frame_idx > max_idx:  # Safety check
                    frame_idx = max_idx
                frame = self.frames[frame_idx]
                show_progress = True
        else:
            # Display an empty/blank preview if no frames
            blank_frame = np.ones((320, 320, 3), dtype=np.uint8) * 200  # Light gray
            frame = Image.fromarray(cv2.cvtColor(blank_frame, cv2.COLOR_BGR2RGB))
            show_progress = False
        
        # Process and display the frame (shared code for both cases)    
        frame_resized = frame.resize((320,320))
        arr = np.array(frame_resized)
        
        # Draw current frame number overlay
        if self.frames and len(self.frames) > 0:
            cv2.putText(
                arr, 
                f"Frame: {frame_idx}", 
                (10, 30),  # Position (x, y)
                cv2.FONT_HERSHEY_SIMPLEX,  # Font
                0.7,  # Scale
                (255, 255, 255),  # Color (white)
                2  # Thickness
            )
        
        # Draw progress indicator line at bottom
        indicator_height = 2
        
        # Only show progress bar when we have a valid range
        if show_progress:
            total = end - start + 1  # +1 to include both start and end frames
            pos = self.preview_idx % total
            bar_w = int(320 * (pos / max(total-1, 1)))
        else:
            # Just show a full bar for single frame
            bar_w = 320
            
        arr[-indicator_height:, :320] = [220, 220, 220]  # light gray background
        arr[-indicator_height:, :bar_w] = [100, 100, 255]    # red progress
        # Convert RGB to BGR for OpenCV, then to QImage
        arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
        h, w, ch = arr.shape
        bytes_per_line = ch * w
        qimg = QImage(arr.data, w, h, bytes_per_line, QImage.Format_BGR888)
        pixmap = QPixmap.fromImage(qimg)
        self.preview_label.setPixmap(pixmap)
        self.preview_idx += 1

    def save_annotation(self):
        start = self.current_start
        end = self.current_end
        is_loop = self.loop_checkbox.isChecked()
        
        # Save to new file (or overwrite)
        if self.current_json is not None:
            try:
                out_path = self.current_json.with_suffix(".hf.json")
                hf_data = {
                    "loop": bool(is_loop),
                    "best_cut": [start, end]
                }
                with open(out_path, "w") as f:
                    json.dump(hf_data, f, indent=2)
                print(f"Annotation saved to {out_path}")
                
                # After saving, load the next unannotated file
                self.load_next_unannotated()
            except Exception as e:
                print(f"Error saving annotation: {e}")
        else:
            print("No JSON file loaded. Cannot save annotation.")
    
    def is_annotated(self, json_file):
        """Check if a JSON file has a corresponding human feedback (.hf.json) file"""
        hf_file = json_file.with_suffix(".hf.json")
        return hf_file.exists()
        
    def load_human_feedback(self):
        """Load the human feedback from .hf.json file if it exists and update UI accordingly"""
        if self.current_json is None:
            return
            
        hf_file = self.current_json.with_suffix(".hf.json")
        
        if hf_file.exists():
            try:
                with open(hf_file) as f:
                    hf_data = json.load(f)
                    
                # Update the "Is loop" checkbox
                if "loop" in hf_data:
                    self.loop_checkbox.setChecked(bool(hf_data["loop"]))
                
                # Update the start and end positions if available
                if "best_cut" in hf_data and isinstance(hf_data["best_cut"], list) and len(hf_data["best_cut"]) >= 2:
                    start, end = hf_data["best_cut"][0], hf_data["best_cut"][1]
                    
                    # Block signals temporarily to avoid triggering callbacks
                    self.start_spin.blockSignals(True)
                    self.end_spin.blockSignals(True)
                    
                    # Set spin box values and update our tracking variables
                    self.start_spin.setValue(start)
                    self.end_spin.setValue(end)
                    self.current_start = start
                    self.current_end = end
                    
                    # Re-enable signals
                    self.start_spin.blockSignals(False)
                    self.end_spin.blockSignals(False)
                    
                    # Reset preview
                    self.preview_idx = 0
            except (json.JSONDecodeError, IOError) as e:
                print(f"Error loading human feedback file {hf_file}: {e}")
        else:
            # No human feedback file exists, set checkbox to checked
            self.loop_checkbox.setChecked(True)
            print(f"No human feedback file found for {self.current_json.name}, defaulting 'Is loop' to enabled")
        
    def find_first_unannotated(self):
        """Find the index of the first unannotated JSON file"""
        for idx, json_file in enumerate(self.json_files):
            if not self.is_annotated(json_file):
                return idx
        # If all files are annotated, return 0
        return 0 if self.json_files else None
    
    def find_next_unannotated(self, current_idx):
        """Find the index of the next unannotated JSON file after current_idx"""
        if current_idx is None:
            return self.find_first_unannotated()
            
        # Start from the next file
        for idx in range(current_idx + 1, len(self.json_files)):
            if not self.is_annotated(self.json_files[idx]):
                return idx
                
        # If no more unannotated files after current, wrap around to the beginning
        for idx in range(0, current_idx + 1):
            if not self.is_annotated(self.json_files[idx]):
                return idx
                
        # If all files are annotated, return the current index
        return current_idx
    
    def load_first_unannotated(self):
        """Load the first unannotated JSON file in the list"""
        if not self.json_files:
            return
            
        idx = self.find_first_unannotated()
        if idx is not None:
            self.file_list.setCurrentRow(idx)
            self.load_json(self.json_files[idx])
    
    def load_next_unannotated(self):
        """Load the next unannotated JSON file after the current one"""
        if not self.json_files or self.current_json is None:
            return
            
        current_idx = self.json_files.index(self.current_json)
        next_idx = self.find_next_unannotated(current_idx)
        
        if next_idx is not None and next_idx != current_idx:
            self.file_list.setCurrentRow(next_idx)
            self.load_json(self.json_files[next_idx])

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = LoopLabeler()
    win.show()
    sys.exit(app.exec_())