Compare commits
36 Commits
f0b0114fc5
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 216ca1e460 | |||
| 0db2ee4587 | |||
| d43813cc2a | |||
| 97424ea0af | |||
| eafc5de6f2 | |||
| fa710e914e | |||
| e3e337af88 | |||
| 15ca74ad4b | |||
| a11d76fd5f | |||
| cf1238bbff | |||
| d3b7f31730 | |||
| 52c06c4db7 | |||
| 3a320f3187 | |||
| c37e2bd5e0 | |||
| 9418661be9 | |||
| 7349015177 | |||
| 918a6e9414 | |||
| 5909c0ec99 | |||
| 286b0410ff | |||
| 0c18f570d4 | |||
| 3f2160405a | |||
| f3f57f7c53 | |||
| 957aab0656 | |||
| 0a94548f5e | |||
| 124fbacd2a | |||
| 0f0aeed2f1 | |||
| fe6e55de16 | |||
| dd454ebf6f | |||
| 2854907359 | |||
| 48417b6d73 | |||
| ce7abd8a29 | |||
| df12413c5d | |||
| c56b07f999 | |||
| c89cecd43f | |||
| 37f6166b37 | |||
| dc31b0bebb |
219
engine.py
219
engine.py
@@ -27,10 +27,19 @@ class SorterEngine:
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS processed_log
|
||||
(source_path TEXT PRIMARY KEY, category TEXT, action_type TEXT)''')
|
||||
|
||||
# Seed categories if empty
|
||||
# --- NEW: FOLDER TAGS TABLE (persists tags by folder) ---
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS folder_tags
|
||||
(folder_path TEXT, filename TEXT, category TEXT, tag_index INTEGER,
|
||||
PRIMARY KEY (folder_path, filename))''')
|
||||
|
||||
# --- NEW: PROFILE CATEGORIES TABLE (each profile has its own categories) ---
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS profile_categories
|
||||
(profile TEXT, category TEXT, PRIMARY KEY (profile, category))''')
|
||||
|
||||
# Seed categories if empty (legacy table)
|
||||
cursor.execute("SELECT COUNT(*) FROM categories")
|
||||
if cursor.fetchone()[0] == 0:
|
||||
for cat in ["_TRASH", "Default", "Action", "Solo"]:
|
||||
for cat in ["_TRASH", "control", "Default", "Action", "Solo"]:
|
||||
cursor.execute("INSERT OR IGNORE INTO categories VALUES (?)", (cat,))
|
||||
|
||||
conn.commit()
|
||||
@@ -103,21 +112,45 @@ class SorterEngine:
|
||||
"tab5_source": r[7], "tab5_out": r[8]
|
||||
} for r in rows}
|
||||
|
||||
# --- 3. CATEGORY MANAGEMENT (Sorted A-Z) ---
|
||||
# --- 3. CATEGORY MANAGEMENT (Profile-based) ---
|
||||
@staticmethod
|
||||
def get_categories():
|
||||
def get_categories(profile=None):
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT name FROM categories ORDER BY name COLLATE NOCASE ASC")
|
||||
cats = [r[0] for r in cursor.fetchall()]
|
||||
|
||||
# Ensure table exists
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS profile_categories
|
||||
(profile TEXT, category TEXT, PRIMARY KEY (profile, category))''')
|
||||
|
||||
if profile:
|
||||
cursor.execute("SELECT category FROM profile_categories WHERE profile = ? ORDER BY category COLLATE NOCASE ASC", (profile,))
|
||||
cats = [r[0] for r in cursor.fetchall()]
|
||||
# If no categories for this profile, seed with defaults
|
||||
if not cats:
|
||||
for cat in ["_TRASH", "control"]:
|
||||
cursor.execute("INSERT OR IGNORE INTO profile_categories VALUES (?, ?)", (profile, cat))
|
||||
conn.commit()
|
||||
cats = ["_TRASH", "control"]
|
||||
else:
|
||||
# Fallback to legacy table
|
||||
cursor.execute("SELECT name FROM categories ORDER BY name COLLATE NOCASE ASC")
|
||||
cats = [r[0] for r in cursor.fetchall()]
|
||||
|
||||
conn.close()
|
||||
return cats
|
||||
|
||||
@staticmethod
|
||||
def add_category(name):
|
||||
def add_category(name, profile=None):
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("INSERT OR IGNORE INTO categories VALUES (?)", (name,))
|
||||
|
||||
if profile:
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS profile_categories
|
||||
(profile TEXT, category TEXT, PRIMARY KEY (profile, category))''')
|
||||
cursor.execute("INSERT OR IGNORE INTO profile_categories VALUES (?, ?)", (profile, name))
|
||||
else:
|
||||
cursor.execute("INSERT OR IGNORE INTO categories VALUES (?)", (name,))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@@ -241,6 +274,15 @@ class SorterEngine:
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@staticmethod
|
||||
def clear_staging_area():
|
||||
"""Clears all items from the staging area."""
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM staging_area")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@staticmethod
|
||||
def get_staged_data():
|
||||
"""Retrieves current tagged/staged images."""
|
||||
@@ -253,9 +295,14 @@ class SorterEngine:
|
||||
return {r[0]: {"cat": r[1], "name": r[2], "marked": r[3]} for r in rows}
|
||||
|
||||
@staticmethod
|
||||
def commit_global(output_root, cleanup_mode, operation="Copy", source_root=None):
|
||||
def commit_global(output_root, cleanup_mode, operation="Copy", source_root=None, profile=None):
|
||||
"""Commits ALL staged files and fixes permissions."""
|
||||
data = SorterEngine.get_staged_data()
|
||||
|
||||
# Save folder tags BEFORE processing (so we can restore them later)
|
||||
if source_root:
|
||||
SorterEngine.save_folder_tags(source_root, profile)
|
||||
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
@@ -494,11 +541,16 @@ class SorterEngine:
|
||||
conn.close()
|
||||
|
||||
@staticmethod
|
||||
def delete_category(name):
|
||||
def delete_category(name, profile=None):
|
||||
"""Deletes a category and clears any staged tags associated with it."""
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM categories WHERE name = ?", (name,))
|
||||
|
||||
if profile:
|
||||
cursor.execute("DELETE FROM profile_categories WHERE profile = ? AND category = ?", (profile, name))
|
||||
else:
|
||||
cursor.execute("DELETE FROM categories WHERE name = ?", (name,))
|
||||
|
||||
cursor.execute("DELETE FROM staging_area WHERE target_category = ?", (name,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
@@ -513,4 +565,147 @@ class SorterEngine:
|
||||
for idx, img_path in enumerate(all_images):
|
||||
if img_path in staged_keys:
|
||||
tagged_pages.add(idx // page_size)
|
||||
return tagged_pages
|
||||
return tagged_pages
|
||||
|
||||
# --- 7. FOLDER TAG PERSISTENCE ---
|
||||
@staticmethod
|
||||
def save_folder_tags(folder_path, profile=None):
|
||||
"""
|
||||
Saves current staging data associated with a folder for later restoration.
|
||||
Call this BEFORE clearing the staging area.
|
||||
"""
|
||||
import re
|
||||
staged = SorterEngine.get_staged_data()
|
||||
if not staged:
|
||||
return 0
|
||||
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Ensure table exists with profile column
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS folder_tags
|
||||
(profile TEXT, folder_path TEXT, filename TEXT, category TEXT, tag_index INTEGER,
|
||||
PRIMARY KEY (profile, folder_path, filename))''')
|
||||
|
||||
# Check if old schema (without profile) - migrate if needed
|
||||
cursor.execute("PRAGMA table_info(folder_tags)")
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
if 'profile' not in columns:
|
||||
cursor.execute("DROP TABLE folder_tags")
|
||||
cursor.execute('''CREATE TABLE folder_tags
|
||||
(profile TEXT, folder_path TEXT, filename TEXT, category TEXT, tag_index INTEGER,
|
||||
PRIMARY KEY (profile, folder_path, filename))''')
|
||||
conn.commit()
|
||||
|
||||
profile = profile or "Default"
|
||||
saved_count = 0
|
||||
for orig_path, info in staged.items():
|
||||
# Only save tags for files that are in this folder (or subfolders)
|
||||
if orig_path.startswith(folder_path):
|
||||
filename = os.path.basename(orig_path)
|
||||
category = info['cat']
|
||||
|
||||
# Extract index from the new_name (e.g., "Action_042.jpg" -> 42)
|
||||
new_name = info['name']
|
||||
match = re.search(r'_(\d+)', new_name)
|
||||
tag_index = int(match.group(1)) if match else 0
|
||||
|
||||
cursor.execute(
|
||||
"INSERT OR REPLACE INTO folder_tags VALUES (?, ?, ?, ?, ?)",
|
||||
(profile, folder_path, filename, category, tag_index)
|
||||
)
|
||||
saved_count += 1
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return saved_count
|
||||
|
||||
@staticmethod
|
||||
def restore_folder_tags(folder_path, all_images, profile=None):
|
||||
"""
|
||||
Restores previously saved tags for a folder back into the staging area.
|
||||
Call this when loading/reloading a folder.
|
||||
Returns the number of tags restored.
|
||||
"""
|
||||
try:
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Ensure table exists with profile column
|
||||
cursor.execute('''CREATE TABLE IF NOT EXISTS folder_tags
|
||||
(profile TEXT, folder_path TEXT, filename TEXT, category TEXT, tag_index INTEGER,
|
||||
PRIMARY KEY (profile, folder_path, filename))''')
|
||||
|
||||
# Check if old schema (without profile) - migrate if needed
|
||||
cursor.execute("PRAGMA table_info(folder_tags)")
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
if 'profile' not in columns:
|
||||
cursor.execute("DROP TABLE folder_tags")
|
||||
cursor.execute('''CREATE TABLE folder_tags
|
||||
(profile TEXT, folder_path TEXT, filename TEXT, category TEXT, tag_index INTEGER,
|
||||
PRIMARY KEY (profile, folder_path, filename))''')
|
||||
conn.commit()
|
||||
|
||||
profile = profile or "Default"
|
||||
|
||||
# Get saved tags for this folder and profile
|
||||
cursor.execute(
|
||||
"SELECT filename, category, tag_index FROM folder_tags WHERE profile = ? AND folder_path = ?",
|
||||
(profile, folder_path)
|
||||
)
|
||||
saved_tags = {row[0]: {"cat": row[1], "index": row[2]} for row in cursor.fetchall()}
|
||||
|
||||
if not saved_tags:
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
# Build a map of filename -> full path from current images
|
||||
filename_to_path = {}
|
||||
for img_path in all_images:
|
||||
fname = os.path.basename(img_path)
|
||||
if fname not in filename_to_path:
|
||||
filename_to_path[fname] = img_path
|
||||
|
||||
# Restore tags to staging area
|
||||
restored = 0
|
||||
for filename, tag_info in saved_tags.items():
|
||||
if filename in filename_to_path:
|
||||
full_path = filename_to_path[filename]
|
||||
cursor.execute("SELECT 1 FROM staging_area WHERE original_path = ?", (full_path,))
|
||||
if not cursor.fetchone():
|
||||
ext = os.path.splitext(filename)[1]
|
||||
new_name = f"{tag_info['cat']}_{tag_info['index']:03d}{ext}"
|
||||
cursor.execute(
|
||||
"INSERT OR REPLACE INTO staging_area VALUES (?, ?, ?, 1)",
|
||||
(full_path, tag_info['cat'], new_name)
|
||||
)
|
||||
restored += 1
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return restored
|
||||
except Exception as e:
|
||||
print(f"Error restoring folder tags: {e}")
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def clear_folder_tags(folder_path):
|
||||
"""Clears saved tags for a specific folder."""
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM folder_tags WHERE folder_path = ?", (folder_path,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@staticmethod
|
||||
def get_saved_folder_tags(folder_path):
|
||||
"""Returns saved tags for a folder (for debugging/display)."""
|
||||
conn = sqlite3.connect(SorterEngine.DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"SELECT filename, category, tag_index FROM folder_tags WHERE folder_path = ?",
|
||||
(folder_path,)
|
||||
)
|
||||
result = {row[0]: {"cat": row[1], "index": row[2]} for row in cursor.fetchall()}
|
||||
conn.close()
|
||||
return result
|
||||
538
gallery_app.py
538
gallery_app.py
@@ -28,8 +28,16 @@ class AppState:
|
||||
self.preview_quality = 50
|
||||
|
||||
# Tagging State
|
||||
self.active_cat = "Default"
|
||||
self.active_cat = "control"
|
||||
self.next_index = 1
|
||||
self.hovered_image = None # Track currently hovered image for keyboard shortcuts
|
||||
self.category_hotkeys: Dict[str, str] = {} # Maps hotkey -> category name
|
||||
|
||||
# Undo Stack
|
||||
self.undo_stack: List[Dict] = [] # Stores last actions for undo
|
||||
|
||||
# Filter Mode
|
||||
self.filter_mode = "all" # "all", "tagged", "untagged"
|
||||
|
||||
# Batch Settings
|
||||
self.batch_mode = "Copy"
|
||||
@@ -49,36 +57,69 @@ class AppState:
|
||||
def load_active_profile(self):
|
||||
"""Load paths from active profile."""
|
||||
p_data = self.profiles.get(self.profile_name, {})
|
||||
self.source_dir = p_data.get("tab5_source", "/storage")
|
||||
self.output_dir = p_data.get("tab5_out", "/storage")
|
||||
self.input_base = p_data.get("tab5_source", "/storage")
|
||||
self.output_base = p_data.get("tab5_out", "/storage")
|
||||
self.folder_name = ""
|
||||
|
||||
@property
|
||||
def source_dir(self):
|
||||
"""Computed source path: input_base/folder_name or just input_base."""
|
||||
if self.folder_name:
|
||||
return os.path.join(self.input_base, self.folder_name)
|
||||
return self.input_base
|
||||
|
||||
@property
|
||||
def output_dir(self):
|
||||
"""Computed output path: output_base/folder_name or just output_base."""
|
||||
if self.folder_name:
|
||||
return os.path.join(self.output_base, self.folder_name)
|
||||
return self.output_base
|
||||
|
||||
def save_current_profile(self):
|
||||
"""Save current paths to active profile."""
|
||||
if self.profile_name not in self.profiles:
|
||||
self.profiles[self.profile_name] = {}
|
||||
self.profiles[self.profile_name]["tab5_source"] = self.source_dir
|
||||
self.profiles[self.profile_name]["tab5_out"] = self.output_dir
|
||||
SorterEngine.save_tab_paths(self.profile_name, t5_s=self.source_dir, t5_o=self.output_dir)
|
||||
self.profiles[self.profile_name]["tab5_source"] = self.input_base
|
||||
self.profiles[self.profile_name]["tab5_out"] = self.output_base
|
||||
SorterEngine.save_tab_paths(self.profile_name, t5_s=self.input_base, t5_o=self.output_base)
|
||||
ui.notify(f"Profile '{self.profile_name}' saved!", type='positive')
|
||||
|
||||
def get_categories(self) -> List[str]:
|
||||
"""Get list of categories, ensuring active_cat exists."""
|
||||
cats = SorterEngine.get_categories() or ["Default"]
|
||||
cats = SorterEngine.get_categories(self.profile_name) or ["control"]
|
||||
if self.active_cat not in cats:
|
||||
self.active_cat = cats[0]
|
||||
return cats
|
||||
|
||||
def get_filtered_images(self) -> List[str]:
|
||||
"""Get images based on current filter mode."""
|
||||
if self.filter_mode == "all":
|
||||
return self.all_images
|
||||
elif self.filter_mode == "tagged":
|
||||
return [img for img in self.all_images if img in self.staged_data]
|
||||
elif self.filter_mode == "untagged":
|
||||
return [img for img in self.all_images if img not in self.staged_data]
|
||||
return self.all_images
|
||||
|
||||
@property
|
||||
def total_pages(self) -> int:
|
||||
"""Calculate total pages."""
|
||||
return math.ceil(len(self.all_images) / self.page_size) if self.all_images else 0
|
||||
"""Calculate total pages based on filtered images."""
|
||||
filtered = self.get_filtered_images()
|
||||
return math.ceil(len(filtered) / self.page_size) if filtered else 0
|
||||
|
||||
def get_current_batch(self) -> List[str]:
|
||||
"""Get images for current page."""
|
||||
if not self.all_images:
|
||||
"""Get images for current page based on filter."""
|
||||
filtered = self.get_filtered_images()
|
||||
if not filtered:
|
||||
return []
|
||||
start = self.page * self.page_size
|
||||
return self.all_images[start : start + self.page_size]
|
||||
return filtered[start : start + self.page_size]
|
||||
|
||||
def get_stats(self) -> Dict:
|
||||
"""Get image statistics for display."""
|
||||
total = len(self.all_images)
|
||||
tagged = len([img for img in self.all_images if img in self.staged_data])
|
||||
return {"total": total, "tagged": tagged, "untagged": total - tagged}
|
||||
|
||||
state = AppState()
|
||||
|
||||
@@ -112,8 +153,22 @@ def load_images():
|
||||
ui.notify(f"Source not found: {state.source_dir}", type='warning')
|
||||
return
|
||||
|
||||
# Auto-save current tags before switching folders
|
||||
if state.all_images and state.staged_data:
|
||||
saved = SorterEngine.save_folder_tags(state.source_dir, state.profile_name)
|
||||
if saved > 0:
|
||||
ui.notify(f"Auto-saved {saved} tags", type='info')
|
||||
|
||||
# Clear staging area when loading a new folder
|
||||
SorterEngine.clear_staging_area()
|
||||
|
||||
state.all_images = SorterEngine.get_images(state.source_dir, recursive=True)
|
||||
|
||||
# Restore previously saved tags for this folder and profile
|
||||
restored = SorterEngine.restore_folder_tags(state.source_dir, state.all_images, state.profile_name)
|
||||
if restored > 0:
|
||||
ui.notify(f"Restored {restored} tags from previous session", type='info')
|
||||
|
||||
# Reset page if out of bounds
|
||||
if state.page >= state.total_pages:
|
||||
state.page = 0
|
||||
@@ -176,6 +231,17 @@ def action_tag(img_path: str, manual_idx: Optional[int] = None):
|
||||
ui.notify(f"Conflict: {name} exists. Using suffix.", type='warning')
|
||||
name = f"{state.active_cat}_{idx:03d}_{len(staged_names)+1}{ext}"
|
||||
|
||||
# Save to undo stack
|
||||
state.undo_stack.append({
|
||||
"action": "tag",
|
||||
"path": img_path,
|
||||
"category": state.active_cat,
|
||||
"name": name,
|
||||
"index": idx
|
||||
})
|
||||
if len(state.undo_stack) > 50: # Limit undo history
|
||||
state.undo_stack.pop(0)
|
||||
|
||||
SorterEngine.stage_image(img_path, state.active_cat, name)
|
||||
|
||||
# Only auto-increment if we used the default next_index (not manual)
|
||||
@@ -187,15 +253,79 @@ def action_tag(img_path: str, manual_idx: Optional[int] = None):
|
||||
|
||||
def action_untag(img_path: str):
|
||||
"""Remove staging from an image."""
|
||||
# Save to undo stack
|
||||
if img_path in state.staged_data:
|
||||
info = state.staged_data[img_path]
|
||||
state.undo_stack.append({
|
||||
"action": "untag",
|
||||
"path": img_path,
|
||||
"category": info['cat'],
|
||||
"name": info['name'],
|
||||
"index": _extract_index(info['name'])
|
||||
})
|
||||
if len(state.undo_stack) > 50:
|
||||
state.undo_stack.pop(0)
|
||||
|
||||
SorterEngine.clear_staged_item(img_path)
|
||||
refresh_staged_info()
|
||||
refresh_ui()
|
||||
|
||||
def action_delete(img_path: str):
|
||||
"""Delete image to trash."""
|
||||
# Save to undo stack
|
||||
state.undo_stack.append({
|
||||
"action": "delete",
|
||||
"path": img_path
|
||||
})
|
||||
if len(state.undo_stack) > 50:
|
||||
state.undo_stack.pop(0)
|
||||
|
||||
SorterEngine.delete_to_trash(img_path)
|
||||
load_images()
|
||||
|
||||
def action_undo():
|
||||
"""Undo the last action."""
|
||||
if not state.undo_stack:
|
||||
ui.notify("Nothing to undo", type='warning')
|
||||
return
|
||||
|
||||
last = state.undo_stack.pop()
|
||||
|
||||
if last["action"] == "tag":
|
||||
# Undo tag = untag
|
||||
SorterEngine.clear_staged_item(last["path"])
|
||||
ui.notify(f"Undid tag: {os.path.basename(last['path'])}", type='info')
|
||||
|
||||
elif last["action"] == "untag":
|
||||
# Undo untag = re-tag with same settings
|
||||
SorterEngine.stage_image(last["path"], last["category"], last["name"])
|
||||
ui.notify(f"Undid untag: {os.path.basename(last['path'])}", type='info')
|
||||
|
||||
elif last["action"] == "delete":
|
||||
# Undo delete = restore from trash
|
||||
trash_path = os.path.join(os.path.dirname(last["path"]), "_DELETED", os.path.basename(last["path"]))
|
||||
if os.path.exists(trash_path):
|
||||
import shutil
|
||||
shutil.move(trash_path, last["path"])
|
||||
ui.notify(f"Restored: {os.path.basename(last['path'])}", type='info')
|
||||
else:
|
||||
ui.notify("Cannot restore - file not in trash", type='warning')
|
||||
|
||||
refresh_staged_info()
|
||||
refresh_ui()
|
||||
|
||||
def action_save_tags():
|
||||
"""Save current tags to database for later restoration."""
|
||||
if not state.all_images:
|
||||
ui.notify("No folder loaded", type='warning')
|
||||
return
|
||||
|
||||
saved = SorterEngine.save_folder_tags(state.source_dir, state.profile_name)
|
||||
if saved > 0:
|
||||
ui.notify(f"Saved {saved} tags", type='positive')
|
||||
else:
|
||||
ui.notify("No tags to save", type='info')
|
||||
|
||||
def action_apply_page():
|
||||
"""Apply staged changes for current page only."""
|
||||
batch = state.get_current_batch()
|
||||
@@ -215,7 +345,8 @@ async def action_apply_global():
|
||||
state.output_dir,
|
||||
state.cleanup_mode,
|
||||
state.batch_mode,
|
||||
state.source_dir
|
||||
state.source_dir,
|
||||
state.profile_name
|
||||
)
|
||||
load_images()
|
||||
ui.notify("Global apply complete!", type='positive')
|
||||
@@ -260,6 +391,66 @@ def open_zoom_dialog(path: str, title: Optional[str] = None, show_untag: bool =
|
||||
ui.image(f"/full_res?path={path}").classes('w-full h-auto object-contain max-h-[85vh]')
|
||||
dialog.open()
|
||||
|
||||
def open_hotkey_dialog(category: str):
|
||||
"""Open dialog to set/change hotkey for a category."""
|
||||
# Find current hotkey if any
|
||||
current_hotkey = None
|
||||
for hk, cat in state.category_hotkeys.items():
|
||||
if cat == category:
|
||||
current_hotkey = hk
|
||||
break
|
||||
|
||||
with ui.dialog() as dialog, ui.card().classes('p-4 bg-gray-800'):
|
||||
ui.label(f'Set Hotkey for "{category}"').classes('font-bold text-white mb-2')
|
||||
|
||||
ui.label('Press a letter key (A-Z) to assign as hotkey').classes('text-gray-400 text-sm mb-4')
|
||||
|
||||
if current_hotkey:
|
||||
ui.label(f'Current: {current_hotkey.upper()}').classes('text-blue-400 mb-2')
|
||||
|
||||
hotkey_input = ui.input(
|
||||
placeholder='Type a letter...',
|
||||
value=current_hotkey or ''
|
||||
).props('dark outlined dense autofocus').classes('w-full')
|
||||
|
||||
def save_hotkey():
|
||||
key = hotkey_input.value.lower().strip()
|
||||
if key and len(key) == 1 and key.isalpha():
|
||||
# Remove old hotkey for this category
|
||||
to_remove = [hk for hk, c in state.category_hotkeys.items() if c == category]
|
||||
for hk in to_remove:
|
||||
del state.category_hotkeys[hk]
|
||||
|
||||
# Remove if another category had this hotkey
|
||||
if key in state.category_hotkeys:
|
||||
del state.category_hotkeys[key]
|
||||
|
||||
# Set new hotkey
|
||||
state.category_hotkeys[key] = category
|
||||
ui.notify(f'Hotkey "{key.upper()}" set for {category}', type='positive')
|
||||
dialog.close()
|
||||
render_sidebar()
|
||||
elif key == '':
|
||||
# Clear hotkey
|
||||
to_remove = [hk for hk, c in state.category_hotkeys.items() if c == category]
|
||||
for hk in to_remove:
|
||||
del state.category_hotkeys[hk]
|
||||
ui.notify(f'Hotkey cleared for {category}', type='info')
|
||||
dialog.close()
|
||||
render_sidebar()
|
||||
else:
|
||||
ui.notify('Please enter a single letter (A-Z)', type='warning')
|
||||
|
||||
with ui.row().classes('w-full justify-end gap-2 mt-4'):
|
||||
ui.button('Clear', on_click=lambda: (
|
||||
hotkey_input.set_value(''),
|
||||
save_hotkey()
|
||||
)).props('flat color=grey')
|
||||
ui.button('Cancel', on_click=dialog.close).props('flat')
|
||||
ui.button('Save', on_click=save_hotkey).props('color=green')
|
||||
|
||||
dialog.open()
|
||||
|
||||
def render_sidebar():
|
||||
"""Render category management sidebar."""
|
||||
state.sidebar_container.clear()
|
||||
@@ -295,20 +486,46 @@ def render_sidebar():
|
||||
.props(f'color={color} size=sm flat') \
|
||||
.classes('w-full border border-gray-800')
|
||||
|
||||
# Category selector
|
||||
# Category Manager (expanded)
|
||||
ui.label("📂 Categories").classes('text-sm font-bold text-gray-400 mt-2')
|
||||
|
||||
categories = state.get_categories()
|
||||
|
||||
def on_category_change(e):
|
||||
state.active_cat = e.value
|
||||
refresh_staged_info()
|
||||
render_sidebar()
|
||||
|
||||
ui.select(
|
||||
categories,
|
||||
value=state.active_cat,
|
||||
label="Active Category",
|
||||
on_change=on_category_change
|
||||
).classes('w-full').props('dark outlined')
|
||||
# Category list with hotkey buttons
|
||||
for cat in categories:
|
||||
is_active = cat == state.active_cat
|
||||
hotkey = None
|
||||
# Find if this category has a hotkey
|
||||
for hk, cat_name in state.category_hotkeys.items():
|
||||
if cat_name == cat:
|
||||
hotkey = hk
|
||||
break
|
||||
|
||||
with ui.row().classes('w-full items-center no-wrap gap-1'):
|
||||
# Category button
|
||||
ui.button(
|
||||
cat,
|
||||
on_click=lambda c=cat: (
|
||||
setattr(state, 'active_cat', c),
|
||||
refresh_staged_info(),
|
||||
render_sidebar()
|
||||
)
|
||||
).props(f'{"" if is_active else "flat"} color={"green" if is_active else "grey"} dense') \
|
||||
.classes('flex-grow text-left')
|
||||
|
||||
# Hotkey badge/button
|
||||
def make_hotkey_handler(category):
|
||||
def handler():
|
||||
open_hotkey_dialog(category)
|
||||
return handler
|
||||
|
||||
if hotkey:
|
||||
ui.button(hotkey.upper(), on_click=make_hotkey_handler(cat)) \
|
||||
.props('flat dense color=blue size=sm').classes('w-8')
|
||||
else:
|
||||
ui.button('+', on_click=make_hotkey_handler(cat)) \
|
||||
.props('flat dense color=grey size=sm').classes('w-8') \
|
||||
.tooltip('Set hotkey')
|
||||
|
||||
# Add new category
|
||||
with ui.row().classes('w-full items-center no-wrap mt-2'):
|
||||
@@ -317,7 +534,7 @@ def render_sidebar():
|
||||
|
||||
def add_category():
|
||||
if new_cat_input.value:
|
||||
SorterEngine.add_category(new_cat_input.value)
|
||||
SorterEngine.add_category(new_cat_input.value, state.profile_name)
|
||||
state.active_cat = new_cat_input.value
|
||||
refresh_staged_info()
|
||||
render_sidebar()
|
||||
@@ -327,7 +544,11 @@ def render_sidebar():
|
||||
# Delete category
|
||||
with ui.expansion('Danger Zone', icon='warning').classes('w-full text-red-400 mt-2'):
|
||||
def delete_category():
|
||||
SorterEngine.delete_category(state.active_cat)
|
||||
# Also remove any hotkey for this category
|
||||
to_remove = [hk for hk, c in state.category_hotkeys.items() if c == state.active_cat]
|
||||
for hk in to_remove:
|
||||
del state.category_hotkeys[hk]
|
||||
SorterEngine.delete_category(state.active_cat, state.profile_name)
|
||||
refresh_staged_info()
|
||||
render_sidebar()
|
||||
|
||||
@@ -346,6 +567,26 @@ def render_sidebar():
|
||||
render_sidebar()
|
||||
|
||||
ui.button('🔄', on_click=reset_index).props('flat color=white')
|
||||
|
||||
# Keyboard shortcuts help
|
||||
ui.separator().classes('my-4 bg-gray-700')
|
||||
with ui.expansion('⌨️ Keyboard Shortcuts', icon='keyboard').classes('w-full text-gray-400'):
|
||||
shortcuts = [
|
||||
("1-9", "Tag hovered image with index"),
|
||||
("0", "Tag with next index"),
|
||||
("U", "Untag hovered image*"),
|
||||
("F", "Cycle filter*"),
|
||||
("Ctrl+S", "Save tags"),
|
||||
("Ctrl+Z", "Undo last action"),
|
||||
("A-Z", "Switch category (set above)"),
|
||||
("← →", "Previous/Next page"),
|
||||
("Dbl-click", "Tag/Untag image"),
|
||||
]
|
||||
for key, desc in shortcuts:
|
||||
with ui.row().classes('w-full justify-between text-xs'):
|
||||
ui.label(key).classes('text-green-400 font-mono')
|
||||
ui.label(desc).classes('text-gray-500')
|
||||
ui.label("*unless assigned to category").classes('text-gray-600 text-xs mt-1')
|
||||
|
||||
def render_gallery():
|
||||
"""Render image gallery grid."""
|
||||
@@ -362,7 +603,13 @@ def render_image_card(img_path: str):
|
||||
is_staged = img_path in state.staged_data
|
||||
thumb_size = 800
|
||||
|
||||
with ui.card().classes('p-2 bg-gray-900 border border-gray-700 no-shadow'):
|
||||
card = ui.card().classes('p-2 bg-gray-900 border border-gray-700 no-shadow hover:border-green-500 transition-colors')
|
||||
|
||||
with card:
|
||||
# Track hover for keyboard shortcuts
|
||||
card.on('mouseenter', lambda p=img_path: setattr(state, 'hovered_image', p))
|
||||
card.on('mouseleave', lambda: setattr(state, 'hovered_image', None))
|
||||
|
||||
# Header with filename and actions
|
||||
with ui.row().classes('w-full justify-between no-wrap mb-1'):
|
||||
ui.label(os.path.basename(img_path)[:15]).classes('text-xs text-gray-400 truncate')
|
||||
@@ -376,11 +623,17 @@ def render_image_card(img_path: str):
|
||||
on_click=lambda p=img_path: action_delete(p)
|
||||
).props('flat size=sm dense color=red')
|
||||
|
||||
# Thumbnail
|
||||
ui.image(f"/thumbnail?path={img_path}&size={thumb_size}&q={state.preview_quality}") \
|
||||
.classes('w-full h-64 bg-black rounded') \
|
||||
# Thumbnail with double-click to tag
|
||||
img = ui.image(f"/thumbnail?path={img_path}&size={thumb_size}&q={state.preview_quality}") \
|
||||
.classes('w-full h-64 bg-black rounded cursor-pointer') \
|
||||
.props('fit=contain no-spinner')
|
||||
|
||||
# Double-click to tag (if not already tagged)
|
||||
if not is_staged:
|
||||
img.on('dblclick', lambda p=img_path: action_tag(p))
|
||||
else:
|
||||
img.on('dblclick', lambda p=img_path: action_untag(p))
|
||||
|
||||
# Tagging UI
|
||||
if is_staged:
|
||||
info = state.staged_data[img_path]
|
||||
@@ -404,10 +657,43 @@ def render_pagination():
|
||||
"""Render pagination controls."""
|
||||
state.pagination_container.clear()
|
||||
|
||||
if state.total_pages <= 1:
|
||||
return
|
||||
stats = state.get_stats()
|
||||
|
||||
with state.pagination_container:
|
||||
# Stats bar
|
||||
with ui.row().classes('w-full justify-center items-center gap-4 mb-2'):
|
||||
ui.label(f"📁 {stats['total']} images").classes('text-gray-400')
|
||||
ui.label(f"🏷️ {stats['tagged']} tagged").classes('text-green-400')
|
||||
ui.label(f"⬜ {stats['untagged']} untagged").classes('text-gray-500')
|
||||
|
||||
# Filter toggle
|
||||
filter_colors = {"all": "grey", "tagged": "green", "untagged": "orange"}
|
||||
filter_icons = {"all": "filter_list", "tagged": "label", "untagged": "label_off"}
|
||||
ui.button(
|
||||
f"Filter: {state.filter_mode}",
|
||||
icon=filter_icons[state.filter_mode],
|
||||
on_click=lambda: (
|
||||
setattr(state, 'filter_mode', {"all": "untagged", "untagged": "tagged", "tagged": "all"}[state.filter_mode]),
|
||||
setattr(state, 'page', 0),
|
||||
refresh_ui()
|
||||
)
|
||||
).props(f'flat color={filter_colors[state.filter_mode]}').classes('ml-4')
|
||||
|
||||
# Save button
|
||||
ui.button(
|
||||
icon='save',
|
||||
on_click=action_save_tags
|
||||
).props('flat color=blue').tooltip('Save tags (Ctrl+S)')
|
||||
|
||||
# Undo button
|
||||
ui.button(
|
||||
icon='undo',
|
||||
on_click=action_undo
|
||||
).props('flat color=white').tooltip('Undo (Ctrl+Z)')
|
||||
|
||||
if state.total_pages <= 1:
|
||||
return
|
||||
|
||||
# Page slider
|
||||
ui.slider(
|
||||
min=0,
|
||||
@@ -416,6 +702,9 @@ def render_pagination():
|
||||
on_change=lambda e: set_page(int(e.value))
|
||||
).classes('w-1/2 mb-2').props('color=green')
|
||||
|
||||
# Page info
|
||||
ui.label(f"Page {state.page + 1} / {state.total_pages}").classes('text-gray-400 text-sm mb-2')
|
||||
|
||||
# Page buttons
|
||||
with ui.row().classes('items-center gap-2'):
|
||||
# Previous button
|
||||
@@ -450,14 +739,97 @@ def refresh_ui():
|
||||
render_gallery()
|
||||
|
||||
def handle_keyboard(e):
|
||||
"""Handle keyboard navigation."""
|
||||
"""Handle keyboard navigation and shortcuts (fallback)."""
|
||||
if not e.action.keydown:
|
||||
return
|
||||
|
||||
if e.key.arrow_left and state.page > 0:
|
||||
key = e.key.name if hasattr(e.key, 'name') else str(e.key)
|
||||
ctrl = e.modifiers.ctrl if hasattr(e.modifiers, 'ctrl') else False
|
||||
key_lower = key.lower() if isinstance(key, str) else key
|
||||
|
||||
# Navigation - arrow keys
|
||||
if key == 'ArrowLeft' and state.page > 0:
|
||||
set_page(state.page - 1)
|
||||
elif e.key.arrow_right and state.page < state.total_pages - 1:
|
||||
elif key == 'ArrowRight' and state.page < state.total_pages - 1:
|
||||
set_page(state.page + 1)
|
||||
|
||||
# Undo (Ctrl+Z)
|
||||
elif key_lower == 'z' and ctrl:
|
||||
action_undo()
|
||||
|
||||
# Save (Ctrl+S)
|
||||
elif key_lower == 's' and ctrl:
|
||||
action_save_tags()
|
||||
|
||||
# Custom category hotkeys (single letters A-Z, not ctrl)
|
||||
elif not ctrl and len(key) == 1 and key_lower.isalpha() and key_lower in state.category_hotkeys:
|
||||
state.active_cat = state.category_hotkeys[key_lower]
|
||||
refresh_staged_info()
|
||||
refresh_ui()
|
||||
ui.notify(f"Category: {state.active_cat}", type='info')
|
||||
|
||||
# Number keys 1-9 to tag hovered image
|
||||
elif key in '123456789' and not ctrl:
|
||||
if state.hovered_image and state.hovered_image not in state.staged_data:
|
||||
action_tag(state.hovered_image, int(key))
|
||||
|
||||
# 0 key to tag with next_index
|
||||
elif key == '0' and not ctrl and state.hovered_image and state.hovered_image not in state.staged_data:
|
||||
action_tag(state.hovered_image)
|
||||
|
||||
# U to untag hovered image (only if not assigned as category hotkey)
|
||||
elif key_lower == 'u' and not ctrl and 'u' not in state.category_hotkeys:
|
||||
if state.hovered_image and state.hovered_image in state.staged_data:
|
||||
action_untag(state.hovered_image)
|
||||
|
||||
# F to cycle filter modes (only if not assigned as category hotkey)
|
||||
elif key_lower == 'f' and not ctrl and 'f' not in state.category_hotkeys:
|
||||
modes = ["all", "untagged", "tagged"]
|
||||
current_idx = modes.index(state.filter_mode)
|
||||
state.filter_mode = modes[(current_idx + 1) % 3]
|
||||
state.page = 0 # Reset to first page when changing filter
|
||||
refresh_ui()
|
||||
ui.notify(f"Filter: {state.filter_mode}", type='info')
|
||||
|
||||
def process_key(key: str, ctrl: bool):
|
||||
"""Process keyboard input from JS event."""
|
||||
# Navigation
|
||||
if key == 'arrowleft' and state.page > 0:
|
||||
set_page(state.page - 1)
|
||||
elif key == 'arrowright' and state.page < state.total_pages - 1:
|
||||
set_page(state.page + 1)
|
||||
# Undo
|
||||
elif key == 'z' and ctrl:
|
||||
action_undo()
|
||||
# Save
|
||||
elif key == 's' and ctrl:
|
||||
action_save_tags()
|
||||
# Custom category hotkeys
|
||||
elif not ctrl and len(key) == 1 and key.isalpha() and key in state.category_hotkeys:
|
||||
state.active_cat = state.category_hotkeys[key]
|
||||
refresh_staged_info()
|
||||
refresh_ui()
|
||||
ui.notify(f"Category: {state.active_cat}", type='info')
|
||||
# Tag with number
|
||||
elif key in '123456789' and not ctrl:
|
||||
if state.hovered_image and state.hovered_image not in state.staged_data:
|
||||
action_tag(state.hovered_image, int(key))
|
||||
# Tag with next index
|
||||
elif key == '0' and not ctrl:
|
||||
if state.hovered_image and state.hovered_image not in state.staged_data:
|
||||
action_tag(state.hovered_image)
|
||||
# Untag (only if 'u' not assigned to category)
|
||||
elif key == 'u' and not ctrl and 'u' not in state.category_hotkeys:
|
||||
if state.hovered_image and state.hovered_image in state.staged_data:
|
||||
action_untag(state.hovered_image)
|
||||
# Filter (only if 'f' not assigned to category)
|
||||
elif key == 'f' and not ctrl and 'f' not in state.category_hotkeys:
|
||||
modes = ["all", "untagged", "tagged"]
|
||||
current_idx = modes.index(state.filter_mode)
|
||||
state.filter_mode = modes[(current_idx + 1) % 3]
|
||||
state.page = 0
|
||||
refresh_ui()
|
||||
ui.notify(f"Filter: {state.filter_mode}", type='info')
|
||||
|
||||
# ==========================================
|
||||
# MAIN LAYOUT
|
||||
@@ -469,22 +841,79 @@ def build_header():
|
||||
with ui.row().classes('w-full items-center gap-4 no-wrap px-4'):
|
||||
ui.label('🖼️ NiceSorter').classes('text-xl font-bold shrink-0 text-green-400')
|
||||
|
||||
# Profile selector
|
||||
profile_names = list(state.profiles.keys())
|
||||
|
||||
# Profile selector with add/delete
|
||||
def change_profile(e):
|
||||
# Auto-save before switching profile
|
||||
if state.all_images and state.staged_data:
|
||||
SorterEngine.save_folder_tags(state.source_dir, state.profile_name)
|
||||
|
||||
state.profile_name = e.value
|
||||
state.load_active_profile()
|
||||
load_images()
|
||||
|
||||
# Reset to first available category for new profile
|
||||
cats = state.get_categories()
|
||||
state.active_cat = cats[0] if cats else "control"
|
||||
|
||||
# Clear staging and hotkeys for new profile
|
||||
SorterEngine.clear_staging_area()
|
||||
state.category_hotkeys = {} # Reset hotkeys when switching profile
|
||||
state.all_images = []
|
||||
state.staged_data = {}
|
||||
|
||||
refresh_staged_info()
|
||||
refresh_ui()
|
||||
|
||||
ui.select(profile_names, value=state.profile_name, on_change=change_profile) \
|
||||
.props('dark dense options-dense borderless').classes('w-32')
|
||||
profile_select = ui.select(
|
||||
list(state.profiles.keys()),
|
||||
value=state.profile_name,
|
||||
on_change=change_profile
|
||||
).props('dark dense options-dense borderless').classes('w-32')
|
||||
|
||||
def add_profile():
|
||||
with ui.dialog() as dialog, ui.card().classes('p-4'):
|
||||
ui.label('New Profile Name').classes('font-bold')
|
||||
name_input = ui.input(placeholder='Profile name').props('autofocus')
|
||||
|
||||
def do_create():
|
||||
name = name_input.value
|
||||
if name and name not in state.profiles:
|
||||
state.profiles[name] = {"tab5_source": "/storage", "tab5_out": "/storage"}
|
||||
SorterEngine.save_tab_paths(name, t5_s="/storage", t5_o="/storage")
|
||||
state.profile_name = name
|
||||
state.load_active_profile()
|
||||
dialog.close()
|
||||
ui.notify(f"Profile '{name}' created", type='positive')
|
||||
# Rebuild header to update profile list
|
||||
ui.navigate.reload()
|
||||
elif name in state.profiles:
|
||||
ui.notify("Profile already exists", type='warning')
|
||||
|
||||
with ui.row().classes('w-full justify-end gap-2 mt-2'):
|
||||
ui.button('Cancel', on_click=dialog.close).props('flat')
|
||||
ui.button('Create', on_click=do_create).props('color=green')
|
||||
dialog.open()
|
||||
|
||||
def delete_profile():
|
||||
if len(state.profiles) <= 1:
|
||||
ui.notify("Cannot delete the last profile", type='warning')
|
||||
return
|
||||
deleted_name = state.profile_name
|
||||
del state.profiles[state.profile_name]
|
||||
state.profile_name = list(state.profiles.keys())[0]
|
||||
state.load_active_profile()
|
||||
ui.notify(f"Profile '{deleted_name}' deleted", type='info')
|
||||
ui.navigate.reload()
|
||||
|
||||
ui.button(icon='add', on_click=add_profile).props('flat round dense color=green').tooltip('New profile')
|
||||
ui.button(icon='delete', on_click=delete_profile).props('flat round dense color=red').tooltip('Delete profile')
|
||||
|
||||
# Source and output paths
|
||||
with ui.row().classes('flex-grow gap-2'):
|
||||
ui.input('Source').bind_value(state, 'source_dir') \
|
||||
ui.input('Input Base').bind_value(state, 'input_base') \
|
||||
.classes('flex-grow').props('dark dense outlined')
|
||||
ui.input('Output').bind_value(state, 'output_dir') \
|
||||
ui.input('Output Base').bind_value(state, 'output_base') \
|
||||
.classes('flex-grow').props('dark dense outlined')
|
||||
ui.input('Folder (optional)').bind_value(state, 'folder_name') \
|
||||
.classes('flex-grow').props('dark dense outlined')
|
||||
|
||||
ui.button(icon='save', on_click=state.save_current_profile) \
|
||||
@@ -561,7 +990,26 @@ build_header()
|
||||
build_sidebar()
|
||||
build_main_content()
|
||||
|
||||
ui.keyboard(on_key=handle_keyboard)
|
||||
# JavaScript keyboard handler for Firefox compatibility
|
||||
ui.add_body_html('''
|
||||
<script>
|
||||
document.addEventListener('keydown', function(e) {
|
||||
// Skip if typing in input
|
||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
|
||||
|
||||
const key = e.key.toLowerCase();
|
||||
const ctrl = e.ctrlKey || e.metaKey;
|
||||
|
||||
// Prevent browser defaults for our shortcuts
|
||||
if (ctrl && (key === 's' || key === 'z')) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
''')
|
||||
|
||||
# Use NiceGUI keyboard
|
||||
ui.keyboard(on_key=handle_keyboard, ignore=[])
|
||||
ui.dark_mode().enable()
|
||||
load_images()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user