Files
character-browser/templates/scenes/index.html
Aodhan Collins 7d79e626a5 Add REST API for preset-based generation and fallback cover images
REST API (routes/api.py): Three endpoints behind API key auth for
programmatic image generation via presets — list presets, queue
generation with optional overrides, and poll job status.

Shared generation logic extracted from routes/presets.py into
services/generation.py so both web UI and API use the same code path.

Fallback covers: library index pages now show a random generated image
at reduced opacity when no cover is assigned, instead of "No Image".

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 21:19:12 +00:00

190 lines
10 KiB
HTML

{% extends "layout.html" %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h2>Scene Library</h2>
<div class="d-flex gap-1 align-items-center">
<button id="batch-generate-btn" class="btn btn-sm btn-outline-success btn-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Generate cover images for scenes without one" data-requires="comfyui"><img src="{{ url_for('static', filename='icons/new-cover-batch.png') }}"></button>
<button id="regenerate-all-btn" class="btn btn-sm btn-outline-danger btn-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Regenerate cover images for all scenes" data-requires="comfyui"><img src="{{ url_for('static', filename='icons/new-cover-batch.png') }}"></button>
<form action="{{ url_for('bulk_create_scenes_from_loras') }}" method="post" class="d-contents">
<button type="submit" class="btn btn-sm btn-primary btn-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Create new scene entries from all LoRA files"><img src="{{ url_for('static', filename='icons/new-file.png') }}"></button>
</form>
<form action="{{ url_for('bulk_create_scenes_from_loras') }}" method="post" class="d-contents">
<input type="hidden" name="overwrite" value="true">
<button type="submit" class="btn btn-sm btn-danger btn-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Overwrite all scene metadata from LoRA files (uses API credits)" onclick="return confirm('WARNING: This will re-run LLM generation for ALL scene LoRAs, consuming significant API credits and overwriting ALL existing scene metadata. Are you absolutely sure?')"><img src="{{ url_for('static', filename='icons/new-file.png') }}"></button>
</form>
<a href="{{ url_for('create_scene') }}" class="btn btn-sm btn-success">Create New Scene</a>
<form action="{{ url_for('rescan_scenes') }}" method="post" class="d-contents">
<button type="submit" class="btn btn-sm btn-outline-primary btn-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Rescan scene files from disk"><img src="{{ url_for('static', filename='icons/refresh.png') }}"></button>
</form>
</div>
</div>
<div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-5 row-cols-xl-6 g-3">
{% for scene in scenes %}
<div class="col" id="card-{{ scene.slug }}">
<div class="card h-100 character-card {% if request.args.get('highlight') == scene.slug %}border-success border-3 highlight-card{% endif %}" onclick="window.location.href='/scene/{{ scene.slug }}'">
<div class="img-container">
{% if scene.image_path %}
<img id="img-{{ scene.slug }}" src="{{ url_for('static', filename='uploads/' + scene.image_path) }}" alt="{{ scene.name }}">
<span id="no-img-{{ scene.slug }}" class="text-muted d-none">No Image</span>
{% else %}
{% set fallback = random_gen_image('scenes', scene.slug) %}
{% if fallback %}
<img id="img-{{ scene.slug }}" src="{{ url_for('static', filename='uploads/' + fallback) }}" alt="{{ scene.name }}" class="fallback-cover">
<span id="no-img-{{ scene.slug }}" class="text-muted d-none">No Image</span>
{% else %}
<img id="img-{{ scene.slug }}" src="" alt="{{ scene.name }}" class="d-none">
<span id="no-img-{{ scene.slug }}" class="text-muted">No Image</span>
{% endif %}
{% endif %}
</div>
<div class="card-body">
<h5 class="card-title text-center">{{ scene.name }}</h5>
<p class="card-text small text-center text-muted">
{% set ns = namespace(parts=[]) %}
{% if scene.data.scene is mapping %}
{% for v in scene.data.scene.values() %}
{% if v %}{% set ns.parts = ns.parts + [v] %}{% endif %}
{% endfor %}
{% endif %}
{% if scene.data.lora and scene.data.lora.lora_triggers %}
{% set ns.parts = ns.parts + [scene.data.lora.lora_triggers] %}
{% endif %}
{{ ns.parts | join(', ') }}
</p>
</div>
<div class="card-footer d-flex justify-content-between align-items-center p-1">
{% if scene.data.lora and scene.data.lora.lora_name %}
{% set lora_name = scene.data.lora.lora_name.split('/')[-1].replace('.safetensors', '') %}
<small class="text-muted text-truncate" title="{{ scene.data.lora.lora_name }}">{{ lora_name }}</small>
{% else %}<span></span>{% endif %}
<button class="btn btn-sm btn-outline-danger py-0 px-1 flex-shrink-0 ms-1 resource-delete-btn" title="Delete"
data-category="scenes" data-slug="{{ scene.slug }}" data-name="{{ scene.name | e }}">🗑</button>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block scripts %}
<style>
.highlight-card {
animation: highlight-pulse 2s ease-in-out 3;
box-shadow: 0 0 20px rgba(25, 135, 84, 0.5) !important;
}
@keyframes highlight-pulse {
0%, 100% { box-shadow: 0 0 20px rgba(25, 135, 84, 0.5); }
50% { box-shadow: 0 0 30px rgba(25, 135, 84, 0.8); }
}
</style>
<script>
document.addEventListener('DOMContentLoaded', () => {
// Handle highlight parameter
const highlightSlug = new URLSearchParams(window.location.search).get('highlight');
if (highlightSlug) {
const card = document.getElementById(`card-${highlightSlug}`);
if (card) {
card.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
const batchBtn = document.getElementById('batch-generate-btn');
const regenAllBtn = document.getElementById('regenerate-all-btn');
const sceneNameText = document.getElementById('current-scene-name');
const stepProgressText = document.getElementById('current-step-progress');
async function waitForJob(jobId) {
return new Promise((resolve, reject) => {
const poll = setInterval(async () => {
try {
const resp = await fetch(`/api/queue/${jobId}/status`);
const data = await resp.json();
if (data.status === 'done') { clearInterval(poll); resolve(data); }
else if (data.status === 'failed' || data.status === 'removed') { clearInterval(poll); reject(new Error(data.error || 'Job failed')); }
else if (data.status === 'processing') nodeStatus.textContent = 'Generating…';
else nodeStatus.textContent = 'Queued…';
} catch (err) {}
}, 1500);
});
}
async function runBatch() {
const response = await fetch('/get_missing_scenes');
const data = await response.json();
const missing = data.missing;
if (missing.length === 0) {
alert("No scenes missing cover images.");
return;
}
batchBtn.disabled = true;
regenAllBtn.disabled = true;
// Phase 1: Queue all jobs upfront
const jobs = [];
for (const scene of missing) {
try {
const genResp = await fetch(`/scene/${scene.slug}/generate`, {
method: 'POST',
body: new URLSearchParams({ action: 'replace', character_slug: '' }),
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
const genData = await genResp.json();
if (genData.job_id) jobs.push({ item: scene, jobId: genData.job_id });
} catch (err) {
console.error(`Failed to queue ${scene.name}:`, err);
}
}
// Phase 2: Poll all concurrently
let currentItem = '';
await Promise.all(jobs.map(async ({ item, jobId }) => {
currentItem = item.name;
itemNameText.textContent = `Processing: ${currentItem}`;
try {
const jobResult = await waitForJob(jobId);
if (jobResult.result && jobResult.result.image_url) {
const img = document.getElementById(`img-${item.slug}`);
const noImgSpan = document.getElementById(`no-img-${item.slug}`);
if (img) { img.src = jobResult.result.image_url; img.classList.remove('d-none'); }
if (noImgSpan) noImgSpan.classList.add('d-none');
}
} catch (err) {
console.error(`Failed for ${item.name}:`, err);
}
}));
batchBtn.disabled = false;
alert(`Batch generation complete! ${jobs.length} scene images processed.`);
}
batchBtn.addEventListener('click', async () => {
const response = await fetch('/get_missing_scenes');
const data = await response.json();
if (data.missing.length === 0) {
alert("No scenes missing cover images.");
return;
}
if (!confirm(`Generate cover images for ${data.missing.length} scenes?`)) return;
runBatch();
});
regenAllBtn.addEventListener('click', async () => {
if (!confirm("This will unassign ALL current scene cover images and generate new ones. Proceed?")) return;
const clearResp = await fetch('/clear_all_scene_covers', { method: 'POST' });
if (clearResp.ok) {
document.querySelectorAll('.img-container img').forEach(img => img.classList.add('d-none'));
document.querySelectorAll('.img-container .text-muted').forEach(span => span.classList.remove('d-none'));
runBatch();
}
});
});
</script>
{% endblock %}