import filter work and cleanup

This commit is contained in:
Bryan Van Deusen
2026-01-18 21:57:08 -05:00
parent b3331bad76
commit 482c5a8ead
6 changed files with 725 additions and 146 deletions
+146 -3
View File
@@ -244,24 +244,34 @@ def search_tags():
Query params:
- q: search query (matches tag name, case-insensitive)
- limit: max results (default 10)
- exclude_kind: comma-separated list of tag kinds to exclude (e.g., 'archive')
"""
query = request.args.get('q', '').strip().lower()
limit = request.args.get('limit', 10, type=int)
exclude_kind = request.args.get('exclude_kind', '').strip()
exclude_kinds = [k.strip() for k in exclude_kind.split(',') if k.strip()]
if not query:
# Return most-used tags when no query
tags = (
base_query = (
Tag.query
.join(image_tags)
.group_by(Tag.id)
)
if exclude_kinds:
base_query = base_query.filter(~Tag.kind.in_(exclude_kinds))
tags = (
base_query
.order_by(func.count(image_tags.c.image_id).desc())
.limit(limit)
.all()
)
else:
base_query = Tag.query.filter(Tag.name.ilike(f'%{query}%'))
if exclude_kinds:
base_query = base_query.filter(~Tag.kind.in_(exclude_kinds))
tags = (
Tag.query
.filter(Tag.name.ilike(f'%{query}%'))
base_query
.order_by(Tag.name)
.limit(limit)
.all()
@@ -571,3 +581,136 @@ def get_import_stats():
return jsonify(ok=True, stats=stats)
except Exception as e:
return jsonify(ok=False, error=str(e)), 500
# ----------------------------
# Image filter/cleanup endpoints
# ----------------------------
@main.get("/api/filter-scan")
def scan_filterable_images():
"""
Scan existing images against current filter settings.
Returns counts and IDs of images that would be filtered.
Query params:
- filter_type: 'transparency' or 'dimensions'
- threshold: for transparency (0.0-1.0), or min_width/min_height for dimensions
- min_width: minimum width (for dimensions filter)
- min_height: minimum height (for dimensions filter)
- limit: max results to return (default 100)
"""
from app.utils.image_importer import is_mostly_transparent
filter_type = request.args.get("filter_type", "transparency")
limit = request.args.get("limit", 100, type=int)
results = []
if filter_type == "transparency":
threshold = request.args.get("threshold", 0.9, type=float)
# Only check images that could have transparency
images = ImageRecord.query.filter(
ImageRecord.filepath.ilike("%.png") |
ImageRecord.filepath.ilike("%.gif") |
ImageRecord.filepath.ilike("%.webp")
).limit(limit * 5).all() # Check more to find enough matches
for img in images:
if len(results) >= limit:
break
if img.filepath and os.path.exists(img.filepath):
try:
if is_mostly_transparent(img.filepath, threshold):
results.append({
"id": img.id,
"filename": img.filename,
"filepath": img.filepath,
"thumb_url": url_for('main.serve_image',
filename=(img.thumb_path or img.filepath).replace('/images/', ''))
})
except Exception:
pass
elif filter_type == "dimensions":
min_width = request.args.get("min_width", 0, type=int)
min_height = request.args.get("min_height", 0, type=int)
if min_width <= 0 and min_height <= 0:
return jsonify(ok=True, count=0, images=[], message="No dimension filter set")
query = ImageRecord.query
if min_width > 0:
query = query.filter(ImageRecord.width < min_width)
if min_height > 0:
query = query.filter(ImageRecord.height < min_height)
images = query.limit(limit).all()
for img in images:
results.append({
"id": img.id,
"filename": img.filename,
"filepath": img.filepath,
"width": img.width,
"height": img.height,
"thumb_url": url_for('main.serve_image',
filename=(img.thumb_path or img.filepath).replace('/images/', ''))
})
# Get total count (without limit) for progress indication
total_count = len(results)
return jsonify(ok=True, count=total_count, images=results, filter_type=filter_type)
@main.post("/api/filter-delete")
def delete_filtered_images():
"""
Delete images by their IDs after filter review.
Query params:
- image_ids: comma-separated list of image IDs to delete
- confirm: must be 'true' to actually delete
"""
image_ids_str = request.form.get("image_ids", "")
confirm = request.form.get("confirm") == "true"
if not confirm:
return jsonify(ok=False, error="Confirmation required"), 400
if not image_ids_str:
return jsonify(ok=False, error="No image IDs provided"), 400
try:
image_ids = [int(x) for x in image_ids_str.split(",") if x.strip()]
except ValueError:
return jsonify(ok=False, error="Invalid image IDs"), 400
deleted_count = 0
errors = []
for img_id in image_ids:
img = ImageRecord.query.get(img_id)
if not img:
continue
try:
# Remove image file from disk
if img.filepath and os.path.exists(img.filepath):
os.remove(img.filepath)
# Remove thumbnail if exists
if img.thumb_path and os.path.exists(img.thumb_path):
os.remove(img.thumb_path)
# Delete DB record
db.session.delete(img)
deleted_count += 1
except Exception as e:
errors.append(f"Failed to delete {img.filename}: {e}")
db.session.commit()
return jsonify(
ok=True,
deleted_count=deleted_count,
errors=errors if errors else None
)
+6 -2
View File
@@ -159,8 +159,8 @@ document.addEventListener('DOMContentLoaded', () => {
async function fetchAutocomplete(query) {
try {
const url = query
? `/api/tags/search?q=${encodeURIComponent(query)}&limit=8`
: `/api/tags/search?limit=8`;
? `/api/tags/search?q=${encodeURIComponent(query)}&limit=8&exclude_kind=archive`
: `/api/tags/search?limit=8&exclude_kind=archive`;
const r = await fetch(url);
const j = await r.json();
renderAutocomplete(j.tags || []);
@@ -296,6 +296,10 @@ document.addEventListener('DOMContentLoaded', () => {
modal.classList.add('active');
updateImage(index);
history.replaceState({ modalIndex: index }, '', window.location.href);
// Focus the tag input after modal opens
if (tagInput) {
setTimeout(() => tagInput.focus(), 100);
}
}
function closeModal() {
+4 -2
View File
@@ -133,10 +133,12 @@
}
item.appendChild(imgEl);
if (img.tags && img.tags.length > 0) {
// Filter out archive tags from display (they're still visible in modal)
const visibleTags = (img.tags || []).filter(t => t.kind !== 'archive');
if (visibleTags.length > 0) {
const overlay = document.createElement('div');
overlay.className = 'tag-overlay';
img.tags.forEach(t => {
visibleTags.forEach(t => {
const chip = document.createElement('a');
chip.className = 'tag-chip';
chip.href = `/gallery?tag=${encodeURIComponent(t.name)}`;
+59 -6
View File
@@ -890,17 +890,51 @@ header {
/*------------------------------------------------------------------------------
Settings
------------------------------------------------------------------------------*/
.settings-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1.5rem;
max-width: 1600px;
margin: 1.5rem auto;
padding: 0 1.5rem;
align-items: start;
}
.settings-column {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
@media (max-width: 1200px) {
.settings-grid {
grid-template-columns: repeat(2, 1fr);
}
.settings-column:first-child {
grid-column: 1 / -1;
flex-direction: row;
}
.settings-column:first-child > .settings-container {
flex: 1;
}
}
@media (max-width: 768px) {
.settings-grid {
grid-template-columns: 1fr;
padding: 0 1rem;
}
.settings-column:first-child {
flex-direction: column;
}
}
.settings-container {
max-width: 500px;
margin: 2rem auto;
padding: 2rem;
padding: 1.5rem;
background: var(--panel);
border-radius: 8px;
box-shadow: var(--shadow-2);
border: 1px solid rgba(255, 255, 255, 0.08);
}
.settings-section h2 {
margin-bottom: 1.5rem;
.settings-section h2,
.settings-info h2 {
margin-bottom: 1rem;
text-align: center;
color: var(--text);
font-weight: 500;
@@ -933,7 +967,6 @@ header {
.danger-btn:hover { background-color: var(--btn-danger-hover); }
.settings-info {
margin-top: 2rem;
font-size: 0.9rem;
color: var(--text-muted);
text-align: center;
@@ -1101,6 +1134,26 @@ header {
border-color: var(--btn-primary);
background: rgba(255, 255, 255, 0.12);
}
/* Select dropdowns - ensure dark theme for options */
select.form-input {
cursor: pointer;
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 0.75rem center;
padding-right: 2.5rem;
}
select.form-input option,
select.form-input optgroup {
background: #1a1a1a;
color: #ffffff;
}
select.form-input optgroup {
font-weight: 600;
color: #a0a0a0;
}
.form-button {
padding: 0.75rem;
background-color: var(--btn-primary);
+3 -4
View File
@@ -10,17 +10,16 @@
<div class="gallery-thumb"
style="background-image: url('{{ url_for('main.serve_image', filename=(image.thumb_path or image.filepath) | replace('/images/', '') ) }}');"></div>
{% if image.tags %}
{% set visible_tags = image.tags | selectattr('kind', 'ne', 'archive') | list %}
{% if visible_tags %}
<div class="tag-overlay">
{% for t in image.tags %}
{% for t in visible_tags %}
<a class="tag-chip"
href="{{ url_for('main.gallery', tag=t.name) }}"
title="Filter by {{ t.name }}"
onclick="event.stopPropagation()">
{% if t.kind == 'artist' %}
🎨 {{ t.name.split(':', 1)[1] if ':' in t.name else t.name }}
{% elif t.kind == 'archive' %}
🗜️ {{ t.name.split(':', 1)[1] if ':' in t.name else t.name }}
{% elif t.kind == 'character' %}
👤 {{ t.name.split(':', 1)[1] if ':' in t.name else t.name }}
{% elif t.kind == 'series' %}
+507 -129
View File
@@ -4,136 +4,207 @@
{% block content %}
<h1 style="text-align:center; margin-top: 1rem;">Settings</h1>
<div class="settings-container">
<div class="settings-section">
<h2>Admin Actions</h2>
<div class="settings-actions">
<form action="{{ url_for('main.trigger_image_import') }}" method="get">
<button type="submit" class="btn primary-btn">Trigger Image Import</button>
</form>
<form action="{{ url_for('main.trigger_thumbnail_generation') }}" method="post" onsubmit="return confirm('Are you sure you want to regenerate all thumbnails?');">
<button type="submit" class="btn warning-btn">Regenerate Thumbnails</button>
</form>
<form action="{{ url_for('main.reset_db') }}" method="post" onsubmit="return confirm('Are you sure you want to delete all image records? This action cannot be undone.');">
<button type="submit" class="btn danger-btn">Reset Image Database</button>
</form>
<div class="settings-grid">
<!-- Column 1: Info & Admin Actions -->
<div class="settings-column">
<div class="settings-container">
<div class="settings-info">
<h2>About These Tools</h2>
<p>Use these tools to manage your image library. You can trigger imports, configure filters, and clean up unwanted images.</p>
<p style="margin-top: 0.75rem;"><strong>Note:</strong> Resetting the database does not delete the actual image files from disk.</p>
</div>
</div>
</div>
</div>
<!-- Import Filters Section -->
<div class="settings-container" style="margin-top: 1rem;">
<div class="settings-section">
<h2>Import Filters</h2>
<p class="settings-description">Configure filters to skip certain images during import.</p>
<div class="settings-container">
<div class="settings-section">
<h2>Admin Actions</h2>
<div class="settings-actions">
<form action="{{ url_for('main.trigger_image_import') }}" method="get">
<button type="submit" class="btn primary-btn">Trigger Image Import</button>
</form>
<form id="importSettingsForm" class="form-card">
<div class="form-group">
<label class="form-label">Minimum Width (px)</label>
<input type="number" id="minWidth" name="min_width" class="form-input" min="0" value="0" placeholder="0 = no minimum">
</div>
<form action="{{ url_for('main.trigger_thumbnail_generation') }}" method="post" onsubmit="return confirm('Are you sure you want to regenerate all thumbnails?');">
<button type="submit" class="btn warning-btn">Regenerate Thumbnails</button>
</form>
<div class="form-group">
<label class="form-label">Minimum Height (px)</label>
<input type="number" id="minHeight" name="min_height" class="form-input" min="0" value="0" placeholder="0 = no minimum">
</div>
<div class="form-group">
<label class="form-label checkbox-label">
<input type="checkbox" id="skipTransparent" name="skip_transparent">
Skip mostly transparent images
</label>
<p class="form-help">Useful for filtering out UI elements, overlays, and buttons.</p>
</div>
<div class="form-group" id="transparencyThresholdGroup" style="display: none;">
<label class="form-label">Transparency Threshold (%)</label>
<input type="number" id="transparencyThreshold" name="transparency_threshold" class="form-input" min="50" max="100" value="90">
<p class="form-help">Images with more than this % of transparent pixels will be skipped.</p>
</div>
<div class="form-group">
<label class="form-label">Duplicate Detection Sensitivity</label>
<select id="phashThreshold" name="phash_threshold" class="form-input">
<option value="0">Disabled (import all images)</option>
<option value="1">Strict (only exact visual matches)</option>
<option value="2">Normal (slight variations filtered)</option>
<option value="5">Loose (more variations allowed)</option>
<option value="10">Very Loose (only obvious duplicates filtered)</option>
</select>
<p class="form-help">Controls how similar images must be to be considered duplicates. Higher values allow more variations through.</p>
</div>
<button type="submit" class="btn primary-btn" style="width: 100%;">Save Filter Settings</button>
</form>
<div id="importStats" class="import-stats" style="margin-top: 1rem;">
<h3>Last Import Statistics</h3>
<div class="stats-grid">
<div class="stat-item">
<span class="stat-value" id="statProcessed">-</span>
<span class="stat-label">Processed</span>
</div>
<div class="stat-item">
<span class="stat-value" id="statImported">-</span>
<span class="stat-label">Imported</span>
</div>
<div class="stat-item">
<span class="stat-value" id="statDimension">-</span>
<span class="stat-label">Filtered (size)</span>
</div>
<div class="stat-item">
<span class="stat-value" id="statTransparency">-</span>
<span class="stat-label">Filtered (transparent)</span>
<form action="{{ url_for('main.reset_db') }}" method="post" onsubmit="return confirm('Are you sure you want to delete all image records? This action cannot be undone.');">
<button type="submit" class="btn danger-btn">Reset Image Database</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Filtered Deletion Section -->
<div class="settings-container" style="margin-top: 1rem;">
<div class="settings-section">
<h2>Delete Images by Tag</h2>
<p class="settings-description">Permanently delete all images associated with a specific tag (e.g., remove an artist's entire collection).</p>
<!-- Column 2: Import Filters -->
<div class="settings-column">
<div class="settings-container">
<div class="settings-section">
<h2>Import Filters</h2>
<p class="settings-description">Configure filters to skip certain images during import.</p>
<form id="deleteByTagForm" class="form-card">
<div class="form-group">
<label class="form-label">Select Tag to Delete</label>
<select id="deleteTagSelect" name="tag_id" class="form-input" required>
<option value="">-- Select a tag --</option>
</select>
<form id="importSettingsForm" class="form-card">
<div class="form-group">
<label class="form-label">Minimum Width (px)</label>
<input type="number" id="minWidth" name="min_width" class="form-input" min="0" value="0" placeholder="0 = no minimum">
</div>
<div class="form-group">
<label class="form-label">Minimum Height (px)</label>
<input type="number" id="minHeight" name="min_height" class="form-input" min="0" value="0" placeholder="0 = no minimum">
</div>
<div class="form-group">
<label class="form-label checkbox-label">
<input type="checkbox" id="skipTransparent" name="skip_transparent">
Skip mostly transparent images
</label>
<p class="form-help">Useful for filtering out UI elements, overlays, and buttons.</p>
</div>
<div class="form-group" id="transparencyThresholdGroup" style="display: none;">
<label class="form-label">Transparency Threshold (%)</label>
<input type="number" id="transparencyThreshold" name="transparency_threshold" class="form-input" min="50" max="100" value="90">
<p class="form-help">Images with more than this % of transparent pixels will be skipped.</p>
</div>
<div class="form-group">
<label class="form-label">Duplicate Detection Sensitivity</label>
<select id="phashThreshold" name="phash_threshold" class="form-input">
<option value="0">Disabled (import all images)</option>
<option value="1">Strict (only exact visual matches)</option>
<option value="2">Normal (slight variations filtered)</option>
<option value="5">Loose (more variations allowed)</option>
<option value="10">Very Loose (only obvious duplicates filtered)</option>
</select>
<p class="form-help">Controls how similar images must be to be considered duplicates.</p>
</div>
<button type="submit" class="btn primary-btn" style="width: 100%;">Save Filter Settings</button>
</form>
<div id="importStats" class="import-stats">
<h3>Last Import Statistics</h3>
<div class="stats-grid">
<div class="stat-item">
<span class="stat-value" id="statProcessed">-</span>
<span class="stat-label">Processed</span>
</div>
<div class="stat-item">
<span class="stat-value" id="statImported">-</span>
<span class="stat-label">Imported</span>
</div>
<div class="stat-item">
<span class="stat-value" id="statDimension">-</span>
<span class="stat-label">Filtered (size)</span>
</div>
<div class="stat-item">
<span class="stat-value" id="statTransparency">-</span>
<span class="stat-label">Filtered (transparent)</span>
</div>
</div>
</div>
</div>
<div id="deletePreview" class="delete-preview" style="display: none;">
<p>This will permanently delete <strong id="deleteCount">0</strong> images and their files.</p>
</div>
<div class="form-group" id="confirmationGroup" style="display: none;">
<label class="form-label">Type the tag name to confirm: <code id="confirmTagName"></code></label>
<input type="text" id="deleteConfirmInput" class="form-input" placeholder="Type tag name here..." autocomplete="off">
<p class="form-help">This action cannot be undone.</p>
</div>
<div class="form-group">
<label class="form-label checkbox-label">
<input type="checkbox" id="deleteTagAlso" name="delete_tag">
Also delete the tag itself
</label>
</div>
<button type="submit" class="btn danger-btn" style="width: 100%;" disabled id="deleteByTagBtn">Delete Images</button>
</form>
</div>
</div>
</div>
<div class="settings-container" style="margin-top: 1rem;">
<div class="settings-info">
<p>Use these tools to manually trigger an import or reset the image database. Resetting the database does not delete the actual image files.</p>
<!-- Column 3: Deletion Tools -->
<div class="settings-column">
<div class="settings-container">
<div class="settings-section">
<h2>Delete Images by Tag</h2>
<p class="settings-description">Permanently delete all images associated with a specific tag.</p>
<div id="deleteByTagFeedback"></div>
<form id="deleteByTagForm" class="form-card">
<div class="form-group">
<label class="form-label">Select Tag to Delete</label>
<select id="deleteTagSelect" name="tag_id" class="form-input" required>
<option value="">-- Select a tag --</option>
</select>
</div>
<div id="deletePreview" class="delete-preview" style="display: none;">
<p>This will permanently delete <strong id="deleteCount">0</strong> images and their files.</p>
</div>
<div class="form-group" id="confirmationGroup" style="display: none;">
<label class="form-label">Type the tag name to confirm: <code id="confirmTagName"></code></label>
<input type="text" id="deleteConfirmInput" class="form-input" placeholder="Type tag name here..." autocomplete="off">
<p class="form-help">This action cannot be undone.</p>
</div>
<div class="form-group">
<label class="form-label checkbox-label">
<input type="checkbox" id="deleteTagAlso" name="delete_tag">
Also delete the tag itself
</label>
</div>
<button type="submit" class="btn danger-btn" style="width: 100%;" disabled id="deleteByTagBtn">Delete Images</button>
</form>
</div>
</div>
<div class="settings-container">
<div class="settings-section">
<h2>Clean Up Existing Images</h2>
<p class="settings-description">Scan and remove images that don't meet filter criteria.</p>
<div class="form-card">
<div class="form-group">
<label class="form-label">Filter Type</label>
<select id="cleanupFilterType" class="form-input">
<option value="transparency">Transparency (mostly transparent)</option>
<option value="dimensions">Dimensions (below minimum size)</option>
</select>
</div>
<div id="transparencyOptions">
<div class="form-group">
<label class="form-label">Transparency Threshold (%)</label>
<input type="number" id="cleanupTransparencyThreshold" class="form-input" min="50" max="100" value="90">
<p class="form-help">Images with more than this % transparent pixels will be flagged.</p>
</div>
</div>
<div id="dimensionOptions" style="display: none;">
<div class="form-group">
<label class="form-label">Minimum Width (px)</label>
<input type="number" id="cleanupMinWidth" class="form-input" min="0" value="0">
</div>
<div class="form-group">
<label class="form-label">Minimum Height (px)</label>
<input type="number" id="cleanupMinHeight" class="form-input" min="0" value="0">
</div>
</div>
<button type="button" id="scanFilterBtn" class="btn primary-btn" style="width: 100%;">Scan for Matching Images</button>
</div>
<div id="cleanupResults" style="display: none; margin-top: 1rem;">
<div class="import-stats">
<h3>Scan Results</h3>
<p><strong id="cleanupCount">0</strong> images match the filter criteria.</p>
</div>
<div id="cleanupPreview" class="cleanup-preview"></div>
<div id="cleanupActions" style="display: none; margin-top: 1rem;">
<div class="form-group">
<label class="form-label checkbox-label">
<input type="checkbox" id="cleanupSelectAll">
Select all for deletion
</label>
</div>
<p class="form-help" style="margin-bottom: 0.75rem;">Selected: <strong id="cleanupSelectedCount">0</strong> images</p>
<button type="button" id="deleteSelectedBtn" class="btn danger-btn" style="width: 100%;" disabled>Delete Selected Images</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- end settings-grid -->
<style>
.settings-description {
@@ -198,6 +269,96 @@
margin-bottom: 1rem;
color: var(--flash-danger);
}
.cleanup-preview {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 0.5rem;
max-height: 400px;
overflow-y: auto;
padding: 0.5rem;
background: rgba(255, 255, 255, 0.03);
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
}
.cleanup-item {
position: relative;
aspect-ratio: 1;
border-radius: 6px;
overflow: hidden;
cursor: pointer;
border: 2px solid transparent;
transition: border-color 0.2s ease;
}
.cleanup-item.selected {
border-color: var(--btn-danger);
}
.cleanup-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.cleanup-item .info {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.75);
padding: 0.25rem;
font-size: 0.65rem;
color: #fff;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.cleanup-item .check-overlay {
position: absolute;
top: 4px;
right: 4px;
width: 20px;
height: 20px;
border-radius: 50%;
background: rgba(0, 0, 0, 0.5);
border: 2px solid #fff;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 12px;
}
.cleanup-item.selected .check-overlay {
background: var(--btn-danger);
}
/* Feedback message styles */
.feedback-message {
padding: 1rem;
border-radius: 8px;
margin-bottom: 1rem;
animation: fadeInSlide 0.3s ease-out;
}
.feedback-message.success {
background: rgba(34, 197, 94, 0.15);
border: 1px solid rgba(34, 197, 94, 0.4);
color: #22c55e;
}
.feedback-message.error {
background: rgba(239, 68, 68, 0.15);
border: 1px solid rgba(239, 68, 68, 0.4);
color: #ef4444;
}
.feedback-message strong {
color: inherit;
}
@keyframes fadeInSlide {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
<script>
@@ -298,6 +459,18 @@ document.addEventListener('DOMContentLoaded', () => {
btn.disabled = typed !== selectedTagName;
});
// Helper to show feedback message
function showDeleteByTagFeedback(message, isSuccess) {
const feedbackEl = document.getElementById('deleteByTagFeedback');
feedbackEl.innerHTML = `<div class="feedback-message ${isSuccess ? 'success' : 'error'}">${message}</div>`;
// Scroll feedback into view
feedbackEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
function clearDeleteByTagFeedback() {
document.getElementById('deleteByTagFeedback').innerHTML = '';
}
// Delete by tag form
document.getElementById('deleteByTagForm').addEventListener('submit', async (e) => {
e.preventDefault();
@@ -305,30 +478,63 @@ document.addEventListener('DOMContentLoaded', () => {
const deleteTag = document.getElementById('deleteTagAlso').checked;
const count = document.getElementById('deleteCount').textContent;
const confirmInput = document.getElementById('deleteConfirmInput');
const btn = document.getElementById('deleteByTagBtn');
const previewEl = document.getElementById('deletePreview');
// Clear any previous feedback
clearDeleteByTagFeedback();
// Double-check confirmation matches (defense in depth)
if (confirmInput.value.trim() !== selectedTagName) {
alert('Tag name confirmation does not match.');
showDeleteByTagFeedback('Tag name confirmation does not match.', false);
return;
}
// Show loading state
const originalBtnText = btn.textContent;
btn.disabled = true;
btn.textContent = 'Deleting...';
const fd = new FormData();
fd.append('tag_id', tagId);
fd.append('tag_name', selectedTagName); // Server validates this matches the ID
fd.append('delete_tag', deleteTag ? 'true' : 'false');
const r = await fetch('/api/delete-by-tag', { method: 'POST', body: fd });
const data = await r.json();
if (data.ok) {
alert(`Successfully deleted ${data.deleted_count} images.${data.tag_deleted ? ' Tag was also deleted.' : ''}`);
loadTagsForDeletion();
document.getElementById('deletePreview').style.display = 'none';
document.getElementById('confirmationGroup').style.display = 'none';
document.getElementById('deleteConfirmInput').value = '';
document.getElementById('deleteByTagBtn').disabled = true;
selectedTagName = '';
} else {
alert('Failed to delete images: ' + (data.error || 'Unknown error'));
try {
const r = await fetch('/api/delete-by-tag', { method: 'POST', body: fd });
const data = await r.json();
if (data.ok) {
// Show success message in the dedicated feedback area
let successMsg = `Successfully deleted <strong>${data.deleted_count}</strong> image(s).`;
if (data.tag_deleted) successMsg += ' Tag was also deleted.';
if (data.errors && data.errors.length > 0) {
successMsg += `<br><small>Some errors occurred: ${data.errors.join(', ')}</small>`;
}
showDeleteByTagFeedback(successMsg, true);
// Reload tag list
await loadTagsForDeletion();
// Reset form immediately since feedback is now in a separate area
document.getElementById('deleteTagSelect').value = '';
previewEl.style.display = 'none';
document.getElementById('confirmationGroup').style.display = 'none';
confirmInput.value = '';
document.getElementById('deleteTagAlso').checked = false;
selectedTagName = '';
btn.textContent = originalBtnText;
} else {
// Show error in feedback area
showDeleteByTagFeedback(`Failed to delete images: <strong>${data.error || 'Unknown error'}</strong>`, false);
btn.disabled = false;
btn.textContent = originalBtnText;
}
} catch (err) {
// Network or parsing error
showDeleteByTagFeedback(`Request failed: <strong>${err.message}</strong>`, false);
btn.disabled = false;
btn.textContent = originalBtnText;
}
});
@@ -362,6 +568,178 @@ document.addEventListener('DOMContentLoaded', () => {
});
}
}
// ========================================
// Image Cleanup / Filter Tool
// ========================================
let cleanupImages = [];
let selectedForDeletion = new Set();
// Toggle filter options visibility
document.getElementById('cleanupFilterType').addEventListener('change', () => {
const type = document.getElementById('cleanupFilterType').value;
document.getElementById('transparencyOptions').style.display = type === 'transparency' ? 'block' : 'none';
document.getElementById('dimensionOptions').style.display = type === 'dimensions' ? 'block' : 'none';
// Reset results when changing filter type
document.getElementById('cleanupResults').style.display = 'none';
cleanupImages = [];
selectedForDeletion.clear();
});
// Scan for filterable images
document.getElementById('scanFilterBtn').addEventListener('click', async () => {
const btn = document.getElementById('scanFilterBtn');
const filterType = document.getElementById('cleanupFilterType').value;
btn.disabled = true;
btn.textContent = 'Scanning...';
let url = `/api/filter-scan?filter_type=${filterType}&limit=100`;
if (filterType === 'transparency') {
const threshold = document.getElementById('cleanupTransparencyThreshold').value / 100;
url += `&threshold=${threshold}`;
} else {
const minWidth = document.getElementById('cleanupMinWidth').value || 0;
const minHeight = document.getElementById('cleanupMinHeight').value || 0;
url += `&min_width=${minWidth}&min_height=${minHeight}`;
}
try {
const r = await fetch(url);
const data = await r.json();
if (data.ok) {
cleanupImages = data.images;
selectedForDeletion.clear();
renderCleanupResults();
} else {
alert('Scan failed: ' + (data.error || 'Unknown error'));
}
} catch (e) {
alert('Scan failed: ' + e.message);
} finally {
btn.disabled = false;
btn.textContent = 'Scan for Matching Images';
}
});
function renderCleanupResults() {
const resultsEl = document.getElementById('cleanupResults');
const countEl = document.getElementById('cleanupCount');
const previewEl = document.getElementById('cleanupPreview');
const actionsEl = document.getElementById('cleanupActions');
const filterType = document.getElementById('cleanupFilterType').value;
countEl.textContent = cleanupImages.length;
resultsEl.style.display = 'block';
if (cleanupImages.length === 0) {
previewEl.innerHTML = '<p style="text-align: center; color: var(--text-muted); padding: 1rem;">No images match the filter criteria.</p>';
actionsEl.style.display = 'none';
return;
}
actionsEl.style.display = 'block';
previewEl.innerHTML = cleanupImages.map(img => {
const info = filterType === 'dimensions'
? `${img.width}x${img.height}`
: img.filename.substring(0, 15);
return `
<div class="cleanup-item" data-id="${img.id}">
<img src="${img.thumb_url}" alt="${img.filename}" loading="lazy">
<div class="info">${info}</div>
<div class="check-overlay"></div>
</div>
`;
}).join('');
// Add click handlers for selection
previewEl.querySelectorAll('.cleanup-item').forEach(item => {
item.addEventListener('click', () => {
const id = parseInt(item.dataset.id);
if (selectedForDeletion.has(id)) {
selectedForDeletion.delete(id);
item.classList.remove('selected');
} else {
selectedForDeletion.add(id);
item.classList.add('selected');
}
updateSelectedCount();
});
});
updateSelectedCount();
}
function updateSelectedCount() {
const countEl = document.getElementById('cleanupSelectedCount');
const btn = document.getElementById('deleteSelectedBtn');
const selectAllEl = document.getElementById('cleanupSelectAll');
countEl.textContent = selectedForDeletion.size;
btn.disabled = selectedForDeletion.size === 0;
// Update select all checkbox state
selectAllEl.checked = selectedForDeletion.size === cleanupImages.length && cleanupImages.length > 0;
selectAllEl.indeterminate = selectedForDeletion.size > 0 && selectedForDeletion.size < cleanupImages.length;
}
// Select all toggle
document.getElementById('cleanupSelectAll').addEventListener('change', (e) => {
const checked = e.target.checked;
const previewEl = document.getElementById('cleanupPreview');
cleanupImages.forEach(img => {
if (checked) {
selectedForDeletion.add(img.id);
} else {
selectedForDeletion.delete(img.id);
}
});
previewEl.querySelectorAll('.cleanup-item').forEach(item => {
item.classList.toggle('selected', checked);
});
updateSelectedCount();
});
// Delete selected images
document.getElementById('deleteSelectedBtn').addEventListener('click', async () => {
if (selectedForDeletion.size === 0) return;
const confirmMsg = `Are you sure you want to permanently delete ${selectedForDeletion.size} image(s)? This cannot be undone.`;
if (!confirm(confirmMsg)) return;
const btn = document.getElementById('deleteSelectedBtn');
btn.disabled = true;
btn.textContent = 'Deleting...';
const fd = new FormData();
fd.append('image_ids', Array.from(selectedForDeletion).join(','));
fd.append('confirm', 'true');
try {
const r = await fetch('/api/filter-delete', { method: 'POST', body: fd });
const data = await r.json();
if (data.ok) {
alert(`Successfully deleted ${data.deleted_count} image(s).`);
// Remove deleted images from the list
cleanupImages = cleanupImages.filter(img => !selectedForDeletion.has(img.id));
selectedForDeletion.clear();
renderCleanupResults();
} else {
alert('Delete failed: ' + (data.error || 'Unknown error'));
}
} catch (e) {
alert('Delete failed: ' + e.message);
} finally {
btn.disabled = false;
btn.textContent = 'Delete Selected Images';
}
});
});
</script>
{% endblock %}