K1Z3M1112 commited on
Commit
81613b5
·
verified ·
1 Parent(s): e774bc6

Upload app (2).py

Browse files
Files changed (1) hide show
  1. app (2).py +699 -0
app (2).py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import numpy as np
4
+ import torch
5
+ import random
6
+ from PIL import Image, ImageEnhance, ImageFilter
7
+ from gradio.themes import Soft
8
+ from gradio.themes.utils import colors, fonts, sizes
9
+
10
+ colors.steel_blue = colors.Color(
11
+ name="steel_blue",
12
+ c50="#EBF3F8",
13
+ c100="#D3E5F0",
14
+ c200="#A8CCE1",
15
+ c300="#7DB3D2",
16
+ c400="#529AC3",
17
+ c500="#4682B4",
18
+ c600="#3E72A0",
19
+ c700="#36638C",
20
+ c800="#2E5378",
21
+ c900="#264364",
22
+ c950="#1E3450",
23
+ )
24
+
25
+ class SteelBlueTheme(Soft):
26
+ def __init__(self, **kwargs):
27
+ super().__init__(
28
+ primary_hue=colors.gray,
29
+ secondary_hue=colors.steel_blue,
30
+ neutral_hue=colors.slate,
31
+ text_size=sizes.text_lg,
32
+ font=(fonts.GoogleFont("Outfit"), "Arial", "sans-serif"),
33
+ font_mono=(fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"),
34
+ )
35
+
36
+ steel_blue_theme = SteelBlueTheme()
37
+
38
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
39
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
40
+
41
+ print("=" * 50)
42
+ print("🎨 Enhanced Image-to-Image Photo Restoration")
43
+ print("=" * 50)
44
+ print("Using device:", device)
45
+ print("=" * 50)
46
+
47
+ from diffusers import (
48
+ AutoPipelineForImage2Image,
49
+ StableDiffusionXLImg2ImgPipeline,
50
+ StableDiffusionImg2ImgPipeline,
51
+ AutoencoderKL
52
+ )
53
+ import gc
54
+
55
+ # Initialize model
56
+ pipe = None
57
+ model_name = None
58
+ vae = None
59
+
60
+ try:
61
+ print("🔄 Loading SDXL Refiner with enhanced VAE...")
62
+
63
+ # Try to load better VAE (compatible with SDXL)
64
+ try:
65
+ print("📦 Loading high-quality VAE: madebyollin/sdxl-vae-fp16-fix")
66
+ vae = AutoencoderKL.from_pretrained(
67
+ "madebyollin/sdxl-vae-fp16-fix",
68
+ torch_dtype=dtype
69
+ )
70
+ print("✅ High-quality VAE loaded successfully!")
71
+ vae_name = "SDXL-VAE-FP16-Fix"
72
+ except Exception as vae_error:
73
+ print(f"⚠️ Could not load custom VAE: {vae_error}")
74
+ print("📦 Using default SDXL VAE")
75
+ vae = None
76
+ vae_name = "Default-VAE"
77
+
78
+ # Load SDXL Refiner with custom VAE (if available)
79
+ if vae is not None:
80
+ pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
81
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
82
+ vae=vae,
83
+ torch_dtype=dtype,
84
+ variant="fp16" if torch.cuda.is_available() else None,
85
+ use_safetensors=True
86
+ )
87
+ model_name = f"SDXL-Refiner + {vae_name}"
88
+ print(f"✅ Loaded SDXL-Refiner with {vae_name}")
89
+ else:
90
+ pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
91
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
92
+ torch_dtype=dtype,
93
+ variant="fp16" if torch.cuda.is_available() else None,
94
+ use_safetensors=True
95
+ )
96
+ model_name = "SDXL-Refiner-1.0"
97
+ print("✅ Loaded SDXL-Refiner with default VAE")
98
+
99
+ pipe.to(device)
100
+
101
+ # Enable memory optimizations
102
+ print("⚡ Enabling optimizations...")
103
+ if hasattr(pipe, 'enable_attention_slicing'):
104
+ pipe.enable_attention_slicing(1)
105
+ if hasattr(pipe, 'enable_vae_slicing'):
106
+ pipe.enable_vae_slicing()
107
+ if hasattr(pipe, 'enable_vae_tiling'):
108
+ pipe.enable_vae_tiling()
109
+
110
+ # Model offloading for better memory management
111
+ if device.type == "cpu":
112
+ print("💻 CPU mode - enabling model offloading")
113
+ if hasattr(pipe, 'enable_model_cpu_offload'):
114
+ pipe.enable_model_cpu_offload()
115
+ else:
116
+ print("🚀 GPU mode - enabling sequential CPU offload")
117
+ if hasattr(pipe, 'enable_sequential_cpu_offload'):
118
+ pipe.enable_sequential_cpu_offload()
119
+
120
+ print(f"✅ Model ready: {model_name}")
121
+
122
+ except Exception as e:
123
+ print(f"❌ Error loading model: {e}")
124
+
125
+ MAX_SEED = np.iinfo(np.int32).max
126
+
127
+ # Enhanced restoration presets optimized for SDXL Refiner
128
+ RESTORATION_PRESETS = {
129
+ "ลงสีภาพขาวดำ (Colorize)": {
130
+ "prompt": "perfectly colorized vintage photograph, realistic natural colors, vibrant hues, accurate skin tones, professional photo restoration, historical accuracy, film photography aesthetic",
131
+ "negative": "black and white, grayscale, monochrome, sepia, desaturated, washed out, artificial colors, oversaturated, cartoon",
132
+ "strength": 0.70,
133
+ "aesthetic_score": 7.0
134
+ },
135
+ "ซ่อมแซมเต็มรูปแบบ (Full Restore)": {
136
+ "prompt": "pristine restored photograph, museum quality restoration, no damage, crystal clear details, vibrant accurate colors, professional archival restoration, perfect condition",
137
+ "negative": "scratches, tears, stains, faded, damaged, low quality, blurry, artifacts, deteriorated, aged",
138
+ "strength": 0.65,
139
+ "aesthetic_score": 7.5
140
+ },
141
+ "ลบรอยขีดข่วน (Remove Damage)": {
142
+ "prompt": "clean photograph, flawless surface, no scratches, no tears, no stains, professionally restored, smooth perfect condition",
143
+ "negative": "scratches, damage, tears, cracks, stains, spots, defects, deterioration, wear",
144
+ "strength": 0.55,
145
+ "aesthetic_score": 6.5
146
+ },
147
+ "เพิ่มสีที่เลือนหาย (Enhance Faded)": {
148
+ "prompt": "vibrant saturated colors, rich deep tones, enhanced contrast, vivid hues, color-corrected, professional color grading, cinema quality",
149
+ "negative": "faded, washed out, pale, dull colors, desaturated, flat, low contrast, muddy colors",
150
+ "strength": 0.50,
151
+ "aesthetic_score": 7.0
152
+ },
153
+ "ลดสัญญาณรบกวน (Denoise)": {
154
+ "prompt": "crystal clear photograph, ultra sharp details, noise-free, clean, high resolution 8k, professional quality, perfect clarity, no grain",
155
+ "negative": "noisy, grainy, blurry, pixelated, low quality, compression artifacts, jpeg artifacts, soft",
156
+ "strength": 0.45,
157
+ "aesthetic_score": 6.5
158
+ },
159
+ "เพิ่มความคมชัด (Sharpen)": {
160
+ "prompt": "ultra sharp photograph, crisp details, high definition, tack sharp focus, professional photography, 8k resolution, perfect clarity",
161
+ "negative": "blurry, soft focus, out of focus, low resolution, hazy, unclear, motion blur",
162
+ "strength": 0.40,
163
+ "aesthetic_score": 6.5
164
+ },
165
+ "สไตล์โปรเฟสชันนัล (Pro Photo)": {
166
+ "prompt": "professional studio photography, cinematic lighting, commercial quality, advertising photography, high-end fashion photography, vogue magazine style",
167
+ "negative": "amateur, snapshot, casual photo, low quality, poor lighting, flat",
168
+ "strength": 0.60,
169
+ "aesthetic_score": 8.0
170
+ },
171
+ "สไตล์ภาพยนตร์ (Cinematic)": {
172
+ "prompt": "cinematic film still, movie quality, dramatic lighting, film grain, anamorphic lens, color graded, Hollywood production",
173
+ "negative": "digital, flat, video game, animated, low budget, poor quality",
174
+ "strength": 0.65,
175
+ "aesthetic_score": 7.5
176
+ },
177
+ "เปลี่ยนเป็นอนิเมะ (Anime Style)": {
178
+ "prompt": "beautiful anime art style, high quality manga illustration, studio ghibli quality, cel shaded, vibrant anime colors, detailed anime character",
179
+ "negative": "realistic, photographic, 3d render, western cartoon, ugly, bad anatomy",
180
+ "strength": 0.85,
181
+ "aesthetic_score": 7.0
182
+ },
183
+ "ภาพวาดสีน้ำ (Watercolor)": {
184
+ "prompt": "beautiful watercolor painting, soft edges, artistic brushwork, traditional art medium, colorful artistic interpretation, fine art quality",
185
+ "negative": "photographic, digital art, sharp edges, realistic, computer generated",
186
+ "strength": 0.80,
187
+ "aesthetic_score": 7.0
188
+ },
189
+ "ภาพวาดน้ำมัน (Oil Painting)": {
190
+ "prompt": "classical oil painting, renaissance style, visible brush strokes, artistic masterpiece, museum quality fine art, old master technique",
191
+ "negative": "photographic, digital, modern, flat colors, amateur, low quality",
192
+ "strength": 0.80,
193
+ "aesthetic_score": 7.5
194
+ },
195
+ "กำหนดเอง (Custom)": {
196
+ "prompt": "",
197
+ "negative": "",
198
+ "strength": 0.65,
199
+ "aesthetic_score": 6.0
200
+ }
201
+ }
202
+
203
+ def preprocess_image(image, enhance_quality=True):
204
+ """Pre-process image for better results"""
205
+ if enhance_quality:
206
+ # Auto enhance
207
+ enhancer = ImageEnhance.Sharpness(image)
208
+ image = enhancer.enhance(1.2)
209
+
210
+ enhancer = ImageEnhance.Contrast(image)
211
+ image = enhancer.enhance(1.1)
212
+
213
+ return image
214
+
215
+ def restore_photo(
216
+ input_image,
217
+ preset_name,
218
+ custom_prompt,
219
+ custom_negative,
220
+ strength,
221
+ seed,
222
+ randomize_seed,
223
+ guidance_scale,
224
+ steps,
225
+ enhance_input,
226
+ use_aesthetic_score,
227
+ progress=gr.Progress(track_tqdm=True)
228
+ ):
229
+ """Enhanced image-to-image restoration with SDXL Refiner"""
230
+ if input_image is None:
231
+ raise gr.Error("กรุณาอัพโหลดภาพ")
232
+
233
+ if pipe is None:
234
+ raise gr.Error("โมเดลยังไม่พร้อมใช้งาน")
235
+
236
+ if randomize_seed:
237
+ seed = random.randint(0, MAX_SEED)
238
+
239
+ generator = torch.Generator(device=device).manual_seed(seed)
240
+
241
+ # Get preset settings
242
+ preset = RESTORATION_PRESETS[preset_name]
243
+
244
+ # Use custom prompt if provided
245
+ if custom_prompt.strip():
246
+ prompt = custom_prompt
247
+ negative_prompt = custom_negative if custom_negative.strip() else preset["negative"]
248
+ denoising_strength = strength
249
+ aesthetic_score = preset.get("aesthetic_score", 6.0) if use_aesthetic_score else 6.0
250
+ else:
251
+ prompt = preset["prompt"]
252
+ negative_prompt = preset["negative"]
253
+ denoising_strength = preset["strength"]
254
+ aesthetic_score = preset.get("aesthetic_score", 6.0) if use_aesthetic_score else 6.0
255
+
256
+ # Pre-process image
257
+ original_image = input_image.convert("RGB")
258
+ if enhance_input:
259
+ original_image = preprocess_image(original_image)
260
+
261
+ # Optimize size for processing
262
+ width, height = original_image.size
263
+
264
+ # SDXL Refiner works best at 1024x1024, but we'll optimize for available hardware
265
+ if device.type == "cpu":
266
+ max_size = 768 # Higher than before, Refiner can handle it better
267
+ else:
268
+ max_size = 1024 # Native SDXL resolution
269
+
270
+ if width > max_size or height > max_size:
271
+ if width > height:
272
+ new_width = max_size
273
+ new_height = int(height * (max_size / width))
274
+ else:
275
+ new_height = max_size
276
+ new_width = int(width * (max_size / height))
277
+
278
+ # Make dimensions divisible by 8
279
+ new_width = (new_width // 8) * 8
280
+ new_height = (new_height // 8) * 8
281
+ original_image = original_image.resize((new_width, new_height), Image.LANCZOS)
282
+
283
+ try:
284
+ # SDXL Refiner specific parameters
285
+ result = pipe(
286
+ prompt=prompt,
287
+ negative_prompt=negative_prompt,
288
+ image=original_image,
289
+ strength=denoising_strength,
290
+ guidance_scale=guidance_scale,
291
+ num_inference_steps=steps,
292
+ generator=generator,
293
+ aesthetic_score=aesthetic_score, # SDXL Refiner specific
294
+ negative_aesthetic_score=2.5, # Avoid low quality outputs
295
+ ).images[0]
296
+
297
+ # Clean up memory
298
+ if device.type == "cuda":
299
+ torch.cuda.empty_cache()
300
+ gc.collect()
301
+
302
+ return result, seed
303
+
304
+ except Exception as e:
305
+ raise gr.Error(f"เกิดข้อผิดพลาด: {str(e)}")
306
+
307
+ def update_preset_settings(preset_name):
308
+ """Update UI when preset changes"""
309
+ preset = RESTORATION_PRESETS[preset_name]
310
+ return (
311
+ preset["prompt"],
312
+ preset["negative"],
313
+ preset["strength"]
314
+ )
315
+
316
+ css="""
317
+ #col-container {
318
+ margin: 0 auto;
319
+ max-width: 1400px;
320
+ }
321
+ #main-title h1 {
322
+ font-size: 2.5em !important;
323
+ text-align: center;
324
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
325
+ -webkit-background-clip: text;
326
+ -webkit-text-fill-color: transparent;
327
+ background-clip: text;
328
+ }
329
+ .feature-box {
330
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
331
+ color: white;
332
+ border-radius: 12px;
333
+ padding: 25px;
334
+ margin: 20px 0;
335
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
336
+ }
337
+ .tip-box {
338
+ background: #f0f7ff;
339
+ border-left: 4px solid #4682B4;
340
+ padding: 15px;
341
+ margin: 15px 0;
342
+ border-radius: 8px;
343
+ }
344
+ """
345
+
346
+ with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
347
+ with gr.Column(elem_id="col-container"):
348
+ gr.Markdown("# 📸 Professional Photo Restoration", elem_id="main-title")
349
+ gr.Markdown(f"### ✨ SDXL Refiner 1.0 + Enhanced VAE • Premium Quality")
350
+
351
+ gr.HTML(f"""
352
+ <div class="feature-box">
353
+ <h3>🚀 Professional Image-to-Image Restoration</h3>
354
+ <table style="width:100%; color:white; font-size:1.05em;">
355
+ <tr>
356
+ <td style="padding:8px;">⚡ <strong>Model:</strong></td>
357
+ <td>SDXL Refiner 1.0 - Premium Quality</td>
358
+ </tr>
359
+ <tr>
360
+ <td style="padding:8px;">🎯 <strong>VAE:</strong></td>
361
+ <td>Enhanced FP16-optimized VAE</td>
362
+ </tr>
363
+ <tr>
364
+ <td style="padding:8px;">💎 <strong>Quality:</strong></td>
365
+ <td>Professional restoration & enhancement</td>
366
+ </tr>
367
+ <tr>
368
+ <td style="padding:8px;">🎨 <strong>Features:</strong></td>
369
+ <td>Better detail preservation, accurate colors</td>
370
+ </tr>
371
+ <tr>
372
+ <td style="padding:8px;">💾 <strong>Memory:</strong></td>
373
+ <td>Optimized with VAE tiling and attention slicing</td>
374
+ </tr>
375
+ </table>
376
+ <div style="margin-top:15px; padding:10px; background:rgba(255,255,255,0.1); border-radius:8px;">
377
+ <strong>🔬 Enhanced VAE Benefits:</strong><br>
378
+ ✨ Better FP16/BF16 precision handling<br>
379
+ 🎨 Reduced VAE artifacts<br>
380
+ 📐 Improved detail preservation<br>
381
+ 💎 No NaN issues on mixed precision
382
+ </div>
383
+ </div>
384
+ """)
385
+
386
+ with gr.Row(equal_height=True):
387
+ with gr.Column(scale=1):
388
+ input_image = gr.Image(
389
+ label="📤 อัพโหลดภาพถ่ายเก่า",
390
+ type="pil",
391
+ height=420
392
+ )
393
+
394
+ gr.Markdown("### 🎯 เลือกรูปแบบการซ่อมแซม")
395
+ preset = gr.Dropdown(
396
+ choices=list(RESTORATION_PRESETS.keys()),
397
+ label="เลือกพรีเซ็ต",
398
+ value="ลงสีภาพขาวดำ (Colorize)",
399
+ interactive=True
400
+ )
401
+
402
+ custom_prompt = gr.Textbox(
403
+ label="💬 Prompt (คำสั่งบวก)",
404
+ placeholder="อธิบายผลลัพธ์ที่ต้องการ...",
405
+ lines=2,
406
+ value=RESTORATION_PRESETS["ลงสีภาพขาวดำ (Colorize)"]["prompt"]
407
+ )
408
+
409
+ custom_negative = gr.Textbox(
410
+ label="🚫 Negative Prompt (สิ่งที่ไม่ต้องการ)",
411
+ placeholder="อธิบายสิ่งที่ไม่ต้องการ...",
412
+ lines=2,
413
+ value=RESTORATION_PRESETS["ลงสีภาพขาวดำ (Colorize)"]["negative"]
414
+ )
415
+
416
+ preset.change(
417
+ fn=update_preset_settings,
418
+ inputs=[preset],
419
+ outputs=[custom_prompt, custom_negative, gr.Slider()]
420
+ )
421
+
422
+ run_button = gr.Button("✨ เริ่มซ่อมแซมภาพ", variant="primary", size="lg")
423
+
424
+ with gr.Column(scale=1):
425
+ output_image = gr.Image(
426
+ label="✨ ภาพที่ซ่อมแซมแล้ว",
427
+ interactive=False,
428
+ format="png",
429
+ height=540
430
+ )
431
+
432
+ with gr.Accordion("⚙️ การตั้งค่าขั้นสูง", open=True):
433
+ strength = gr.Slider(
434
+ label="💪 Denoising Strength",
435
+ minimum=0.1,
436
+ maximum=1.0,
437
+ step=0.05,
438
+ value=0.70,
439
+ info="0.3-0.5: เปลี่ยนน้อย | 0.6-0.7: สมดุล | 0.8+: เปลี่ยนมาก"
440
+ )
441
+
442
+ seed = gr.Slider(
443
+ label="🎲 Seed",
444
+ minimum=0,
445
+ maximum=MAX_SEED,
446
+ step=1,
447
+ value=42,
448
+ info="ใช้ seed เดิมได้ผลลัพธ์เหมือนเดิม"
449
+ )
450
+
451
+ randomize_seed = gr.Checkbox(
452
+ label="🔀 สุ่ม Seed ทุกครั้ง",
453
+ value=True
454
+ )
455
+
456
+ guidance_scale = gr.Slider(
457
+ label="💬 Guidance Scale",
458
+ minimum=1.0,
459
+ maximum=15.0,
460
+ step=0.5,
461
+ value=7.5,
462
+ info="ยิ่งสูง = ทำตามคำสั่งมากขึ้น"
463
+ )
464
+
465
+ steps = gr.Slider(
466
+ label="🔢 Inference Steps",
467
+ minimum=10,
468
+ maximum=50,
469
+ step=5,
470
+ value=30,
471
+ info="SDXL Refiner: 20-30 แนะนำ | 40-50 คุณภาพสูงสุด"
472
+ )
473
+
474
+ enhance_input = gr.Checkbox(
475
+ label="✨ ปรับปรุงภาพอินพุตอัตโนมัติ",
476
+ value=True,
477
+ info="เพิ่มความคมชัดและคอนทราสต์"
478
+ )
479
+
480
+ use_aesthetic_score = gr.Checkbox(
481
+ label="🎨 ใช้ Aesthetic Score (SDXL Refiner)",
482
+ value=True,
483
+ info="ปรับคุณภาพภาพให้สวยงามยิ่งขึ้น"
484
+ )
485
+
486
+ gr.HTML("""
487
+ <div class="tip-box">
488
+ <strong>💡 คำแนะนำ SDXL Refiner:</strong><br>
489
+ • <strong>Strength 0.3-0.5:</strong> ซ่อมแซมเล็กน้อย<br>
490
+ • <strong>Strength 0.6-0.7:</strong> ซ่อมแซมปานกลาง ✅<br>
491
+ • <strong>Strength 0.8+:</strong> เปลี่ยนแปลงมาก<br><br>
492
+ • <strong>Guidance 7-9:</strong> สมดุล ✅<br>
493
+ • <strong>Steps 20-30:</strong> คุณภาพดี<br>
494
+ • <strong>Steps 40-50:</strong> คุณภาพสูงสุด
495
+ </div>
496
+ """)
497
+
498
+ # Update strength when preset changes
499
+ preset.change(
500
+ fn=lambda x: RESTORATION_PRESETS[x]["strength"],
501
+ inputs=[preset],
502
+ outputs=[strength]
503
+ )
504
+
505
+ run_button.click(
506
+ fn=restore_photo,
507
+ inputs=[
508
+ input_image, preset, custom_prompt, custom_negative,
509
+ strength, seed, randomize_seed, guidance_scale,
510
+ steps, enhance_input, use_aesthetic_score
511
+ ],
512
+ outputs=[output_image, seed]
513
+ )
514
+
515
+ gr.Markdown(f"""
516
+ ---
517
+ ### 📚 คู่มือการใช้งาน SDXL Refiner Professional
518
+
519
+ #### 🚀 **ทำไมต้อง SDXL Refiner 1.0?**
520
+
521
+ **จุดเด่น:**
522
+ - ✅ **คุณภาพสูงสุด** - ออกแบบมาเพื่อปรับปรุงและซ่อมแซมภาพโดยเฉพาะ
523
+ - ✅ **Aesthetic Score** - ควบคุมความสวยงามของภาพได้
524
+ - ✅ **รองรับ 1024px** - คุณภาพภาพสูงกว่าโมเดลอื่น
525
+ - ✅ **Detail Enhancement** - เพิ่มรายละเอียดได้ดีเยี่ยม
526
+ - ✅ **Color Accuracy** - สีสมจริงและแม่นยำ
527
+ - ✅ **Enhanced VAE** - ลด artifacts, ป้องกัน NaN issues
528
+
529
+ **เมื่อเทียบกับโมเดลอื่น:**
530
+ - **SDXL Refiner**: คุณภาพสูงสุด, เหมาะกับงานคุณภาพ ⭐⭐⭐⭐⭐
531
+ - **SDXL Turbo**: เร็วที่สุด, คุณภาพดี ⭐⭐⭐⭐
532
+ - **SD 1.5**: เบา, คุณภาพปานกลาง ⭐⭐⭐
533
+
534
+ #### 🎯 **วิธีใช้งาน:**
535
+
536
+ 1. **อัพโหลดภาพ** ที่ต้องการซ่อมแซม
537
+ 2. **เลือกพรีเซ็ต** - มี 11 รูปแบบให้เลือก
538
+ 3. **ปรับ Strength** ตามความต้องการ
539
+ 4. **เปิด Aesthetic Score** สำหรับคุณภาพสูงสุด
540
+ 5. **เปิด Input Enhancement** สำหรับผลลัพธ์ดีขึ้น
541
+ 6. **กดปุ่ม "เริ่มซ่อมแซมภาพ"**
542
+ 7. **รอ 1-5 นาที** (ขึ้นกับฮาร์ดแวร์)
543
+
544
+ #### ⚙️ **การตั้งค่าที่แนะนำ:**
545
+
546
+ | งาน | Strength | Guidance | Steps | Aesthetic |
547
+ |-----|----------|----------|-------|-----------|
548
+ | ลงสีภาพขาวดำ | 0.70 | 7-8 | 30 | 7.0 |
549
+ | ซ่อมแซมรอยขีดข่วน | 0.55 | 6-7 | 25-30 | 6.5 |
550
+ | เพิ่มความคมชัด | 0.40 | 5-6 | 20-25 | 6.5 |
551
+ | เปลี่ยนสไตล์ | 0.80-0.85 | 8-10 | 30-40 | 7.0-7.5 |
552
+ | คุณภาพสูงสุด | 0.65 | 7-9 | 40-50 | 7.5-8.0 |
553
+
554
+ #### 💡 **เคล็ดลับ:**
555
+
556
+ **สำหรับ CPU:**
557
+ - ใช้ Steps 20-25
558
+ - Guidance 6-7
559
+ - Strength 0.6-0.7
560
+ - ภาพไม่เกิน 768x768px
561
+ - เปิด Model CPU Offload
562
+ - Expected: 3-5 นาที/ภาพ
563
+
564
+ **สำหรับ GPU (8GB+):**
565
+ - ใช้ Steps 30-40
566
+ - Guidance 7-9
567
+ - Strength ตามต้องการ
568
+ - ภาพได้ถึง 1024x1024px
569
+ - เปิด Aesthetic Score
570
+ - Expected: 45-90 วินาที/ภาพ
571
+
572
+ **สำหรับ GPU (16GB+):**
573
+ - ใช้ Steps 40-50
574
+ - Guidance 8-10
575
+ - ความละเอียดสูงสุด
576
+ - Aesthetic Score 7.5-8.0
577
+ - Expected: 30-60 วินาที/ภาพ
578
+
579
+ #### 🎨 **Aesthetic Score คืออะไร?**
580
+
581
+ Aesthetic Score ช่วยควบคุมคุณภาพและความสวยงามของภาพที่สร้าง:
582
+ - **6.0-6.5**: คุณภาพมาตรฐาน
583
+ - **7.0-7.5**: คุณภาพสูง (แนะนำ) ✅
584
+ - **8.0+**: คุณภาพพรีเมี่ยม
585
+
586
+ #### 📊 **พรีเซ็ตพิเศษ:**
587
+
588
+ - 🎨 **ลงสีภาพขาวดำ** - แปลงภาพขาวดำเป็นสีสมจริง
589
+ - 🔧 **ซ่อมแซมเต็มรูปแบบ** - ลบรอยชำรุด ปรับปรุงคุณภาพ
590
+ - 🧹 **ลบรอยขีดข่วน** - กำจัดรอยเสี��หายต่างๆ
591
+ - 💎 **เพิ่มสีที่เลือนหาย** - ทำให้สีสดใสขึ้น
592
+ - 📐 **ลดสัญญาณรบกวน** - ลดเกรน เพิ่มความคมชัด
593
+ - ✨ **เพิ่มความคมชัด** - ทำให้ภาพคมชัดขึ้น
594
+ - 📸 **สไตล์โปรเฟสชันนัล** - แปลงเป็นภาพถ่ายสตูดิโอ
595
+ - 🎬 **สไตล์ภาพยนตร์** - ให้ความรู้สึกแบบหนัง
596
+ - 🎭 **เปลี่ยนเป็นอนิเมะ** - แปลงเป็นสไตล์อนิเมะ
597
+ - 🖼️ **ภาพวาดสีน้ำ** - แปลงเป็นภาพวาดสีน้ำ
598
+ - 🎨 **ภาพวาดน้ำมัน** - แปลงเป็นภาพวาดน้ำมัน
599
+
600
+ #### 🔬 **Enhanced VAE:**
601
+
602
+ **ทำไมต้องใช้ Enhanced VAE?**
603
+ - ✅ **FP16 Optimization**: ทำงานได้ดีกับ Mixed Precision
604
+ - ✅ **No NaN Issues**: ไม่เกิดปัญหา NaN values
605
+ - ✅ **Better Colors**: สีแม่นยำและสมจริงกว่า
606
+ - ✅ **Less Artifacts**: ลด compression artifacts
607
+ - ✅ **Stable**: เสถียรกว่า VAE มาตรฐาน
608
+
609
+ **VAE ทำอะไร?**
610
+ ```
611
+ Input Image
612
+
613
+ VAE Encoder (ภาพ → Latent Space)
614
+
615
+ Diffusion Model (ปรับปรุง Latent)
616
+
617
+ VAE Decoder (Latent → ภาพคุณภาพสูง)
618
+
619
+ Output Image
620
+ ```
621
+
622
+ #### ⚡ **ประสิทธิภาพ:**
623
+
624
+ **SDXL Refiner Performance:**
625
+ - **CPU (16GB RAM):** 3-5 นาที/ภาพ (768px)
626
+ - **GPU (8GB VRAM):** 45-90 วินาที/ภาพ (1024px)
627
+ - **GPU (12GB VRAM):** 40-75 วินาที/ภาพ (1024px)
628
+ - **GPU (16GB+ VRAM):** 30-60 วินาที/ภาพ (1024px)
629
+
630
+ **ขนาดโมเดล:**
631
+ - SDXL Refiner: ~6GB
632
+ - Enhanced VAE: ~335MB
633
+ - Total: ~6.4GB
634
+
635
+ #### 🎯 **Use Cases:**
636
+
637
+ ✅ **เหมาะสำหรับ:**
638
+ - ภาพถ่ายโบราณที่ต้องการซ่อมแซม
639
+ - ภาพที่ต้องการลงสีอย่างแม่นยำ
640
+ - ภาพที่มีรายละเอียดเยอะ
641
+ - งานที่ต้องการคุณภาพสูงสุด
642
+ - ภาพที่จะนำไปพิมพ์
643
+ - งาน Professional/Commercial
644
+
645
+ ⚠️ **ไม่เหมาะกับ:**
646
+ - งานที่ต้องการความเร็ว (ใช้ SDXL Turbo)
647
+ - เครื่องที่ RAM/VRAM น้อยกว่า 8GB
648
+ - การทดลองแบบรวดเร็วหลายๆ รูป
649
+
650
+ #### 💡 **Tips & Tricks:**
651
+
652
+ **1. การเลือก Strength:**
653
+ - 0.3-0.5: เปลี่ยนแปลงเล็กน้อย (ลดสัญญาณรบกวน)
654
+ - 0.6-0.7: สมดุลดี (แนะนำสำหรับส่วนใหญ่) ✅
655
+ - 0.8-0.9: เปลี่ยนแปลงมาก (เปลี่ยนสไตล์)
656
+
657
+ **2. ปรับปรุงคุณภาพ:**
658
+ - เปิด "Input Enhancement" เสมอ
659
+ - ใช้ Aesthetic Score 7.0-7.5
660
+ - เพิ่ม Steps สำหรับงานสำคัญ (40-50)
661
+ - Guidance ไม่ควรเกิน 10
662
+
663
+ **3. ประหยัดเวลา:**
664
+ - ใช้ Steps 20-25 สำหรับทดลอง
665
+ - Resize ภาพก่อนอัพโหลด
666
+ - ลด Guidance เป็น 6-7
667
+ - ปิด Aesthetic Score ถ้าไม่จำเป็น
668
+
669
+ **4. แก้ปัญหา:**
670
+ - **ภาพเบลอ**: เพิ่ม Steps, ลด Strength
671
+ - **สีไม่ถูก**: ปรับ Guidance, Aesthetic Score
672
+ - **Detail หาย**: ลด Strength เหลือ 0.5-0.6
673
+ - **Out of Memory**: ลดขนาดภาพ, เปิด VAE tiling
674
+ - **ใช้เวลานาน**: ลด Steps, ลด resolution
675
+
676
+ #### 🔄 **Comparison Table:**
677
+
678
+ | Feature | SDXL Refiner | SDXL Turbo | SD 1.5 |
679
+ |---------|--------------|------------|--------|
680
+ | Quality | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
681
+ | Speed | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
682
+ | Memory | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
683
+ | Resolution | 1024px | 768px | 512px |
684
+ | Best For | Quality | Speed | Low-end |
685
+
686
+ ---
687
+
688
+ <div style="text-align:center; color:#666; padding:20px;">
689
+ <strong>🌟 SDXL Refiner 1.0 Professional</strong><br>
690
+ Premium Photo Restoration System<br>
691
+ <em>Highest Quality • Enhanced VAE • Aesthetic Control</em><br><br>
692
+ <div style="font-size:0.9em; margin-top:10px;">
693
+ <strong>Powered by:</strong><br>
694
+ Stability AI (SDXL Refiner) + Enhanced VAE
695
+ </div>
696
+ </div>
697
+ """)
698
+
699
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)