import json import os import re import time import logging from flask import render_template, request, redirect, url_for, flash, session, current_app from werkzeug.utils import secure_filename from sqlalchemy.orm.attributes import flag_modified from models import db, Character, Detailer, Action, Outfit, Style, Scene, Checkpoint, Settings, Look from services.workflow import _prepare_workflow, _get_default_checkpoint from services.job_queue import _enqueue_job, _make_finalize from services.prompts import build_prompt, _resolve_character, _ensure_character_fields, _append_background from services.sync import sync_detailers 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 logger = logging.getLogger('gaze') def register_routes(app): def _queue_detailer_generation(detailer_obj, character=None, selected_fields=None, client_id=None, action=None, extra_positive=None, extra_negative=None, fixed_seed=None): if character: combined_data = character.data.copy() combined_data['character_id'] = character.character_id # Merge detailer prompt into character's tags detailer_prompt = detailer_obj.data.get('prompt', '') if detailer_prompt: if 'tags' not in combined_data: combined_data['tags'] = [] combined_data['tags'].append(detailer_prompt) # Merge detailer lora triggers if present detailer_lora = detailer_obj.data.get('lora', {}) if detailer_lora.get('lora_triggers'): if 'lora' not in combined_data: combined_data['lora'] = {} combined_data['lora']['lora_triggers'] = f"{combined_data['lora'].get('lora_triggers', '')}, {detailer_lora['lora_triggers']}" # Merge character identity and wardrobe fields into selected_fields if selected_fields: _ensure_character_fields(character, selected_fields) else: # Auto-include essential character fields (minimal set for batch/default generation) selected_fields = [] for key in ['base', 'head']: if character.data.get('identity', {}).get(key): selected_fields.append(f'identity::{key}') selected_fields.append('special::name') wardrobe = character.get_active_wardrobe() for key in _WARDROBE_KEYS: if wardrobe.get(key): selected_fields.append(f'wardrobe::{key}') selected_fields.extend(['special::tags', 'lora::lora_triggers']) default_fields = detailer_obj.default_fields active_outfit = character.active_outfit else: # Detailer only - no character detailer_prompt = detailer_obj.data.get('prompt', '') detailer_tags = [detailer_prompt] if detailer_prompt else [] combined_data = { 'character_id': detailer_obj.detailer_id, 'tags': detailer_tags, 'lora': detailer_obj.data.get('lora', {}), } if not selected_fields: selected_fields = ['special::tags', 'lora::lora_triggers'] default_fields = detailer_obj.default_fields active_outfit = 'default' with open('comfy_workflow.json', 'r') as f: workflow = json.load(f) prompts = build_prompt(combined_data, selected_fields, default_fields, active_outfit=active_outfit) _append_background(prompts, character) if extra_positive: prompts["main"] = f"{prompts['main']}, {extra_positive}" ckpt_path, ckpt_data = _get_default_checkpoint() workflow = _prepare_workflow(workflow, character, prompts, detailer=detailer_obj, action=action, custom_negative=extra_negative or None, checkpoint=ckpt_path, checkpoint_data=ckpt_data, fixed_seed=fixed_seed) return workflow @app.route('/detailers') def detailers_index(): detailers = Detailer.query.order_by(Detailer.name).all() return render_template('detailers/index.html', detailers=detailers) @app.route('/detailers/rescan', methods=['POST']) def rescan_detailers(): sync_detailers() flash('Database synced with detailer files.') return redirect(url_for('detailers_index')) @app.route('/detailer/') def detailer_detail(slug): detailer = Detailer.query.filter_by(slug=slug).first_or_404() characters = Character.query.order_by(Character.name).all() actions = Action.query.order_by(Action.name).all() # Load state from session preferences = session.get(f'prefs_detailer_{slug}') preview_image = session.get(f'preview_detailer_{slug}') selected_character = session.get(f'char_detailer_{slug}') selected_action = session.get(f'action_detailer_{slug}') extra_positive = session.get(f'extra_pos_detailer_{slug}', '') extra_negative = session.get(f'extra_neg_detailer_{slug}', '') # List existing preview images upload_dir = os.path.join(app.config['UPLOAD_FOLDER'], f"detailers/{slug}") existing_previews = [] if os.path.isdir(upload_dir): files = sorted([f for f in os.listdir(upload_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))], reverse=True) existing_previews = [f"detailers/{slug}/{f}" for f in files] return render_template('detailers/detail.html', detailer=detailer, characters=characters, actions=actions, preferences=preferences, preview_image=preview_image, selected_character=selected_character, selected_action=selected_action, extra_positive=extra_positive, extra_negative=extra_negative, existing_previews=existing_previews) @app.route('/detailer//edit', methods=['GET', 'POST']) def edit_detailer(slug): detailer = Detailer.query.filter_by(slug=slug).first_or_404() loras = get_available_loras('detailers') if request.method == 'POST': try: # 1. Update basic fields detailer.name = request.form.get('detailer_name') # 2. Rebuild the data dictionary new_data = detailer.data.copy() new_data['detailer_name'] = detailer.name # Update prompt (stored as a plain string) new_data['prompt'] = request.form.get('detailer_prompt', '') # Update lora section if 'lora' in new_data: for key in new_data['lora'].keys(): form_key = f"lora_{key}" if form_key in request.form: val = request.form.get(form_key) if key == 'lora_weight': try: val = float(val) except: val = 1.0 new_data['lora'][key] = val # LoRA weight randomization bounds for bound in ['lora_weight_min', 'lora_weight_max']: val_str = request.form.get(f'lora_{bound}', '').strip() if val_str: try: new_data.setdefault('lora', {})[bound] = float(val_str) except ValueError: pass else: new_data.setdefault('lora', {}).pop(bound, None) # Update Tags (comma separated string to list) tags_raw = request.form.get('tags', '') new_data['tags'] = [t.strip() for t in tags_raw.split(',') if t.strip()] detailer.data = new_data flag_modified(detailer, "data") # 3. Write back to JSON file detailer_file = detailer.filename or f"{re.sub(r'[^a-zA-Z0-9_]', '', detailer.detailer_id)}.json" file_path = os.path.join(app.config['DETAILERS_DIR'], detailer_file) with open(file_path, 'w') as f: json.dump(new_data, f, indent=2) db.session.commit() flash('Detailer updated successfully!') return redirect(url_for('detailer_detail', slug=slug)) except Exception as e: print(f"Edit error: {e}") flash(f"Error saving changes: {str(e)}") return render_template('detailers/edit.html', detailer=detailer, loras=loras) @app.route('/detailer//upload', methods=['POST']) def upload_detailer_image(slug): detailer = Detailer.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 detailer subfolder detailer_folder = os.path.join(app.config['UPLOAD_FOLDER'], f"detailers/{slug}") os.makedirs(detailer_folder, exist_ok=True) filename = secure_filename(file.filename) file_path = os.path.join(detailer_folder, filename) file.save(file_path) # Store relative path in DB detailer.image_path = f"detailers/{slug}/{filename}" db.session.commit() flash('Image uploaded successfully!') return redirect(url_for('detailer_detail', slug=slug)) @app.route('/detailer//generate', methods=['POST']) def generate_detailer_image(slug): detailer_obj = Detailer.query.filter_by(slug=slug).first_or_404() try: # Get action type action = request.form.get('action', 'preview') # Get selected fields selected_fields = request.form.getlist('include_field') # Get selected character (if any) character_slug = request.form.get('character_slug', '') character = _resolve_character(character_slug) if character_slug == '__random__' and character: character_slug = character.slug # Get selected action (if any) action_slug = request.form.get('action_slug', '') action_obj = Action.query.filter_by(slug=action_slug).first() if action_slug else None # Get additional prompts extra_positive = request.form.get('extra_positive', '').strip() extra_negative = request.form.get('extra_negative', '').strip() # Save preferences session[f'char_detailer_{slug}'] = character_slug session[f'action_detailer_{slug}'] = action_slug session[f'extra_pos_detailer_{slug}'] = extra_positive session[f'extra_neg_detailer_{slug}'] = extra_negative session[f'prefs_detailer_{slug}'] = selected_fields session.modified = True # Parse optional seed seed_val = request.form.get('seed', '').strip() fixed_seed = int(seed_val) if seed_val else None # Build workflow using helper workflow = _queue_detailer_generation(detailer_obj, character, selected_fields, action=action_obj, extra_positive=extra_positive, extra_negative=extra_negative, fixed_seed=fixed_seed) char_label = character.name if character else 'no character' label = f"Detailer: {detailer_obj.name} ({char_label}) – {action}" job = _enqueue_job(label, workflow, _make_finalize('detailers', slug, Detailer, action)) if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return {'status': 'queued', 'job_id': job['id']} return redirect(url_for('detailer_detail', slug=slug)) except Exception as e: print(f"Generation error: {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('detailer_detail', slug=slug)) @app.route('/detailer//save_defaults', methods=['POST']) def save_detailer_defaults(slug): detailer = Detailer.query.filter_by(slug=slug).first_or_404() selected_fields = request.form.getlist('include_field') detailer.default_fields = selected_fields db.session.commit() flash('Default prompt selection saved for this detailer!') return redirect(url_for('detailer_detail', slug=slug)) @app.route('/detailer//replace_cover_from_preview', methods=['POST']) def replace_detailer_cover_from_preview(slug): detailer = Detailer.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)): detailer.image_path = preview_path db.session.commit() flash('Cover image updated!') else: flash('No valid preview image selected.', 'error') return redirect(url_for('detailer_detail', slug=slug)) @app.route('/detailer//save_json', methods=['POST']) def save_detailer_json(slug): detailer = Detailer.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 detailer.data = new_data flag_modified(detailer, 'data') db.session.commit() if detailer.filename: file_path = os.path.join(app.config['DETAILERS_DIR'], detailer.filename) with open(file_path, 'w') as f: json.dump(new_data, f, indent=2) return {'success': True} @app.route('/detailers/bulk_create', methods=['POST']) def bulk_create_detailers_from_loras(): _s = Settings.query.first() detailers_lora_dir = ((_s.lora_dir_detailers if _s else None) or '/ImageModels/lora/Illustrious/Detailers').rstrip('/') _lora_subfolder = os.path.basename(detailers_lora_dir) if not os.path.exists(detailers_lora_dir): flash('Detailers LoRA directory not found.', 'error') return redirect(url_for('detailers_index')) overwrite = request.form.get('overwrite') == 'true' created_count = 0 skipped_count = 0 overwritten_count = 0 system_prompt = load_prompt('detailer_system.txt') if not system_prompt: flash('Detailer system prompt file not found.', 'error') return redirect(url_for('detailers_index')) for filename in os.listdir(detailers_lora_dir): if filename.endswith('.safetensors'): name_base = filename.rsplit('.', 1)[0] detailer_id = re.sub(r'[^a-zA-Z0-9_]', '_', name_base.lower()) detailer_name = re.sub(r'[^a-zA-Z0-9]+', ' ', name_base).title() json_filename = f"{detailer_id}.json" json_path = os.path.join(app.config['DETAILERS_DIR'], json_filename) is_existing = os.path.exists(json_path) if is_existing and not overwrite: skipped_count += 1 continue html_filename = f"{name_base}.html" html_path = os.path.join(detailers_lora_dir, html_filename) html_content = "" if os.path.exists(html_path): try: with open(html_path, 'r', encoding='utf-8', errors='ignore') as hf: html_raw = hf.read() clean_html = re.sub(r']*>.*?', '', html_raw, flags=re.DOTALL) clean_html = re.sub(r']*>.*?', '', clean_html, flags=re.DOTALL) clean_html = re.sub(r']*>', '', clean_html) clean_html = re.sub(r'<[^>]+>', ' ', clean_html) html_content = ' '.join(clean_html.split()) except Exception as e: print(f"Error reading HTML {html_filename}: {e}") try: print(f"Asking LLM to describe detailer: {detailer_name}") prompt = f"Describe a detailer LoRA for AI image generation based on the filename: '{filename}'" if html_content: prompt += f"\n\nHere is descriptive text and metadata extracted from an associated HTML file for this LoRA:\n###\n{html_content[:3000]}\n###" llm_response = call_llm(prompt, system_prompt) clean_json = llm_response.replace('```json', '').replace('```', '').strip() detailer_data = json.loads(clean_json) detailer_data['detailer_id'] = detailer_id detailer_data['detailer_name'] = detailer_name if 'lora' not in detailer_data: detailer_data['lora'] = {} detailer_data['lora']['lora_name'] = f"Illustrious/{_lora_subfolder}/{filename}" if not detailer_data['lora'].get('lora_triggers'): detailer_data['lora']['lora_triggers'] = name_base if detailer_data['lora'].get('lora_weight') is None: detailer_data['lora']['lora_weight'] = 1.0 if detailer_data['lora'].get('lora_weight_min') is None: detailer_data['lora']['lora_weight_min'] = 0.7 if detailer_data['lora'].get('lora_weight_max') is None: detailer_data['lora']['lora_weight_max'] = 1.0 with open(json_path, 'w') as f: json.dump(detailer_data, f, indent=2) if is_existing: overwritten_count += 1 else: created_count += 1 # Small delay to avoid API rate limits if many files time.sleep(0.5) except Exception as e: print(f"Error creating detailer for {filename}: {e}") if created_count > 0 or overwritten_count > 0: sync_detailers() msg = f'Successfully processed detailers: {created_count} created, {overwritten_count} overwritten.' if skipped_count > 0: msg += f' (Skipped {skipped_count} existing)' flash(msg) else: flash(f'No new detailers created or overwritten. {skipped_count} existing detailers found.') return redirect(url_for('detailers_index')) @app.route('/detailer/create', methods=['GET', 'POST']) def create_detailer(): if request.method == 'POST': name = request.form.get('name') slug = request.form.get('filename', '').strip() if not slug: slug = re.sub(r'[^a-zA-Z0-9]+', '_', name.lower()).strip('_') safe_slug = re.sub(r'[^a-zA-Z0-9_]', '', slug) if not safe_slug: safe_slug = 'detailer' base_slug = safe_slug counter = 1 while os.path.exists(os.path.join(app.config['DETAILERS_DIR'], f"{safe_slug}.json")): safe_slug = f"{base_slug}_{counter}" counter += 1 detailer_data = { "detailer_id": safe_slug, "detailer_name": name, "prompt": "", "lora": { "lora_name": "", "lora_weight": 1.0, "lora_triggers": "" } } try: file_path = os.path.join(app.config['DETAILERS_DIR'], f"{safe_slug}.json") with open(file_path, 'w') as f: json.dump(detailer_data, f, indent=2) new_detailer = Detailer( detailer_id=safe_slug, slug=safe_slug, filename=f"{safe_slug}.json", name=name, data=detailer_data ) db.session.add(new_detailer) db.session.commit() flash('Detailer created successfully!') return redirect(url_for('detailer_detail', slug=safe_slug)) except Exception as e: print(f"Save error: {e}") flash(f"Failed to create detailer: {e}") return redirect(request.url) return render_template('detailers/create.html')