Major refactor: deduplicate routes, sync, JS, and fix bugs
- Extract 8 common route patterns into factory functions in routes/shared.py (favourite, upload, replace cover, save defaults, clone, save JSON, get missing, clear covers) — removes ~1,100 lines across 9 route files - Extract generic _sync_category() in sync.py — 7 sync functions become one-liner wrappers, removing ~350 lines - Extract shared detail page JS into static/js/detail-common.js — all 9 detail templates now call initDetailPage() with minimal config - Extract layout inline JS into static/js/layout-utils.js (~185 lines) - Extract library toolbar JS into static/js/library-toolbar.js - Fix finalize missing-image bug: raise RuntimeError instead of logging warning so job is marked failed - Fix missing scheduler default in _default_checkpoint_data() - Fix N+1 query in Character.get_available_outfits() with batch IN query - Convert all print() to logger across services and routes - Add missing tags display to styles, scenes, detailers, checkpoints detail - Update delete buttons to use trash.png icon with solid red background - Update CLAUDE.md to reflect new architecture Net reduction: ~1,600 lines Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
145
routes/scenes.py
145
routes/scenes.py
@@ -3,36 +3,24 @@ import os
|
||||
import re
|
||||
import logging
|
||||
|
||||
from flask import render_template, request, redirect, url_for, flash, session, current_app
|
||||
from werkzeug.utils import secure_filename
|
||||
from flask import render_template, request, redirect, url_for, flash, session
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from models import db, Character, Scene, Outfit, Action, Style, Detailer, Checkpoint, Settings, Look
|
||||
from models import db, Character, Scene, Settings
|
||||
from services.workflow import _prepare_workflow, _get_default_checkpoint
|
||||
from services.job_queue import _enqueue_job, _make_finalize, _enqueue_task
|
||||
from services.prompts import build_prompt, _resolve_character, _ensure_character_fields, _append_background
|
||||
from services.prompts import build_prompt, _resolve_character, _ensure_character_fields
|
||||
from services.sync import sync_scenes
|
||||
from services.file_io import get_available_loras
|
||||
from services.llm import load_prompt, call_llm
|
||||
from utils import allowed_file, _LORA_DEFAULTS, _WARDROBE_KEYS
|
||||
from routes.shared import register_common_routes
|
||||
from utils import _WARDROBE_KEYS
|
||||
|
||||
logger = logging.getLogger('gaze')
|
||||
|
||||
|
||||
def register_routes(app):
|
||||
|
||||
@app.route('/get_missing_scenes')
|
||||
def get_missing_scenes():
|
||||
missing = Scene.query.filter((Scene.image_path == None) | (Scene.image_path == '')).order_by(Scene.name).all()
|
||||
return {'missing': [{'slug': s.slug, 'name': s.name} for s in missing]}
|
||||
|
||||
@app.route('/clear_all_scene_covers', methods=['POST'])
|
||||
def clear_all_scene_covers():
|
||||
scenes = Scene.query.all()
|
||||
for scene in scenes:
|
||||
scene.image_path = None
|
||||
db.session.commit()
|
||||
return {'success': True}
|
||||
register_common_routes(app, 'scenes')
|
||||
|
||||
@app.route('/scenes')
|
||||
def scenes_index():
|
||||
@@ -147,40 +135,11 @@ def register_routes(app):
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
except Exception as e:
|
||||
print(f"Edit error: {e}")
|
||||
logger.exception("Edit error: %s", e)
|
||||
flash(f"Error saving changes: {str(e)}")
|
||||
|
||||
return render_template('scenes/edit.html', scene=scene, loras=loras)
|
||||
|
||||
@app.route('/scene/<path:slug>/upload', methods=['POST'])
|
||||
def upload_scene_image(slug):
|
||||
scene = Scene.query.filter_by(slug=slug).first_or_404()
|
||||
|
||||
if 'image' not in request.files:
|
||||
flash('No file part')
|
||||
return redirect(request.url)
|
||||
|
||||
file = request.files['image']
|
||||
if file.filename == '':
|
||||
flash('No selected file')
|
||||
return redirect(request.url)
|
||||
|
||||
if file and allowed_file(file.filename):
|
||||
# Create scene subfolder
|
||||
scene_folder = os.path.join(app.config['UPLOAD_FOLDER'], f"scenes/{slug}")
|
||||
os.makedirs(scene_folder, exist_ok=True)
|
||||
|
||||
filename = secure_filename(file.filename)
|
||||
file_path = os.path.join(scene_folder, filename)
|
||||
file.save(file_path)
|
||||
|
||||
# Store relative path in DB
|
||||
scene.image_path = f"scenes/{slug}/{filename}"
|
||||
db.session.commit()
|
||||
flash('Image uploaded successfully!')
|
||||
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
def _queue_scene_generation(scene_obj, character=None, selected_fields=None, client_id=None, fixed_seed=None, extra_positive=None, extra_negative=None):
|
||||
if character:
|
||||
combined_data = character.data.copy()
|
||||
@@ -306,33 +265,12 @@ def register_routes(app):
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
except Exception as e:
|
||||
print(f"Generation error: {e}")
|
||||
logger.exception("Generation error: %s", e)
|
||||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||||
return {'error': str(e)}, 500
|
||||
flash(f"Error during generation: {str(e)}")
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
@app.route('/scene/<path:slug>/save_defaults', methods=['POST'])
|
||||
def save_scene_defaults(slug):
|
||||
scene = Scene.query.filter_by(slug=slug).first_or_404()
|
||||
selected_fields = request.form.getlist('include_field')
|
||||
scene.default_fields = selected_fields
|
||||
db.session.commit()
|
||||
flash('Default prompt selection saved for this scene!')
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
@app.route('/scene/<path:slug>/replace_cover_from_preview', methods=['POST'])
|
||||
def replace_scene_cover_from_preview(slug):
|
||||
scene = Scene.query.filter_by(slug=slug).first_or_404()
|
||||
preview_path = request.form.get('preview_path')
|
||||
if preview_path and os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], preview_path)):
|
||||
scene.image_path = preview_path
|
||||
db.session.commit()
|
||||
flash('Cover image updated!')
|
||||
else:
|
||||
flash('No valid preview image selected.', 'error')
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
@app.route('/scenes/bulk_create', methods=['POST'])
|
||||
def bulk_create_scenes_from_loras():
|
||||
_s = Settings.query.first()
|
||||
@@ -483,74 +421,9 @@ def register_routes(app):
|
||||
flash('Scene created successfully!')
|
||||
return redirect(url_for('scene_detail', slug=safe_slug))
|
||||
except Exception as e:
|
||||
print(f"Save error: {e}")
|
||||
logger.exception("Save error: %s", e)
|
||||
flash(f"Failed to create scene: {e}")
|
||||
return render_template('scenes/create.html', form_data=form_data)
|
||||
|
||||
return render_template('scenes/create.html', form_data=form_data)
|
||||
|
||||
@app.route('/scene/<path:slug>/clone', methods=['POST'])
|
||||
def clone_scene(slug):
|
||||
scene = Scene.query.filter_by(slug=slug).first_or_404()
|
||||
|
||||
base_id = scene.scene_id
|
||||
import re
|
||||
match = re.match(r'^(.+?)_(\d+)$', base_id)
|
||||
if match:
|
||||
base_name = match.group(1)
|
||||
current_num = int(match.group(2))
|
||||
else:
|
||||
base_name = base_id
|
||||
current_num = 1
|
||||
|
||||
next_num = current_num + 1
|
||||
while True:
|
||||
new_id = f"{base_name}_{next_num:02d}"
|
||||
new_filename = f"{new_id}.json"
|
||||
new_path = os.path.join(app.config['SCENES_DIR'], new_filename)
|
||||
if not os.path.exists(new_path):
|
||||
break
|
||||
next_num += 1
|
||||
|
||||
new_data = scene.data.copy()
|
||||
new_data['scene_id'] = new_id
|
||||
new_data['scene_name'] = f"{scene.name} (Copy)"
|
||||
|
||||
with open(new_path, 'w') as f:
|
||||
json.dump(new_data, f, indent=2)
|
||||
|
||||
new_slug = re.sub(r'[^a-zA-Z0-9_]', '', new_id)
|
||||
new_scene = Scene(
|
||||
scene_id=new_id, slug=new_slug, filename=new_filename,
|
||||
name=new_data['scene_name'], data=new_data
|
||||
)
|
||||
db.session.add(new_scene)
|
||||
db.session.commit()
|
||||
|
||||
flash(f'Scene cloned as "{new_id}"!')
|
||||
return redirect(url_for('scene_detail', slug=new_slug))
|
||||
|
||||
@app.route('/scene/<path:slug>/save_json', methods=['POST'])
|
||||
def save_scene_json(slug):
|
||||
scene = Scene.query.filter_by(slug=slug).first_or_404()
|
||||
try:
|
||||
new_data = json.loads(request.form.get('json_data', ''))
|
||||
except (ValueError, TypeError) as e:
|
||||
return {'success': False, 'error': f'Invalid JSON: {e}'}, 400
|
||||
scene.data = new_data
|
||||
flag_modified(scene, 'data')
|
||||
db.session.commit()
|
||||
if scene.filename:
|
||||
file_path = os.path.join(app.config['SCENES_DIR'], scene.filename)
|
||||
with open(file_path, 'w') as f:
|
||||
json.dump(new_data, f, indent=2)
|
||||
return {'success': True}
|
||||
|
||||
@app.route('/scene/<path:slug>/favourite', methods=['POST'])
|
||||
def toggle_scene_favourite(slug):
|
||||
scene = Scene.query.filter_by(slug=slug).first_or_404()
|
||||
scene.is_favourite = not scene.is_favourite
|
||||
db.session.commit()
|
||||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||||
return {'success': True, 'is_favourite': scene.is_favourite}
|
||||
return redirect(url_for('scene_detail', slug=slug))
|
||||
|
||||
Reference in New Issue
Block a user