-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
206 lines (164 loc) · 6.32 KB
/
Copy pathapp.py
File metadata and controls
206 lines (164 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""Mini Fooocus-inspired image generator using Flask and Stable Diffusion Turbo."""
from __future__ import annotations
import os
import threading
import uuid
from pathlib import Path
from typing import Dict, List
from flask import Flask, jsonify, render_template, request, url_for
try:
import torch
from diffusers import AutoPipelineForText2Image
except Exception as exc: # pragma: no cover - surfaces missing deps quickly
raise RuntimeError(
"The required dependencies for the image generator are missing. "
"Install them with 'pip install -r requirements.txt'."
) from exc
BASE_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = BASE_DIR / "static" / "outputs"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
STYLE_PRESETS: Dict[str, Dict[str, str]] = {
"none": {"label": "Original", "prompt": ""},
"anime": {
"label": "Anime",
"prompt": "anime illustration, vibrant colors, crisp line art, dynamic lighting",
},
"cinematic": {
"label": "Cinematic",
"prompt": "cinematic composition, dramatic lighting, 35mm photograph, depth of field",
},
"realistic": {
"label": "Realistic",
"prompt": "photorealistic, ultra high definition, natural lighting, intricate detail",
},
"cyberpunk": {
"label": "Cyberpunk",
"prompt": "cyberpunk aesthetic, neon lights, futuristic cityscape, high contrast",
},
"three_d": {
"label": "3D Render",
"prompt": "ultra detailed 3d render, octane render, volumetric lighting, studio quality",
},
}
MAX_IMAGES_PER_PROMPT = 8
RECENT_IMAGE_LIMIT = 20
MODEL_ID = "stabilityai/sd-turbo"
def _build_pipeline() -> AutoPipelineForText2Image:
"""Create and optimise the Stable Diffusion pipeline for fast inference."""
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if device == "cuda" else torch.float32
pipeline_kwargs = {"torch_dtype": dtype}
if dtype == torch.float16:
pipeline_kwargs["variant"] = "fp16"
pipe = AutoPipelineForText2Image.from_pretrained(MODEL_ID, **pipeline_kwargs)
pipe.to(device)
pipe.set_progress_bar_config(disable=True)
if device == "cuda":
try:
pipe.enable_xformers_memory_efficient_attention()
except Exception:
# xFormers is optional – continue without it if unavailable.
pass
try:
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
except Exception:
# torch.compile may not be available or may fail on some setups.
pass
return pipe
PIPELINE_LOCK = threading.Lock()
PIPELINE = None
def get_pipeline():
"""Get or initialize the pipeline lazily."""
global PIPELINE
if PIPELINE is None:
try:
PIPELINE = _build_pipeline()
except Exception as exc:
raise RuntimeError(
f"Failed to initialize pipeline: {exc}. "
"Make sure dependencies are installed and you have internet access for model download."
) from exc
return PIPELINE
app = Flask(__name__)
def list_recent_images(limit: int = RECENT_IMAGE_LIMIT) -> List[Dict[str, str]]:
"""Return the newest generated images for the gallery."""
try:
image_paths = sorted(
OUTPUT_DIR.glob("*.png"),
key=lambda p: p.stat().st_mtime,
reverse=True,
)[:limit]
# Use Flask's url_for with app context
with app.app_context():
return [
{
"url": url_for("static", filename=f"outputs/{path.name}"),
"filename": path.name,
}
for path in image_paths
]
except Exception:
# Return empty list if there are any issues
return []
@app.route("/", methods=["GET"])
def index() -> str:
presets = {key: data["label"] for key, data in STYLE_PRESETS.items()}
recent_images = list_recent_images()
return render_template(
"index.html",
presets=presets,
recent_images=recent_images,
image_options=[1, 2, 4, 6, 8],
)
@app.route("/generate", methods=["POST"])
def generate_images():
payload = request.get_json(force=True, silent=True) or {}
prompt = (payload.get("prompt") or "").strip()
style_key = payload.get("style", "none")
count = int(payload.get("count", 1))
if not prompt:
return jsonify({"error": "Please enter a prompt."}), 400
if style_key not in STYLE_PRESETS:
style_key = "none"
count = max(1, min(MAX_IMAGES_PER_PROMPT, count))
style_prompt = STYLE_PRESETS[style_key]["prompt"]
full_prompt = f"{prompt}, {style_prompt}" if style_prompt else prompt
try:
pipe = get_pipeline()
with PIPELINE_LOCK:
with torch.inference_mode():
# SD Turbo doesn't support num_images_per_prompt well, generate one at a time
generated_images = []
for _ in range(count):
result = pipe(
prompt=full_prompt,
guidance_scale=0.0,
num_inference_steps=2,
)
# result.images is a list, even for single image
if isinstance(result.images, list):
generated_images.extend(result.images)
else:
generated_images.append(result.images)
except Exception as exc: # pragma: no cover - runtime failures only
return (
jsonify(
{
"error": "Image generation failed. Please retry or check the console for details.",
"details": str(exc),
}
),
500,
)
saved_images: List[str] = []
for image in generated_images:
filename = f"{uuid.uuid4().hex}.png"
image_path = OUTPUT_DIR / filename
image.save(image_path)
saved_images.append(url_for("static", filename=f"outputs/{filename}"))
return jsonify({"images": saved_images})
if __name__ == "__main__":
host = os.environ.get("FLASK_RUN_HOST", "0.0.0.0")
port = int(os.environ.get("FLASK_RUN_PORT", 5000))
debug = os.environ.get("FLASK_DEBUG", "0") == "1"
app.run(host=host, port=port, debug=debug)