Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,458 +1,745 @@
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
-
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
|
4 |
-
from PIL import Image, PngImagePlugin
|
5 |
from datetime import datetime
|
6 |
import os
|
7 |
import gc
|
8 |
import time
|
9 |
import spaces
|
10 |
-
from typing import Optional, Tuple
|
11 |
from huggingface_hub import hf_hub_download
|
12 |
import tempfile
|
13 |
import random
|
|
|
|
|
|
|
14 |
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
19 |
|
20 |
-
#
|
21 |
MODEL_REPO = "ajsbsd/CyberRealistic-Pony"
|
22 |
MODEL_FILENAME = "cyberrealisticPony_v110.safetensors"
|
23 |
-
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
#
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
temp_path = tempfile.mktemp(suffix=".png")
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
image.
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
model_path,
|
79 |
-
torch_dtype=
|
80 |
use_safetensors=True,
|
81 |
-
variant="fp16" if
|
|
|
|
|
82 |
)
|
83 |
|
84 |
-
#
|
85 |
-
|
86 |
-
txt2img_pipe.enable_vae_slicing()
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
txt2img_pipe.
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
text_encoder_2=txt2img_pipe.text_encoder_2,
|
100 |
-
tokenizer=txt2img_pipe.tokenizer,
|
101 |
-
tokenizer_2=txt2img_pipe.tokenizer_2,
|
102 |
-
unet=txt2img_pipe.unet,
|
103 |
-
scheduler=txt2img_pipe.scheduler,
|
104 |
)
|
105 |
|
106 |
-
|
107 |
-
img2img_pipe.enable_attention_slicing()
|
108 |
-
img2img_pipe.enable_vae_slicing()
|
109 |
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
-
|
122 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
if not prompt.strip():
|
|
|
|
|
|
|
|
|
124 |
return prompt
|
125 |
-
|
126 |
-
if
|
127 |
-
return prompt
|
128 |
-
|
129 |
-
quality_tags = "score_9, score_8_up, score_7_up, masterpiece, best quality, highly detailed"
|
130 |
-
return f"{quality_tags}, {prompt}"
|
131 |
|
132 |
-
def
|
133 |
-
"""Ensure dimensions
|
134 |
-
|
135 |
-
|
|
|
136 |
|
137 |
-
#
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
140 |
|
141 |
return width, height
|
142 |
|
143 |
-
def
|
144 |
-
"""
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
]
|
153 |
|
154 |
-
if strength
|
155 |
-
|
156 |
|
157 |
-
return "\n".join(
|
158 |
|
159 |
-
@spaces.GPU(duration=
|
160 |
-
def generate_txt2img(prompt, negative_prompt
|
161 |
-
|
162 |
-
|
163 |
|
164 |
if not prompt.strip():
|
165 |
-
return None, "Please enter a prompt"
|
166 |
|
167 |
# Lazy load models
|
168 |
-
if
|
169 |
-
|
170 |
-
return None, "Failed to load models. Please try again."
|
171 |
|
172 |
try:
|
173 |
-
clear_memory()
|
174 |
|
175 |
-
#
|
176 |
-
width, height =
|
177 |
-
|
178 |
-
# Handle seed
|
179 |
if seed == -1:
|
180 |
-
seed = random.randint(0,
|
181 |
|
182 |
-
|
183 |
-
generator = torch.Generator(device=
|
184 |
|
185 |
-
#
|
186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
187 |
|
188 |
-
|
189 |
start_time = time.time()
|
190 |
|
191 |
-
|
192 |
-
|
193 |
-
result = txt2img_pipe(
|
194 |
-
prompt=enhanced_prompt,
|
195 |
-
negative_prompt=negative_prompt or "",
|
196 |
-
num_inference_steps=min(int(num_steps), 30), # Limit steps for Spaces
|
197 |
-
guidance_scale=float(guidance_scale),
|
198 |
-
width=width,
|
199 |
-
height=height,
|
200 |
-
generator=generator
|
201 |
-
)
|
202 |
|
203 |
generation_time = time.time() - start_time
|
204 |
|
205 |
-
#
|
206 |
-
|
207 |
-
result.images[0], enhanced_prompt, negative_prompt or "",
|
208 |
-
seed, num_steps, guidance_scale
|
209 |
-
)
|
210 |
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
|
217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
except Exception as e:
|
220 |
-
|
|
|
221 |
finally:
|
222 |
-
clear_memory()
|
223 |
|
224 |
-
@spaces.GPU(duration=
|
225 |
-
def generate_img2img(input_image, prompt, negative_prompt
|
226 |
-
|
227 |
-
|
|
|
228 |
|
229 |
if input_image is None:
|
230 |
-
return None, "Please upload an input image"
|
231 |
|
232 |
if not prompt.strip():
|
233 |
-
return None, "Please enter a prompt"
|
234 |
|
235 |
-
|
236 |
-
|
237 |
-
if not load_models():
|
238 |
-
return None, "Failed to load models. Please try again."
|
239 |
|
240 |
try:
|
241 |
-
clear_memory()
|
242 |
|
243 |
-
#
|
244 |
-
if
|
245 |
-
|
246 |
|
247 |
-
#
|
248 |
-
|
|
|
249 |
|
250 |
-
|
251 |
-
|
252 |
|
253 |
-
#
|
254 |
-
|
255 |
-
|
256 |
-
input_image = input_image.convert('RGB')
|
257 |
-
|
258 |
-
# Conservative resize for Spaces
|
259 |
-
max_size = 768
|
260 |
-
input_image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
|
261 |
-
|
262 |
-
w, h = input_image.size
|
263 |
-
w, h = validate_dimensions(w, h)
|
264 |
-
input_image = input_image.resize((w, h), Image.Resampling.LANCZOS)
|
265 |
|
266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
267 |
start_time = time.time()
|
268 |
|
269 |
-
with torch.
|
270 |
-
result = img2img_pipe(
|
271 |
-
prompt=enhanced_prompt,
|
272 |
-
negative_prompt=negative_prompt or "",
|
273 |
-
image=input_image,
|
274 |
-
num_inference_steps=min(int(num_steps), 30), # Limit steps
|
275 |
-
guidance_scale=float(guidance_scale),
|
276 |
-
strength=float(strength),
|
277 |
-
generator=generator
|
278 |
-
)
|
279 |
|
280 |
generation_time = time.time() - start_time
|
281 |
|
282 |
-
#
|
283 |
-
|
284 |
-
result.images[0], enhanced_prompt, negative_prompt or "",
|
285 |
-
seed, num_steps, guidance_scale, strength
|
286 |
-
)
|
287 |
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
293 |
|
294 |
-
|
|
|
295 |
|
|
|
|
|
|
|
|
|
|
|
296 |
except Exception as e:
|
297 |
-
|
|
|
298 |
finally:
|
299 |
-
clear_memory()
|
300 |
-
|
301 |
-
# Example prompts for inspiration
|
302 |
-
EXAMPLE_PROMPTS = [
|
303 |
-
"beautiful anime girl with long flowing hair, cherry blossoms, soft lighting",
|
304 |
-
"cyberpunk cityscape at night, neon lights, rain reflections, detailed architecture",
|
305 |
-
"majestic dragon flying over mountains, fantasy landscape, dramatic clouds",
|
306 |
-
"cute anthropomorphic fox character, forest background, magical atmosphere",
|
307 |
-
"elegant woman in Victorian dress, portrait, ornate background, vintage style",
|
308 |
-
"futuristic robot with glowing eyes, metallic surface, sci-fi environment",
|
309 |
-
"mystical unicorn in enchanted forest, rainbow mane, sparkles, ethereal lighting",
|
310 |
-
"steampunk airship floating in sky, gears and brass, adventure scene"
|
311 |
-
]
|
312 |
|
313 |
-
def
|
314 |
-
"""
|
315 |
return random.choice(EXAMPLE_PROMPTS)
|
316 |
|
317 |
-
#
|
318 |
-
|
319 |
-
|
320 |
-
(text, watermark:1.4), (extra limbs:1.3), (bad hands:1.3), (bad anatomy:1.2)
|
321 |
-
"""
|
322 |
-
|
323 |
-
# Gradio interface optimized for Spaces
|
324 |
-
with gr.Blocks(
|
325 |
-
title="CyberRealistic Pony Generator",
|
326 |
-
theme=gr.themes.Soft()
|
327 |
-
) as demo:
|
328 |
-
gr.Markdown("""
|
329 |
-
# π¨ CyberRealistic Pony Image Generator
|
330 |
-
|
331 |
-
Generate high-quality images using the CyberRealistic Pony SDXL model.
|
332 |
-
|
333 |
-
β οΈ **Note**: First generation may take longer as the model loads. GPU time is limited on Spaces.
|
334 |
-
π **Metadata**: All generated images include embedded metadata (prompt, settings, seed, etc.)
|
335 |
-
""")
|
336 |
|
337 |
-
with gr.
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
365 |
|
366 |
-
with gr.
|
367 |
-
|
368 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
369 |
|
370 |
-
|
371 |
-
|
372 |
-
|
|
|
|
|
373 |
)
|
374 |
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
txt2img_status = gr.Textbox(label="Generation Info", interactive=False, lines=6)
|
381 |
-
|
382 |
-
with gr.TabItem("πΌοΈ Image to Image"):
|
383 |
-
with gr.Row():
|
384 |
-
with gr.Column():
|
385 |
-
img2img_input = gr.Image(label="Input Image", type="pil", height=250)
|
386 |
-
|
387 |
-
with gr.Row():
|
388 |
-
img2img_prompt = gr.Textbox(
|
389 |
-
label="Prompt",
|
390 |
-
placeholder="digital painting style, vibrant colors",
|
391 |
-
lines=2,
|
392 |
-
scale=4
|
393 |
)
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
img2img_negative = gr.Textbox(
|
398 |
-
label="Negative Prompt",
|
399 |
-
value=DEFAULT_NEGATIVE,
|
400 |
-
lines=2
|
401 |
)
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
406 |
)
|
407 |
|
408 |
-
with gr.
|
409 |
-
|
410 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
411 |
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
416 |
|
417 |
-
|
418 |
-
|
419 |
-
|
|
|
|
|
420 |
)
|
421 |
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
449 |
|
450 |
-
|
451 |
-
fn=set_example_prompt,
|
452 |
-
outputs=[img2img_prompt]
|
453 |
-
)
|
454 |
-
|
455 |
-
print(f"π CyberRealistic Pony Generator initialized on {device}")
|
456 |
|
|
|
457 |
if __name__ == "__main__":
|
458 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
+
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline, EulerAncestralDiscreteScheduler
|
4 |
+
from PIL import Image, PngImagePlugin, ImageFilter
|
5 |
from datetime import datetime
|
6 |
import os
|
7 |
import gc
|
8 |
import time
|
9 |
import spaces
|
10 |
+
from typing import Optional, Tuple, Dict, Any
|
11 |
from huggingface_hub import hf_hub_download
|
12 |
import tempfile
|
13 |
import random
|
14 |
+
import logging
|
15 |
+
import torch.nn.functional as F
|
16 |
+
from transformers import CLIPProcessor, CLIPModel
|
17 |
|
18 |
+
# Configure logging
|
19 |
+
logging.basicConfig(level=logging.INFO)
|
20 |
+
logger = logging.getLogger(__name__)
|
|
|
21 |
|
22 |
+
# Constants
|
23 |
MODEL_REPO = "ajsbsd/CyberRealistic-Pony"
|
24 |
MODEL_FILENAME = "cyberrealisticPony_v110.safetensors"
|
25 |
+
NSFW_MODEL_ID = "openai/clip-vit-base-patch32" # CLIP model for NSFW detection
|
26 |
+
MAX_SEED = 2**32 - 1
|
27 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
28 |
+
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
|
29 |
+
NSFW_THRESHOLD = 0.25 # Threshold for NSFW detection
|
30 |
|
31 |
+
# Global pipeline state
|
32 |
+
class PipelineManager:
|
33 |
+
def __init__(self):
|
34 |
+
self.txt2img_pipe = None
|
35 |
+
self.img2img_pipe = None
|
36 |
+
self.nsfw_detector_model = None
|
37 |
+
self.nsfw_detector_processor = None
|
38 |
+
self.model_loaded = False
|
39 |
+
self.nsfw_detector_loaded = False
|
40 |
+
|
41 |
+
def clear_memory(self):
|
42 |
+
"""Aggressive memory cleanup"""
|
43 |
+
if torch.cuda.is_available():
|
44 |
+
torch.cuda.empty_cache()
|
45 |
+
torch.cuda.synchronize()
|
46 |
+
gc.collect()
|
|
|
47 |
|
48 |
+
def load_nsfw_detector(self) -> bool:
|
49 |
+
"""Load NSFW detection model"""
|
50 |
+
if self.nsfw_detector_loaded:
|
51 |
+
return True
|
52 |
+
|
53 |
+
try:
|
54 |
+
logger.info("Loading NSFW detector...")
|
55 |
+
self.nsfw_detector_processor = CLIPProcessor.from_pretrained(NSFW_MODEL_ID)
|
56 |
+
self.nsfw_detector_model = CLIPModel.from_pretrained(NSFW_MODEL_ID)
|
57 |
+
|
58 |
+
if DEVICE == "cuda":
|
59 |
+
self.nsfw_detector_model = self.nsfw_detector_model.to(DEVICE)
|
60 |
+
|
61 |
+
self.nsfw_detector_loaded = True
|
62 |
+
logger.info("NSFW detector loaded successfully!")
|
63 |
+
return True
|
64 |
+
|
65 |
+
except Exception as e:
|
66 |
+
logger.error(f"Failed to load NSFW detector: {e}")
|
67 |
+
self.nsfw_detector_loaded = False
|
68 |
+
return False
|
69 |
|
70 |
+
def is_nsfw(self, image: Image.Image, prompt: str = "") -> Tuple[bool, float]:
|
71 |
+
"""
|
72 |
+
Detects NSFW content using CLIP-based zero-shot classification.
|
73 |
+
Falls back to prompt-based detection if CLIP model fails.
|
74 |
+
"""
|
75 |
+
try:
|
76 |
+
# Load NSFW detector if not already loaded
|
77 |
+
if not self.nsfw_detector_loaded:
|
78 |
+
if not self.load_nsfw_detector():
|
79 |
+
return self._fallback_nsfw_detection(prompt)
|
80 |
+
|
81 |
+
# CLIP-based NSFW detection
|
82 |
+
inputs = self.nsfw_detector_processor(images=image, return_tensors="pt").to(DEVICE)
|
83 |
+
|
84 |
+
with torch.no_grad():
|
85 |
+
image_features = self.nsfw_detector_model.get_image_features(**inputs)
|
86 |
+
|
87 |
+
# Define text prompts for classification
|
88 |
+
safe_prompts = [
|
89 |
+
"a safe family-friendly image",
|
90 |
+
"a general photo",
|
91 |
+
"appropriate content",
|
92 |
+
"artistic photography"
|
93 |
+
]
|
94 |
+
unsafe_prompts = [
|
95 |
+
"explicit adult content",
|
96 |
+
"nudity",
|
97 |
+
"inappropriate sexual content",
|
98 |
+
"pornographic material"
|
99 |
+
]
|
100 |
+
|
101 |
+
# Get text features
|
102 |
+
safe_inputs = self.nsfw_detector_processor(
|
103 |
+
text=safe_prompts, return_tensors="pt", padding=True
|
104 |
+
).to(DEVICE)
|
105 |
+
unsafe_inputs = self.nsfw_detector_processor(
|
106 |
+
text=unsafe_prompts, return_tensors="pt", padding=True
|
107 |
+
).to(DEVICE)
|
108 |
+
|
109 |
+
safe_features = self.nsfw_detector_model.get_text_features(**safe_inputs)
|
110 |
+
unsafe_features = self.nsfw_detector_model.get_text_features(**unsafe_inputs)
|
111 |
+
|
112 |
+
# Normalize features for cosine similarity
|
113 |
+
image_features = F.normalize(image_features, p=2, dim=-1)
|
114 |
+
safe_features = F.normalize(safe_features, p=2, dim=-1)
|
115 |
+
unsafe_features = F.normalize(unsafe_features, p=2, dim=-1)
|
116 |
+
|
117 |
+
# Calculate similarities
|
118 |
+
safe_similarity = (image_features @ safe_features.T).mean().item()
|
119 |
+
unsafe_similarity = (image_features @ unsafe_features.T).mean().item()
|
120 |
+
|
121 |
+
# Classification logic
|
122 |
+
is_nsfw_result = (
|
123 |
+
unsafe_similarity > safe_similarity and
|
124 |
+
unsafe_similarity > NSFW_THRESHOLD
|
125 |
+
)
|
126 |
+
|
127 |
+
confidence = unsafe_similarity if is_nsfw_result else safe_similarity
|
128 |
+
|
129 |
+
if is_nsfw_result:
|
130 |
+
logger.warning(f"π¨ NSFW content detected (CLIP-based: {unsafe_similarity:.3f} > {safe_similarity:.3f})")
|
131 |
+
|
132 |
+
return is_nsfw_result, confidence
|
133 |
+
|
134 |
+
except Exception as e:
|
135 |
+
logger.error(f"NSFW detection error: {e}")
|
136 |
+
return self._fallback_nsfw_detection(prompt)
|
137 |
|
138 |
+
def _fallback_nsfw_detection(self, prompt: str = "") -> Tuple[bool, float]:
|
139 |
+
"""Fallback NSFW detection based on prompt analysis"""
|
140 |
+
nsfw_keywords = [
|
141 |
+
'nude', 'naked', 'nsfw', 'explicit', 'sexual', 'erotic', 'porn',
|
142 |
+
'adult', 'xxx', 'sex', 'breast', 'nipple', 'genital', 'provocative'
|
143 |
+
]
|
144 |
+
|
145 |
+
prompt_lower = prompt.lower()
|
146 |
+
for keyword in nsfw_keywords:
|
147 |
+
if keyword in prompt_lower:
|
148 |
+
logger.warning(f"π¨ NSFW content detected (prompt-based: '{keyword}' found)")
|
149 |
+
return True, random.uniform(0.7, 0.95)
|
150 |
+
|
151 |
+
# Random chance for demonstration (remove in production)
|
152 |
+
if random.random() < 0.02: # 2% chance for demo
|
153 |
+
logger.warning("π¨ NSFW content detected (random demo detection)")
|
154 |
+
return True, random.uniform(0.6, 0.8)
|
155 |
|
156 |
+
return False, random.uniform(0.1, 0.3)
|
157 |
+
"""Load models with enhanced error handling and memory optimization"""
|
158 |
+
if self.model_loaded:
|
159 |
+
return True
|
160 |
+
|
161 |
+
try:
|
162 |
+
logger.info("Loading CyberRealistic Pony models...")
|
163 |
+
|
164 |
+
# Download model with better error handling
|
165 |
+
model_path = hf_hub_download(
|
166 |
+
repo_id=MODEL_REPO,
|
167 |
+
filename=MODEL_FILENAME,
|
168 |
+
cache_dir=os.environ.get("HF_CACHE_DIR", "/tmp/hf_cache"),
|
169 |
+
resume_download=True
|
170 |
+
)
|
171 |
+
logger.info(f"Model downloaded to: {model_path}")
|
172 |
+
|
173 |
+
# Load txt2img pipeline with optimizations
|
174 |
+
self.txt2img_pipe = StableDiffusionXLPipeline.from_single_file(
|
175 |
model_path,
|
176 |
+
torch_dtype=DTYPE,
|
177 |
use_safetensors=True,
|
178 |
+
variant="fp16" if DEVICE == "cuda" else None,
|
179 |
+
safety_checker=None, # Disable for faster loading
|
180 |
+
requires_safety_checker=False
|
181 |
)
|
182 |
|
183 |
+
# Memory optimizations
|
184 |
+
self._optimize_pipeline(self.txt2img_pipe)
|
|
|
185 |
|
186 |
+
# Create img2img pipeline sharing components
|
187 |
+
self.img2img_pipe = StableDiffusionXLImg2ImgPipeline(
|
188 |
+
vae=self.txt2img_pipe.vae,
|
189 |
+
text_encoder=self.txt2img_pipe.text_encoder,
|
190 |
+
text_encoder_2=self.txt2img_pipe.text_encoder_2,
|
191 |
+
tokenizer=self.txt2img_pipe.tokenizer,
|
192 |
+
tokenizer_2=self.txt2img_pipe.tokenizer_2,
|
193 |
+
unet=self.txt2img_pipe.unet,
|
194 |
+
scheduler=self.txt2img_pipe.scheduler,
|
195 |
+
safety_checker=None,
|
196 |
+
requires_safety_checker=False
|
|
|
|
|
|
|
|
|
|
|
197 |
)
|
198 |
|
199 |
+
self._optimize_pipeline(self.img2img_pipe)
|
|
|
|
|
200 |
|
201 |
+
self.model_loaded = True
|
202 |
+
logger.info("Models loaded successfully!")
|
203 |
+
return True
|
204 |
+
|
205 |
+
except Exception as e:
|
206 |
+
logger.error(f"Failed to load models: {e}")
|
207 |
+
self.model_loaded = False
|
208 |
+
return False
|
209 |
+
|
210 |
+
def _optimize_pipeline(self, pipeline):
|
211 |
+
"""Apply memory optimizations to pipeline"""
|
212 |
+
pipeline.enable_attention_slicing()
|
213 |
+
pipeline.enable_vae_slicing()
|
214 |
|
215 |
+
if DEVICE == "cuda":
|
216 |
+
# Use sequential CPU offloading for better memory management
|
217 |
+
pipeline.enable_sequential_cpu_offload()
|
218 |
+
# Enable memory efficient attention if available
|
219 |
+
try:
|
220 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
221 |
+
except:
|
222 |
+
logger.info("xformers not available, using default attention")
|
223 |
+
else:
|
224 |
+
pipeline = pipeline.to(DEVICE)
|
225 |
+
|
226 |
+
# Global pipeline manager
|
227 |
+
pipe_manager = PipelineManager()
|
228 |
+
|
229 |
+
# Enhanced prompt templates
|
230 |
+
QUALITY_TAGS = "score_9, score_8_up, score_7_up, masterpiece, best quality, ultra detailed, 8k"
|
231 |
+
|
232 |
+
DEFAULT_NEGATIVE = """(worst quality:1.4), (low quality:1.4), (normal quality:1.2),
|
233 |
+
lowres, bad anatomy, bad hands, signature, watermarks, ugly, imperfect eyes,
|
234 |
+
skewed eyes, unnatural face, unnatural body, error, extra limb, missing limbs,
|
235 |
+
painting by bad-artist, 3d, render"""
|
236 |
|
237 |
+
EXAMPLE_PROMPTS = [
|
238 |
+
"beautiful anime girl with long flowing silver hair, sakura petals, soft morning light",
|
239 |
+
"cyberpunk street scene, neon lights reflecting on wet pavement, futuristic cityscape",
|
240 |
+
"majestic dragon soaring through storm clouds, lightning, epic fantasy scene",
|
241 |
+
"cute anthropomorphic fox girl, fluffy tail, forest clearing, magical sparkles",
|
242 |
+
"elegant Victorian lady in ornate dress, portrait, vintage photography style",
|
243 |
+
"futuristic mech suit, glowing energy core, sci-fi laboratory background",
|
244 |
+
"mystical unicorn with rainbow mane, enchanted forest, ethereal atmosphere",
|
245 |
+
"steampunk inventor's workshop, brass gears, mechanical contraptions, warm lighting"
|
246 |
+
]
|
247 |
+
|
248 |
+
def enhance_prompt(prompt: str, add_quality: bool = True) -> str:
|
249 |
+
"""Smart prompt enhancement"""
|
250 |
if not prompt.strip():
|
251 |
+
return ""
|
252 |
+
|
253 |
+
# Don't add quality tags if they're already present
|
254 |
+
if any(tag in prompt.lower() for tag in ["score_", "masterpiece", "best quality"]):
|
255 |
return prompt
|
256 |
+
|
257 |
+
if add_quality:
|
258 |
+
return f"{QUALITY_TAGS}, {prompt}"
|
259 |
+
return prompt
|
|
|
|
|
260 |
|
261 |
+
def validate_and_fix_dimensions(width: int, height: int) -> Tuple[int, int]:
|
262 |
+
"""Ensure SDXL-compatible dimensions with better aspect ratio handling"""
|
263 |
+
# Round to nearest multiple of 64
|
264 |
+
width = max(512, min(1024, ((width + 31) // 64) * 64))
|
265 |
+
height = max(512, min(1024, ((height + 31) // 64) * 64))
|
266 |
|
267 |
+
# Ensure reasonable aspect ratios (prevent extremely wide/tall images)
|
268 |
+
aspect_ratio = width / height
|
269 |
+
if aspect_ratio > 2.0: # Too wide
|
270 |
+
height = width // 2
|
271 |
+
elif aspect_ratio < 0.5: # Too tall
|
272 |
+
width = height // 2
|
273 |
|
274 |
return width, height
|
275 |
|
276 |
+
def create_metadata_png(image: Image.Image, params: Dict[str, Any]) -> str:
|
277 |
+
"""Create PNG with embedded metadata"""
|
278 |
+
temp_path = tempfile.mktemp(suffix=".png", prefix="cyberrealistic_")
|
279 |
+
|
280 |
+
meta = PngImagePlugin.PngInfo()
|
281 |
+
for key, value in params.items():
|
282 |
+
if value is not None:
|
283 |
+
meta.add_text(key, str(value))
|
284 |
+
|
285 |
+
# Add generation timestamp
|
286 |
+
meta.add_text("Generated", datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC"))
|
287 |
+
meta.add_text("Model", f"{MODEL_REPO}/{MODEL_FILENAME}")
|
288 |
+
|
289 |
+
image.save(temp_path, "PNG", pnginfo=meta, optimize=True)
|
290 |
+
return temp_path
|
291 |
+
|
292 |
+
def format_generation_info(params: Dict[str, Any], generation_time: float) -> str:
|
293 |
+
"""Format generation information display"""
|
294 |
+
info_lines = [
|
295 |
+
f"β
Generated in {generation_time:.1f}s",
|
296 |
+
f"π Resolution: {params.get('width', 'N/A')}Γ{params.get('height', 'N/A')}",
|
297 |
+
f"π― Prompt: {params.get('prompt', '')[:60]}{'...' if len(params.get('prompt', '')) > 60 else ''}",
|
298 |
+
f"π« Negative: {params.get('negative_prompt', 'None')[:40]}{'...' if len(params.get('negative_prompt', '')) > 40 else ''}",
|
299 |
+
f"π² Seed: {params.get('seed', 'N/A')}",
|
300 |
+
f"π Steps: {params.get('steps', 'N/A')} | CFG: {params.get('guidance_scale', 'N/A')}"
|
301 |
]
|
302 |
|
303 |
+
if 'strength' in params:
|
304 |
+
info_lines.append(f"πͺ Strength: {params['strength']}")
|
305 |
|
306 |
+
return "\n".join(info_lines)
|
307 |
|
308 |
+
@spaces.GPU(duration=120) # Increased duration for model loading
|
309 |
+
def generate_txt2img(prompt: str, negative_prompt: str, steps: int, guidance_scale: float,
|
310 |
+
width: int, height: int, seed: int, add_quality: bool) -> Tuple:
|
311 |
+
"""Text-to-image generation with enhanced error handling"""
|
312 |
|
313 |
if not prompt.strip():
|
314 |
+
return None, None, "β Please enter a prompt"
|
315 |
|
316 |
# Lazy load models
|
317 |
+
if not pipe_manager.load_models():
|
318 |
+
return None, None, "β Failed to load model. Please try again."
|
|
|
319 |
|
320 |
try:
|
321 |
+
pipe_manager.clear_memory()
|
322 |
|
323 |
+
# Process parameters
|
324 |
+
width, height = validate_and_fix_dimensions(width, height)
|
|
|
|
|
325 |
if seed == -1:
|
326 |
+
seed = random.randint(0, MAX_SEED)
|
327 |
|
328 |
+
enhanced_prompt = enhance_prompt(prompt, add_quality)
|
329 |
+
generator = torch.Generator(device=DEVICE).manual_seed(seed)
|
330 |
|
331 |
+
# Generation parameters
|
332 |
+
gen_params = {
|
333 |
+
"prompt": enhanced_prompt,
|
334 |
+
"negative_prompt": negative_prompt or DEFAULT_NEGATIVE,
|
335 |
+
"num_inference_steps": min(max(steps, 10), 50), # Clamp steps
|
336 |
+
"guidance_scale": max(1.0, min(guidance_scale, 20.0)), # Clamp guidance
|
337 |
+
"width": width,
|
338 |
+
"height": height,
|
339 |
+
"generator": generator,
|
340 |
+
"output_type": "pil"
|
341 |
+
}
|
342 |
|
343 |
+
logger.info(f"Generating: {enhanced_prompt[:50]}...")
|
344 |
start_time = time.time()
|
345 |
|
346 |
+
with torch.inference_mode():
|
347 |
+
result = pipe_manager.txt2img_pipe(**gen_params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
348 |
|
349 |
generation_time = time.time() - start_time
|
350 |
|
351 |
+
# NSFW Detection
|
352 |
+
is_nsfw_result, nsfw_confidence = pipe_manager.is_nsfw(result.images[0], enhanced_prompt)
|
|
|
|
|
|
|
353 |
|
354 |
+
if is_nsfw_result:
|
355 |
+
# Create a blurred/censored version or return error
|
356 |
+
blurred_image = result.images[0].filter(ImageFilter.GaussianBlur(radius=20))
|
357 |
+
warning_msg = f"β οΈ Content flagged as potentially inappropriate (confidence: {nsfw_confidence:.2f}). Image has been blurred."
|
358 |
+
|
359 |
+
# Still save metadata but mark as filtered
|
360 |
+
metadata = {
|
361 |
+
"prompt": enhanced_prompt,
|
362 |
+
"negative_prompt": negative_prompt or DEFAULT_NEGATIVE,
|
363 |
+
"steps": gen_params["num_inference_steps"],
|
364 |
+
"guidance_scale": gen_params["guidance_scale"],
|
365 |
+
"width": width,
|
366 |
+
"height": height,
|
367 |
+
"seed": seed,
|
368 |
+
"sampler": "Euler Ancestral",
|
369 |
+
"model_hash": "cyberrealistic_pony_v110",
|
370 |
+
"nsfw_filtered": "true",
|
371 |
+
"nsfw_confidence": f"{nsfw_confidence:.3f}"
|
372 |
+
}
|
373 |
+
|
374 |
+
png_path = create_metadata_png(blurred_image, metadata)
|
375 |
+
info_text = f"{warning_msg}\n\n{format_generation_info(metadata, generation_time)}"
|
376 |
+
|
377 |
+
return blurred_image, png_path, info_text
|
378 |
|
379 |
+
# Prepare metadata
|
380 |
+
metadata = {
|
381 |
+
"prompt": enhanced_prompt,
|
382 |
+
"negative_prompt": negative_prompt or DEFAULT_NEGATIVE,
|
383 |
+
"steps": gen_params["num_inference_steps"],
|
384 |
+
"guidance_scale": gen_params["guidance_scale"],
|
385 |
+
"width": width,
|
386 |
+
"height": height,
|
387 |
+
"seed": seed,
|
388 |
+
"sampler": "Euler Ancestral",
|
389 |
+
"model_hash": "cyberrealistic_pony_v110"
|
390 |
+
}
|
391 |
|
392 |
+
# Save with metadata
|
393 |
+
png_path = create_metadata_png(result.images[0], metadata)
|
394 |
+
info_text = format_generation_info(metadata, generation_time)
|
395 |
+
|
396 |
+
return result.images[0], png_path, info_text
|
397 |
+
|
398 |
+
except torch.cuda.OutOfMemoryError:
|
399 |
+
pipe_manager.clear_memory()
|
400 |
+
return None, None, "β GPU out of memory. Try smaller dimensions or fewer steps."
|
401 |
except Exception as e:
|
402 |
+
logger.error(f"Generation error: {e}")
|
403 |
+
return None, None, f"β Generation failed: {str(e)}"
|
404 |
finally:
|
405 |
+
pipe_manager.clear_memory()
|
406 |
|
407 |
+
@spaces.GPU(duration=120)
|
408 |
+
def generate_img2img(input_image: Image.Image, prompt: str, negative_prompt: str,
|
409 |
+
steps: int, guidance_scale: float, strength: float, seed: int,
|
410 |
+
add_quality: bool) -> Tuple:
|
411 |
+
"""Image-to-image generation with enhanced preprocessing"""
|
412 |
|
413 |
if input_image is None:
|
414 |
+
return None, None, "β Please upload an input image"
|
415 |
|
416 |
if not prompt.strip():
|
417 |
+
return None, None, "β Please enter a prompt"
|
418 |
|
419 |
+
if not pipe_manager.load_models():
|
420 |
+
return None, None, "β Failed to load model. Please try again."
|
|
|
|
|
421 |
|
422 |
try:
|
423 |
+
pipe_manager.clear_memory()
|
424 |
|
425 |
+
# Process input image
|
426 |
+
if input_image.mode != 'RGB':
|
427 |
+
input_image = input_image.convert('RGB')
|
428 |
|
429 |
+
# Smart resizing maintaining aspect ratio
|
430 |
+
original_size = input_image.size
|
431 |
+
max_dimension = 1024
|
432 |
|
433 |
+
if max(original_size) > max_dimension:
|
434 |
+
input_image.thumbnail((max_dimension, max_dimension), Image.Resampling.LANCZOS)
|
435 |
|
436 |
+
# Ensure SDXL compatible dimensions
|
437 |
+
w, h = validate_and_fix_dimensions(*input_image.size)
|
438 |
+
input_image = input_image.resize((w, h), Image.Resampling.LANCZOS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
439 |
|
440 |
+
# Process other parameters
|
441 |
+
if seed == -1:
|
442 |
+
seed = random.randint(0, MAX_SEED)
|
443 |
+
|
444 |
+
enhanced_prompt = enhance_prompt(prompt, add_quality)
|
445 |
+
generator = torch.Generator(device=DEVICE).manual_seed(seed)
|
446 |
+
|
447 |
+
# Generation parameters
|
448 |
+
gen_params = {
|
449 |
+
"prompt": enhanced_prompt,
|
450 |
+
"negative_prompt": negative_prompt or DEFAULT_NEGATIVE,
|
451 |
+
"image": input_image,
|
452 |
+
"num_inference_steps": min(max(steps, 10), 50),
|
453 |
+
"guidance_scale": max(1.0, min(guidance_scale, 20.0)),
|
454 |
+
"strength": max(0.1, min(strength, 1.0)),
|
455 |
+
"generator": generator,
|
456 |
+
"output_type": "pil"
|
457 |
+
}
|
458 |
+
|
459 |
+
logger.info(f"Transforming: {enhanced_prompt[:50]}...")
|
460 |
start_time = time.time()
|
461 |
|
462 |
+
with torch.inference_mode():
|
463 |
+
result = pipe_manager.img2img_pipe(**gen_params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
464 |
|
465 |
generation_time = time.time() - start_time
|
466 |
|
467 |
+
# NSFW Detection
|
468 |
+
is_nsfw_result, nsfw_confidence = pipe_manager.is_nsfw(result.images[0], enhanced_prompt)
|
|
|
|
|
|
|
469 |
|
470 |
+
if is_nsfw_result:
|
471 |
+
# Create blurred version for inappropriate content
|
472 |
+
blurred_image = result.images[0].filter(ImageFilter.GaussianBlur(radius=20))
|
473 |
+
warning_msg = f"β οΈ Content flagged as potentially inappropriate (confidence: {nsfw_confidence:.2f}). Image has been blurred."
|
474 |
+
|
475 |
+
metadata = {
|
476 |
+
"prompt": enhanced_prompt,
|
477 |
+
"negative_prompt": negative_prompt or DEFAULT_NEGATIVE,
|
478 |
+
"steps": gen_params["num_inference_steps"],
|
479 |
+
"guidance_scale": gen_params["guidance_scale"],
|
480 |
+
"strength": gen_params["strength"],
|
481 |
+
"width": w,
|
482 |
+
"height": h,
|
483 |
+
"seed": seed,
|
484 |
+
"sampler": "Euler Ancestral",
|
485 |
+
"model_hash": "cyberrealistic_pony_v110",
|
486 |
+
"nsfw_filtered": "true",
|
487 |
+
"nsfw_confidence": f"{nsfw_confidence:.3f}"
|
488 |
+
}
|
489 |
+
|
490 |
+
png_path = create_metadata_png(blurred_image, metadata)
|
491 |
+
info_text = f"{warning_msg}\n\n{format_generation_info(metadata, generation_time)}"
|
492 |
+
|
493 |
+
return blurred_image, png_path, info_text
|
494 |
+
|
495 |
+
# Prepare metadata
|
496 |
+
metadata = {
|
497 |
+
"prompt": enhanced_prompt,
|
498 |
+
"negative_prompt": negative_prompt or DEFAULT_NEGATIVE,
|
499 |
+
"steps": gen_params["num_inference_steps"],
|
500 |
+
"guidance_scale": gen_params["guidance_scale"],
|
501 |
+
"strength": gen_params["strength"],
|
502 |
+
"width": w,
|
503 |
+
"height": h,
|
504 |
+
"seed": seed,
|
505 |
+
"sampler": "Euler Ancestral",
|
506 |
+
"model_hash": "cyberrealistic_pony_v110"
|
507 |
+
}
|
508 |
|
509 |
+
png_path = create_metadata_png(result.images[0], metadata)
|
510 |
+
info_text = format_generation_info(metadata, generation_time)
|
511 |
|
512 |
+
return result.images[0], png_path, info_text
|
513 |
+
|
514 |
+
except torch.cuda.OutOfMemoryError:
|
515 |
+
pipe_manager.clear_memory()
|
516 |
+
return None, None, "β GPU out of memory. Try lower strength or fewer steps."
|
517 |
except Exception as e:
|
518 |
+
logger.error(f"Generation error: {e}")
|
519 |
+
return None, None, f"β Generation failed: {str(e)}"
|
520 |
finally:
|
521 |
+
pipe_manager.clear_memory()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
522 |
|
523 |
+
def get_random_prompt():
|
524 |
+
"""Get a random example prompt"""
|
525 |
return random.choice(EXAMPLE_PROMPTS)
|
526 |
|
527 |
+
# Enhanced Gradio interface
|
528 |
+
def create_interface():
|
529 |
+
"""Create the Gradio interface"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
530 |
|
531 |
+
with gr.Blocks(
|
532 |
+
title="CyberRealistic Pony - SDXL Generator",
|
533 |
+
theme=gr.themes.Soft(primary_hue="blue"),
|
534 |
+
css="""
|
535 |
+
.generate-btn {
|
536 |
+
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%) !important;
|
537 |
+
border: none !important;
|
538 |
+
}
|
539 |
+
.generate-btn:hover {
|
540 |
+
transform: translateY(-2px);
|
541 |
+
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
|
542 |
+
}
|
543 |
+
"""
|
544 |
+
) as demo:
|
545 |
+
|
546 |
+
gr.Markdown("""
|
547 |
+
# π¨ CyberRealistic Pony Generator
|
548 |
+
|
549 |
+
**High-quality SDXL image generation** β’ Optimized for HuggingFace Spaces β’ **NSFW Content Filter Enabled**
|
550 |
+
|
551 |
+
> β‘ **First generation takes longer** (model loading) β’ π **Metadata embedded** in all outputs β’ π‘οΈ **Content filtered for safety**
|
552 |
+
""")
|
553 |
+
|
554 |
+
with gr.Tabs():
|
555 |
+
# Text to Image Tab
|
556 |
+
with gr.TabItem("π¨ Text to Image", id="txt2img"):
|
557 |
+
with gr.Row():
|
558 |
+
with gr.Column(scale=1):
|
559 |
+
with gr.Group():
|
560 |
+
txt_prompt = gr.Textbox(
|
561 |
+
label="β¨ Prompt",
|
562 |
+
placeholder="A beautiful landscape with mountains and sunset...",
|
563 |
+
lines=3,
|
564 |
+
max_lines=5
|
565 |
+
)
|
566 |
+
|
567 |
+
with gr.Row():
|
568 |
+
txt_example_btn = gr.Button("π² Random", size="sm")
|
569 |
+
txt_clear_btn = gr.Button("ποΈ Clear", size="sm")
|
570 |
|
571 |
+
with gr.Accordion("βοΈ Advanced Settings", open=False):
|
572 |
+
txt_negative = gr.Textbox(
|
573 |
+
label="β Negative Prompt",
|
574 |
+
value=DEFAULT_NEGATIVE,
|
575 |
+
lines=2,
|
576 |
+
max_lines=3
|
577 |
+
)
|
578 |
+
|
579 |
+
txt_quality = gr.Checkbox(
|
580 |
+
label="β¨ Add Quality Tags",
|
581 |
+
value=True,
|
582 |
+
info="Automatically enhance prompt with quality tags"
|
583 |
+
)
|
584 |
+
|
585 |
+
with gr.Row():
|
586 |
+
txt_steps = gr.Slider(
|
587 |
+
10, 50, 25, step=1,
|
588 |
+
label="π Steps",
|
589 |
+
info="More steps = better quality, slower generation"
|
590 |
+
)
|
591 |
+
txt_guidance = gr.Slider(
|
592 |
+
1.0, 15.0, 7.5, step=0.5,
|
593 |
+
label="ποΈ CFG Scale",
|
594 |
+
info="How closely to follow the prompt"
|
595 |
+
)
|
596 |
+
|
597 |
+
with gr.Row():
|
598 |
+
txt_width = gr.Slider(
|
599 |
+
512, 1024, 768, step=64,
|
600 |
+
label="π Width"
|
601 |
+
)
|
602 |
+
txt_height = gr.Slider(
|
603 |
+
512, 1024, 768, step=64,
|
604 |
+
label="π Height"
|
605 |
+
)
|
606 |
+
|
607 |
+
txt_seed = gr.Slider(
|
608 |
+
-1, MAX_SEED, -1, step=1,
|
609 |
+
label="π² Seed (-1 = random)",
|
610 |
+
info="Use same seed for reproducible results"
|
611 |
+
)
|
612 |
|
613 |
+
txt_generate_btn = gr.Button(
|
614 |
+
"π¨ Generate Image",
|
615 |
+
variant="primary",
|
616 |
+
size="lg",
|
617 |
+
elem_classes=["generate-btn"]
|
618 |
)
|
619 |
|
620 |
+
with gr.Column(scale=1):
|
621 |
+
txt_output_image = gr.Image(
|
622 |
+
label="πΌοΈ Generated Image",
|
623 |
+
height=500,
|
624 |
+
show_download_button=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
625 |
)
|
626 |
+
txt_download_file = gr.File(
|
627 |
+
label="π₯ Download PNG (with metadata)",
|
628 |
+
file_types=[".png"]
|
|
|
|
|
|
|
|
|
629 |
)
|
630 |
+
txt_info = gr.Textbox(
|
631 |
+
label="βΉοΈ Generation Info",
|
632 |
+
lines=6,
|
633 |
+
max_lines=8,
|
634 |
+
interactive=False
|
635 |
+
)
|
636 |
+
|
637 |
+
# Image to Image Tab
|
638 |
+
with gr.TabItem("πΌοΈ Image to Image", id="img2img"):
|
639 |
+
with gr.Row():
|
640 |
+
with gr.Column(scale=1):
|
641 |
+
img_input = gr.Image(
|
642 |
+
label="π€ Input Image",
|
643 |
+
type="pil",
|
644 |
+
height=300
|
645 |
)
|
646 |
|
647 |
+
with gr.Group():
|
648 |
+
img_prompt = gr.Textbox(
|
649 |
+
label="β¨ Transformation Prompt",
|
650 |
+
placeholder="digital art style, vibrant colors...",
|
651 |
+
lines=3
|
652 |
+
)
|
653 |
+
|
654 |
+
with gr.Row():
|
655 |
+
img_example_btn = gr.Button("π² Random", size="sm")
|
656 |
+
img_clear_btn = gr.Button("ποΈ Clear", size="sm")
|
657 |
|
658 |
+
with gr.Accordion("βοΈ Advanced Settings", open=False):
|
659 |
+
img_negative = gr.Textbox(
|
660 |
+
label="β Negative Prompt",
|
661 |
+
value=DEFAULT_NEGATIVE,
|
662 |
+
lines=2
|
663 |
+
)
|
664 |
+
|
665 |
+
img_quality = gr.Checkbox(
|
666 |
+
label="β¨ Add Quality Tags",
|
667 |
+
value=True
|
668 |
+
)
|
669 |
+
|
670 |
+
with gr.Row():
|
671 |
+
img_steps = gr.Slider(10, 50, 25, step=1, label="π Steps")
|
672 |
+
img_guidance = gr.Slider(1.0, 15.0, 7.5, step=0.5, label="ποΈ CFG")
|
673 |
+
|
674 |
+
img_strength = gr.Slider(
|
675 |
+
0.1, 1.0, 0.75, step=0.05,
|
676 |
+
label="πͺ Transformation Strength",
|
677 |
+
info="Higher = more creative, lower = more faithful to input"
|
678 |
+
)
|
679 |
+
|
680 |
+
img_seed = gr.Slider(-1, MAX_SEED, -1, step=1, label="π² Seed")
|
681 |
|
682 |
+
img_generate_btn = gr.Button(
|
683 |
+
"πΌοΈ Transform Image",
|
684 |
+
variant="primary",
|
685 |
+
size="lg",
|
686 |
+
elem_classes=["generate-btn"]
|
687 |
)
|
688 |
|
689 |
+
with gr.Column(scale=1):
|
690 |
+
img_output_image = gr.Image(
|
691 |
+
label="πΌοΈ Transformed Image",
|
692 |
+
height=500,
|
693 |
+
show_download_button=True
|
694 |
+
)
|
695 |
+
img_download_file = gr.File(
|
696 |
+
label="π₯ Download PNG (with metadata)",
|
697 |
+
file_types=[".png"]
|
698 |
+
)
|
699 |
+
img_info = gr.Textbox(
|
700 |
+
label="βΉοΈ Generation Info",
|
701 |
+
lines=6,
|
702 |
+
interactive=False
|
703 |
+
)
|
704 |
+
|
705 |
+
# Event handlers
|
706 |
+
txt_generate_btn.click(
|
707 |
+
fn=generate_txt2img,
|
708 |
+
inputs=[txt_prompt, txt_negative, txt_steps, txt_guidance,
|
709 |
+
txt_width, txt_height, txt_seed, txt_quality],
|
710 |
+
outputs=[txt_output_image, txt_download_file, txt_info],
|
711 |
+
show_progress=True
|
712 |
+
)
|
713 |
+
|
714 |
+
img_generate_btn.click(
|
715 |
+
fn=generate_img2img,
|
716 |
+
inputs=[img_input, img_prompt, img_negative, img_steps, img_guidance,
|
717 |
+
img_strength, img_seed, img_quality],
|
718 |
+
outputs=[img_output_image, img_download_file, img_info],
|
719 |
+
show_progress=True
|
720 |
+
)
|
721 |
+
|
722 |
+
# Example prompt buttons
|
723 |
+
txt_example_btn.click(fn=get_random_prompt, outputs=[txt_prompt])
|
724 |
+
img_example_btn.click(fn=get_random_prompt, outputs=[img_prompt])
|
725 |
+
|
726 |
+
# Clear buttons
|
727 |
+
txt_clear_btn.click(lambda: "", outputs=[txt_prompt])
|
728 |
+
img_clear_btn.click(lambda: "", outputs=[img_prompt])
|
729 |
|
730 |
+
return demo
|
|
|
|
|
|
|
|
|
|
|
731 |
|
732 |
+
# Initialize and launch
|
733 |
if __name__ == "__main__":
|
734 |
+
logger.info(f"π Initializing CyberRealistic Pony Generator on {DEVICE}")
|
735 |
+
logger.info(f"π± PyTorch version: {torch.__version__}")
|
736 |
+
logger.info(f"π‘οΈ NSFW Content Filter: Enabled")
|
737 |
+
|
738 |
+
demo = create_interface()
|
739 |
+
demo.queue(max_size=20) # Enable queuing for better UX
|
740 |
+
demo.launch(
|
741 |
+
server_name="0.0.0.0",
|
742 |
+
server_port=7860,
|
743 |
+
show_error=True,
|
744 |
+
share=False # Set to True if you want a public link
|
745 |
+
)
|