Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
|
|
| 6 |
import torch
|
| 7 |
from PIL import Image
|
| 8 |
import time
|
|
|
|
| 9 |
|
| 10 |
# Ustawienia środowiska dla lepszej wydajności na CPU
|
| 11 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
@@ -15,58 +16,99 @@ torch.set_grad_enabled(False) # Wyłącz gradienty dla inferencji
|
|
| 15 |
if device == "cpu":
|
| 16 |
os.environ["OMP_NUM_THREADS"] = str(os.cpu_count())
|
| 17 |
torch.set_num_threads(os.cpu_count())
|
|
|
|
| 18 |
|
| 19 |
model_repo_id = "dhead/wai-nsfw-illustrious-sdxl-v140-sdxl"
|
| 20 |
|
| 21 |
# Optymalizacje typu danych
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
torch_dtype = torch.float32
|
| 32 |
-
pipe = DiffusionPipeline.from_pretrained(
|
| 33 |
-
model_repo_id,
|
| 34 |
-
torch_dtype=torch_dtype,
|
| 35 |
-
use_safetensors=True
|
| 36 |
-
)
|
| 37 |
|
| 38 |
# Optymalizacje potoku
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
pipe = pipe.to(device)
|
| 41 |
|
| 42 |
-
#
|
| 43 |
if device == "cpu":
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
MAX_SEED = np.iinfo(np.int32).max
|
| 48 |
MAX_IMAGE_SIZE = 1024
|
| 49 |
-
DEFAULT_IMAGE_SIZE =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
def
|
| 52 |
-
"""Automatyczna optymalizacja parametrów na podstawie promptu"""
|
| 53 |
prompt_lower = prompt.lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
# Dostosuj liczbę kroków na podstawie złożoności promptu
|
| 56 |
-
complex_keywords = ['detailed', 'intricate', 'complex', '8k', 'ultra detailed']
|
| 57 |
if any(keyword in prompt_lower for keyword in complex_keywords):
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
|
| 62 |
-
# Dostosuj
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
width = min(width, 768)
|
| 66 |
height = min(height, 768)
|
| 67 |
-
steps = min(steps, 20)
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
def infer(
|
| 72 |
prompt,
|
|
@@ -80,7 +122,11 @@ def infer(
|
|
| 80 |
enable_optimizations=True,
|
| 81 |
progress=gr.Progress(track_tqdm=True),
|
| 82 |
):
|
|
|
|
|
|
|
|
|
|
| 83 |
start_time = time.time()
|
|
|
|
| 84 |
|
| 85 |
if randomize_seed:
|
| 86 |
seed = random.randint(0, MAX_SEED)
|
|
@@ -88,10 +134,19 @@ def infer(
|
|
| 88 |
generator = torch.Generator().manual_seed(seed)
|
| 89 |
|
| 90 |
# Automatyczne optymalizacje
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
if enable_optimizations:
|
| 92 |
-
num_inference_steps, width, height =
|
| 93 |
|
| 94 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
image = pipe(
|
| 96 |
prompt=prompt,
|
| 97 |
negative_prompt=negative_prompt,
|
|
@@ -103,55 +158,66 @@ def infer(
|
|
| 103 |
).images[0]
|
| 104 |
|
| 105 |
generation_time = time.time() - start_time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
except Exception as e:
|
| 110 |
-
return None, seed, f"Error: {str(e)}"
|
| 111 |
|
| 112 |
def save_image(image, prompt, seed):
|
| 113 |
"""Zapisz wygenerowany obraz"""
|
| 114 |
if image is None:
|
| 115 |
return "No image to save"
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
def
|
| 136 |
-
"""
|
| 137 |
-
|
| 138 |
-
for prompt in prompts.split('\n'):
|
| 139 |
-
prompt = prompt.strip()
|
| 140 |
-
if prompt:
|
| 141 |
-
for i in range(num_images):
|
| 142 |
-
kwargs['prompt'] = prompt
|
| 143 |
-
kwargs['randomize_seed'] = True
|
| 144 |
-
image, seed, info = infer(**kwargs)
|
| 145 |
-
if image:
|
| 146 |
-
results.append((image, prompt, seed, info))
|
| 147 |
-
return results
|
| 148 |
|
|
|
|
| 149 |
examples = [
|
| 150 |
-
"
|
| 151 |
-
"
|
| 152 |
-
"
|
| 153 |
-
"
|
| 154 |
-
"
|
| 155 |
]
|
| 156 |
|
| 157 |
css = """
|
|
@@ -165,15 +231,19 @@ css = """
|
|
| 165 |
gap: 10px;
|
| 166 |
margin-top: 20px;
|
| 167 |
}
|
| 168 |
-
.gallery-item {
|
| 169 |
-
border-radius: 8px;
|
| 170 |
-
overflow: hidden;
|
| 171 |
-
}
|
| 172 |
.performance-info {
|
| 173 |
background: #f0f0f0;
|
| 174 |
padding: 10px;
|
| 175 |
border-radius: 5px;
|
| 176 |
margin: 10px 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
}
|
| 178 |
"""
|
| 179 |
|
|
@@ -181,7 +251,15 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 181 |
with gr.Column(elem_id="col-container"):
|
| 182 |
gr.Markdown("""
|
| 183 |
# 🎨 Advanced Text-to-Image Generator
|
| 184 |
-
*Optimized for CPU performance
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
""")
|
| 186 |
|
| 187 |
with gr.Row():
|
|
@@ -190,7 +268,7 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 190 |
label="Prompt",
|
| 191 |
show_label=False,
|
| 192 |
max_lines=2,
|
| 193 |
-
placeholder="
|
| 194 |
container=False,
|
| 195 |
)
|
| 196 |
with gr.Column(scale=1):
|
|
@@ -198,15 +276,15 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 198 |
|
| 199 |
with gr.Row():
|
| 200 |
with gr.Column():
|
| 201 |
-
result = gr.Image(label="Generated Image", show_label=True, height=
|
| 202 |
with gr.Row():
|
| 203 |
save_btn = gr.Button("💾 Save Image")
|
| 204 |
clear_btn = gr.Button("🗑️ Clear")
|
| 205 |
|
| 206 |
performance_info = gr.Textbox(
|
| 207 |
-
label="Generation
|
| 208 |
interactive=False,
|
| 209 |
-
max_lines=
|
| 210 |
)
|
| 211 |
|
| 212 |
with gr.Column():
|
|
@@ -216,7 +294,7 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 216 |
label="Negative Prompt",
|
| 217 |
max_lines=2,
|
| 218 |
placeholder="What to exclude from the image...",
|
| 219 |
-
value="blurry, low quality, distorted"
|
| 220 |
)
|
| 221 |
|
| 222 |
with gr.Row():
|
|
@@ -230,7 +308,7 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 230 |
enable_optimizations = gr.Checkbox(
|
| 231 |
label="Enable Auto-Optimizations",
|
| 232 |
value=True,
|
| 233 |
-
info="Automatically adjust settings for better performance"
|
| 234 |
)
|
| 235 |
|
| 236 |
with gr.Tab("Dimensions & Quality"):
|
|
@@ -256,58 +334,41 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 256 |
minimum=1.0,
|
| 257 |
maximum=10.0,
|
| 258 |
step=0.1,
|
| 259 |
-
value=
|
| 260 |
)
|
| 261 |
num_inference_steps = gr.Slider(
|
| 262 |
label="Inference Steps",
|
| 263 |
minimum=10,
|
| 264 |
-
maximum=
|
| 265 |
step=1,
|
| 266 |
value=20,
|
| 267 |
)
|
| 268 |
|
| 269 |
-
with gr.Accordion("🔄 Batch Generation", open=False):
|
| 270 |
-
batch_prompts = gr.Textbox(
|
| 271 |
-
label="Batch Prompts (one per line)",
|
| 272 |
-
lines=3,
|
| 273 |
-
placeholder="Enter multiple prompts, one per line..."
|
| 274 |
-
)
|
| 275 |
-
num_images_per_prompt = gr.Slider(
|
| 276 |
-
label="Images per prompt",
|
| 277 |
-
minimum=1,
|
| 278 |
-
maximum=5,
|
| 279 |
-
step=1,
|
| 280 |
-
value=1
|
| 281 |
-
)
|
| 282 |
-
batch_button = gr.Button("Generate Batch", variant="secondary")
|
| 283 |
-
|
| 284 |
-
batch_gallery = gr.Gallery(
|
| 285 |
-
label="Batch Results",
|
| 286 |
-
show_label=True,
|
| 287 |
-
columns=3,
|
| 288 |
-
height="auto"
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
# Przykłady
|
| 292 |
gr.Examples(
|
| 293 |
examples=examples,
|
| 294 |
inputs=[prompt],
|
| 295 |
-
label="Click any example to load it
|
| 296 |
)
|
| 297 |
|
| 298 |
# Sekcja informacyjna
|
| 299 |
-
with gr.Accordion("ℹ️ Usage Tips", open=
|
| 300 |
gr.Markdown("""
|
| 301 |
-
**Performance Tips for CPU:**
|
| 302 |
-
- Use 512x512
|
| 303 |
-
-
|
| 304 |
-
- Enable
|
| 305 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
-
**
|
| 308 |
-
-
|
| 309 |
-
-
|
| 310 |
-
-
|
| 311 |
""")
|
| 312 |
|
| 313 |
# Główne zdarzenia
|
|
@@ -336,38 +397,26 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
| 336 |
)
|
| 337 |
|
| 338 |
clear_btn.click(
|
| 339 |
-
fn=
|
| 340 |
outputs=[result, seed, performance_info]
|
| 341 |
)
|
| 342 |
|
| 343 |
-
batch_button.click(
|
| 344 |
-
fn=batch_generate,
|
| 345 |
-
inputs=[
|
| 346 |
-
batch_prompts,
|
| 347 |
-
num_images_per_prompt,
|
| 348 |
-
negative_prompt,
|
| 349 |
-
seed,
|
| 350 |
-
randomize_seed,
|
| 351 |
-
width,
|
| 352 |
-
height,
|
| 353 |
-
guidance_scale,
|
| 354 |
-
num_inference_steps,
|
| 355 |
-
enable_optimizations,
|
| 356 |
-
],
|
| 357 |
-
outputs=[batch_gallery]
|
| 358 |
-
)
|
| 359 |
-
|
| 360 |
# Automatyczne czyszczenie przy zmianie promptu
|
| 361 |
prompt.change(
|
| 362 |
-
fn=
|
| 363 |
outputs=[result, seed, performance_info]
|
| 364 |
)
|
| 365 |
|
| 366 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
# Konfiguracja launch dla lepszej wydajności
|
| 368 |
demo.launch(
|
| 369 |
server_name="0.0.0.0",
|
| 370 |
share=False,
|
| 371 |
show_error=True,
|
| 372 |
-
max_file_size="
|
|
|
|
| 373 |
)
|
|
|
|
| 6 |
import torch
|
| 7 |
from PIL import Image
|
| 8 |
import time
|
| 9 |
+
import psutil
|
| 10 |
|
| 11 |
# Ustawienia środowiska dla lepszej wydajności na CPU
|
| 12 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 16 |
if device == "cpu":
|
| 17 |
os.environ["OMP_NUM_THREADS"] = str(os.cpu_count())
|
| 18 |
torch.set_num_threads(os.cpu_count())
|
| 19 |
+
print(f"Using {os.cpu_count()} CPU threads")
|
| 20 |
|
| 21 |
model_repo_id = "dhead/wai-nsfw-illustrious-sdxl-v140-sdxl"
|
| 22 |
|
| 23 |
# Optymalizacje typu danych
|
| 24 |
+
try:
|
| 25 |
+
if torch.cuda.is_available():
|
| 26 |
+
torch_dtype = torch.float16
|
| 27 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 28 |
+
model_repo_id,
|
| 29 |
+
torch_dtype=torch_dtype,
|
| 30 |
+
use_safetensors=True,
|
| 31 |
+
variant="fp16" if any(f for f in ["fp16", "fp16-safetensors"] if f in model_repo_id) else None
|
| 32 |
+
)
|
| 33 |
+
else:
|
| 34 |
+
torch_dtype = torch.float32
|
| 35 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 36 |
+
model_repo_id,
|
| 37 |
+
torch_dtype=torch_dtype,
|
| 38 |
+
use_safetensors=True
|
| 39 |
+
)
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Error loading model: {e}")
|
| 42 |
+
# Fallback to basic loading
|
| 43 |
+
pipe = DiffusionPipeline.from_pretrained(model_repo_id)
|
| 44 |
torch_dtype = torch.float32
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# Optymalizacje potoku
|
| 47 |
+
try:
|
| 48 |
+
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
| 49 |
+
except:
|
| 50 |
+
print("Using default scheduler")
|
| 51 |
+
|
| 52 |
pipe = pipe.to(device)
|
| 53 |
|
| 54 |
+
# Optymalizacje tylko dla CPU
|
| 55 |
if device == "cpu":
|
| 56 |
+
try:
|
| 57 |
+
pipe.enable_attention_slicing()
|
| 58 |
+
print("Attention slicing enabled")
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"Could not enable attention slicing: {e}")
|
| 61 |
|
| 62 |
MAX_SEED = np.iinfo(np.int32).max
|
| 63 |
MAX_IMAGE_SIZE = 1024
|
| 64 |
+
DEFAULT_IMAGE_SIZE = 512 # Zmniejszony domyślny rozmiar dla CPU
|
| 65 |
+
|
| 66 |
+
def get_memory_info():
|
| 67 |
+
"""Pobierz informacje o użyciu pamięci"""
|
| 68 |
+
memory = psutil.virtual_memory()
|
| 69 |
+
return {
|
| 70 |
+
'total': memory.total / (1024**3),
|
| 71 |
+
'available': memory.available / (1024**3),
|
| 72 |
+
'used': memory.used / (1024**3),
|
| 73 |
+
'percent': memory.percent
|
| 74 |
+
}
|
| 75 |
|
| 76 |
+
def optimize_for_prompt_and_memory(prompt, width, height):
|
| 77 |
+
"""Automatyczna optymalizacja parametrów na podstawie promptu i dostępnej pamięci"""
|
| 78 |
prompt_lower = prompt.lower()
|
| 79 |
+
memory_info = get_memory_info()
|
| 80 |
+
|
| 81 |
+
# Bazowa liczba kroków na podstawie złożoności promptu
|
| 82 |
+
complex_keywords = ['detailed', 'intricate', 'complex', '8k', 'ultra detailed', 'high detail']
|
| 83 |
+
simple_keywords = ['simple', 'minimal', 'basic', 'sketch']
|
| 84 |
+
|
| 85 |
+
base_steps = 20
|
| 86 |
|
|
|
|
|
|
|
| 87 |
if any(keyword in prompt_lower for keyword in complex_keywords):
|
| 88 |
+
base_steps = min(25, base_steps + 5)
|
| 89 |
+
elif any(keyword in prompt_lower for keyword in simple_keywords):
|
| 90 |
+
base_steps = max(15, base_steps - 5)
|
| 91 |
|
| 92 |
+
# Dostosuj na podstawie dostępnej pamięci
|
| 93 |
+
if memory_info['available'] < 4: # Mniej niż 4GB dostępne
|
| 94 |
+
base_steps = max(15, base_steps - 5)
|
| 95 |
+
width = min(width, 512)
|
| 96 |
+
height = min(height, 512)
|
| 97 |
+
elif memory_info['available'] < 8: # Mniej niż 8GB dostępne
|
| 98 |
+
base_steps = max(18, base_steps - 2)
|
| 99 |
width = min(width, 768)
|
| 100 |
height = min(height, 768)
|
|
|
|
| 101 |
|
| 102 |
+
# Ogranicz całkowitą liczbę pikseli
|
| 103 |
+
total_pixels = width * height
|
| 104 |
+
if total_pixels > 1024 * 1024:
|
| 105 |
+
scale_factor = (1024 * 1024) / total_pixels
|
| 106 |
+
width = int(width * scale_factor ** 0.5)
|
| 107 |
+
height = int(height * scale_factor ** 0.5)
|
| 108 |
+
width = (width // 32) * 32 # Zaokrąglij do wielokrotności 32
|
| 109 |
+
height = (height // 32) * 32
|
| 110 |
+
|
| 111 |
+
return base_steps, width, height
|
| 112 |
|
| 113 |
def infer(
|
| 114 |
prompt,
|
|
|
|
| 122 |
enable_optimizations=True,
|
| 123 |
progress=gr.Progress(track_tqdm=True),
|
| 124 |
):
|
| 125 |
+
if not prompt.strip():
|
| 126 |
+
return None, 0, "Please enter a prompt"
|
| 127 |
+
|
| 128 |
start_time = time.time()
|
| 129 |
+
memory_before = get_memory_info()
|
| 130 |
|
| 131 |
if randomize_seed:
|
| 132 |
seed = random.randint(0, MAX_SEED)
|
|
|
|
| 134 |
generator = torch.Generator().manual_seed(seed)
|
| 135 |
|
| 136 |
# Automatyczne optymalizacje
|
| 137 |
+
original_steps = num_inference_steps
|
| 138 |
+
original_width = width
|
| 139 |
+
original_height = height
|
| 140 |
+
|
| 141 |
if enable_optimizations:
|
| 142 |
+
num_inference_steps, width, height = optimize_for_prompt_and_memory(prompt, width, height)
|
| 143 |
|
| 144 |
try:
|
| 145 |
+
# Sprawdź dostępną pamięć przed generowaniem
|
| 146 |
+
memory_info = get_memory_info()
|
| 147 |
+
if memory_info['available'] < 2: # Mniej niż 2GB dostępne
|
| 148 |
+
return None, seed, "Error: Not enough memory available. Please try with lower resolution or fewer steps."
|
| 149 |
+
|
| 150 |
image = pipe(
|
| 151 |
prompt=prompt,
|
| 152 |
negative_prompt=negative_prompt,
|
|
|
|
| 158 |
).images[0]
|
| 159 |
|
| 160 |
generation_time = time.time() - start_time
|
| 161 |
+
memory_after = get_memory_info()
|
| 162 |
+
|
| 163 |
+
info_text = f"✅ Generation time: {generation_time:.1f}s | "
|
| 164 |
+
info_text += f"Steps: {num_inference_steps} | "
|
| 165 |
+
info_text += f"Size: {width}x{height} | "
|
| 166 |
+
info_text += f"Memory: {memory_after['used']:.1f}GB used"
|
| 167 |
|
| 168 |
+
if enable_optimizations and (original_steps != num_inference_steps or original_width != width or original_height != height):
|
| 169 |
+
info_text += f" | ⚡ Auto-optimized"
|
| 170 |
+
|
| 171 |
+
return image, seed, info_text
|
| 172 |
|
| 173 |
+
except torch.cuda.OutOfMemoryError:
|
| 174 |
+
return None, seed, "❌ CUDA Out of Memory Error. Please reduce image size or steps."
|
| 175 |
+
except RuntimeError as e:
|
| 176 |
+
if "out of memory" in str(e).lower():
|
| 177 |
+
return None, seed, "❌ System Out of Memory Error. Please reduce image size or steps."
|
| 178 |
+
else:
|
| 179 |
+
return None, seed, f"❌ Runtime Error: {str(e)}"
|
| 180 |
except Exception as e:
|
| 181 |
+
return None, seed, f"❌ Error: {str(e)}"
|
| 182 |
|
| 183 |
def save_image(image, prompt, seed):
|
| 184 |
"""Zapisz wygenerowany obraz"""
|
| 185 |
if image is None:
|
| 186 |
return "No image to save"
|
| 187 |
|
| 188 |
+
try:
|
| 189 |
+
timestamp = int(time.time())
|
| 190 |
+
filename = f"generated_{timestamp}_{seed}.png"
|
| 191 |
+
|
| 192 |
+
# Tworzenie folderu jeśli nie istnieje
|
| 193 |
+
os.makedirs("generated_images", exist_ok=True)
|
| 194 |
+
filepath = os.path.join("generated_images", filename)
|
| 195 |
+
|
| 196 |
+
image.save(filepath)
|
| 197 |
+
|
| 198 |
+
# Zapisz metadane
|
| 199 |
+
metadata_file = f"generated_images/metadata_{timestamp}.txt"
|
| 200 |
+
with open(metadata_file, "w") as f:
|
| 201 |
+
f.write(f"Prompt: {prompt}\n")
|
| 202 |
+
f.write(f"Seed: {seed}\n")
|
| 203 |
+
f.write(f"Timestamp: {timestamp}\n")
|
| 204 |
+
f.write(f"Model: {model_repo_id}\n")
|
| 205 |
+
|
| 206 |
+
return f"✅ Image saved as {filename}"
|
| 207 |
+
except Exception as e:
|
| 208 |
+
return f"❌ Error saving image: {str(e)}"
|
| 209 |
|
| 210 |
+
def clear_all():
|
| 211 |
+
"""Wyczyść wszystkie wyniki"""
|
| 212 |
+
return None, 0, "Ready for new generation"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
+
# Przykłady
|
| 215 |
examples = [
|
| 216 |
+
"A beautiful sunset over mountains, digital art",
|
| 217 |
+
"A cute cat wearing a wizard hat, fantasy art",
|
| 218 |
+
"Futuristic city with flying cars, cyberpunk style",
|
| 219 |
+
"Peaceful forest with glowing mushrooms, magical",
|
| 220 |
+
"A bowl of fruit on a table, still life painting",
|
| 221 |
]
|
| 222 |
|
| 223 |
css = """
|
|
|
|
| 231 |
gap: 10px;
|
| 232 |
margin-top: 20px;
|
| 233 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
.performance-info {
|
| 235 |
background: #f0f0f0;
|
| 236 |
padding: 10px;
|
| 237 |
border-radius: 5px;
|
| 238 |
margin: 10px 0;
|
| 239 |
+
font-family: monospace;
|
| 240 |
+
}
|
| 241 |
+
.memory-warning {
|
| 242 |
+
background: #fff3cd;
|
| 243 |
+
border: 1px solid #ffeaa7;
|
| 244 |
+
padding: 10px;
|
| 245 |
+
border-radius: 5px;
|
| 246 |
+
margin: 10px 0;
|
| 247 |
}
|
| 248 |
"""
|
| 249 |
|
|
|
|
| 251 |
with gr.Column(elem_id="col-container"):
|
| 252 |
gr.Markdown("""
|
| 253 |
# 🎨 Advanced Text-to-Image Generator
|
| 254 |
+
*Optimized for CPU performance - 18GB RAM*
|
| 255 |
+
""")
|
| 256 |
+
|
| 257 |
+
# Wyświetl informacje o systemie
|
| 258 |
+
memory_info = get_memory_info()
|
| 259 |
+
gr.Markdown(f"""
|
| 260 |
+
<div class="performance-info">
|
| 261 |
+
💻 **System Info**: CPU Mode | 🧠 **Memory**: {memory_info['used']:.1f}GB / {memory_info['total']:.1f}GB used ({memory_info['percent']:.1f}%)
|
| 262 |
+
</div>
|
| 263 |
""")
|
| 264 |
|
| 265 |
with gr.Row():
|
|
|
|
| 268 |
label="Prompt",
|
| 269 |
show_label=False,
|
| 270 |
max_lines=2,
|
| 271 |
+
placeholder="Describe the image you want to generate...",
|
| 272 |
container=False,
|
| 273 |
)
|
| 274 |
with gr.Column(scale=1):
|
|
|
|
| 276 |
|
| 277 |
with gr.Row():
|
| 278 |
with gr.Column():
|
| 279 |
+
result = gr.Image(label="Generated Image", show_label=True, height=400)
|
| 280 |
with gr.Row():
|
| 281 |
save_btn = gr.Button("💾 Save Image")
|
| 282 |
clear_btn = gr.Button("🗑️ Clear")
|
| 283 |
|
| 284 |
performance_info = gr.Textbox(
|
| 285 |
+
label="Generation Information",
|
| 286 |
interactive=False,
|
| 287 |
+
max_lines=3
|
| 288 |
)
|
| 289 |
|
| 290 |
with gr.Column():
|
|
|
|
| 294 |
label="Negative Prompt",
|
| 295 |
max_lines=2,
|
| 296 |
placeholder="What to exclude from the image...",
|
| 297 |
+
value="blurry, low quality, distorted, bad anatomy"
|
| 298 |
)
|
| 299 |
|
| 300 |
with gr.Row():
|
|
|
|
| 308 |
enable_optimizations = gr.Checkbox(
|
| 309 |
label="Enable Auto-Optimizations",
|
| 310 |
value=True,
|
| 311 |
+
info="Automatically adjust settings for better performance and memory usage"
|
| 312 |
)
|
| 313 |
|
| 314 |
with gr.Tab("Dimensions & Quality"):
|
|
|
|
| 334 |
minimum=1.0,
|
| 335 |
maximum=10.0,
|
| 336 |
step=0.1,
|
| 337 |
+
value=7.0,
|
| 338 |
)
|
| 339 |
num_inference_steps = gr.Slider(
|
| 340 |
label="Inference Steps",
|
| 341 |
minimum=10,
|
| 342 |
+
maximum=30,
|
| 343 |
step=1,
|
| 344 |
value=20,
|
| 345 |
)
|
| 346 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
# Przykłady
|
| 348 |
gr.Examples(
|
| 349 |
examples=examples,
|
| 350 |
inputs=[prompt],
|
| 351 |
+
label="Quick Start Examples - Click any example below to load it:"
|
| 352 |
)
|
| 353 |
|
| 354 |
# Sekcja informacyjna
|
| 355 |
+
with gr.Accordion("ℹ️ Usage Tips & Information", open=True):
|
| 356 |
gr.Markdown("""
|
| 357 |
+
**🎯 Performance Tips for CPU (18GB RAM):**
|
| 358 |
+
- Use **512x512** resolution for fastest generation
|
| 359 |
+
- **15-25 steps** usually provide good quality
|
| 360 |
+
- Enable **Auto-Optimizations** for best results
|
| 361 |
+
- Keep **Guidance Scale** between 5.0-8.0
|
| 362 |
+
|
| 363 |
+
**⚠️ Memory Management:**
|
| 364 |
+
- Larger images (1024x1024) will use more memory
|
| 365 |
+
- Complex prompts may require more steps
|
| 366 |
+
- System automatically optimizes based on available memory
|
| 367 |
|
| 368 |
+
**💡 Prompt Tips:**
|
| 369 |
+
- Be specific and descriptive
|
| 370 |
+
- Include style keywords (digital art, painting, photo, etc.)
|
| 371 |
+
- Use negative prompts to exclude unwanted elements
|
| 372 |
""")
|
| 373 |
|
| 374 |
# Główne zdarzenia
|
|
|
|
| 397 |
)
|
| 398 |
|
| 399 |
clear_btn.click(
|
| 400 |
+
fn=clear_all,
|
| 401 |
outputs=[result, seed, performance_info]
|
| 402 |
)
|
| 403 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
# Automatyczne czyszczenie przy zmianie promptu
|
| 405 |
prompt.change(
|
| 406 |
+
fn=clear_all,
|
| 407 |
outputs=[result, seed, performance_info]
|
| 408 |
)
|
| 409 |
|
| 410 |
if __name__ == "__main__":
|
| 411 |
+
print("Starting Text-to-Image Application...")
|
| 412 |
+
print(f"Device: {device}")
|
| 413 |
+
print(f"Torch threads: {torch.get_num_threads()}")
|
| 414 |
+
|
| 415 |
# Konfiguracja launch dla lepszej wydajności
|
| 416 |
demo.launch(
|
| 417 |
server_name="0.0.0.0",
|
| 418 |
share=False,
|
| 419 |
show_error=True,
|
| 420 |
+
max_file_size="50MB",
|
| 421 |
+
inbrowser=False
|
| 422 |
)
|