feat: Auto-initialize config files for zero-config Docker deployment

This commit is contained in:
Khoa.vo 2025-12-30 19:38:17 +07:00
parent ad9586b7fb
commit 9d81329194

53
app.py
View file

@ -111,7 +111,7 @@ def save_preview_image(preview_dir, extension='.png', source_bytes=None, source_
return None return None
FAVORITES_FILE = os.path.join(os.path.dirname(__file__), 'template_favorites.json') FAVORITES_FILE = get_config_path('template_favorites.json')
def load_template_favorites(): def load_template_favorites():
if os.path.exists(FAVORITES_FILE): if os.path.exists(FAVORITES_FILE):
@ -131,7 +131,7 @@ def save_template_favorites(favorites):
except Exception as e: except Exception as e:
print(f"Failed to persist template favorites: {e}") print(f"Failed to persist template favorites: {e}")
GALLERY_FAVORITES_FILE = os.path.join(os.path.dirname(__file__), 'gallery_favorites.json') GALLERY_FAVORITES_FILE = get_config_path('gallery_favorites.json')
def load_gallery_favorites(): def load_gallery_favorites():
if os.path.exists(GALLERY_FAVORITES_FILE): if os.path.exists(GALLERY_FAVORITES_FILE):
@ -196,6 +196,34 @@ UPLOADS_DIR = os.path.join(app.static_folder, 'uploads')
os.makedirs(UPLOADS_DIR, exist_ok=True) os.makedirs(UPLOADS_DIR, exist_ok=True)
ALLOWED_GALLERY_EXTS = ('.png', '.jpg', '.jpeg', '.webp') ALLOWED_GALLERY_EXTS = ('.png', '.jpg', '.jpeg', '.webp')
# Configuration Directory Setup
CONFIG_DIR = os.environ.get('CONFIG_DIR', os.path.dirname(__file__))
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR, exist_ok=True)
def get_config_path(filename):
return os.path.join(CONFIG_DIR, filename)
def initialize_config_files():
"""Copy default config files to CONFIG_DIR if they don't exist."""
defaults = ['prompts.json', 'user_prompts.json', 'gallery_favorites.json']
source_dir = os.path.dirname(__file__)
for filename in defaults:
dest_path = get_config_path(filename)
if not os.path.exists(dest_path):
source_path = os.path.join(source_dir, filename)
if os.path.exists(source_path):
print(f"Initializing {filename} in {CONFIG_DIR}...", flush=True)
try:
import shutil
shutil.copy2(source_path, dest_path)
except Exception as e:
print(f"Error initializing {filename}: {e}", flush=True)
# Run initialization on startup
initialize_config_files()
def normalize_gallery_path(path): def normalize_gallery_path(path):
"""Return a clean path relative to /static without traversal.""" """Return a clean path relative to /static without traversal."""
@ -734,23 +762,6 @@ def delete_image():
try: try:
send2trash(filepath) send2trash(filepath)
# Clean up favorites entry if it exists
favorites = load_gallery_favorites()
cleaned_favorites = [
item for item in favorites
if item != storage_key and item != os.path.basename(filepath)
]
if cleaned_favorites != favorites:
save_gallery_favorites(cleaned_favorites)
return jsonify({'success': True, 'source': resolved_source})
except Exception as e:
return jsonify({'error': str(e)}), 500
else:
return jsonify({'error': 'File not found'}), 404
@app.route('/gallery')
def get_gallery():
# List all images in the chosen source directory, sorted by modification time (newest first) # List all images in the chosen source directory, sorted by modification time (newest first)
source_param = (request.args.get('source') or 'generated').lower() source_param = (request.args.get('source') or 'generated').lower()
base_dir = UPLOADS_DIR if source_param == 'uploads' else GENERATED_DIR base_dir = UPLOADS_DIR if source_param == 'uploads' else GENERATED_DIR
@ -775,7 +786,7 @@ def get_prompts():
all_prompts = [] all_prompts = []
# Read prompts.json file # Read prompts.json file
prompts_path = os.path.join(os.path.dirname(__file__), 'prompts.json') prompts_path = get_config_path('prompts.json')
if os.path.exists(prompts_path): if os.path.exists(prompts_path):
with open(prompts_path, 'r', encoding='utf-8') as f: with open(prompts_path, 'r', encoding='utf-8') as f:
try: try:
@ -789,7 +800,7 @@ def get_prompts():
pass pass
# Read user_prompts.json file and mark as user templates # Read user_prompts.json file and mark as user templates
user_prompts_path = os.path.join(os.path.dirname(__file__), 'user_prompts.json') user_prompts_path = get_config_path('user_prompts.json')
if os.path.exists(user_prompts_path): if os.path.exists(user_prompts_path):
try: try:
with open(user_prompts_path, 'r', encoding='utf-8') as f: with open(user_prompts_path, 'r', encoding='utf-8') as f: