Fix import_categories and enhance folder creation
This commit is contained in:
16
pyproject.toml
Normal file
16
pyproject.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "media_classifier"
|
||||
version = "0.1.0"
|
||||
description = "A GUI tool for classifying images and videos into subfolders."
|
||||
dependencies = [
|
||||
"Pillow",
|
||||
"opencv-python",
|
||||
"PySide6",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
media-classify = "media_classifier.main:main"
|
||||
7
src/media_classifier.egg-info/PKG-INFO
Normal file
7
src/media_classifier.egg-info/PKG-INFO
Normal file
@@ -0,0 +1,7 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: media_classifier
|
||||
Version: 0.1.0
|
||||
Summary: A GUI tool for classifying images and videos into subfolders.
|
||||
Requires-Dist: Pillow
|
||||
Requires-Dist: opencv-python
|
||||
Requires-Dist: PySide6
|
||||
15
src/media_classifier.egg-info/SOURCES.txt
Normal file
15
src/media_classifier.egg-info/SOURCES.txt
Normal file
@@ -0,0 +1,15 @@
|
||||
pyproject.toml
|
||||
src/media_classifier/__init__.py
|
||||
src/media_classifier/main.py
|
||||
src/media_classifier.egg-info/PKG-INFO
|
||||
src/media_classifier.egg-info/SOURCES.txt
|
||||
src/media_classifier.egg-info/dependency_links.txt
|
||||
src/media_classifier.egg-info/entry_points.txt
|
||||
src/media_classifier.egg-info/requires.txt
|
||||
src/media_classifier.egg-info/top_level.txt
|
||||
src/media_classifier/core/__init__.py
|
||||
src/media_classifier/core/classifier.py
|
||||
src/media_classifier/ui/__init__.py
|
||||
src/media_classifier/ui/app.py
|
||||
src/media_classifier/utils/__init__.py
|
||||
src/media_classifier/utils/media_utils.py
|
||||
1
src/media_classifier.egg-info/dependency_links.txt
Normal file
1
src/media_classifier.egg-info/dependency_links.txt
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
2
src/media_classifier.egg-info/entry_points.txt
Normal file
2
src/media_classifier.egg-info/entry_points.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
[console_scripts]
|
||||
media-classify = media_classifier.main:main
|
||||
3
src/media_classifier.egg-info/requires.txt
Normal file
3
src/media_classifier.egg-info/requires.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
Pillow
|
||||
opencv-python
|
||||
PySide6
|
||||
1
src/media_classifier.egg-info/top_level.txt
Normal file
1
src/media_classifier.egg-info/top_level.txt
Normal file
@@ -0,0 +1 @@
|
||||
media_classifier
|
||||
0
src/media_classifier/__init__.py
Normal file
0
src/media_classifier/__init__.py
Normal file
BIN
src/media_classifier/__pycache__/__init__.cpython-38.pyc
Normal file
BIN
src/media_classifier/__pycache__/__init__.cpython-38.pyc
Normal file
Binary file not shown.
BIN
src/media_classifier/__pycache__/main.cpython-38.pyc
Normal file
BIN
src/media_classifier/__pycache__/main.cpython-38.pyc
Normal file
Binary file not shown.
0
src/media_classifier/core/__init__.py
Normal file
0
src/media_classifier/core/__init__.py
Normal file
BIN
src/media_classifier/core/__pycache__/__init__.cpython-38.pyc
Normal file
BIN
src/media_classifier/core/__pycache__/__init__.cpython-38.pyc
Normal file
Binary file not shown.
BIN
src/media_classifier/core/__pycache__/classifier.cpython-38.pyc
Normal file
BIN
src/media_classifier/core/__pycache__/classifier.cpython-38.pyc
Normal file
Binary file not shown.
44
src/media_classifier/core/classifier.py
Normal file
44
src/media_classifier/core/classifier.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import os
|
||||
import shutil
|
||||
|
||||
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
|
||||
VIDEO_EXTENSIONS = {'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv'}
|
||||
|
||||
class MediaScanner:
|
||||
@staticmethod
|
||||
def scan(directory, categories=None):
|
||||
files = []
|
||||
for root, dirs, files_in_dir in os.walk(directory):
|
||||
# Calculate relative path from the base directory
|
||||
rel_path = os.path.relpath(root, directory)
|
||||
|
||||
# If we are at the root, rel_path is '.' (on Windows/Unix usually)
|
||||
is_root = (rel_path == "." or rel_path == "")
|
||||
|
||||
# Split relative path into parts to check structure
|
||||
parts = rel_path.split(os.sep) if not is_root else []
|
||||
|
||||
for file in files_in_dir:
|
||||
ext = os.path.splitext(file)[1].lower()
|
||||
if ext in IMAGE_EXTENSIONS or ext in VIDEO_EXTENSIONS:
|
||||
# Rule 1: Keep root files
|
||||
if is_root:
|
||||
files.append(os.path.join(root, file))
|
||||
# Rule 2: Keep if it follows category/label structure and categories are provided
|
||||
elif categories and len(parts) == 2:
|
||||
cat, lab = parts[0], parts[1]
|
||||
if cat in categories and lab in categories[cat]:
|
||||
files.append(os.path.join(root, file))
|
||||
# Rule 3: If no categories provided, keep everything (legacy/default behavior)
|
||||
elif categories is None:
|
||||
files.append(os.path.join(root, file))
|
||||
return files
|
||||
|
||||
class FileClassifier:
|
||||
@staticmethod
|
||||
def move_to_category(src_path, base_dir, category, label):
|
||||
dest_dir = os.path.join(base_dir, category, label)
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
dest_path = os.path.join(dest_dir, os.path.basename(src_path))
|
||||
shutil.move(src_path, dest_path)
|
||||
return dest_path
|
||||
4
src/media_classifier/main.py
Normal file
4
src/media_classifier/main.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from media_classifier.ui.app import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
0
src/media_classifier/ui/__init__.py
Normal file
0
src/media_classifier/ui/__init__.py
Normal file
BIN
src/media_classifier/ui/__pycache__/__init__.cpython-38.pyc
Normal file
BIN
src/media_classifier/ui/__pycache__/__init__.cpython-38.pyc
Normal file
Binary file not shown.
BIN
src/media_classifier/ui/__pycache__/app.cpython-38.pyc
Normal file
BIN
src/media_classifier/ui/__pycache__/app.cpython-38.pyc
Normal file
Binary file not shown.
712
src/media_classifier/ui/app.py
Normal file
712
src/media_classifier/ui/app.py
Normal file
@@ -0,0 +1,712 @@
|
||||
import os
|
||||
import cv2
|
||||
import sys
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
|
||||
QPushButton, QLabel, QFileDialog, QComboBox, QSlider,
|
||||
QMessageBox, QMenu, QDialog, QLineEdit, QFormLayout
|
||||
)
|
||||
from PySide6.QtCore import Qt, QTimer, Slot, QThread, Signal
|
||||
from PySide6.QtGui import (
|
||||
QImage, QPixmap, QAction, QKeyEvent, QWheelEvent,
|
||||
QMouseEvent, QPainter, QTransform
|
||||
)
|
||||
import ctypes
|
||||
from PySide6.QtOpenGLWidgets import QOpenGLWidget
|
||||
from PySide6.QtGui import QOpenGLFunctions
|
||||
from media_classifier.core.classifier import MediaScanner, FileClassifier
|
||||
from media_classifier.utils.media_utils import get_processed_image, VideoHandler
|
||||
|
||||
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
|
||||
VIDEO_EXTENSIONS = {'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv'}
|
||||
|
||||
def format_time(seconds):
|
||||
h = int(seconds // 3600)
|
||||
m = int((seconds % 3600) // 60)
|
||||
s = int(seconds % 60)
|
||||
if h > 0:
|
||||
return f"{h:02}:{m:02}:{s:02}"
|
||||
return f"{m:02}:{s:02}"
|
||||
|
||||
class VideoWorker(QThread):
|
||||
frame_ready = Signal(object, object) # frame, worker instance
|
||||
status_updated = Signal(int, float, int, object) # current_f, sec, total, worker instance
|
||||
|
||||
def __init__(self, path):
|
||||
super().__init__()
|
||||
self.path = path
|
||||
self._stop = False
|
||||
self._paused = False
|
||||
self.playback_speed = 1.0
|
||||
self.seek_to = None
|
||||
self.cap_fps = 30
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
cap = cv2.VideoCapture(self.path)
|
||||
if not cap.isOpened():
|
||||
return
|
||||
|
||||
self.cap_fps = cap.get(cv2.CAP_PROP_FPS)
|
||||
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
|
||||
while not self._stop:
|
||||
if self.seek_to is not None:
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, self.seek_to)
|
||||
self.seek_to = None
|
||||
# If seeked, we want to show the frame immediately even if paused
|
||||
ret, frame = cap.read()
|
||||
if ret:
|
||||
self.frame_ready.emit(frame, self)
|
||||
current_f = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
|
||||
current_sec = current_f / self.cap_fps if self.cap_fps > 0 else 0
|
||||
self.status_updated.emit(current_f, current_sec, total_frames, self)
|
||||
|
||||
if self._paused:
|
||||
QThread.msleep(100)
|
||||
continue
|
||||
|
||||
frames_to_read = int(self.playback_speed) if self.playback_speed >= 1 else 1
|
||||
last_img = None
|
||||
for _ in range(frames_to_read):
|
||||
ret, frame = cap.read()
|
||||
if not ret:
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
||||
break
|
||||
last_img = frame
|
||||
|
||||
if last_img is not None:
|
||||
current_f = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
|
||||
current_sec = current_f / self.cap_fps if self.cap_fps > 0 else 0
|
||||
self.frame_ready.emit(last_img, self)
|
||||
self.status_updated.emit(current_f, current_sec, total_frames, self)
|
||||
|
||||
if self.cap_fps > 0:
|
||||
QThread.msleep(int(1000 / self.cap_fps / self.playback_speed))
|
||||
else:
|
||||
QThread.msleep(33)
|
||||
|
||||
cap.release()
|
||||
except Exception as e:
|
||||
print(f"VideoWorker error: {e}")
|
||||
|
||||
def stop(self):
|
||||
self._stop = True
|
||||
|
||||
def set_paused(self, paused):
|
||||
self._paused = paused
|
||||
|
||||
def set_speed(self, speed):
|
||||
self.playback_speed = speed
|
||||
|
||||
def seek(self, frame):
|
||||
self.seek_to = frame
|
||||
|
||||
class MediaViewerWidget(QWidget):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.zoom_scale = 1.0
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.last_mouse_pos = None
|
||||
self.image = None
|
||||
|
||||
class MediaViewerWidget(QWidget):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.zoom_scale = 1.0
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.last_mouse_pos = None
|
||||
self.image = None
|
||||
|
||||
def set_image(self, image):
|
||||
if image is None:
|
||||
self.image = None
|
||||
else:
|
||||
# Convert to QImage if it's numpy/cv2 or PIL
|
||||
if hasattr(image, 'shape'): # Numpy/CV2 (BGR)
|
||||
h, w, ch = image.shape
|
||||
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
||||
self.image = QImage(rgb.data, w, h, rgb.strides[0], QImage.Format.Format_RGB888).copy()
|
||||
elif hasattr(image, 'tobytes'): # PIL Image
|
||||
import numpy as np
|
||||
# Convert to RGB to handle Grayscale, RGBA, etc. consistently
|
||||
img_rgb = image.convert("RGB")
|
||||
arr = np.array(img_rgb)
|
||||
h, w, ch = arr.shape
|
||||
self.image = QImage(arr.data, w, h, arr.strides[0], QImage.Format.Format_RGB888).copy()
|
||||
else:
|
||||
self.image = None
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, event):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
|
||||
|
||||
# Background
|
||||
painter.fillRect(self.rect(), Qt.GlobalColor.black)
|
||||
|
||||
if self.image is None:
|
||||
return
|
||||
|
||||
pixmap = QPixmap.fromImage(self.image)
|
||||
pw, ph = pixmap.width(), pixmap.height()
|
||||
cw, ch = self.width(), self.height()
|
||||
|
||||
if pw == 0 or ph == 0:
|
||||
return
|
||||
|
||||
aspect = cw / ch if ch > 0 else 1
|
||||
img_aspect = pw / ph if ph > 0 else 1
|
||||
|
||||
# Calculate scale to fit image in view
|
||||
fit_scale = min(cw/pw, ch/ph)
|
||||
|
||||
painter.save()
|
||||
|
||||
# Center and Scale
|
||||
# We apply the user's zoom_scale on top of the fit_scale
|
||||
final_scale = fit_scale * self.zoom_scale
|
||||
|
||||
# Calculate center offset
|
||||
off_x = (cw - pw * final_scale) / 2 + self.offset_x
|
||||
off_y = (ch - ph * final_scale) / 2 + self.offset_y
|
||||
|
||||
painter.translate(off_x, off_y)
|
||||
painter.scale(final_scale, final_scale)
|
||||
|
||||
painter.drawPixmap(0, 0, pixmap)
|
||||
painter.restore()
|
||||
|
||||
def wheelEvent(self, event: QWheelEvent):
|
||||
factor = 1.1 if event.angleDelta().y() > 0 else 0.9
|
||||
self.zoom_scale *= factor
|
||||
self.zoom_scale = max(1.0, min(self.zoom_scale, 20.0))
|
||||
self.update()
|
||||
|
||||
def mousePressEvent(self, event: QMouseEvent):
|
||||
if event.button() == Qt.MouseButton.LeftButton:
|
||||
self.last_mouse_pos = event.position()
|
||||
|
||||
def mouseMoveEvent(self, event: QMouseEvent):
|
||||
if self.last_mouse_pos:
|
||||
pos = event.position()
|
||||
dx = pos.x() - self.last_mouse_pos.x()
|
||||
dy = pos.y() - self.last_mouse_pos.y()
|
||||
self.offset_x += dx
|
||||
self.offset_y += dy
|
||||
self.last_mouse_pos = pos
|
||||
self.update()
|
||||
|
||||
def mouseReleaseEvent(self, event: QMouseEvent):
|
||||
self.last_mouse_pos = None
|
||||
|
||||
class JumpSlider(QSlider):
|
||||
def mousePressEvent(self, event):
|
||||
if event.button() == Qt.MouseButton.LeftButton:
|
||||
# Calculate the value based on click position relative to slider width
|
||||
val = self.minimum() + (event.position().x() - self.rect().x()) * (self.maximum() - self.minimum()) / self.width()
|
||||
self.setValue(int(val))
|
||||
super().mousePressEvent(event)
|
||||
|
||||
class CategoryManagerDialog(QDialog):
|
||||
def __init__(self, categories, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Manage Categories")
|
||||
self.categories = categories # Reference to the dict
|
||||
self.resize(600, 500)
|
||||
self.base_dir = getattr(parent, 'current_dir', "")
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
content_layout = QHBoxLayout()
|
||||
|
||||
# Left side: Category list
|
||||
left_panel = QVBoxLayout()
|
||||
self.cat_list = QComboBox() # Use combo box for simple selection or a ListWidget
|
||||
from PySide6.QtWidgets import QListWidget, QListWidgetItem
|
||||
self.cat_widget = QListWidget()
|
||||
for cat in self.categories:
|
||||
item = QListWidgetItem(cat)
|
||||
self.cat_widget.addItem(item)
|
||||
|
||||
self.cat_widget.currentRowChanged.connect(self.on_category_selected)
|
||||
|
||||
add_cat_btn = QPushButton("+ Add Category")
|
||||
add_cat_btn.clicked.connect(self.add_category)
|
||||
del_cat_btn = QPushButton("- Remove Selected Category")
|
||||
del_cat_btn.clicked.connect(self.remove_category)
|
||||
|
||||
left_panel.addWidget(QLabel("Categories:"))
|
||||
left_panel.addWidget(self.cat_widget)
|
||||
left_panel.addWidget(add_cat_btn)
|
||||
left_panel.addWidget(del_cat_btn)
|
||||
|
||||
# Right side: Label management for selected category
|
||||
self.right_panel = QWidget()
|
||||
self.right_layout = QVBoxLayout(self.right_panel)
|
||||
self.label_widget = QListWidget()
|
||||
self.label_widget.itemDoubleClicked.connect(self.remove_label) # Double click to remove
|
||||
|
||||
self.current_cat_name = None
|
||||
|
||||
self.label_input = QLineEdit()
|
||||
self.label_input.setPlaceholderText("New label name...")
|
||||
add_lab_btn = QPushButton("Add Label")
|
||||
add_lab_btn.clicked.connect(self.add_label)
|
||||
|
||||
self.right_layout.addWidget(QLabel("Labels (Double-click to remove):"))
|
||||
self.right_layout.addWidget(self.label_widget)
|
||||
self.right_layout.addWidget(self.label_input)
|
||||
self.right_layout.addWidget(add_lab_btn)
|
||||
|
||||
content_layout.addLayout(left_panel, 1)
|
||||
content_layout.addWidget(self.right_panel, 2)
|
||||
layout.addLayout(content_layout)
|
||||
|
||||
# Bottom buttons for special operations and confirmation
|
||||
bottom_panel = QHBoxLayout()
|
||||
import_btn = QPushButton("Import Categories")
|
||||
import_btn.clicked.connect(self.import_categories)
|
||||
create_folders_btn = QPushButton("Create Folders")
|
||||
create_folders_btn.clicked.connect(self.create_folders)
|
||||
ok_btn = QPushButton("OK")
|
||||
ok_btn.setDefault(True)
|
||||
ok_btn.clicked.connect(self.accept)
|
||||
|
||||
bottom_panel.addWidget(import_btn)
|
||||
bottom_panel.addWidget(create_folders_btn)
|
||||
bottom_panel.addStretch()
|
||||
bottom_panel.addWidget(ok_btn)
|
||||
layout.addLayout(bottom_panel)
|
||||
|
||||
def on_category_selected(self, index):
|
||||
if index < 0: return
|
||||
self.current_cat_name = self.cat_widget.item(index).text()
|
||||
self.refresh_labels()
|
||||
|
||||
def refresh_labels(self):
|
||||
self.label_widget.clear()
|
||||
if self.current_cat_name in self.categories:
|
||||
for lab in self.categories[self.current_cat_name]:
|
||||
self.label_widget.addItem(lab)
|
||||
|
||||
def add_category(self):
|
||||
from PySide6.QtWidgets import QInputDialog
|
||||
name, ok = QInputDialog.getText(self, "New Category", "Category Name:")
|
||||
if ok and name:
|
||||
name = name.strip()
|
||||
if name and name not in self.categories:
|
||||
self.categories[name] = []
|
||||
self.cat_widget.addItem(name)
|
||||
self.on_category_selected(self.cat_widget.count() - 1)
|
||||
|
||||
def remove_category(self):
|
||||
index = self.cat_widget.currentRow()
|
||||
if index < 0: return
|
||||
name = self.cat_widget.item(index).text()
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
reply = QMessageBox.question(self, "Confirm", f"Remove category '{name}' and all its labels?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
|
||||
if reply == QMessageBox.StandardButton.Yes:
|
||||
del self.categories[name]
|
||||
self.cat_widget.takeItem(index)
|
||||
self.current_cat_name = None
|
||||
self.label_widget.clear()
|
||||
|
||||
def add_label(self):
|
||||
if not self.current_cat_name: return
|
||||
lab = self.label_input.text().strip()
|
||||
if lab and lab not in self.categories[self.current_cat_name]:
|
||||
self.categories[self.current_cat_name].append(lab)
|
||||
self.refresh_labels()
|
||||
self.label_input.clear()
|
||||
|
||||
def remove_label(self, item):
|
||||
if not self.current_cat_name: return
|
||||
lab = item.text()
|
||||
self.categories[self.current_cat_name].remove(lab)
|
||||
self.refresh_labels()
|
||||
|
||||
def import_categories(self):
|
||||
if not self.base_dir:
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
QMessageBox.warning(self, "No Directory", "Please select a directory in the main window first.")
|
||||
return
|
||||
if not os.path.exists(self.base_dir):
|
||||
return
|
||||
|
||||
try:
|
||||
# Root entries are depth 0. Folders at depth 1 are categories. Folders at depth 2 are labels.
|
||||
found_any = False
|
||||
for item in os.listdir(self.base_dir):
|
||||
item_path = os.path.join(self.base_dir, item)
|
||||
if os.path.isdir(item_path):
|
||||
# Potential category folder
|
||||
if item not in self.categories:
|
||||
self.categories[item] = []
|
||||
|
||||
for sub_item in os.listdir(item_path):
|
||||
sub_item_path = os.path.join(item_path, sub_item)
|
||||
if os.path.isdir(sub_item_path):
|
||||
if sub_item not in self.categories[item]:
|
||||
self.categories[item].append(sub_item)
|
||||
found_any = True
|
||||
|
||||
if not found_any:
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
QMessageBox.information(self, "Import", "No category/label folder structure found.")
|
||||
return
|
||||
|
||||
self.cat_widget.clear()
|
||||
for cat in self.categories:
|
||||
from PySide6.QtWidgets import QListWidgetItem
|
||||
self.cat_widget.addItem(QListWidgetItem(cat))
|
||||
except Exception as e:
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
QMessageBox.critical(self, "Import Error", f"An error occurred: {e}")
|
||||
|
||||
def create_folders(self):
|
||||
if not self.base_dir:
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
QMessageBox.warning(self, "No Directory", "Please select a directory in the main window first.")
|
||||
return
|
||||
if not self.current_cat_name:
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
QMessageBox.warning(self, "No Category", "Please select a category first.")
|
||||
return
|
||||
import os
|
||||
try:
|
||||
labels = self.categories.get(self.current_cat_name, [])
|
||||
for lab in labels:
|
||||
os.makedirs(os.path.join(self.base_dir, self.current_cat_name, lab), exist_ok=True)
|
||||
except Exception as e:
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
QMessageBox.critical(self, "Create Folders Error", f"An error occurred: {e}")
|
||||
|
||||
class MediaClassifierApp(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setWindowTitle("Media Classifier")
|
||||
self.resize(1000, 800)
|
||||
|
||||
self.current_dir = ""
|
||||
self.files = []
|
||||
self.current_file_idx = 0
|
||||
self.playing_video = False
|
||||
self.video_worker = None
|
||||
self.playback_speed = 1.0
|
||||
self.is_dragging_slider = False
|
||||
|
||||
self.categories = {
|
||||
"Quality": ["high", "medium", "low"],
|
||||
"Action": ["save", "remove"]
|
||||
}
|
||||
|
||||
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self.setup_ui()
|
||||
|
||||
def setup_ui(self):
|
||||
central_widget = QWidget()
|
||||
self.setCentralWidget(central_widget)
|
||||
main_layout = QVBoxLayout(central_widget)
|
||||
|
||||
top_panel = QHBoxLayout()
|
||||
self.dir_label = QLabel("No directory selected")
|
||||
browse_btn = QPushButton("Browse")
|
||||
browse_btn.setToolTip("Select directory to scan")
|
||||
browse_btn.clicked.connect(self.browse_directory)
|
||||
browse_btn.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
add_cat_btn = QPushButton("Manage Categories")
|
||||
add_cat_btn.setToolTip("Add or edit classification sets")
|
||||
add_cat_btn.clicked.connect(self.add_category_dialog)
|
||||
add_cat_btn.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
top_panel.addWidget(self.dir_label)
|
||||
top_panel.addWidget(browse_btn)
|
||||
top_panel.addWidget(add_cat_btn)
|
||||
main_layout.addLayout(top_panel)
|
||||
|
||||
self.viewer = MediaViewerWidget()
|
||||
self.viewer.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
main_layout.addWidget(self.viewer, stretch=1)
|
||||
|
||||
self.video_controls = QWidget()
|
||||
video_layout = QHBoxLayout(self.video_controls)
|
||||
|
||||
self.btn_play_pause = QPushButton("Pause")
|
||||
self.btn_play_pause.setToolTip("Play/Pause video (Space)")
|
||||
self.btn_play_pause.clicked.connect(self.toggle_playback)
|
||||
self.btn_play_pause.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
|
||||
self.seek_slider = JumpSlider(Qt.Orientation.Horizontal)
|
||||
self.seek_slider.valueChanged.connect(self.seek_video)
|
||||
self.seek_slider.sliderPressed.connect(self.on_slider_pressed)
|
||||
self.seek_slider.sliderReleased.connect(self.on_slider_released)
|
||||
|
||||
self.time_label = QLabel("00:00 / 00:00")
|
||||
self.time_label.setFixedWidth(150)
|
||||
|
||||
speed_label = QLabel(" Speed:")
|
||||
self.speed_combo = QComboBox()
|
||||
self.speed_combo.addItems(["0.5", "1.0", "1.5", "2.0"])
|
||||
self.speed_combo.setCurrentText("1.0")
|
||||
self.speed_combo.currentTextChanged.connect(self.change_speed)
|
||||
|
||||
video_layout.addWidget(self.btn_play_pause)
|
||||
video_layout.addWidget(self.seek_slider)
|
||||
video_layout.addWidget(self.time_label)
|
||||
video_layout.addWidget(speed_label)
|
||||
video_layout.addWidget(self.speed_combo)
|
||||
main_layout.addWidget(self.video_controls)
|
||||
|
||||
self.info_label = QLabel("")
|
||||
self.info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
main_layout.addWidget(self.info_label)
|
||||
|
||||
nav_panel = QHBoxLayout()
|
||||
prev_btn = QPushButton("← Previous")
|
||||
prev_btn.setToolTip("Previous file (Left arrow)")
|
||||
prev_btn.clicked.connect(self.prev_file)
|
||||
prev_btn.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
next_btn = QPushButton("Next →")
|
||||
next_btn.setToolTip("Next file (Right arrow)")
|
||||
next_btn.clicked.connect(self.next_file)
|
||||
next_btn.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
nav_panel.addWidget(prev_btn)
|
||||
nav_panel.addWidget(next_btn)
|
||||
main_layout.addLayout(nav_panel)
|
||||
|
||||
self.btn_container = QWidget()
|
||||
self.btn_layout = QHBoxLayout(self.btn_container)
|
||||
main_layout.addWidget(self.btn_container)
|
||||
self.refresh_buttons()
|
||||
|
||||
menu_bar = self.menuBar()
|
||||
settings_menu = menu_bar.addMenu("Settings")
|
||||
add_cat_action = QAction("Manage Categories", self)
|
||||
add_cat_action.triggered.connect(self.add_category_dialog)
|
||||
settings_menu.addAction(add_cat_action)
|
||||
|
||||
def keyPressEvent(self, event: QKeyEvent):
|
||||
if event.key() == Qt.Key.Key_Space:
|
||||
self.toggle_playback()
|
||||
elif event.key() == Qt.Key.Key_Left:
|
||||
self.prev_file()
|
||||
elif event.key() == Qt.Key.Key_Right:
|
||||
self.next_file()
|
||||
elif event.text() and '1' <= event.text() <= '9':
|
||||
idx = int(event.text()) - 1
|
||||
flat_labels = []
|
||||
for cat, labs in self.categories.items():
|
||||
for lab in labs:
|
||||
flat_labels.append((cat, lab))
|
||||
if idx < len(flat_labels):
|
||||
cat, lab = flat_labels[idx]
|
||||
self.classify(cat, lab)
|
||||
|
||||
def browse_directory(self):
|
||||
dir_path = QFileDialog.getExistingDirectory(self, "Select Directory")
|
||||
if dir_path:
|
||||
self.current_dir = dir_path
|
||||
self.dir_label.setText(dir_path)
|
||||
self.scan_files()
|
||||
self.show_current_file()
|
||||
|
||||
def scan_files(self):
|
||||
self.stop_video()
|
||||
self.viewer.set_image(None)
|
||||
self.files = MediaScanner.scan(self.current_dir, self.categories)
|
||||
self.current_file_idx = 0
|
||||
if not self.files:
|
||||
QMessageBox.information(self, "Info", "No images or videos found.")
|
||||
|
||||
def stop_video(self):
|
||||
self.playing_video = False
|
||||
if self.video_worker:
|
||||
self.video_worker.stop()
|
||||
self.video_worker.wait()
|
||||
self.video_worker = None
|
||||
self.btn_play_pause.setText("Play")
|
||||
|
||||
def show_current_file(self):
|
||||
self.stop_video()
|
||||
self.viewer.set_image(None) # Clear current media immediately
|
||||
self.viewer.zoom_scale = 1.0
|
||||
self.viewer.offset_x = 0
|
||||
self.viewer.offset_y = 0
|
||||
|
||||
if not self.files or self.current_file_idx >= len(self.files):
|
||||
self.info_label.setText("No more files")
|
||||
self.viewer.set_image(None)
|
||||
self.video_controls.hide()
|
||||
return
|
||||
|
||||
file_path = self.files[self.current_file_idx]
|
||||
filename = os.path.basename(file_path)
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
|
||||
class_info = ""
|
||||
rel_path = os.path.relpath(file_path, self.current_dir)
|
||||
parts = rel_path.split(os.sep)
|
||||
if len(parts) >= 3:
|
||||
cat, lab = parts[0], parts[1]
|
||||
if cat in self.categories and lab in self.categories.get(cat, []):
|
||||
class_info = f" [Current: {cat} -> {lab}]"
|
||||
|
||||
self.info_label.setText(f"File {self.current_file_idx + 1}/{len(self.files)}: {filename}{class_info}")
|
||||
|
||||
if ext in IMAGE_EXTENSIONS:
|
||||
from PIL import Image
|
||||
try:
|
||||
img = Image.open(file_path)
|
||||
self.viewer.set_image(img)
|
||||
except Exception as e:
|
||||
QMessageBox.critical(self, "Error", f"Image error: {e}")
|
||||
self.video_controls.hide()
|
||||
elif ext in VIDEO_EXTENSIONS:
|
||||
self.start_video(file_path)
|
||||
self.video_controls.show()
|
||||
else:
|
||||
self.viewer.set_image(None)
|
||||
self.info_label.setText(f"Unsupported file: {filename}")
|
||||
self.video_controls.hide()
|
||||
|
||||
def start_video(self, path):
|
||||
try:
|
||||
self.video_worker = VideoWorker(path)
|
||||
self.video_worker.frame_ready.connect(self.on_frame_ready)
|
||||
self.video_worker.status_updated.connect(self.on_status_updated)
|
||||
|
||||
handler = VideoHandler(path)
|
||||
fps = handler.cap.get(cv2.CAP_PROP_FPS)
|
||||
total_frames = handler.total_frames
|
||||
duration_sec = total_frames / fps if fps > 0 else 0
|
||||
handler.close()
|
||||
|
||||
self.seek_slider.setRange(0, max(0, total_frames - 1))
|
||||
self.seek_slider.setValue(0)
|
||||
self.time_label.setText(f"00:00 / {format_time(duration_sec)}")
|
||||
|
||||
self.playing_video = True
|
||||
self.btn_play_pause.setText("Pause")
|
||||
self.video_worker.set_speed(self.playback_speed)
|
||||
self.video_worker.start()
|
||||
except Exception as e:
|
||||
QMessageBox.critical(self, "Error", f"Video error: {e}")
|
||||
|
||||
@Slot(object, object)
|
||||
def on_frame_ready(self, frame, worker):
|
||||
if worker == self.video_worker:
|
||||
self.viewer.set_image(frame)
|
||||
|
||||
@Slot(int, float, int, object)
|
||||
def on_status_updated(self, current_f, current_sec, total_frames, worker):
|
||||
if worker != self.video_worker:
|
||||
return
|
||||
if self.video_worker:
|
||||
fps = self.video_worker.cap_fps if hasattr(self.video_worker, 'cap_fps') else 30
|
||||
duration_sec = total_frames / fps if fps > 0 else 0
|
||||
else:
|
||||
duration_sec = total_frames / 30
|
||||
|
||||
self.time_label.setText(f"{format_time(current_sec)} / {format_time(duration_sec)}")
|
||||
|
||||
if not self.is_dragging_slider:
|
||||
self.seek_slider.blockSignals(True)
|
||||
self.seek_slider.setValue(current_f)
|
||||
self.seek_slider.blockSignals(False)
|
||||
|
||||
def on_slider_pressed(self):
|
||||
self.is_dragging_slider = True
|
||||
if self.video_worker:
|
||||
self.video_worker.set_paused(True)
|
||||
|
||||
def on_slider_released(self):
|
||||
self.is_dragging_slider = False
|
||||
if self.playing_video and self.video_worker:
|
||||
self.video_worker.set_paused(False)
|
||||
|
||||
def toggle_playback(self):
|
||||
if not self.video_worker: return
|
||||
self.playing_video = not self.playing_video
|
||||
self.btn_play_pause.setText("Play" if not self.playing_video else "Pause")
|
||||
self.video_worker.set_paused(not self.playing_video)
|
||||
|
||||
def seek_video(self, val):
|
||||
if self.video_worker:
|
||||
self.video_worker.seek(val)
|
||||
|
||||
def change_speed(self, text):
|
||||
self.playback_speed = float(text)
|
||||
if self.video_worker:
|
||||
self.video_worker.set_speed(self.playback_speed)
|
||||
|
||||
def prev_file(self):
|
||||
if not self.files: return
|
||||
self.current_file_idx = (self.current_file_idx - 1) % len(self.files)
|
||||
self.show_current_file()
|
||||
|
||||
def next_file(self):
|
||||
if not self.files: return
|
||||
self.current_file_idx = (self.current_file_idx + 1) % len(self.files)
|
||||
self.show_current_file()
|
||||
|
||||
def classify(self, category, label):
|
||||
if not self.files or self.current_file_idx >= len(self.files): return
|
||||
self.stop_video()
|
||||
src_path = self.files[self.current_file_idx]
|
||||
new_path = FileClassifier.move_to_category(src_path, self.current_dir, category, label)
|
||||
self.files[self.current_file_idx] = new_path
|
||||
self.next_file()
|
||||
|
||||
def refresh_buttons(self):
|
||||
while self.btn_layout.count():
|
||||
item = self.btn_layout.takeAt(0)
|
||||
widget = item.widget()
|
||||
if widget: widget.deleteLater()
|
||||
|
||||
flat_labels = []
|
||||
for cat, labs in self.categories.items():
|
||||
for lab in labs:
|
||||
flat_labels.append((cat, lab))
|
||||
|
||||
label_to_idx = { (cat, lab): i+1 for i, (cat, lab) in enumerate(flat_labels) }
|
||||
|
||||
for cat_name, labels in self.categories.items():
|
||||
cat_container = QWidget()
|
||||
cat_lay = QVBoxLayout(cat_container)
|
||||
lbl = QLabel(cat_name)
|
||||
lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
cat_lay.addWidget(lbl)
|
||||
|
||||
btns_lay = QHBoxLayout()
|
||||
for label in labels:
|
||||
idx = label_to_idx.get((cat_name, label), "?")
|
||||
btn = QPushButton(f"({idx}) {label}")
|
||||
btn.setToolTip(f"Classify as {cat_name} -> {label} (Hotkey: {idx})")
|
||||
btn.clicked.connect(lambda checked=False, c=cat_name, l=label: self.classify(c, l))
|
||||
btn.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
btns_lay.addWidget(btn)
|
||||
cat_lay.addLayout(btns_lay)
|
||||
self.btn_layout.addWidget(cat_container)
|
||||
|
||||
def add_category_dialog(self):
|
||||
dlg = CategoryManagerDialog(self.categories, self)
|
||||
if dlg.exec():
|
||||
self.refresh_buttons()
|
||||
self.scan_files()
|
||||
self.show_current_file()
|
||||
|
||||
def main():
|
||||
try:
|
||||
app = QApplication(sys.argv)
|
||||
window = MediaClassifierApp()
|
||||
window.show()
|
||||
sys.exit(app.exec())
|
||||
except Exception as e:
|
||||
import traceback
|
||||
with open("crash_log.txt", "w") as f:
|
||||
f.write(traceback.format_exc())
|
||||
print(f"Crashed: {e}")
|
||||
sys.exit(1)
|
||||
0
src/media_classifier/utils/__init__.py
Normal file
0
src/media_classifier/utils/__init__.py
Normal file
BIN
src/media_classifier/utils/__pycache__/__init__.cpython-38.pyc
Normal file
BIN
src/media_classifier/utils/__pycache__/__init__.cpython-38.pyc
Normal file
Binary file not shown.
Binary file not shown.
61
src/media_classifier/utils/media_utils.py
Normal file
61
src/media_classifier/utils/media_utils.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
def get_processed_image(img, zoom_scale, offset_x, offset_y, target_w, target_h):
|
||||
"""
|
||||
Crops and resizes an image based on zoom and offset.
|
||||
Supports both PIL Images and numpy arrays (BGR).
|
||||
"""
|
||||
# Convert to numpy array if it's a PIL Image
|
||||
if isinstance(img, Image.Image):
|
||||
frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
||||
else:
|
||||
frame = img
|
||||
|
||||
h, w = frame.shape[:2]
|
||||
|
||||
# Zooming logic: determine the size of the viewport
|
||||
crop_w = w / zoom_scale
|
||||
crop_h = h / zoom_scale
|
||||
|
||||
# Ensure crop stays within bounds
|
||||
left = int(max(0, min(offset_x, w - crop_w)))
|
||||
top = int(max(0, min(offset_y, h - crop_h)))
|
||||
right = int(left + crop_w)
|
||||
bottom = int(top + crop_h)
|
||||
|
||||
cropped = frame[top:bottom, left:right]
|
||||
|
||||
# Maintain aspect ratio during final resize to fit canvas
|
||||
curr_h, curr_w = cropped.shape[:2]
|
||||
scale = min(target_w / curr_w, target_h / curr_h)
|
||||
new_w, new_h = int(curr_w * scale), int(curr_h * scale)
|
||||
|
||||
# Use INTER_LINEAR for speed (much faster than LANCZOS equivalent in PIL)
|
||||
resized = cv2.resize(cropped, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
# Convert back to RGB PIL Image for Tkinter
|
||||
return Image.fromarray(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB))
|
||||
|
||||
class VideoHandler:
|
||||
def __init__(self, path):
|
||||
self.cap = cv2.VideoCapture(path)
|
||||
if not self.cap.isOpened():
|
||||
raise IOError(f"Could not open video file {path}")
|
||||
self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
|
||||
def get_frame(self, frame_index=None):
|
||||
if frame_index is not None:
|
||||
self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
|
||||
|
||||
ret, frame = self.cap.read()
|
||||
if ret:
|
||||
# Return as BGR numpy array for efficiency (processed in get_processed_image)
|
||||
return frame
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
if self.cap:
|
||||
self.cap.release()
|
||||
self.cap = None
|
||||
13
src/simple_gui_test.py
Normal file
13
src/simple_gui_test.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import sys
|
||||
from PySide6.QtWidgets import QApplication, QLabel
|
||||
|
||||
def test_gui():
|
||||
print("Starting Simple GUI Test...")
|
||||
app = QApplication(sys.argv)
|
||||
label = QLabel("Hello OpenGL")
|
||||
label.show()
|
||||
print("GUI created and shown.")
|
||||
# We don't need app.exec() for a simple check if it crashes at creation
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_gui()
|
||||
36
src/test_gl.py
Normal file
36
src/test_gl.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import sys
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from media_classifier.ui.app import MediaViewerWidget
|
||||
import numpy as np
|
||||
|
||||
def test_opengl():
|
||||
print("Initializing QApplication...")
|
||||
app = QApplication(sys.argv)
|
||||
|
||||
print("Creating MediaViewerWidget...")
|
||||
viewer = MediaViewerWidget()
|
||||
# We need to show the widget for OpenGL context to be created in some versions,
|
||||
# or call makeCurrent().
|
||||
viewer.show()
|
||||
|
||||
print("Testing set_image with numpy array (BGR)...")
|
||||
try:
|
||||
dummy_img = np.zeros((480, 640, 3), dtype=np.uint8)
|
||||
viewer.set_image(dummy_img)
|
||||
print("Numpy image set successfully.")
|
||||
except Exception as e:
|
||||
print(f"Error setting numpy image: {e}")
|
||||
|
||||
print("Testing set_image with PIL Image...")
|
||||
try:
|
||||
from PIL import Image
|
||||
dummy_pil = Image.new('RGB', (640, 480), color='red')
|
||||
viewer.set_image(dummy_pil)
|
||||
print("PIL image set successfully.")
|
||||
except Exception as e:
|
||||
print(f"Error setting PIL image: {e}")
|
||||
|
||||
print("OpenGL test completed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_opengl()
|
||||
Reference in New Issue
Block a user