Julian Bilcke commited on
Commit
5f4445f
·
1 Parent(s): 7203e08

rethinking this project to be Gradio+API+PDF based

Browse files
Files changed (5) hide show
  1. CLAUDE.md +92 -0
  2. app.py +546 -24
  3. page_layouts.yaml +127 -0
  4. requirements.txt +4 -1
  5. style_presets.yaml +221 -0
CLAUDE.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ This is a Gradio application for image generation using the Qwen-Image model with Lightning LoRA acceleration. It's designed to run on Hugging Face Spaces with GPU support, providing fast 8-step image generation with advanced text rendering capabilities.
8
+
9
+ ## Commands
10
+
11
+ ### Run the application locally
12
+ ```bash
13
+ python app.py
14
+ ```
15
+
16
+ ### Install dependencies
17
+ ```bash
18
+ pip install -r requirements.txt
19
+ ```
20
+
21
+ ## Architecture
22
+
23
+ ### Core Components
24
+
25
+ 1. **Model Pipeline** (`app.py:130-164`)
26
+ - Uses `Qwen/Qwen-Image` diffusion model with custom FlowMatchEulerDiscreteScheduler
27
+ - Loads Lightning LoRA weights for 8-step acceleration
28
+ - Configured for bfloat16 precision on CUDA
29
+
30
+ 2. **Prompt Enhancement System** (`app.py:41-125`)
31
+ - `polish_prompt()`: Uses Hugging Face InferenceClient with Cerebras provider to enhance prompts
32
+ - `get_caption_language()`: Detects Chinese vs English prompts
33
+ - `rewrite()`: Language-specific prompt enhancement with different system prompts for Chinese/English
34
+ - Requires `HF_TOKEN` environment variable for API access
35
+
36
+ 3. **Style Presets System** (`app.py:16-87`)
37
+ - `load_style_presets()`: Loads style presets from `style_presets.yaml`
38
+ - `apply_style_preset()`: Applies selected style to prompts
39
+ - Supports custom styles and random style selection
40
+ - Each preset includes prefix, suffix, and negative prompt components
41
+
42
+ 4. **Page Layouts System** (`app.py:89-111`)
43
+ - `load_page_layouts()`: Loads multi-image layouts from `page_layouts.yaml`
44
+ - Supports 1-4 images per page with various layout configurations
45
+ - Dynamic layout selection based on number of images
46
+
47
+ 5. **PDF Generation** (`app.py:166-223`)
48
+ - `create_pdf_with_layout()`: Creates PDF with multiple images in selected layout
49
+ - Uses ReportLab for high-quality PDF generation
50
+ - Preserves image quality at 95% JPEG compression
51
+ - A4 page size with flexible positioning system
52
+
53
+ 6. **Multi-Image Generation** (`app.py:225-307`)
54
+ - `infer_multiple()`: Generates multiple images and combines into PDF
55
+ - Progressive generation with status updates
56
+ - Seed management for reproducibility across multiple images
57
+ - Returns PDF file, preview image, and seed information
58
+
59
+ 7. **Gradio Interface** (`app.py:380-500+`)
60
+ - Slider for selecting 1-4 images per page
61
+ - Dynamic layout dropdown that updates based on image count
62
+ - Style preset dropdown with custom style text option
63
+ - PDF download and image preview outputs
64
+ - Advanced settings for all generation parameters
65
+
66
+ ## Key Configuration
67
+
68
+ - **Scheduler Config** (`app.py:133-148`): Custom configuration for FlowMatchEulerDiscreteScheduler with exponential time shifting
69
+ - **Aspect Ratios** (`app.py:170-188`): Predefined aspect ratios optimized for 1024 base resolution
70
+ - **Style Presets** (`style_presets.yaml`): Configurable style presets with prompt modifiers and negative prompts
71
+ - **Page Layouts** (`page_layouts.yaml`): Flexible layout system for 1-4 images per page
72
+ - **Default Settings**: 8 inference steps, guidance scale 1.0, prompt enhancement enabled, 1 image per page
73
+
74
+ ## Environment Variables
75
+
76
+ - `HF_TOKEN`: Required for prompt enhancement via Hugging Face InferenceClient
77
+ - Used for accessing Cerebras provider for Qwen3-235B model
78
+
79
+ ## Key Features
80
+
81
+ - **Session-based storage**: Each user session gets a unique temporary directory that persists for 24 hours
82
+ - **Multi-page PDF generation**: Users can generate up to 128 pages in a single document
83
+ - **Dynamic page addition**: Click "Generate page N" to add the next page to the PDF
84
+ - **Flexible layouts**: Different layout options for 1-4 images per page
85
+ - **Style presets**: 20+ predefined artistic styles
86
+ - **Automatic cleanup**: Old sessions are automatically cleaned after 24 hours
87
+
88
+ ## Model Dependencies
89
+
90
+ - Main model: `Qwen/Qwen-Image`
91
+ - LoRA weights: `lightx2v/Qwen-Image-Lightning` (V1.1 safetensors)
92
+ - Prompt enhancement model: `Qwen/Qwen3-235B-A22B-Instruct-2507` via Cerebras
app.py CHANGED
@@ -5,10 +5,121 @@ import torch
5
  import spaces
6
  import math
7
  import os
 
 
 
 
 
 
 
 
 
 
8
 
9
  from PIL import Image
10
  from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler
11
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  # --- New Prompt Enhancement using Hugging Face InferenceClient ---
14
 
@@ -161,9 +272,209 @@ def get_image_size(aspect_ratio):
161
  # Default to 1:1 if something goes wrong
162
  return 1024, 1024
163
 
164
- # --- Main Inference Function (with hardcoded negative prompt) ---
165
- @spaces.GPU(duration=60)
166
- def infer(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  prompt,
168
  seed=42,
169
  randomize_seed=False,
@@ -171,7 +482,107 @@ def infer(
171
  guidance_scale=1.0,
172
  num_inference_steps=8,
173
  prompt_enhance=True,
 
 
 
 
 
174
  progress=gr.Progress(track_tqdm=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  ):
176
  """
177
  Generates an image based on a text prompt using the Qwen-Image-Lightning model.
@@ -181,42 +592,50 @@ def infer(
181
  seed (int): The seed for the random number generator for reproducibility.
182
  randomize_seed (bool): If True, a random seed is used.
183
  aspect_ratio (str): The desired aspect ratio of the output image.
184
- guidance_scale (float): Corresponds to `true_cfg_scale`. A higher value
185
- encourages the model to generate images that are more closely related
186
  to the prompt.
187
  num_inference_steps (int): The number of denoising steps.
188
- prompt_enhance (bool): If True, the prompt is rewritten by an external
189
  LLM to add more detail.
 
 
190
  progress (gr.Progress): A Gradio Progress object to track the generation
191
  progress in the UI.
192
 
193
  Returns:
194
- tuple[Image.Image, int]: A tuple containing the generated PIL Image and
195
  the integer seed used for the generation.
196
  """
197
- # Use a blank negative prompt as per the lightning model's recommendation
198
- negative_prompt = " "
199
-
200
  if randomize_seed:
201
  seed = random.randint(0, MAX_SEED)
202
 
203
  # Convert aspect ratio to width and height
204
  width, height = get_image_size(aspect_ratio)
205
-
206
  # Set up the generator for reproducibility
207
  generator = torch.Generator(device="cuda").manual_seed(seed)
208
-
209
- print(f"Calling pipeline with prompt: '{prompt}'")
 
 
 
 
 
 
210
  if prompt_enhance:
211
- prompt = rewrite(prompt)
212
-
213
- print(f"Actual Prompt: '{prompt}'")
 
 
 
214
  print(f"Negative Prompt: '{negative_prompt}'")
215
  print(f"Seed: {seed}, Size: {width}x{height}, Steps: {num_inference_steps}, True CFG Scale: {guidance_scale}")
216
 
217
  # Generate the image
218
  image = pipe(
219
- prompt=prompt,
220
  negative_prompt=negative_prompt,
221
  width=width,
222
  height=height,
@@ -227,6 +646,9 @@ def infer(
227
 
228
  return image, seed
229
 
 
 
 
230
  # --- Examples and UI Layout ---
231
  examples = [
232
  "A capybara wearing a suit holding a sign that reads Hello World",
@@ -254,6 +676,9 @@ css = """
254
  """
255
 
256
  with gr.Blocks(css=css) as demo:
 
 
 
257
  with gr.Column(elem_id="col-container"):
258
  gr.HTML("""
259
  <div id="logo-title">
@@ -269,9 +694,18 @@ with gr.Blocks(css=css) as demo:
269
  placeholder="Enter your prompt",
270
  container=False,
271
  )
272
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
273
 
274
- result = gr.Image(label="Result", show_label=False, type="pil")
 
 
 
 
 
 
 
275
 
276
  with gr.Accordion("Advanced Settings", open=False):
277
  seed = gr.Slider(
@@ -292,13 +726,48 @@ with gr.Blocks(css=css) as demo:
292
  )
293
  prompt_enhance = gr.Checkbox(label="Prompt Enhance", value=True)
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  with gr.Row():
296
  guidance_scale = gr.Slider(
297
  label="Guidance scale (True CFG Scale)",
298
  minimum=1.0,
299
  maximum=5.0,
300
  step=0.1,
301
- value=1.0,
302
  )
303
 
304
  num_inference_steps = gr.Slider(
@@ -309,11 +778,47 @@ with gr.Blocks(css=css) as demo:
309
  value=8,
310
  )
311
 
312
- gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
- gr.on(
 
315
  triggers=[run_button.click, prompt.submit],
316
- fn=infer,
317
  inputs=[
318
  prompt,
319
  seed,
@@ -322,8 +827,25 @@ with gr.Blocks(css=css) as demo:
322
  guidance_scale,
323
  num_inference_steps,
324
  prompt_enhance,
 
 
 
 
 
325
  ],
326
- outputs=[result, seed],
 
 
 
 
 
 
 
 
 
 
 
 
327
  )
328
 
329
  if __name__ == "__main__":
 
5
  import spaces
6
  import math
7
  import os
8
+ import yaml
9
+ import io
10
+ import tempfile
11
+ import shutil
12
+ import uuid
13
+ import time
14
+ import json
15
+ from typing import List, Tuple, Dict, Optional
16
+ from datetime import datetime, timedelta
17
+ from pathlib import Path
18
 
19
  from PIL import Image
20
  from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler
21
  from huggingface_hub import InferenceClient
22
+ from reportlab.lib.pagesizes import A4
23
+ from reportlab.pdfgen import canvas
24
+ from reportlab.pdfbase import pdfmetrics
25
+ from reportlab.lib.utils import ImageReader
26
+ from PyPDF2 import PdfReader, PdfWriter
27
+
28
+ # --- Style Presets Loading ---
29
+
30
+ def load_style_presets():
31
+ """Load style presets from YAML file."""
32
+ try:
33
+ with open('style_presets.yaml', 'r') as f:
34
+ data = yaml.safe_load(f)
35
+ # Filter only enabled presets
36
+ presets = {k: v for k, v in data['presets'].items() if v.get('enabled', True)}
37
+ return presets
38
+ except Exception as e:
39
+ print(f"Error loading style presets: {e}")
40
+ return {"no_style": {"id": "no_style", "label": "No style (custom)", "prompt_prefix": "", "prompt_suffix": "", "negative_prompt": ""}}
41
+
42
+ # Load presets at startup
43
+ STYLE_PRESETS = load_style_presets()
44
+
45
+ # --- Page Layouts Loading ---
46
+
47
+ def load_page_layouts():
48
+ """Load page layouts from YAML file."""
49
+ try:
50
+ with open('page_layouts.yaml', 'r') as f:
51
+ data = yaml.safe_load(f)
52
+ return data['layouts']
53
+ except Exception as e:
54
+ print(f"Error loading page layouts: {e}")
55
+ # Fallback to basic layouts
56
+ return {
57
+ 1: [{"id": "full_page", "label": "Full Page", "positions": [[0.05, 0.05, 0.9, 0.9]]}],
58
+ 2: [{"id": "horizontal_split", "label": "Horizontal Split", "positions": [[0.05, 0.05, 0.425, 0.9], [0.525, 0.05, 0.425, 0.9]]}],
59
+ 3: [{"id": "grid", "label": "Grid", "positions": [[0.05, 0.05, 0.283, 0.5], [0.358, 0.05, 0.283, 0.5], [0.666, 0.05, 0.283, 0.5]]}],
60
+ 4: [{"id": "grid_2x2", "label": "2x2 Grid", "positions": [[0.05, 0.05, 0.425, 0.425], [0.525, 0.05, 0.425, 0.425], [0.05, 0.525, 0.425, 0.425], [0.525, 0.525, 0.425, 0.425]]}]
61
+ }
62
+
63
+ # Load layouts at startup
64
+ PAGE_LAYOUTS = load_page_layouts()
65
+
66
+ def get_layout_choices(num_images: int) -> List[Tuple[str, str]]:
67
+ """Get available layout choices for a given number of images."""
68
+ key = f"{num_images}_image" if num_images == 1 else f"{num_images}_images"
69
+ if key in PAGE_LAYOUTS:
70
+ return [(layout["label"], layout["id"]) for layout in PAGE_LAYOUTS[key]]
71
+ return [("Default", "default")]
72
+
73
+ def get_random_style_preset():
74
+ """Get a random style preset (excluding 'no_style' and 'random')."""
75
+ eligible_keys = [k for k in STYLE_PRESETS.keys() if k not in ['no_style', 'random']]
76
+ if eligible_keys:
77
+ return random.choice(eligible_keys)
78
+ return 'no_style'
79
+
80
+ def apply_style_preset(prompt, style_preset_key, custom_style_text=""):
81
+ """
82
+ Apply style preset to the prompt.
83
+
84
+ Args:
85
+ prompt: The user's base prompt
86
+ style_preset_key: The key of the selected style preset
87
+ custom_style_text: Custom style text when 'no_style' is selected
88
+
89
+ Returns:
90
+ tuple: (styled_prompt, negative_prompt)
91
+ """
92
+ if style_preset_key == 'no_style':
93
+ # Use custom style text if provided
94
+ if custom_style_text and custom_style_text.strip():
95
+ styled_prompt = f"{custom_style_text}, {prompt}"
96
+ else:
97
+ styled_prompt = prompt
98
+ return styled_prompt, ""
99
+
100
+ if style_preset_key == 'random':
101
+ # Select a random style
102
+ style_preset_key = get_random_style_preset()
103
+
104
+ if style_preset_key in STYLE_PRESETS:
105
+ preset = STYLE_PRESETS[style_preset_key]
106
+ prefix = preset.get('prompt_prefix', '')
107
+ suffix = preset.get('prompt_suffix', '')
108
+ negative = preset.get('negative_prompt', '')
109
+
110
+ # Build the styled prompt
111
+ parts = []
112
+ if prefix:
113
+ parts.append(prefix)
114
+ parts.append(prompt)
115
+ if suffix:
116
+ parts.append(suffix)
117
+
118
+ styled_prompt = ', '.join(parts)
119
+ return styled_prompt, negative
120
+
121
+ # Fallback to original prompt if preset not found
122
+ return prompt, ""
123
 
124
  # --- New Prompt Enhancement using Hugging Face InferenceClient ---
125
 
 
272
  # Default to 1:1 if something goes wrong
273
  return 1024, 1024
274
 
275
+ # --- Session Management Functions ---
276
+
277
+ class SessionManager:
278
+ """Manages user session data and temporary file storage."""
279
+
280
+ def __init__(self, session_id: str = None):
281
+ self.session_id = session_id or str(uuid.uuid4())
282
+ self.base_dir = Path(tempfile.gettempdir()) / "gradio_comic_sessions"
283
+ self.session_dir = self.base_dir / self.session_id
284
+ self.session_dir.mkdir(parents=True, exist_ok=True)
285
+ self.metadata_file = self.session_dir / "metadata.json"
286
+ self.pdf_path = self.session_dir / "comic.pdf"
287
+ self.load_or_create_metadata()
288
+
289
+ def load_or_create_metadata(self):
290
+ """Load existing metadata or create new."""
291
+ if self.metadata_file.exists():
292
+ with open(self.metadata_file, 'r') as f:
293
+ self.metadata = json.load(f)
294
+ else:
295
+ self.metadata = {
296
+ "created_at": datetime.now().isoformat(),
297
+ "pages": [],
298
+ "total_pages": 0
299
+ }
300
+ self.save_metadata()
301
+
302
+ def save_metadata(self):
303
+ """Save metadata to file."""
304
+ with open(self.metadata_file, 'w') as f:
305
+ json.dump(self.metadata, f, indent=2)
306
+
307
+ def add_page(self, images: List[Image.Image], layout_id: str, seeds: List[int]):
308
+ """Add a new page to the session."""
309
+ page_num = self.metadata["total_pages"] + 1
310
+ page_dir = self.session_dir / f"page_{page_num}"
311
+ page_dir.mkdir(exist_ok=True)
312
+
313
+ # Save images
314
+ image_paths = []
315
+ for i, img in enumerate(images):
316
+ img_path = page_dir / f"image_{i+1}.jpg"
317
+ img.save(img_path, 'JPEG', quality=95)
318
+ image_paths.append(str(img_path))
319
+
320
+ # Update metadata
321
+ self.metadata["pages"].append({
322
+ "page_num": page_num,
323
+ "layout_id": layout_id,
324
+ "num_images": len(images),
325
+ "image_paths": image_paths,
326
+ "seeds": seeds,
327
+ "created_at": datetime.now().isoformat()
328
+ })
329
+ self.metadata["total_pages"] = page_num
330
+ self.save_metadata()
331
+
332
+ return page_num
333
+
334
+ def get_all_pages_images(self) -> List[Tuple[List[Image.Image], str, int]]:
335
+ """Get all images from all pages."""
336
+ pages_data = []
337
+ for page in self.metadata["pages"]:
338
+ images = []
339
+ for img_path in page["image_paths"]:
340
+ if Path(img_path).exists():
341
+ images.append(Image.open(img_path))
342
+ if images:
343
+ pages_data.append((images, page["layout_id"], page["num_images"]))
344
+ return pages_data
345
+
346
+ def cleanup_old_sessions(self, max_age_hours: int = 24):
347
+ """Clean up sessions older than max_age_hours."""
348
+ if not self.base_dir.exists():
349
+ return
350
+
351
+ cutoff_time = datetime.now() - timedelta(hours=max_age_hours)
352
+
353
+ for session_dir in self.base_dir.iterdir():
354
+ if session_dir.is_dir():
355
+ metadata_file = session_dir / "metadata.json"
356
+ if metadata_file.exists():
357
+ try:
358
+ with open(metadata_file, 'r') as f:
359
+ metadata = json.load(f)
360
+ created_at = datetime.fromisoformat(metadata["created_at"])
361
+ if created_at < cutoff_time:
362
+ shutil.rmtree(session_dir)
363
+ print(f"Cleaned up old session: {session_dir.name}")
364
+ except Exception as e:
365
+ print(f"Error cleaning session {session_dir.name}: {e}")
366
+
367
+ # --- PDF Generation Functions ---
368
+
369
+ def create_single_page_pdf(images: List[Image.Image], layout_id: str, num_images: int) -> bytes:
370
+ """
371
+ Create a single PDF page with images arranged according to the selected layout.
372
+
373
+ Args:
374
+ images: List of PIL images
375
+ layout_id: ID of the selected layout
376
+ num_images: Number of images to include
377
+
378
+ Returns:
379
+ PDF page as bytes
380
+ """
381
+ # Create a bytes buffer for the PDF
382
+ pdf_buffer = io.BytesIO()
383
+
384
+ # Create canvas with A4 size
385
+ pdf = canvas.Canvas(pdf_buffer, pagesize=A4)
386
+ page_width, page_height = A4
387
+
388
+ # Get the layout configuration
389
+ key = f"{num_images}_image" if num_images == 1 else f"{num_images}_images"
390
+ layouts = PAGE_LAYOUTS.get(key, [])
391
+ layout = next((l for l in layouts if l["id"] == layout_id), None)
392
+
393
+ if not layout:
394
+ # Fallback to default grid layout
395
+ if num_images == 1:
396
+ positions = [[0.05, 0.05, 0.9, 0.9]]
397
+ elif num_images == 2:
398
+ positions = [[0.05, 0.05, 0.425, 0.9], [0.525, 0.05, 0.425, 0.9]]
399
+ elif num_images == 3:
400
+ positions = [[0.05, 0.05, 0.283, 0.9], [0.358, 0.05, 0.283, 0.9], [0.666, 0.05, 0.283, 0.9]]
401
+ else:
402
+ positions = [[0.05, 0.05, 0.425, 0.425], [0.525, 0.05, 0.425, 0.425],
403
+ [0.05, 0.525, 0.425, 0.425], [0.525, 0.525, 0.425, 0.425]]
404
+ else:
405
+ positions = layout["positions"]
406
+
407
+ # Draw each image according to the layout
408
+ for i, (image, pos) in enumerate(zip(images[:num_images], positions)):
409
+ if i >= len(images):
410
+ break
411
+
412
+ x_rel, y_rel, w_rel, h_rel = pos
413
+
414
+ # Convert relative positions to absolute positions
415
+ # Note: In ReportLab, y=0 is at the bottom
416
+ x = x_rel * page_width
417
+ y = (1 - y_rel - h_rel) * page_height # Flip Y coordinate
418
+ width = w_rel * page_width
419
+ height = h_rel * page_height
420
+
421
+ # Convert PIL image to format suitable for ReportLab
422
+ img_buffer = io.BytesIO()
423
+ # Save with good quality
424
+ image.save(img_buffer, format='JPEG', quality=95)
425
+ img_buffer.seek(0)
426
+
427
+ # Draw the image on the PDF
428
+ pdf.drawImage(ImageReader(img_buffer), x, y, width=width, height=height, preserveAspectRatio=True)
429
+
430
+ # Save the PDF
431
+ pdf.save()
432
+
433
+ # Get the PDF bytes
434
+ pdf_buffer.seek(0)
435
+ pdf_bytes = pdf_buffer.read()
436
+
437
+ return pdf_bytes
438
+
439
+ def create_multi_page_pdf(session_manager: SessionManager) -> str:
440
+ """
441
+ Create a multi-page PDF from all pages in the session.
442
+
443
+ Args:
444
+ session_manager: SessionManager instance with page data
445
+
446
+ Returns:
447
+ Path to the created PDF file
448
+ """
449
+ pages_data = session_manager.get_all_pages_images()
450
+
451
+ if not pages_data:
452
+ return None
453
+
454
+ # Create PDF writer
455
+ pdf_writer = PdfWriter()
456
+
457
+ # Create each page
458
+ for images, layout_id, num_images in pages_data:
459
+ page_pdf_bytes = create_single_page_pdf(images, layout_id, num_images)
460
+
461
+ # Read the single page PDF
462
+ page_pdf_reader = PdfReader(io.BytesIO(page_pdf_bytes))
463
+
464
+ # Add the page to the writer
465
+ for page in page_pdf_reader.pages:
466
+ pdf_writer.add_page(page)
467
+
468
+ # Write to file
469
+ pdf_path = session_manager.pdf_path
470
+ with open(pdf_path, 'wb') as f:
471
+ pdf_writer.write(f)
472
+
473
+ return str(pdf_path)
474
+
475
+ # --- Main Inference Function (with session support) ---
476
+ @spaces.GPU(duration=120) # Increased duration for multiple images
477
+ def infer_page(
478
  prompt,
479
  seed=42,
480
  randomize_seed=False,
 
482
  guidance_scale=1.0,
483
  num_inference_steps=8,
484
  prompt_enhance=True,
485
+ style_preset="no_style",
486
+ custom_style_text="",
487
+ num_images=1,
488
+ layout="default",
489
+ session_state=None,
490
  progress=gr.Progress(track_tqdm=True),
491
+ ):
492
+ """
493
+ Generates images for a new page and adds them to the PDF.
494
+
495
+ Args:
496
+ prompt (str): The text prompt to generate images from.
497
+ seed (int): The seed for the random number generator for reproducibility.
498
+ randomize_seed (bool): If True, a random seed is used for each image.
499
+ aspect_ratio (str): The desired aspect ratio of the output images.
500
+ guidance_scale (float): Corresponds to `true_cfg_scale`.
501
+ num_inference_steps (int): The number of denoising steps.
502
+ prompt_enhance (bool): If True, the prompt is rewritten by an external LLM.
503
+ style_preset (str): The key of the style preset to apply.
504
+ custom_style_text (str): Custom style text when 'no_style' is selected.
505
+ num_images (int): Number of images to generate (1-4).
506
+ layout (str): The layout ID for arranging images in the PDF.
507
+ session_state: Current session state dictionary.
508
+ progress (gr.Progress): A Gradio Progress object to track generation.
509
+
510
+ Returns:
511
+ tuple: Updated session state, PDF path, preview image, page info, and updated button label.
512
+ """
513
+ # Initialize or retrieve session
514
+ if session_state is None or "session_id" not in session_state:
515
+ session_state = {"session_id": str(uuid.uuid4()), "page_count": 0}
516
+
517
+ session_manager = SessionManager(session_state["session_id"])
518
+
519
+ # Clean up old sessions periodically
520
+ if random.random() < 0.1: # 10% chance to cleanup on each request
521
+ session_manager.cleanup_old_sessions()
522
+
523
+ # Check page limit
524
+ if session_manager.metadata["total_pages"] >= 128:
525
+ return session_state, None, None, "Maximum page limit (128) reached!", f"Page limit reached"
526
+
527
+ generated_images = []
528
+ used_seeds = []
529
+
530
+ # Generate the requested number of images
531
+ for i in range(int(num_images)):
532
+ progress(i / num_images, f"Generating image {i+1} of {num_images} for page {session_manager.metadata['total_pages'] + 1}")
533
+
534
+ current_seed = seed + i if not randomize_seed else random.randint(0, MAX_SEED)
535
+
536
+ # Generate single image
537
+ image, used_seed = infer_single(
538
+ prompt=prompt,
539
+ seed=current_seed,
540
+ randomize_seed=False, # We handle randomization here
541
+ aspect_ratio=aspect_ratio,
542
+ guidance_scale=guidance_scale,
543
+ num_inference_steps=num_inference_steps,
544
+ prompt_enhance=prompt_enhance,
545
+ style_preset=style_preset,
546
+ custom_style_text=custom_style_text,
547
+ )
548
+
549
+ generated_images.append(image)
550
+ used_seeds.append(used_seed)
551
+
552
+ # Add page to session
553
+ progress(0.8, "Adding page to document...")
554
+ page_num = session_manager.add_page(generated_images, layout, used_seeds)
555
+
556
+ # Create multi-page PDF
557
+ progress(0.9, "Creating PDF...")
558
+ pdf_path = create_multi_page_pdf(session_manager)
559
+
560
+ progress(1.0, "Done!")
561
+
562
+ # Update session state
563
+ session_state["page_count"] = page_num
564
+
565
+ # Prepare page info
566
+ seeds_str = ", ".join(str(s) for s in used_seeds)
567
+ page_info = f"Page {page_num} added\nSeeds: {seeds_str}\nTotal pages: {page_num}"
568
+
569
+ # Next button label
570
+ next_page_num = page_num + 1
571
+ button_label = f"Generate page {next_page_num}" if next_page_num <= 128 else "Page limit reached"
572
+
573
+ return session_state, pdf_path, generated_images[0] if generated_images else None, page_info, button_label
574
+
575
+ # Rename the original infer function
576
+ def infer_single(
577
+ prompt,
578
+ seed=42,
579
+ randomize_seed=False,
580
+ aspect_ratio="1:1",
581
+ guidance_scale=1.0,
582
+ num_inference_steps=8,
583
+ prompt_enhance=True,
584
+ style_preset="no_style",
585
+ custom_style_text="",
586
  ):
587
  """
588
  Generates an image based on a text prompt using the Qwen-Image-Lightning model.
 
592
  seed (int): The seed for the random number generator for reproducibility.
593
  randomize_seed (bool): If True, a random seed is used.
594
  aspect_ratio (str): The desired aspect ratio of the output image.
595
+ guidance_scale (float): Corresponds to `true_cfg_scale`. A higher value
596
+ encourages the model to generate images that are more closely related
597
  to the prompt.
598
  num_inference_steps (int): The number of denoising steps.
599
+ prompt_enhance (bool): If True, the prompt is rewritten by an external
600
  LLM to add more detail.
601
+ style_preset (str): The key of the style preset to apply.
602
+ custom_style_text (str): Custom style text when 'no_style' is selected.
603
  progress (gr.Progress): A Gradio Progress object to track the generation
604
  progress in the UI.
605
 
606
  Returns:
607
+ tuple[Image.Image, int]: A tuple containing the generated PIL Image and
608
  the integer seed used for the generation.
609
  """
 
 
 
610
  if randomize_seed:
611
  seed = random.randint(0, MAX_SEED)
612
 
613
  # Convert aspect ratio to width and height
614
  width, height = get_image_size(aspect_ratio)
615
+
616
  # Set up the generator for reproducibility
617
  generator = torch.Generator(device="cuda").manual_seed(seed)
618
+
619
+ print(f"Original prompt: '{prompt}'")
620
+ print(f"Style preset: '{style_preset}'")
621
+
622
+ # Apply style preset first
623
+ styled_prompt, style_negative_prompt = apply_style_preset(prompt, style_preset, custom_style_text)
624
+
625
+ # Then apply prompt enhancement if enabled
626
  if prompt_enhance:
627
+ styled_prompt = rewrite(styled_prompt)
628
+
629
+ # Use style negative prompt if available, otherwise default
630
+ negative_prompt = style_negative_prompt if style_negative_prompt else " "
631
+
632
+ print(f"Final Prompt: '{styled_prompt}'")
633
  print(f"Negative Prompt: '{negative_prompt}'")
634
  print(f"Seed: {seed}, Size: {width}x{height}, Steps: {num_inference_steps}, True CFG Scale: {guidance_scale}")
635
 
636
  # Generate the image
637
  image = pipe(
638
+ prompt=styled_prompt,
639
  negative_prompt=negative_prompt,
640
  width=width,
641
  height=height,
 
646
 
647
  return image, seed
648
 
649
+ # Keep the old infer function for backward compatibility
650
+ infer = infer_single
651
+
652
  # --- Examples and UI Layout ---
653
  examples = [
654
  "A capybara wearing a suit holding a sign that reads Hello World",
 
676
  """
677
 
678
  with gr.Blocks(css=css) as demo:
679
+ # Session state
680
+ session_state = gr.State(value={"session_id": str(uuid.uuid4()), "page_count": 0})
681
+
682
  with gr.Column(elem_id="col-container"):
683
  gr.HTML("""
684
  <div id="logo-title">
 
694
  placeholder="Enter your prompt",
695
  container=False,
696
  )
697
+ with gr.Column(scale=0):
698
+ run_button = gr.Button("Generate page 1", variant="primary")
699
+ reset_button = gr.Button("Start New Document", variant="secondary")
700
 
701
+ with gr.Row():
702
+ with gr.Column(scale=1):
703
+ result_preview = gr.Image(label="Preview", show_label=True, type="pil")
704
+ with gr.Column(scale=1):
705
+ pdf_output = gr.File(label="Download PDF", show_label=True)
706
+ page_info = gr.Textbox(label="Page Info", show_label=True, interactive=False, lines=3)
707
+ gr.Markdown("""**Note:** Your images and PDF are saved for up to 24 hours.
708
+ You can continue adding pages (up to 128) by clicking the generate button.""")
709
 
710
  with gr.Accordion("Advanced Settings", open=False):
711
  seed = gr.Slider(
 
726
  )
727
  prompt_enhance = gr.Checkbox(label="Prompt Enhance", value=True)
728
 
729
+ with gr.Row():
730
+ # Create dropdown choices from loaded presets
731
+ style_choices = [(preset["label"], key) for key, preset in STYLE_PRESETS.items()]
732
+ style_preset = gr.Dropdown(
733
+ label="Style Preset",
734
+ choices=style_choices,
735
+ value="no_style",
736
+ interactive=True
737
+ )
738
+
739
+ custom_style_text = gr.Textbox(
740
+ label="Custom Style Text",
741
+ placeholder="Enter custom style keywords (e.g., 'oil painting, impressionist')",
742
+ visible=False,
743
+ lines=2
744
+ )
745
+
746
+ with gr.Row():
747
+ num_images_slider = gr.Slider(
748
+ label="Images per page",
749
+ minimum=1,
750
+ maximum=4,
751
+ step=1,
752
+ value=1,
753
+ info="Number of images to generate for the PDF"
754
+ )
755
+
756
+ layout_dropdown = gr.Dropdown(
757
+ label="Page Layout",
758
+ choices=[("Full Page", "full_page")],
759
+ value="full_page",
760
+ interactive=True,
761
+ info="How images are arranged on the page"
762
+ )
763
+
764
  with gr.Row():
765
  guidance_scale = gr.Slider(
766
  label="Guidance scale (True CFG Scale)",
767
  minimum=1.0,
768
  maximum=5.0,
769
  step=0.1,
770
+ value=1.0,
771
  )
772
 
773
  num_inference_steps = gr.Slider(
 
778
  value=8,
779
  )
780
 
781
+ # Add interaction to show/hide custom style text field
782
+ def toggle_custom_style(style_value):
783
+ return gr.update(visible=(style_value == "no_style"))
784
+
785
+ style_preset.change(
786
+ fn=toggle_custom_style,
787
+ inputs=[style_preset],
788
+ outputs=[custom_style_text]
789
+ )
790
+
791
+ # Update layout dropdown when number of images changes
792
+ def update_layout_choices(num_images):
793
+ choices = get_layout_choices(int(num_images))
794
+ return gr.update(choices=choices, value=choices[0][1] if choices else "default")
795
+
796
+ num_images_slider.change(
797
+ fn=update_layout_choices,
798
+ inputs=[num_images_slider],
799
+ outputs=[layout_dropdown]
800
+ )
801
+
802
+ # Update examples to show some with different styles and image counts
803
+ styled_examples = [
804
+ ["A capybara wearing a suit holding a sign that reads Hello World", "no_style", "", 1],
805
+ ["sharks raining down on san francisco", "flying_saucer", "", 2],
806
+ ["A beautiful landscape with mountains and a lake", "klimt", "", 3],
807
+ ["A knight fighting a dragon", "medieval", "", 4],
808
+ ]
809
+
810
+ gr.Examples(
811
+ examples=styled_examples,
812
+ inputs=[prompt, style_preset, custom_style_text, num_images_slider],
813
+ outputs=None, # Don't show outputs for examples
814
+ fn=None,
815
+ cache_examples=False
816
+ )
817
 
818
+ # Define the main generation event
819
+ generation_event = gr.on(
820
  triggers=[run_button.click, prompt.submit],
821
+ fn=infer_page,
822
  inputs=[
823
  prompt,
824
  seed,
 
827
  guidance_scale,
828
  num_inference_steps,
829
  prompt_enhance,
830
+ style_preset,
831
+ custom_style_text,
832
+ num_images_slider,
833
+ layout_dropdown,
834
+ session_state,
835
  ],
836
+ outputs=[session_state, pdf_output, result_preview, page_info, run_button],
837
+ )
838
+
839
+ # Reset button functionality
840
+ def reset_session():
841
+ new_state = {"session_id": str(uuid.uuid4()), "page_count": 0}
842
+ return new_state, None, None, "", "Generate page 1"
843
+
844
+ # Connect the reset button
845
+ reset_button.click(
846
+ fn=reset_session,
847
+ inputs=[],
848
+ outputs=[session_state, pdf_output, result_preview, page_info, run_button]
849
  )
850
 
851
  if __name__ == "__main__":
page_layouts.yaml ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Page layouts configuration for multi-image PDF generation
2
+ # Each layout defines how images are arranged on a page
3
+ # Positions are defined as (x, y, width, height) in relative units (0-1)
4
+
5
+ layouts:
6
+ 1_image:
7
+ - id: "full_page"
8
+ label: "Full Page"
9
+ description: "Single image covering the full page"
10
+ positions:
11
+ - [0.05, 0.05, 0.9, 0.9] # x, y, width, height (5% margins)
12
+
13
+ 2_images:
14
+ - id: "horizontal_split"
15
+ label: "Layout A - Horizontal Split"
16
+ description: "Two images side by side"
17
+ positions:
18
+ - [0.05, 0.05, 0.425, 0.9] # Left image
19
+ - [0.525, 0.05, 0.425, 0.9] # Right image
20
+
21
+ - id: "vertical_split"
22
+ label: "Layout B - Vertical Split"
23
+ description: "Two images stacked vertically"
24
+ positions:
25
+ - [0.05, 0.05, 0.9, 0.425] # Top image
26
+ - [0.05, 0.525, 0.9, 0.425] # Bottom image
27
+
28
+ - id: "dominant_left"
29
+ label: "Layout C - Large Left"
30
+ description: "Large image on left, small on right"
31
+ positions:
32
+ - [0.05, 0.05, 0.6, 0.9] # Large left image
33
+ - [0.7, 0.25, 0.25, 0.5] # Small right image
34
+
35
+ - id: "dominant_top"
36
+ label: "Layout D - Large Top"
37
+ description: "Large image on top, small on bottom"
38
+ positions:
39
+ - [0.05, 0.05, 0.9, 0.6] # Large top image
40
+ - [0.25, 0.7, 0.5, 0.25] # Small bottom image
41
+
42
+ 3_images:
43
+ - id: "grid_horizontal"
44
+ label: "Layout A - Horizontal Strip"
45
+ description: "Three images in a row"
46
+ positions:
47
+ - [0.05, 0.25, 0.283, 0.5] # Left
48
+ - [0.358, 0.25, 0.283, 0.5] # Middle
49
+ - [0.666, 0.25, 0.283, 0.5] # Right
50
+
51
+ - id: "grid_vertical"
52
+ label: "Layout B - Vertical Strip"
53
+ description: "Three images in a column"
54
+ positions:
55
+ - [0.25, 0.05, 0.5, 0.283] # Top
56
+ - [0.25, 0.358, 0.5, 0.283] # Middle
57
+ - [0.25, 0.666, 0.5, 0.283] # Bottom
58
+
59
+ - id: "hero_top"
60
+ label: "Layout C - Hero Top"
61
+ description: "Large image on top, two small below"
62
+ positions:
63
+ - [0.05, 0.05, 0.9, 0.5] # Large top
64
+ - [0.05, 0.6, 0.425, 0.35] # Bottom left
65
+ - [0.525, 0.6, 0.425, 0.35] # Bottom right
66
+
67
+ - id: "hero_left"
68
+ label: "Layout D - Hero Left"
69
+ description: "Large image on left, two small on right"
70
+ positions:
71
+ - [0.05, 0.05, 0.5, 0.9] # Large left
72
+ - [0.6, 0.05, 0.35, 0.425] # Top right
73
+ - [0.6, 0.525, 0.35, 0.425] # Bottom right
74
+
75
+ - id: "diagonal"
76
+ label: "Layout E - Diagonal"
77
+ description: "Diagonal arrangement"
78
+ positions:
79
+ - [0.05, 0.05, 0.4, 0.4] # Top left
80
+ - [0.3, 0.3, 0.4, 0.4] # Center
81
+ - [0.55, 0.55, 0.4, 0.4] # Bottom right
82
+
83
+ 4_images:
84
+ - id: "grid_2x2"
85
+ label: "Layout A - 2x2 Grid"
86
+ description: "Four equal images in a grid"
87
+ positions:
88
+ - [0.05, 0.05, 0.425, 0.425] # Top left
89
+ - [0.525, 0.05, 0.425, 0.425] # Top right
90
+ - [0.05, 0.525, 0.425, 0.425] # Bottom left
91
+ - [0.525, 0.525, 0.425, 0.425] # Bottom right
92
+
93
+ - id: "strip_horizontal"
94
+ label: "Layout B - Horizontal Strip"
95
+ description: "Four images in a row"
96
+ positions:
97
+ - [0.05, 0.3, 0.2125, 0.4] # First
98
+ - [0.2875, 0.3, 0.2125, 0.4] # Second
99
+ - [0.525, 0.3, 0.2125, 0.4] # Third
100
+ - [0.7625, 0.3, 0.2125, 0.4] # Fourth
101
+
102
+ - id: "strip_vertical"
103
+ label: "Layout C - Vertical Strip"
104
+ description: "Four images in a column"
105
+ positions:
106
+ - [0.3, 0.05, 0.4, 0.2125] # First
107
+ - [0.3, 0.2875, 0.4, 0.2125] # Second
108
+ - [0.3, 0.525, 0.4, 0.2125] # Third
109
+ - [0.3, 0.7625, 0.4, 0.2125] # Fourth
110
+
111
+ - id: "hero_with_strip"
112
+ label: "Layout D - Hero with Strip"
113
+ description: "One large image with three small ones"
114
+ positions:
115
+ - [0.05, 0.05, 0.6, 0.6] # Large main
116
+ - [0.7, 0.05, 0.25, 0.283] # Small top
117
+ - [0.7, 0.358, 0.25, 0.283] # Small middle
118
+ - [0.7, 0.666, 0.25, 0.283] # Small bottom
119
+
120
+ - id: "l_shape"
121
+ label: "Layout E - L Shape"
122
+ description: "L-shaped arrangement"
123
+ positions:
124
+ - [0.05, 0.05, 0.425, 0.425] # Top left (large)
125
+ - [0.525, 0.05, 0.425, 0.425] # Top right (large)
126
+ - [0.05, 0.525, 0.425, 0.425] # Bottom left
127
+ - [0.525, 0.7, 0.425, 0.25] # Bottom right (small)
requirements.txt CHANGED
@@ -4,4 +4,7 @@ transformers
4
  accelerate
5
  safetensors
6
  sentencepiece
7
- dashscope
 
 
 
 
4
  accelerate
5
  safetensors
6
  sentencepiece
7
+ dashscope
8
+ pyyaml
9
+ reportlab
10
+ pypdf2
style_presets.yaml ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Style presets for image generation
2
+ # Each preset defines how to modify the user's prompt with style-specific prefixes and suffixes
3
+
4
+ presets:
5
+ no_style:
6
+ id: "no_style"
7
+ label: "No style (custom)"
8
+ enabled: true
9
+ prompt_prefix: ""
10
+ prompt_suffix: ""
11
+ negative_prompt: ""
12
+
13
+ random:
14
+ id: "random"
15
+ label: "Random style"
16
+ enabled: true
17
+ # This will be handled specially in code
18
+ prompt_prefix: ""
19
+ prompt_suffix: ""
20
+ negative_prompt: ""
21
+
22
+ japanese_manga:
23
+ id: "japanese_manga"
24
+ label: "Japanese Manga"
25
+ enabled: true
26
+ prompt_prefix: "grayscale, detailed drawing, japanese manga"
27
+ prompt_suffix: ""
28
+ negative_prompt: "franco-belgian comic, color album, color, american comic, photo, painting, 3D render"
29
+
30
+ nihonga:
31
+ id: "nihonga"
32
+ label: "Nihonga"
33
+ enabled: true
34
+ prompt_prefix: "japanese nihonga painting about"
35
+ prompt_suffix: "Nihonga, ancient japanese painting, intricate, detailed, detailed painting"
36
+ negative_prompt: "franco-belgian comic, color album, color, manga, comic, american comic, photo, painting, 3D render"
37
+
38
+ franco_belgian:
39
+ id: "franco_belgian"
40
+ label: "Franco-Belgian"
41
+ enabled: true
42
+ prompt_prefix: "bande dessinée, franco-belgian comic"
43
+ prompt_suffix: "comic album, detailed drawing"
44
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, photo, painting, 3D render"
45
+
46
+ american_comic_90:
47
+ id: "american_comic_90"
48
+ label: "American Comic (modern)"
49
+ enabled: true
50
+ prompt_prefix: "digital color comicbook style, modern american comic"
51
+ prompt_suffix: "detailed drawing"
52
+ negative_prompt: "manga, anime, american comic, action, grayscale, monochrome, photo, painting, 3D render"
53
+
54
+ # american_comic_40 is commented out in the original
55
+ # american_comic_40:
56
+ # id: "american_comic_40"
57
+ # label: "American Comic (1940)"
58
+ # enabled: false
59
+ # prompt_prefix: "american comic"
60
+ # prompt_suffix: "single panel, american comic, comicbook style, 1940, 40s, color comicbook, color drawing"
61
+ # negative_prompt: "manga, anime, american comic, action, grayscale, monochrome, photo, painting, 3D render"
62
+
63
+ american_comic_50:
64
+ id: "american_comic_50"
65
+ label: "American Comic (1950)"
66
+ enabled: true
67
+ prompt_prefix: "1950, 50s, vintage american color comic"
68
+ prompt_suffix: "detailed drawing"
69
+ negative_prompt: "manga, anime, american comic, action, grayscale, monochrome, photo, painting, 3D render"
70
+
71
+ # american_comic_60 is commented out in the original
72
+ # american_comic_60:
73
+ # id: "american_comic_60"
74
+ # label: "American Comic (1960)"
75
+ # enabled: false
76
+ # prompt_prefix: "american comic"
77
+ # prompt_suffix: "single panel, american comic, comicbook style, 1960, 60s, color comicbook, color drawing"
78
+ # negative_prompt: "manga, anime, american comic, action, grayscale, monochrome, photo, painting, 3D render"
79
+
80
+ flying_saucer:
81
+ id: "flying_saucer"
82
+ label: "Flying Saucer (Pulp Sci-Fi)"
83
+ enabled: true
84
+ prompt_prefix: "vintage science fiction, color pulp comic panel, 1940"
85
+ prompt_suffix: "detailed drawing"
86
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, photo, painting, 3D render"
87
+
88
+ humanoid:
89
+ id: "humanoid"
90
+ label: "Humanoid (Moebius)"
91
+ enabled: true
92
+ prompt_prefix: "color comic panel, style of Moebius"
93
+ prompt_suffix: "detailed drawing, french comic panel, franco-belgian style, bande dessinée, single panel"
94
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, photo, painting, 3D render"
95
+
96
+ haddock:
97
+ id: "haddock"
98
+ label: "Haddock (Tintin)"
99
+ enabled: true
100
+ prompt_prefix: "color comic panel, style of Hergé, tintin style"
101
+ prompt_suffix: "by Hergé, french comic panel, franco-belgian style"
102
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, photo, painting, 3D render"
103
+
104
+ # lurid is commented out in the original
105
+ # lurid:
106
+ # id: "lurid"
107
+ # label: "Lurid (Underground)"
108
+ # enabled: false
109
+ # prompt_prefix: "satirical color comic, underground comix, 1970"
110
+ # prompt_suffix: ""
111
+ # negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
112
+
113
+ armorican:
114
+ id: "armorican"
115
+ label: "Armorican (Asterix)"
116
+ enabled: true
117
+ prompt_prefix: "color comic panel, romans, gauls, french comic panel, franco-belgian style, about"
118
+ prompt_suffix: "bande dessinée, single panel"
119
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, photo, painting, 3D render"
120
+
121
+ render:
122
+ id: "render"
123
+ label: "3D Render (Pixar)"
124
+ enabled: true
125
+ prompt_prefix: "3D render animation, Pixar, cute, funny, Unreal engine"
126
+ prompt_suffix: "crisp, sharp"
127
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
128
+
129
+ klimt:
130
+ id: "klimt"
131
+ label: "Klimt"
132
+ enabled: true
133
+ prompt_prefix: "golden, patchwork, style of Gustav Klimt, Gustav Klimt painting"
134
+ prompt_suffix: "detailed painting, intricate details"
135
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
136
+
137
+ medieval:
138
+ id: "medieval"
139
+ label: "Medieval Illuminated"
140
+ enabled: true
141
+ prompt_prefix: "medieval illuminated manuscript, illuminated manuscript of, medieval"
142
+ prompt_suffix: "intricate details"
143
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
144
+
145
+ # glass is commented out in the original
146
+ # glass:
147
+ # id: "glass"
148
+ # label: "Stained Glass"
149
+ # enabled: false
150
+ # prompt_prefix: "stained glass, vitrail, stained glass"
151
+ # prompt_suffix: "medieval"
152
+ # negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
153
+
154
+ # voynich is commented out in the original
155
+ # voynich:
156
+ # id: "voynich"
157
+ # label: "Voynich"
158
+ # enabled: false
159
+ # prompt_prefix: "voynich, voynich page"
160
+ # prompt_suffix: "medieval"
161
+ # negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
162
+
163
+ egyptian:
164
+ id: "egyptian"
165
+ label: "Egyptian"
166
+ enabled: true
167
+ prompt_prefix: "ancient egyptian wall painting, ancient egypt"
168
+ prompt_suffix: ""
169
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
170
+
171
+ # psx is commented out in the original
172
+ # psx:
173
+ # id: "psx"
174
+ # label: "PSX"
175
+ # enabled: false
176
+ # prompt_prefix: "videogame screenshot, 3dfx, 3D dos game, software rendering"
177
+ # prompt_suffix: ""
178
+ # negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
179
+
180
+ # pixel is commented out in the original
181
+ # pixel:
182
+ # id: "pixel"
183
+ # label: "Pixel Art"
184
+ # enabled: false
185
+ # prompt_prefix: "pixelart, isometric, pixelated, low res"
186
+ # prompt_suffix: ""
187
+ # negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
188
+
189
+ photonovel:
190
+ id: "photonovel"
191
+ label: "Vintage Photonovel"
192
+ enabled: true
193
+ prompt_prefix: "vintage photo, 1950, 1960, french new wave, faded colors, color movie screencap"
194
+ prompt_suffix: ""
195
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
196
+
197
+ stockphoto:
198
+ id: "stockphoto"
199
+ label: "Stock Photo"
200
+ enabled: true
201
+ prompt_prefix: "cinematic, hyperrealistic, footage, sharp 8k, analog, instagram, photoshoot"
202
+ prompt_suffix: "crisp details"
203
+ negative_prompt: "manga, anime, american comic, grayscale, monochrome, painting"
204
+
205
+ # video_3d_style was in the original but commented out
206
+ # video_3d_style:
207
+ # id: "video_3d_style"
208
+ # label: "[video] 3D style"
209
+ # enabled: false
210
+ # prompt_prefix: ""
211
+ # prompt_suffix: ""
212
+ # negative_prompt: ""
213
+
214
+ # neutral preset from original
215
+ neutral:
216
+ id: "neutral"
217
+ label: "Neutral"
218
+ enabled: true
219
+ prompt_prefix: ""
220
+ prompt_suffix: ""
221
+ negative_prompt: ""