Files
character-browser/templates/actions/detail.html
Aodhan Collins 5e4348ebc1 Add extra prompts, endless generation, random character default, and small fixes
- Add extra positive/negative prompt textareas to all 9 detail pages with session persistence
- Add Endless generation button to all detail pages (continuous preview generation until stopped)
- Default character selector to "Random Character" on all secondary detail pages
- Fix queue clear endpoint (remove spurious auth check)
- Refactor app.py into routes/ and services/ modules
- Update CLAUDE.md with new architecture documentation
- Various data file updates and cleanup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 02:07:16 +00:00

479 lines
28 KiB
HTML

{% extends "layout.html" %}
{% block content %}
<!-- JSON Editor Modal -->
<div class="modal fade" id="jsonEditorModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit JSON — {{ action.name }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<ul class="nav nav-tabs mb-3" role="tablist">
<li class="nav-item"><button class="nav-link active" id="json-simple-tab" type="button">Simple</button></li>
<li class="nav-item"><button class="nav-link" id="json-advanced-tab" type="button">Advanced JSON</button></li>
</ul>
<div id="json-editor-error" class="alert alert-danger d-none"></div>
<div id="json-simple-panel"></div>
<div id="json-advanced-panel" class="d-none">
<textarea id="json-editor-textarea" class="form-control font-monospace" rows="20" spellcheck="false"></textarea>
</div>
<script type="application/json" id="json-raw-data">{{ action.data | tojson }}</script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="json-save-btn">Save</button>
</div>
</div>
</div>
</div>
{% macro selection_checkbox(section, key, label, value) %}
<input class="form-check-input me-1" type="checkbox" name="include_field" value="{{ section }}::{{ key }}"
{% if preferences is not none %}
{% if section + '::' + key in preferences %}checked{% endif %}
{% elif action.default_fields is not none %}
{% if section + '::' + key in action.default_fields %}checked{% endif %}
{% else %}
{% if value %}checked{% endif %}
{% endif %}>
{% endmacro %}
<div class="row">
<div class="col-md-4">
<div class="card mb-4">
<div class="img-container" style="height: auto; min-height: 400px; cursor: pointer;" onclick="openGallery([this.querySelector('img') ? this.querySelector('img').src : this.src || ''], 0)">
{% if action.image_path %}
<img src="{{ url_for('static', filename='uploads/' + action.image_path) }}" alt="{{ action.name }}" class="img-fluid" data-preview-path="{{ action.image_path }}">
{% else %}
<span class="text-muted">No Image Attached</span>
{% endif %}
</div>
<div class="card-body">
{# Character Selector #}
<div class="mb-3">
<label for="character_select" class="form-label">Preview with Character</label>
<select class="form-select" id="character_select" name="character_slug" form="generate-form">
<option value="">-- No Character (Action Only) --</option>
<option value="__random__" {% if selected_character == '__random__' or not selected_character %}selected{% endif %}>🎲 Random Character</option>
{% for char in characters %}
<option value="{{ char.slug }}" {% if selected_character == char.slug %}selected{% endif %}>{{ char.name }}</option>
{% endfor %}
</select>
<div class="form-text">Select a character to preview this action on their model.</div>
</div>
{# Additional Prompts #}
<div class="mb-2">
<label for="extra_positive" class="form-label">Additional Positive</label>
<textarea class="form-control form-control-sm font-monospace" id="extra_positive" name="extra_positive" rows="2" placeholder="e.g. masterpiece, best quality" form="generate-form">{{ extra_positive or '' }}</textarea>
</div>
<div class="mb-3">
<label for="extra_negative" class="form-label">Additional Negative</label>
<textarea class="form-control form-control-sm font-monospace" id="extra_negative" name="extra_negative" rows="2" placeholder="e.g. blurry, low quality" form="generate-form">{{ extra_negative or '' }}</textarea>
</div>
<div class="d-grid gap-2">
<div class="input-group input-group-sm mb-1">
<span class="input-group-text">Seed</span>
<input type="number" class="form-control" id="seed-input" name="seed" form="generate-form" placeholder="Random" min="1" step="1">
<button type="button" class="btn btn-outline-secondary" id="seed-clear-btn" title="Clear (random)">&times;</button>
</div>
<button type="submit" name="action" value="preview" class="btn btn-success" form="generate-form" data-requires="comfyui">Generate Preview</button>
<button type="button" class="btn btn-outline-info" id="endless-btn" onclick="window._endlessStart()" data-requires="comfyui">Endless</button>
<button type="button" class="btn btn-danger d-none" id="endless-stop-btn" onclick="window._endlessStop()">Stop Endless</button>
<small class="text-muted d-none" id="endless-counter"></small>
<button type="submit" form="generate-form" formaction="{{ url_for('save_action_defaults', slug=action.slug) }}" class="btn btn-sm btn-outline-secondary mt-2">Save as Default Selection</button>
</div>
</div>
</div>
<div id="progress-container" class="mb-4 d-none">
<label id="progress-label" class="form-label">Generating...</label>
<div class="progress" role="progressbar" aria-label="Generation Progress" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%">0%</div>
</div>
</div>
<div class="card mb-4 {% if preview_image %}border-success{% else %}border-secondary d-none{% endif %}" id="preview-card">
<div class="card-header {% if preview_image %}bg-success{% else %}bg-secondary{% endif %} text-white d-flex justify-content-between align-items-center" id="preview-card-header">
<span>Selected Preview</span>
<form action="{{ url_for('replace_action_cover_from_preview', slug=action.slug) }}" method="post" class="m-0" id="replace-cover-form">
<input type="hidden" name="preview_path" id="preview-path" value="{{ preview_image or '' }}">
<button type="submit" class="btn btn-sm btn-outline-light" id="replace-cover-btn" {% if not preview_image %}disabled{% endif %}>Replace Cover</button>
</form>
</div>
<div class="card-body p-0">
<div class="img-container" style="height: auto; min-height: 400px; cursor: pointer;" onclick="openGallery([this.querySelector('img') ? this.querySelector('img').src : this.src || ''], 0)">
<img id="preview-img" src="{{ url_for('static', filename='uploads/' + preview_image) if preview_image else '' }}" alt="Preview" class="img-fluid">
</div>
</div>
</div>
<div class="card mb-4">
<div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
<span>Tags</span>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" name="include_field" value="special::tags" id="includeTags" form="generate-form"
{% if preferences is not none %}
{% if 'special::tags' in preferences %}checked{% endif %}
{% elif action.default_fields is not none %}
{% if 'special::tags' in action.default_fields %}checked{% endif %}
{% endif %}>
<label class="form-check-label text-white small {% if action.default_fields is not none and 'special::tags' in action.default_fields %}text-accent{% endif %}" for="includeTags">Include</label>
</div>
</div>
<div class="card-body">
{% for tag in action.data.tags %}
<span class="badge bg-secondary">{{ tag }}</span>
{% else %}
<span class="text-muted">No tags</span>
{% endfor %}
</div>
</div>
</div>
<div class="col-md-8">
<div class="d-flex justify-content-between align-items-center mb-3">
<div>
<h1 class="mb-0">{{ action.name }}</h1>
<a href="{{ url_for('edit_action', slug=action.slug) }}" class="btn btn-sm btn-link text-decoration-none">Edit Profile</a>
<form action="{{ url_for('clone_action', slug=action.slug) }}" method="post" style="display: inline;">
<button type="submit" class="btn btn-sm btn-link text-decoration-none">Clone Action</button>
</form>
</div>
<div class="d-flex gap-2">
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#jsonEditorModal">Edit JSON</button>
<a href="{{ url_for('transfer_resource', category='actions', slug=action.slug) }}" class="btn btn-outline-primary">Transfer</a>
<a href="{{ url_for('actions_index') }}" class="btn btn-outline-secondary">Back to Library</a>
</div>
</div>
<ul class="nav nav-tabs mb-4" id="detailTabs" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="settings-tab" data-bs-toggle="tab" data-bs-target="#settings-pane" type="button" role="tab">Settings</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="previews-tab" data-bs-toggle="tab" data-bs-target="#previews-pane" type="button" role="tab">
Previews{% if existing_previews %} <span class="badge bg-secondary">{{ existing_previews|length }}</span>{% endif %}
</button>
</li>
{% if action.data.get('lora', {}).get('lora_name', '') != '' %}
<li class="nav-item" role="presentation">
<button class="nav-link" id="strengths-tab" data-bs-toggle="tab" data-bs-target="#strengths-pane" type="button" role="tab">Strengths</button>
</li>
{% endif %}
</ul>
<div class="tab-content" id="detailTabContent">
<div class="tab-pane fade show active" id="settings-pane" role="tabpanel">
<form id="generate-form" action="{{ url_for('generate_action_image', slug=action.slug) }}" method="post">
{# Action details section #}
{% set action_details = action.data.get('action', {}) %}
<div class="card mb-4">
<div class="card-header bg-light">
<strong>Action Details</strong>
</div>
<div class="card-body">
<dl class="row mb-0">
{% for key, value in action_details.items() %}
<dt class="col-sm-4 text-capitalize">
{{ selection_checkbox('action', key, key.replace('_', ' '), value) }}
{{ key.replace('_', ' ') }}
</dt>
<dd class="col-sm-8">{{ value if value else '--' }}</dd>
{% endfor %}
</dl>
</div>
</div>
{# Defaults (Pose/Expression Aggregates) #}
<div class="card mb-4 border-info">
<div class="card-header bg-info text-white">
<strong>Prompt Aggregates (Character Overrides)</strong>
</div>
<div class="card-body">
<div class="form-text mb-3">These fields will override character defaults when a character is selected.</div>
<dl class="row mb-0">
<dt class="col-sm-4 text-capitalize">
{{ selection_checkbox('defaults', 'pose', 'Pose', True) }}
Pose (Combined)
</dt>
<dd class="col-sm-8 text-muted small">Aggregated from Action Pose fields</dd>
<dt class="col-sm-4 text-capitalize">
{{ selection_checkbox('defaults', 'expression', 'Expression', True) }}
Expression (Combined)
</dt>
<dd class="col-sm-8 text-muted small">Aggregated from Action Expression fields</dd>
<dt class="col-sm-4 text-capitalize">
{{ selection_checkbox('defaults', 'scene', 'Scene', action_details.get('additional')) }}
Scene (Additional)
</dt>
<dd class="col-sm-8 small">{{ action_details.get('additional') if action_details.get('additional') else '--' }}</dd>
</dl>
</div>
</div>
{# Character Identity/Wardrobe context when character is selected #}
<div id="character-context" class="{% if not selected_character or selected_character == '__random__' %}d-none{% endif %}">
<div class="alert alert-info">
<i class="bi bi-info-circle"></i> When a character is selected, their identity and active wardrobe fields will be automatically included based on the character's default selection.
</div>
</div>
{# LoRA section #}
{% set lora = action.data.get('lora', {}) %}
{% if lora %}
<div class="card mb-4">
<div class="card-header bg-light d-flex justify-content-between align-items-center">
<strong>LoRA</strong>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" name="include_field" value="lora::lora_triggers" id="includeLora"
{% if preferences is not none %}
{% if 'lora::lora_triggers' in preferences %}checked{% endif %}
{% elif action.default_fields is not none %}
{% if 'lora::lora_triggers' in action.default_fields %}checked{% endif %}
{% else %}
checked
{% endif %}>
<label class="form-check-label small" for="includeLora">Include Triggers</label>
</div>
</div>
<div class="card-body">
<dl class="row mb-0">
{% for key, value in lora.items() %}
<dt class="col-sm-4 text-capitalize">{{ key.replace('_', ' ') }}</dt>
<dd class="col-sm-8">{{ value if value else '--' }}</dd>
{% endfor %}
</dl>
</div>
</div>
{% endif %}
</form>
</div>
<div class="tab-pane fade" id="previews-pane" role="tabpanel">
<div class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted small">{{ existing_previews|length }} preview(s)</span>
<div class="d-flex gap-2">
<button type="button" id="generate-all-btn" class="btn btn-primary btn-sm" data-requires="comfyui">Generate All Characters</button>
<button type="button" id="stop-all-btn" class="btn btn-danger btn-sm d-none">Stop</button>
</div>
</div>
<div id="batch-progress" class="mb-3 d-none">
<label id="batch-label" class="form-label small fw-semibold"></label>
<div class="progress" style="height: 8px;">
<div id="batch-bar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
</div>
</div>
<div id="preview-gallery" class="row row-cols-2 row-cols-md-3 g-2">
{% for img in existing_previews %}
<div class="col">
<img src="{{ url_for('static', filename='uploads/' + img) }}"
class="img-fluid rounded preview-img"
style="cursor: pointer; aspect-ratio: 1; object-fit: cover; width: 100%;"
data-preview-path="{{ img }}">
</div>
{% else %}
<div class="col-12 text-muted small" id="gallery-empty">No previews yet. Generate some!</div>
{% endfor %}
</div>
</div>
{% set sg_has_lora = action.data.get('lora', {}).get('lora_name', '') != '' %}
{% if sg_has_lora %}
<div class="tab-pane fade" id="strengths-pane" role="tabpanel">
{% set sg_entity = action %}
{% set sg_category = 'actions' %}
{% include 'partials/strengths_gallery.html' %}
</div>
{% endif %}
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('generate-form');
const progressBar = document.getElementById('progress-bar');
const progressContainer = document.getElementById('progress-container');
const progressLabel = document.getElementById('progress-label');
const previewCard = document.getElementById('preview-card');
const previewImg = document.getElementById('preview-img');
const previewPath = document.getElementById('preview-path');
const replaceBtn = document.getElementById('replace-cover-btn');
const previewHeader = document.getElementById('preview-card-header');
const charSelect = document.getElementById('character_select');
const charContext = document.getElementById('character-context');
charSelect.addEventListener('change', () => {
charContext.classList.toggle('d-none', !charSelect.value || charSelect.value === '__random__');
});
function selectPreview(relativePath, imageUrl) {
if (!relativePath) return;
previewImg.src = imageUrl;
previewPath.value = relativePath;
replaceBtn.disabled = false;
previewCard.classList.remove('d-none');
previewHeader.classList.replace('bg-secondary', 'bg-success');
previewCard.classList.replace('border-secondary', 'border-success');
}
document.addEventListener('click', e => {
const img = e.target.closest('img[data-preview-path]');
if (img) selectPreview(img.dataset.previewPath, img.src);
});
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 progressLabel.textContent = data.status === 'processing' ? 'Generating…' : 'Queued…';
} catch (err) { console.error('Poll error:', err); }
}, 1500);
});
}
form.addEventListener('submit', async (e) => {
const submitter = e.submitter;
if (!submitter || submitter.value !== 'preview') return;
e.preventDefault();
const formData = new FormData(form);
formData.append('action', 'preview');
progressContainer.classList.remove('d-none');
progressBar.style.width = '100%'; progressBar.textContent = '';
progressBar.classList.add('progress-bar-striped', 'progress-bar-animated');
progressLabel.textContent = 'Queuing…';
try {
const response = await fetch(form.getAttribute('action'), {
method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
const data = await response.json();
if (data.error) { alert('Error: ' + data.error); return; }
progressLabel.textContent = 'Queued…';
const jobResult = await waitForJob(data.job_id);
if (jobResult.result?.image_url) {
selectPreview(jobResult.result.relative_path, jobResult.result.image_url);
addToPreviewGallery(jobResult.result.image_url, jobResult.result.relative_path, '');
}
updateSeedFromResult(jobResult.result);
} catch (err) { console.error(err); alert('Generation failed: ' + err.message); }
finally { progressContainer.classList.add('d-none'); progressBar.classList.remove('progress-bar-striped', 'progress-bar-animated'); }
});
// Endless mode callback
window._onEndlessResult = function(jobResult) {
if (jobResult.result?.image_url) {
selectPreview(jobResult.result.relative_path, jobResult.result.image_url);
addToPreviewGallery(jobResult.result.image_url, jobResult.result.relative_path, '');
}
};
const allCharacters = [
{% for char in characters %}{ slug: "{{ char.slug }}", name: {{ char.name | tojson }} },
{% endfor %}
];
let stopBatch = false;
const generateAllBtn = document.getElementById('generate-all-btn');
const stopAllBtn = document.getElementById('stop-all-btn');
const batchProgress = document.getElementById('batch-progress');
const batchLabel = document.getElementById('batch-label');
const batchBar = document.getElementById('batch-bar');
function addToPreviewGallery(imageUrl, relativePath, charName) {
const gallery = document.getElementById('preview-gallery');
const placeholder = document.getElementById('gallery-empty');
if (placeholder) placeholder.remove();
const col = document.createElement('div');
col.className = 'col';
col.innerHTML = `<div class="position-relative preview-img-wrapper">
<img src="${imageUrl}" class="img-fluid rounded preview-img"
style="cursor: pointer; aspect-ratio: 1; object-fit: cover; width: 100%;"
data-preview-path="${relativePath}"
title="${charName}">
${charName ? `<div class="position-absolute bottom-0 start-0 w-100 bg-dark bg-opacity-50 text-white p-1 rounded-bottom" style="font-size: 0.7rem; line-height: 1.2;">${charName}</div>` : ''}
</div>`;
gallery.insertBefore(col, gallery.firstChild);
// Add click handler for gallery navigation
const img = col.querySelector('.preview-img');
img.addEventListener('click', () => {
const allImages = Array.from(document.querySelectorAll('#preview-gallery .preview-img')).map(i => i.src);
const index = allImages.indexOf(imageUrl);
openGallery(allImages, index);
});
const badge = document.querySelector('#previews-tab .badge');
if (badge) badge.textContent = parseInt(badge.textContent || '0') + 1;
else document.getElementById('previews-tab').insertAdjacentHTML('beforeend', ' <span class="badge bg-secondary">1</span>');
}
generateAllBtn.addEventListener('click', async () => {
if (allCharacters.length === 0) { alert('No characters available.'); return; }
stopBatch = false;
generateAllBtn.disabled = true;
stopAllBtn.classList.remove('d-none');
batchProgress.classList.remove('d-none');
bootstrap.Tab.getOrCreateInstance(document.getElementById('previews-tab')).show();
const genForm = document.getElementById('generate-form');
const formAction = genForm.getAttribute('action');
batchLabel.textContent = 'Queuing all characters…';
const pending = [];
for (const char of allCharacters) {
if (stopBatch) break;
const fd = new FormData();
genForm.querySelectorAll('input[name="include_field"]:checked').forEach(cb => fd.append('include_field', cb.value));
fd.append('character_slug', char.slug);
fd.append('action', 'preview');
try {
const resp = await fetch(formAction, { method: 'POST', body: fd, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
const data = await resp.json();
if (!data.error) pending.push({ char, jobId: data.job_id });
} catch (err) { console.error(`Submit error for ${char.name}:`, err); }
}
batchBar.style.width = '0%';
let done = 0;
const total = pending.length;
batchLabel.textContent = `0 / ${total} complete`;
await Promise.all(pending.map(({ char, jobId }) =>
waitForJob(jobId).then(result => {
done++;
batchBar.style.width = `${Math.round((done / total) * 100)}%`;
batchLabel.textContent = `${done} / ${total} complete`;
if (result.result?.image_url) addToPreviewGallery(result.result.image_url, result.result.relative_path, char.name);
}).catch(err => { done++; console.error(`Failed for ${char.name}:`, err); })
));
batchBar.style.width = '100%';
batchLabel.textContent = stopBatch ? 'Stopped.' : 'Complete!';
generateAllBtn.disabled = false;
stopAllBtn.classList.add('d-none');
setTimeout(() => { batchProgress.classList.add('d-none'); batchBar.style.width = '0%'; }, 3000);
});
stopAllBtn.addEventListener('click', () => {
stopBatch = true;
stopAllBtn.classList.add('d-none');
batchLabel.textContent = 'Stopping…';
});
initJsonEditor('{{ url_for("save_action_json", slug=action.slug) }}');
// Register preview gallery for navigation
registerGallery('#preview-gallery', '.preview-img');
});
</script>
{% endblock %}