added dedup tools to settings. first pass of mass tag editting to gallery view.
This commit is contained in:
@@ -6,9 +6,6 @@ from flask.cli import with_appcontext
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.engine import Engine
|
||||
import sqlite3
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
@@ -56,14 +53,6 @@ def celery_beat_command():
|
||||
'--loglevel=info'
|
||||
])
|
||||
|
||||
@event.listens_for(Engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection, connection_record):
|
||||
# Only apply to SQLite connections
|
||||
if isinstance(dbapi_connection, sqlite3.Connection):
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys = ON")
|
||||
cursor.close()
|
||||
|
||||
def create_app(config_class='config.Config'):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config_class)
|
||||
|
||||
+264
@@ -1316,3 +1316,267 @@ def list_import_batches():
|
||||
for b in batches
|
||||
]
|
||||
})
|
||||
|
||||
|
||||
# =============================================
|
||||
# Duplicate Detection API
|
||||
# =============================================
|
||||
|
||||
@main.route('/api/duplicates/scan', methods=['POST'])
|
||||
def scan_duplicates():
|
||||
"""
|
||||
Scan for duplicate images using perceptual hash comparison.
|
||||
Returns groups of similar images within the specified hamming distance.
|
||||
"""
|
||||
import imagehash
|
||||
|
||||
threshold = request.form.get('threshold', 10, type=int)
|
||||
limit = request.form.get('limit', 100, type=int)
|
||||
|
||||
# Get all images with perceptual hashes
|
||||
images = ImageRecord.query.filter(
|
||||
ImageRecord.perceptual_hash.isnot(None)
|
||||
).all()
|
||||
|
||||
if not images:
|
||||
return jsonify({'ok': True, 'groups': [], 'message': 'No images with perceptual hashes found'})
|
||||
|
||||
# Build hash lookup
|
||||
hash_data = []
|
||||
for img in images:
|
||||
try:
|
||||
phash = imagehash.hex_to_hash(img.perceptual_hash)
|
||||
hash_data.append({
|
||||
'id': img.id,
|
||||
'hash': phash,
|
||||
'width': img.width,
|
||||
'height': img.height,
|
||||
'filename': img.filename,
|
||||
'filepath': img.filepath,
|
||||
'thumb_path': img.thumb_path,
|
||||
'file_size': img.file_size
|
||||
})
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Find duplicate groups
|
||||
duplicate_groups = []
|
||||
processed = set()
|
||||
|
||||
for i, img1 in enumerate(hash_data):
|
||||
if img1['id'] in processed:
|
||||
continue
|
||||
|
||||
group = [img1]
|
||||
|
||||
for j, img2 in enumerate(hash_data[i+1:], start=i+1):
|
||||
if img2['id'] in processed:
|
||||
continue
|
||||
|
||||
distance = img1['hash'] - img2['hash']
|
||||
if distance <= threshold:
|
||||
group.append(img2)
|
||||
processed.add(img2['id'])
|
||||
|
||||
if len(group) > 1:
|
||||
processed.add(img1['id'])
|
||||
# Sort group by resolution (largest first)
|
||||
group.sort(key=lambda x: x['width'] * x['height'], reverse=True)
|
||||
duplicate_groups.append(group)
|
||||
|
||||
if len(duplicate_groups) >= limit:
|
||||
break
|
||||
|
||||
# Format response
|
||||
result_groups = []
|
||||
for group in duplicate_groups:
|
||||
result_groups.append([
|
||||
{
|
||||
'id': img['id'],
|
||||
'filename': img['filename'],
|
||||
'width': img['width'],
|
||||
'height': img['height'],
|
||||
'file_size': img['file_size'],
|
||||
'thumb_url': url_for('main.serve_image',
|
||||
filename=(img['thumb_path'] or img['filepath']).replace('/images/', ''))
|
||||
}
|
||||
for img in group
|
||||
])
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'groups': result_groups,
|
||||
'total_groups': len(result_groups),
|
||||
'threshold': threshold
|
||||
})
|
||||
|
||||
|
||||
@main.route('/api/duplicates/delete', methods=['POST'])
|
||||
def delete_duplicates():
|
||||
"""
|
||||
Delete specified duplicate images.
|
||||
Expects JSON body with 'image_ids' array.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
image_ids = data.get('image_ids', [])
|
||||
|
||||
if not image_ids:
|
||||
return jsonify({'ok': False, 'error': 'No image IDs provided'})
|
||||
|
||||
deleted_count = 0
|
||||
errors = []
|
||||
|
||||
for image_id in image_ids:
|
||||
try:
|
||||
image = ImageRecord.query.get(image_id)
|
||||
if not image:
|
||||
errors.append(f"Image {image_id} not found")
|
||||
continue
|
||||
|
||||
# Delete physical files
|
||||
if image.filepath and os.path.exists(image.filepath):
|
||||
os.remove(image.filepath)
|
||||
if image.thumb_path and os.path.exists(image.thumb_path):
|
||||
os.remove(image.thumb_path)
|
||||
|
||||
# Delete database record
|
||||
db.session.delete(image)
|
||||
deleted_count += 1
|
||||
|
||||
except Exception as e:
|
||||
errors.append(f"Error deleting {image_id}: {str(e)}")
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'deleted_count': deleted_count,
|
||||
'errors': errors if errors else None
|
||||
})
|
||||
|
||||
|
||||
# =============================================
|
||||
# Bulk Tag Operations API
|
||||
# =============================================
|
||||
|
||||
@main.route('/api/images/common-tags', methods=['POST'])
|
||||
def get_common_tags():
|
||||
"""
|
||||
Get tags that are common to all specified images.
|
||||
Expects JSON body with 'image_ids' array.
|
||||
Returns tags that appear on EVERY selected image.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
image_ids = data.get('image_ids', [])
|
||||
|
||||
if not image_ids:
|
||||
return jsonify({'ok': True, 'tags': []})
|
||||
|
||||
# Find tags that appear on ALL selected images
|
||||
# We use a subquery approach: count occurrences of each tag and filter
|
||||
# for tags where the count equals the number of images
|
||||
num_images = len(image_ids)
|
||||
|
||||
# Query: get tags where the count of associated images (from our list) equals num_images
|
||||
common_tags = db.session.query(Tag).join(image_tags).filter(
|
||||
image_tags.c.image_id.in_(image_ids)
|
||||
).group_by(Tag.id).having(
|
||||
func.count(image_tags.c.image_id) == num_images
|
||||
).order_by(Tag.name).all()
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'tags': [
|
||||
{'id': t.id, 'name': t.name, 'kind': t.kind}
|
||||
for t in common_tags
|
||||
]
|
||||
})
|
||||
|
||||
|
||||
@main.route('/api/images/bulk-add-tag', methods=['POST'])
|
||||
def bulk_add_tag():
|
||||
"""
|
||||
Add a tag to multiple images at once.
|
||||
Expects JSON body with 'image_ids' array and 'tag_name' string.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
image_ids = data.get('image_ids', [])
|
||||
tag_name = (data.get('tag_name') or '').strip()
|
||||
|
||||
if not image_ids:
|
||||
return jsonify({'ok': False, 'error': 'No image IDs provided'}), 400
|
||||
|
||||
if not tag_name:
|
||||
return jsonify({'ok': False, 'error': 'No tag name provided'}), 400
|
||||
|
||||
# Determine tag kind from name
|
||||
if ':' in tag_name:
|
||||
kind = tag_name.split(':', 1)[0]
|
||||
else:
|
||||
kind = 'user'
|
||||
|
||||
# Get or create the tag
|
||||
tag = Tag.query.filter_by(name=tag_name).first()
|
||||
if not tag:
|
||||
tag = Tag(name=tag_name, kind=kind)
|
||||
db.session.add(tag)
|
||||
db.session.flush()
|
||||
|
||||
# Get images that don't already have this tag
|
||||
images = ImageRecord.query.filter(
|
||||
ImageRecord.id.in_(image_ids)
|
||||
).all()
|
||||
|
||||
added_count = 0
|
||||
for img in images:
|
||||
if tag not in img.tags:
|
||||
img.tags.append(tag)
|
||||
added_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'added_count': added_count,
|
||||
'tag': {'id': tag.id, 'name': tag.name, 'kind': tag.kind}
|
||||
})
|
||||
|
||||
|
||||
@main.route('/api/images/bulk-remove-tag', methods=['POST'])
|
||||
def bulk_remove_tag():
|
||||
"""
|
||||
Remove a tag from multiple images at once.
|
||||
Expects JSON body with 'image_ids' array and 'tag_name' string.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
image_ids = data.get('image_ids', [])
|
||||
tag_name = (data.get('tag_name') or '').strip()
|
||||
|
||||
if not image_ids:
|
||||
return jsonify({'ok': False, 'error': 'No image IDs provided'}), 400
|
||||
|
||||
if not tag_name:
|
||||
return jsonify({'ok': False, 'error': 'No tag name provided'}), 400
|
||||
|
||||
# Find the tag
|
||||
tag = Tag.query.filter_by(name=tag_name).first()
|
||||
if not tag:
|
||||
return jsonify({'ok': True, 'removed_count': 0, 'message': 'Tag not found'})
|
||||
|
||||
# Get images that have this tag
|
||||
images = ImageRecord.query.filter(
|
||||
ImageRecord.id.in_(image_ids)
|
||||
).all()
|
||||
|
||||
removed_count = 0
|
||||
for img in images:
|
||||
if tag in img.tags:
|
||||
img.tags.remove(tag)
|
||||
removed_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'removed_count': removed_count
|
||||
})
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
// /app/static/js/bulk-select.js
|
||||
// Multi-select mode controller for bulk tag operations
|
||||
// Works with gallery-infinite.js and showcase.js
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const state = {
|
||||
isSelectMode: false,
|
||||
selectedIds: new Set()
|
||||
};
|
||||
|
||||
// DOM elements (populated on init)
|
||||
const dom = {};
|
||||
|
||||
// Autocomplete state
|
||||
let autocompleteItems = [];
|
||||
let autocompleteSelectedIndex = -1;
|
||||
let autocompleteDebounce = null;
|
||||
|
||||
function init() {
|
||||
dom.selectBtn = document.getElementById('selectModeBtn');
|
||||
dom.panel = document.getElementById('bulkEditorPanel');
|
||||
dom.closeBtn = document.getElementById('closeBulkEditor');
|
||||
dom.countEl = document.getElementById('selectedCount');
|
||||
dom.clearBtn = document.getElementById('clearSelectionBtn');
|
||||
dom.addForm = document.getElementById('bulkAddTagForm');
|
||||
dom.tagInput = document.getElementById('bulkTagInput');
|
||||
dom.autocomplete = document.getElementById('bulkTagAutocomplete');
|
||||
dom.commonTags = document.getElementById('commonTagsList');
|
||||
|
||||
if (!dom.selectBtn || !dom.panel) return;
|
||||
|
||||
setupEventListeners();
|
||||
}
|
||||
|
||||
function setupEventListeners() {
|
||||
// Toggle select mode
|
||||
dom.selectBtn.addEventListener('click', toggleSelectMode);
|
||||
dom.closeBtn?.addEventListener('click', exitSelectMode);
|
||||
dom.clearBtn?.addEventListener('click', clearSelection);
|
||||
|
||||
// Image click handling (delegated) - use capture phase to intercept before modal
|
||||
document.addEventListener('click', handleImageClick, true);
|
||||
|
||||
// Bulk add tag form
|
||||
dom.addForm?.addEventListener('submit', handleBulkAddTag);
|
||||
|
||||
// Tag autocomplete
|
||||
setupAutocomplete();
|
||||
|
||||
// Listen for gallery updates (new images loaded)
|
||||
document.addEventListener('galleryUpdated', updateSelectionUI);
|
||||
document.addEventListener('showcaseUpdated', updateSelectionUI);
|
||||
|
||||
// Keyboard shortcut: Escape to exit select mode
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && state.isSelectMode) {
|
||||
// Only exit if modal is not open
|
||||
const modal = document.getElementById('imageModal');
|
||||
if (!modal || !modal.classList.contains('active')) {
|
||||
exitSelectMode();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function toggleSelectMode() {
|
||||
state.isSelectMode = !state.isSelectMode;
|
||||
document.body.classList.toggle('select-mode', state.isSelectMode);
|
||||
dom.selectBtn.textContent = state.isSelectMode ? 'Cancel' : 'Select';
|
||||
dom.selectBtn.classList.toggle('active', state.isSelectMode);
|
||||
|
||||
if (state.isSelectMode) {
|
||||
dom.panel.classList.add('active');
|
||||
updateCommonTagsDisplay();
|
||||
} else {
|
||||
dom.panel.classList.remove('active');
|
||||
clearSelection();
|
||||
}
|
||||
}
|
||||
|
||||
function exitSelectMode() {
|
||||
if (state.isSelectMode) {
|
||||
toggleSelectMode();
|
||||
}
|
||||
}
|
||||
|
||||
function handleImageClick(e) {
|
||||
if (!state.isSelectMode) return;
|
||||
|
||||
const item = e.target.closest('.img-clickable');
|
||||
if (!item) return;
|
||||
|
||||
// Don't interfere with tag chip clicks
|
||||
if (e.target.closest('.tag-chip')) return;
|
||||
|
||||
// Prevent modal from opening in select mode
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
const id = parseInt(item.dataset.id);
|
||||
if (isNaN(id)) return;
|
||||
|
||||
if (state.selectedIds.has(id)) {
|
||||
state.selectedIds.delete(id);
|
||||
item.classList.remove('selected');
|
||||
} else {
|
||||
state.selectedIds.add(id);
|
||||
item.classList.add('selected');
|
||||
}
|
||||
|
||||
updateCount();
|
||||
loadCommonTags();
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
state.selectedIds.clear();
|
||||
document.querySelectorAll('.img-clickable.selected').forEach(el => {
|
||||
el.classList.remove('selected');
|
||||
});
|
||||
updateCount();
|
||||
updateCommonTagsDisplay();
|
||||
}
|
||||
|
||||
function updateCount() {
|
||||
if (dom.countEl) {
|
||||
dom.countEl.textContent = state.selectedIds.size;
|
||||
}
|
||||
}
|
||||
|
||||
function updateSelectionUI() {
|
||||
// Re-apply selected class to any newly loaded images that are in selection
|
||||
document.querySelectorAll('.img-clickable').forEach(item => {
|
||||
const id = parseInt(item.dataset.id);
|
||||
if (state.selectedIds.has(id)) {
|
||||
item.classList.add('selected');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateCommonTagsDisplay() {
|
||||
if (state.selectedIds.size === 0) {
|
||||
if (dom.commonTags) {
|
||||
dom.commonTags.innerHTML = '<span class="text-muted">No images selected</span>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCommonTags() {
|
||||
if (state.selectedIds.size === 0) {
|
||||
updateCommonTagsDisplay();
|
||||
return;
|
||||
}
|
||||
|
||||
const ids = Array.from(state.selectedIds);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/images/common-tags', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ image_ids: ids })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.ok) {
|
||||
renderCommonTags(data.tags);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load common tags:', err);
|
||||
}
|
||||
}
|
||||
|
||||
function renderCommonTags(tags) {
|
||||
if (!dom.commonTags) return;
|
||||
|
||||
if (!tags || tags.length === 0) {
|
||||
dom.commonTags.innerHTML = '<span class="text-muted">No common tags</span>';
|
||||
return;
|
||||
}
|
||||
|
||||
dom.commonTags.innerHTML = tags.map(t => {
|
||||
const icon = getTagIcon(t.kind);
|
||||
const display = t.name.includes(':') ? t.name.split(':')[1] : t.name;
|
||||
const escapedName = escapeHtml(t.name);
|
||||
const escapedDisplay = escapeHtml(display);
|
||||
return `<span class="tag-chip removable" data-name="${escapedName}">
|
||||
${icon} ${escapedDisplay}
|
||||
<button class="x" title="Remove from all selected">×</button>
|
||||
</span>`;
|
||||
}).join('');
|
||||
|
||||
// Add remove handlers
|
||||
dom.commonTags.querySelectorAll('.tag-chip .x').forEach(btn => {
|
||||
btn.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const chip = e.target.closest('.tag-chip');
|
||||
const name = chip.dataset.name;
|
||||
chip.style.opacity = '0.5';
|
||||
await bulkRemoveTag(name);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function handleBulkAddTag(e) {
|
||||
e.preventDefault();
|
||||
const name = dom.tagInput.value.trim();
|
||||
if (!name || state.selectedIds.size === 0) return;
|
||||
|
||||
dom.tagInput.disabled = true;
|
||||
await bulkAddTag(name);
|
||||
dom.tagInput.value = '';
|
||||
dom.tagInput.disabled = false;
|
||||
dom.tagInput.focus();
|
||||
hideAutocomplete();
|
||||
}
|
||||
|
||||
async function bulkAddTag(name) {
|
||||
const ids = Array.from(state.selectedIds);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/images/bulk-add-tag', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ image_ids: ids, tag_name: name })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.ok) {
|
||||
loadCommonTags(); // Refresh common tags
|
||||
} else {
|
||||
console.error('Failed to add tag:', data.error);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to add tag:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function bulkRemoveTag(name) {
|
||||
const ids = Array.from(state.selectedIds);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/images/bulk-remove-tag', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ image_ids: ids, tag_name: name })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.ok) {
|
||||
loadCommonTags(); // Refresh common tags
|
||||
} else {
|
||||
console.error('Failed to remove tag:', data.error);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to remove tag:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Autocomplete
|
||||
// ---------------------------
|
||||
function setupAutocomplete() {
|
||||
if (!dom.tagInput || !dom.autocomplete) return;
|
||||
|
||||
// Show autocomplete on focus
|
||||
dom.tagInput.addEventListener('focus', () => {
|
||||
const val = dom.tagInput.value.trim();
|
||||
fetchAutocomplete(val);
|
||||
});
|
||||
|
||||
// Hide autocomplete on blur (with delay for click)
|
||||
dom.tagInput.addEventListener('blur', () => {
|
||||
setTimeout(hideAutocomplete, 200);
|
||||
});
|
||||
|
||||
// Search as user types
|
||||
dom.tagInput.addEventListener('input', () => {
|
||||
clearTimeout(autocompleteDebounce);
|
||||
autocompleteDebounce = setTimeout(() => {
|
||||
fetchAutocomplete(dom.tagInput.value.trim());
|
||||
}, 150);
|
||||
});
|
||||
|
||||
// Keyboard navigation
|
||||
dom.tagInput.addEventListener('keydown', (e) => {
|
||||
if (!dom.autocomplete.classList.contains('active')) return;
|
||||
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
const nextIndex = Math.min(autocompleteSelectedIndex + 1, autocompleteItems.length - 1);
|
||||
selectAutocompleteItem(nextIndex);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
const prevIndex = Math.max(autocompleteSelectedIndex - 1, 0);
|
||||
selectAutocompleteItem(prevIndex);
|
||||
} else if (e.key === 'Enter' && autocompleteSelectedIndex >= 0) {
|
||||
e.preventDefault();
|
||||
const selected = autocompleteItems[autocompleteSelectedIndex];
|
||||
if (selected) {
|
||||
dom.tagInput.value = selected.name;
|
||||
hideAutocomplete();
|
||||
// Submit the form
|
||||
dom.addForm.dispatchEvent(new Event('submit', { cancelable: true }));
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
hideAutocomplete();
|
||||
}
|
||||
});
|
||||
|
||||
// Click on autocomplete item
|
||||
dom.autocomplete.addEventListener('mousedown', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const item = e.target.closest('.tag-autocomplete-item');
|
||||
if (!item) return;
|
||||
const name = item.dataset.name;
|
||||
if (name) {
|
||||
dom.tagInput.value = name;
|
||||
hideAutocomplete();
|
||||
dom.addForm.dispatchEvent(new Event('submit', { cancelable: true }));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hideAutocomplete() {
|
||||
if (dom.autocomplete) {
|
||||
dom.autocomplete.classList.remove('active');
|
||||
dom.autocomplete.innerHTML = '';
|
||||
}
|
||||
autocompleteItems = [];
|
||||
autocompleteSelectedIndex = -1;
|
||||
}
|
||||
|
||||
function positionAutocomplete() {
|
||||
if (!dom.autocomplete || !dom.tagInput) return;
|
||||
const rect = dom.tagInput.getBoundingClientRect();
|
||||
dom.autocomplete.style.top = `${rect.bottom + 4}px`;
|
||||
dom.autocomplete.style.left = `${rect.left}px`;
|
||||
dom.autocomplete.style.width = `${rect.width}px`;
|
||||
}
|
||||
|
||||
async function fetchAutocomplete(query) {
|
||||
try {
|
||||
// Exclude system-managed tag kinds from autocomplete
|
||||
const excludeKinds = 'archive,post,source';
|
||||
const url = query
|
||||
? `/api/tags/search?q=${encodeURIComponent(query)}&limit=8&exclude_kind=${excludeKinds}`
|
||||
: `/api/tags/search?limit=8&exclude_kind=${excludeKinds}`;
|
||||
const r = await fetch(url);
|
||||
const j = await r.json();
|
||||
renderAutocomplete(j.tags || []);
|
||||
} catch {
|
||||
hideAutocomplete();
|
||||
}
|
||||
}
|
||||
|
||||
function renderAutocomplete(tags) {
|
||||
if (!dom.autocomplete) return;
|
||||
autocompleteItems = tags;
|
||||
autocompleteSelectedIndex = -1;
|
||||
|
||||
if (tags.length === 0) {
|
||||
dom.autocomplete.innerHTML = '<div class="tag-autocomplete-empty">No matching tags</div>';
|
||||
positionAutocomplete();
|
||||
dom.autocomplete.classList.add('active');
|
||||
return;
|
||||
}
|
||||
|
||||
dom.autocomplete.innerHTML = tags.map((t, i) => {
|
||||
const icon = getTagIcon(t.kind);
|
||||
const displayName = t.name.includes(':') ? t.name.split(':')[1] : t.name;
|
||||
return `<div class="tag-autocomplete-item" data-index="${i}" data-name="${escapeHtml(t.name)}">
|
||||
<span>${icon} ${escapeHtml(displayName)}</span>
|
||||
<span class="tag-kind">${t.kind || 'user'}</span>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
positionAutocomplete();
|
||||
dom.autocomplete.classList.add('active');
|
||||
}
|
||||
|
||||
function selectAutocompleteItem(index) {
|
||||
const items = dom.autocomplete?.querySelectorAll('.tag-autocomplete-item');
|
||||
if (!items) return;
|
||||
items.forEach((el, i) => {
|
||||
el.classList.toggle('selected', i === index);
|
||||
});
|
||||
autocompleteSelectedIndex = index;
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Helpers
|
||||
// ---------------------------
|
||||
function getTagIcon(kind) {
|
||||
const icons = {
|
||||
artist: '🎨',
|
||||
archive: '🗜️',
|
||||
character: '👤',
|
||||
series: '📺',
|
||||
rating: '⚠️',
|
||||
source: '🌐',
|
||||
post: '📌'
|
||||
};
|
||||
return icons[kind] || '#';
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// Initialize on DOM ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -1507,3 +1507,229 @@ select.form-input optgroup {
|
||||
top: 45px;
|
||||
}
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
Gallery Header Layout
|
||||
------------------------------------------------------------------------------*/
|
||||
.gallery-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.gallery-header-left {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.gallery-header-left h1 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.gallery-header-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
Bulk Select Mode
|
||||
------------------------------------------------------------------------------*/
|
||||
/* Select mode body state */
|
||||
body.select-mode .img-clickable {
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Selection checkbox overlay */
|
||||
body.select-mode .img-clickable::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 2px solid rgba(255, 255, 255, 0.8);
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
z-index: 10;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
body.select-mode .img-clickable.selected::before {
|
||||
background: var(--btn-primary);
|
||||
border-color: var(--btn-primary);
|
||||
}
|
||||
|
||||
body.select-mode .img-clickable.selected::after {
|
||||
content: '\2713';
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
color: white;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 11;
|
||||
}
|
||||
|
||||
/* Selected image highlight */
|
||||
body.select-mode .img-clickable.selected {
|
||||
outline: 3px solid var(--btn-primary);
|
||||
outline-offset: -3px;
|
||||
}
|
||||
|
||||
/* Prevent hover effects in select mode */
|
||||
body.select-mode .gallery-item:hover {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
/* Select button active state */
|
||||
#selectModeBtn.active {
|
||||
background: var(--btn-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
Bulk Editor Panel (slide-in sidebar)
|
||||
------------------------------------------------------------------------------*/
|
||||
.bulk-editor-panel {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 320px;
|
||||
height: 100vh;
|
||||
background: var(--panel);
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.1);
|
||||
z-index: 1100;
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: var(--shadow-3);
|
||||
}
|
||||
|
||||
.bulk-editor-panel.active {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.bulk-editor-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.bulk-editor-header h3 {
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.bulk-editor-stats {
|
||||
padding: 0.75rem 1rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.bulk-editor-section {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.bulk-editor-section h4 {
|
||||
margin: 0 0 0.75rem 0;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.bulk-editor-section .form-help {
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.bulk-editor-section .tags {
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.bulk-editor-actions {
|
||||
padding: 1rem;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
/* Removable tag chips in bulk editor */
|
||||
.bulk-editor-section .tag-chip.removable {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 8px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
color: var(--text);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.bulk-editor-section .tag-chip.removable:hover {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.bulk-editor-section .tag-chip .x {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
margin-left: 2px;
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.bulk-editor-section .tag-chip .x:hover {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
/* Text muted helper */
|
||||
.text-muted {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* Mobile: full-width panel from bottom */
|
||||
@media (max-width: 640px) {
|
||||
.bulk-editor-panel {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-height: 60vh;
|
||||
top: auto;
|
||||
bottom: 0;
|
||||
transform: translateY(100%);
|
||||
border-left: none;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 16px 16px 0 0;
|
||||
}
|
||||
|
||||
.bulk-editor-panel.active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.gallery-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.gallery-header-actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,13 +15,18 @@
|
||||
<!-- Main Gallery Content -->
|
||||
<main class="gallery-main">
|
||||
<div class="gallery-header">
|
||||
<h1>Gallery</h1>
|
||||
{% if active_tag %}
|
||||
<div class="active-filter">
|
||||
Filtered by: <span class="filter-tag">{{ active_tag }}</span>
|
||||
<a href="{{ url_for('main.gallery') }}" class="clear-filter" title="Clear filter">×</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="gallery-header-left">
|
||||
<h1>Gallery</h1>
|
||||
{% if active_tag %}
|
||||
<div class="active-filter">
|
||||
Filtered by: <span class="filter-tag">{{ active_tag }}</span>
|
||||
<a href="{{ url_for('main.gallery') }}" class="clear-filter" title="Clear filter">×</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="gallery-header-actions">
|
||||
<button id="selectModeBtn" class="btn secondary-btn">Select</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Gallery Grid with Date Sections -->
|
||||
@@ -61,6 +66,35 @@
|
||||
<!-- Modal -->
|
||||
{% include '_gallery_modal.html' %}
|
||||
|
||||
<!-- Bulk Editor Panel -->
|
||||
<aside id="bulkEditorPanel" class="bulk-editor-panel">
|
||||
<div class="bulk-editor-header">
|
||||
<h3>Bulk Edit</h3>
|
||||
<button id="closeBulkEditor" class="modal-close-btn">×</button>
|
||||
</div>
|
||||
<div class="bulk-editor-stats">
|
||||
<span id="selectedCount">0</span> images selected
|
||||
</div>
|
||||
<div class="bulk-editor-section">
|
||||
<h4>Add Tags</h4>
|
||||
<form id="bulkAddTagForm" class="tag-form" autocomplete="off">
|
||||
<div class="tag-form-wrapper">
|
||||
<input type="text" id="bulkTagInput" name="name" placeholder="Add tag..." autocomplete="off">
|
||||
<div id="bulkTagAutocomplete" class="tag-autocomplete"></div>
|
||||
</div>
|
||||
<button type="submit">Add</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="bulk-editor-section">
|
||||
<h4>Remove Tags</h4>
|
||||
<p class="form-help">Common tags across selected images:</p>
|
||||
<div id="commonTagsList" class="tags"></div>
|
||||
</div>
|
||||
<div class="bulk-editor-actions">
|
||||
<button id="clearSelectionBtn" class="btn secondary-btn">Clear Selection</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Pass initial state to JS -->
|
||||
<script>
|
||||
window.galleryState = {
|
||||
@@ -72,4 +106,5 @@
|
||||
|
||||
<script src="{{ url_for('static', filename='js/gallery-infinite.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/modal-pagination.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/bulk-select.js') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
+312
-1
@@ -206,6 +206,46 @@
|
||||
</div>
|
||||
</div><!-- end settings-grid -->
|
||||
|
||||
<!-- Duplicate Detection (Full Width) -->
|
||||
<div class="settings-container" style="max-width: 1200px; margin: 2rem auto;">
|
||||
<div class="settings-section">
|
||||
<h2>Duplicate Detection</h2>
|
||||
<p class="settings-description">Scan for visually similar images using perceptual hash comparison. The first image in each group has the highest resolution and will be kept.</p>
|
||||
|
||||
<div class="form-card" style="margin-bottom: 1rem;">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Hamming Distance Threshold</label>
|
||||
<select id="dupThreshold" class="form-input">
|
||||
<option value="5">Strict (5) - Nearly identical</option>
|
||||
<option value="10" selected>Normal (10) - Minor variations</option>
|
||||
<option value="15">Loose (15) - Similar images</option>
|
||||
<option value="20">Very Loose (20) - Broadly similar</option>
|
||||
</select>
|
||||
<p class="form-help">Lower values find only very similar images. Higher values find more potential duplicates but may include false positives.</p>
|
||||
</div>
|
||||
|
||||
<button type="button" id="scanDuplicatesBtn" class="btn primary-btn" style="width: 100%;">Scan for Duplicates</button>
|
||||
</div>
|
||||
|
||||
<div id="dupResults" style="display: none;">
|
||||
<div class="import-stats" style="margin-bottom: 1rem;">
|
||||
<h3>Scan Results</h3>
|
||||
<p>Found <strong id="dupGroupCount">0</strong> group(s) of potential duplicates.</p>
|
||||
</div>
|
||||
|
||||
<div id="dupGroups"></div>
|
||||
|
||||
<div id="dupActions" style="margin-top: 1rem; display: none;">
|
||||
<p class="form-help" style="margin-bottom: 0.75rem;">
|
||||
Selected for deletion: <strong id="dupSelectedCount">0</strong> image(s)
|
||||
<span style="color: var(--text-muted);">(The highest resolution image in each group is protected)</span>
|
||||
</p>
|
||||
<button type="button" id="deleteDuplicatesBtn" class="btn danger-btn" disabled>Delete Selected Duplicates</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Import Queue Status (Full Width) -->
|
||||
<div class="settings-container" style="max-width: 1200px; margin: 2rem auto;">
|
||||
<div class="settings-section">
|
||||
@@ -256,7 +296,6 @@
|
||||
<button id="retryFailedBtn" class="btn warning-btn">Retry Failed Tasks</button>
|
||||
<button id="clearCompletedBtn" class="btn secondary-btn">Clear Completed</button>
|
||||
<button id="regenMissingThumbsBtn" class="btn secondary-btn">Regenerate Missing Thumbnails</button>
|
||||
<a href="/flower" target="_blank" class="btn secondary-btn" style="text-decoration: none;">Open Flower Dashboard</a>
|
||||
</div>
|
||||
|
||||
<div id="celeryWorkerInfo" style="margin-top: 1rem;">
|
||||
@@ -492,6 +531,83 @@
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
/* Duplicate detection styles */
|
||||
.dup-group {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.dup-group-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.75rem;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.dup-group-header h4 {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.dup-group-images {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.dup-image {
|
||||
position: relative;
|
||||
width: 150px;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.2s ease;
|
||||
}
|
||||
.dup-image.selected {
|
||||
border-color: var(--btn-danger);
|
||||
}
|
||||
.dup-image.protected {
|
||||
border-color: var(--btn-primary);
|
||||
cursor: default;
|
||||
}
|
||||
.dup-image img {
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
.dup-image-info {
|
||||
background: rgba(0, 0, 0, 0.75);
|
||||
padding: 0.35rem 0.5rem;
|
||||
font-size: 0.7rem;
|
||||
color: #fff;
|
||||
}
|
||||
.dup-image-info .resolution {
|
||||
font-weight: 600;
|
||||
}
|
||||
.dup-image-info .size {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
.dup-badge {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.65rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.dup-badge.keep {
|
||||
background: var(--btn-primary);
|
||||
color: #fff;
|
||||
}
|
||||
.dup-badge.delete {
|
||||
background: var(--btn-danger);
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
@@ -1044,6 +1160,201 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
btn.textContent = 'Delete Selected Images';
|
||||
}
|
||||
});
|
||||
|
||||
// ========================================
|
||||
// Duplicate Detection
|
||||
// ========================================
|
||||
let duplicateGroups = [];
|
||||
let selectedDuplicates = new Set();
|
||||
|
||||
function formatFileSize(bytes) {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
|
||||
}
|
||||
|
||||
document.getElementById('scanDuplicatesBtn').addEventListener('click', async () => {
|
||||
const btn = document.getElementById('scanDuplicatesBtn');
|
||||
const threshold = document.getElementById('dupThreshold').value;
|
||||
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Scanning...';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('threshold', threshold);
|
||||
fd.append('limit', '50');
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/duplicates/scan', { method: 'POST', body: fd });
|
||||
const data = await r.json();
|
||||
|
||||
if (data.ok) {
|
||||
duplicateGroups = data.groups;
|
||||
selectedDuplicates.clear();
|
||||
renderDuplicateResults();
|
||||
} else {
|
||||
alert('Scan failed: ' + (data.error || 'Unknown error'));
|
||||
}
|
||||
} catch (e) {
|
||||
alert('Scan failed: ' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Scan for Duplicates';
|
||||
}
|
||||
});
|
||||
|
||||
function renderDuplicateResults() {
|
||||
const resultsEl = document.getElementById('dupResults');
|
||||
const countEl = document.getElementById('dupGroupCount');
|
||||
const groupsEl = document.getElementById('dupGroups');
|
||||
const actionsEl = document.getElementById('dupActions');
|
||||
|
||||
countEl.textContent = duplicateGroups.length;
|
||||
resultsEl.style.display = 'block';
|
||||
|
||||
if (duplicateGroups.length === 0) {
|
||||
groupsEl.innerHTML = '<p style="text-align: center; color: var(--text-muted); padding: 1rem;">No duplicate images found.</p>';
|
||||
actionsEl.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
actionsEl.style.display = 'block';
|
||||
|
||||
// Auto-select all non-first images for deletion
|
||||
duplicateGroups.forEach((group, groupIdx) => {
|
||||
group.forEach((img, imgIdx) => {
|
||||
if (imgIdx > 0) {
|
||||
selectedDuplicates.add(img.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
groupsEl.innerHTML = duplicateGroups.map((group, groupIdx) => `
|
||||
<div class="dup-group" data-group="${groupIdx}">
|
||||
<div class="dup-group-header">
|
||||
<h4>Group ${groupIdx + 1} (${group.length} images)</h4>
|
||||
<button type="button" class="btn secondary-btn btn-sm" onclick="toggleGroupSelection(${groupIdx})">Toggle Selection</button>
|
||||
</div>
|
||||
<div class="dup-group-images">
|
||||
${group.map((img, imgIdx) => `
|
||||
<div class="dup-image ${imgIdx === 0 ? 'protected' : 'selected'}"
|
||||
data-id="${img.id}"
|
||||
data-group="${groupIdx}"
|
||||
data-protected="${imgIdx === 0}">
|
||||
<img src="${img.thumb_url}" alt="${img.filename}" loading="lazy">
|
||||
<span class="dup-badge ${imgIdx === 0 ? 'keep' : 'delete'}">${imgIdx === 0 ? 'KEEP' : 'DELETE'}</span>
|
||||
<div class="dup-image-info">
|
||||
<div class="resolution">${img.width}x${img.height}</div>
|
||||
<div class="size">${formatFileSize(img.file_size)}</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
// Add click handlers
|
||||
groupsEl.querySelectorAll('.dup-image:not(.protected)').forEach(item => {
|
||||
item.addEventListener('click', () => {
|
||||
const id = parseInt(item.dataset.id);
|
||||
const badge = item.querySelector('.dup-badge');
|
||||
|
||||
if (selectedDuplicates.has(id)) {
|
||||
selectedDuplicates.delete(id);
|
||||
item.classList.remove('selected');
|
||||
badge.textContent = 'KEEP';
|
||||
badge.classList.remove('delete');
|
||||
badge.classList.add('keep');
|
||||
} else {
|
||||
selectedDuplicates.add(id);
|
||||
item.classList.add('selected');
|
||||
badge.textContent = 'DELETE';
|
||||
badge.classList.remove('keep');
|
||||
badge.classList.add('delete');
|
||||
}
|
||||
updateDupSelectedCount();
|
||||
});
|
||||
});
|
||||
|
||||
updateDupSelectedCount();
|
||||
}
|
||||
|
||||
window.toggleGroupSelection = function(groupIdx) {
|
||||
const group = duplicateGroups[groupIdx];
|
||||
const groupEl = document.querySelector(`.dup-group[data-group="${groupIdx}"]`);
|
||||
|
||||
// Check if any non-protected images are selected
|
||||
const nonProtected = group.slice(1);
|
||||
const allSelected = nonProtected.every(img => selectedDuplicates.has(img.id));
|
||||
|
||||
nonProtected.forEach(img => {
|
||||
const itemEl = groupEl.querySelector(`.dup-image[data-id="${img.id}"]`);
|
||||
const badge = itemEl.querySelector('.dup-badge');
|
||||
|
||||
if (allSelected) {
|
||||
selectedDuplicates.delete(img.id);
|
||||
itemEl.classList.remove('selected');
|
||||
badge.textContent = 'KEEP';
|
||||
badge.classList.remove('delete');
|
||||
badge.classList.add('keep');
|
||||
} else {
|
||||
selectedDuplicates.add(img.id);
|
||||
itemEl.classList.add('selected');
|
||||
badge.textContent = 'DELETE';
|
||||
badge.classList.remove('keep');
|
||||
badge.classList.add('delete');
|
||||
}
|
||||
});
|
||||
|
||||
updateDupSelectedCount();
|
||||
};
|
||||
|
||||
function updateDupSelectedCount() {
|
||||
const countEl = document.getElementById('dupSelectedCount');
|
||||
const btn = document.getElementById('deleteDuplicatesBtn');
|
||||
|
||||
countEl.textContent = selectedDuplicates.size;
|
||||
btn.disabled = selectedDuplicates.size === 0;
|
||||
}
|
||||
|
||||
document.getElementById('deleteDuplicatesBtn').addEventListener('click', async () => {
|
||||
if (selectedDuplicates.size === 0) return;
|
||||
|
||||
const confirmMsg = `Are you sure you want to permanently delete ${selectedDuplicates.size} duplicate image(s)? This cannot be undone.`;
|
||||
if (!confirm(confirmMsg)) return;
|
||||
|
||||
const btn = document.getElementById('deleteDuplicatesBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Deleting...';
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/duplicates/delete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ image_ids: Array.from(selectedDuplicates) })
|
||||
});
|
||||
const data = await r.json();
|
||||
|
||||
if (data.ok) {
|
||||
alert(`Successfully deleted ${data.deleted_count} duplicate image(s).`);
|
||||
|
||||
// Remove deleted images from groups
|
||||
duplicateGroups = duplicateGroups.map(group =>
|
||||
group.filter(img => !selectedDuplicates.has(img.id))
|
||||
).filter(group => group.length > 1); // Remove groups with only 1 image left
|
||||
|
||||
selectedDuplicates.clear();
|
||||
renderDuplicateResults();
|
||||
} else {
|
||||
alert('Delete failed: ' + (data.error || 'Unknown error'));
|
||||
}
|
||||
} catch (e) {
|
||||
alert('Delete failed: ' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Delete Selected Duplicates';
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user