sprite-dx-data / loop_labeler_ui.py
Candle
fixes
07ef62b
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_())