File size: 34,531 Bytes
af9b56f
e7d7766
af9b56f
 
 
e7d7766
af9b56f
b199ca4
af9b56f
 
 
 
 
 
 
b199ca4
af9b56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0539159
af9b56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7d7766
af9b56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c2d80a
af9b56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7d7766
 
af9b56f
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# integrated_app.py
"""
統合画像処理アプリケーション
- タブ1: Twitter隠し絵ジェネレーター(透過マスク方式)
- タブ2: 透過ツール(モバイル最適化版 + 複数色パレット対応)
"""

import gradio as gr
import numpy as np
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
import cv2
import warnings
import tempfile
import os
warnings.filterwarnings('ignore')

# ========================
# 共通ユーティリティ関数
# ========================

def hex_to_rgb(hex_color: str):
    """ '#rrggbb' -> np.array([r,g,b], dtype=np.uint8) """
    if not isinstance(hex_color, str):
        return np.array([255, 255, 255], dtype=np.uint8)
    s = hex_color.lstrip('#')
    if len(s) != 6:
        return np.array([255, 255, 255], dtype=np.uint8)
    return np.array([int(s[i:i+2], 16) for i in (0, 2, 4)], dtype=np.uint8)

def resize_image_for_processing(image, max_size=800):
    """処理用に画像をリサイズ(メモリ節約)"""
    width, height = image.size
    if max(width, height) > max_size:
        if width > height:
            new_width = max_size
            new_height = int(height * max_size / width)
        else:
            new_height = max_size
            new_width = int(width * max_size / height)
        return image.resize((new_width, new_height), Image.LANCZOS)
    return image

# ========================
# Twitter隠し絵機能
# ========================

def adjust_image(image, brightness=0, contrast=0, saturation=0, gamma=1.0):
    """画像の色調補正"""
    if image is None:
        return None
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)
    image = image.convert('RGB')
    if brightness != 0:
        image = ImageEnhance.Brightness(image).enhance(1 + brightness / 100.0)
    if contrast != 0:
        image = ImageEnhance.Contrast(image).enhance(1 + contrast / 100.0)
    if saturation != 0:
        image = ImageEnhance.Color(image).enhance(1 + saturation / 100.0)
    if gamma != 1.0:
        table = [int(((i / 255.0) ** (1.0 / gamma)) * 255) for i in range(256)]
        image = image.point(table * 3)
    return image

def extract_line_art(image, method="canny", canny_low=50, canny_high=150, 
                     blur_before=1, invert=True, enhance_contrast=1.2):
    """画像から線画を抽出する"""
    if image is None:
        return None
    
    img_array = np.array(image.convert('RGB'))
    gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
    
    if blur_before > 0:
        gray = cv2.GaussianBlur(gray, (blur_before*2+1, blur_before*2+1), 0)
    
    if method == "canny":
        edges = cv2.Canny(gray, canny_low, canny_high)
    elif method == "sobel":
        sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
        sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
        edges = np.sqrt(sobelx**2 + sobely**2)
        edges = np.uint8(np.clip(edges, 0, 255))
    elif method == "laplacian":
        edges = cv2.Laplacian(gray, cv2.CV_64F)
        edges = np.uint8(np.absolute(edges))
    else:
        edges = cv2.Canny(gray, canny_low, canny_high)
    
    if invert:
        edges = 255 - edges
    
    edges_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
    result = Image.fromarray(edges_rgb)
    
    if enhance_contrast != 1.0:
        result = ImageEnhance.Contrast(result).enhance(enhance_contrast)
    
    return result

def create_alpha_mask_from_hidden(hidden_image, threshold=128, blur_radius=1, soften=0):
    """隠し画像からアルファマスク生成"""
    if hidden_image is None:
        return None
    
    h_rgb = hidden_image.convert('RGB')
    h_arr = np.array(h_rgb)
    gray = cv2.cvtColor(h_arr, cv2.COLOR_RGB2GRAY)
    
    if blur_radius > 0:
        k = blur_radius * 2 + 1
        gray = cv2.GaussianBlur(gray, (k, k), 0)
    
    if soften <= 0:
        alpha = np.where(gray < threshold, 0, 255).astype(np.uint8)
    else:
        low = threshold - soften
        high = threshold + soften
        alpha = np.zeros_like(gray, dtype=np.float32)
        alpha = np.where(gray <= low, 0.0, alpha)
        alpha = np.where(gray >= high, 255.0, alpha)
        between = (gray > low) & (gray < high)
        alpha[between] = ((gray[between] - low) / (high - low)) * 255.0
        alpha = np.clip(alpha, 0, 255).astype(np.uint8)
    
    return alpha

def save_transparent_png(image):
    """透過PNG画像を一時ファイルに保存してファイルパスを返す"""
    if image is None:
        return None
    
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
    temp_file.close()
    
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    
    image.save(temp_file.name, 'PNG', optimize=True)
    return temp_file.name

def preview_normal_adjustment(image, brightness=0, contrast=0, saturation=0, gamma=1.0,
                             enable_line_art=False, line_method="canny", 
                             canny_low=50, canny_high=150, blur_before=1):
    """通常画像の調整プレビュー"""
    if image is None:
        return None
    
    adjusted = adjust_image(image, brightness, contrast, saturation, gamma)
    
    if enable_line_art:
        adjusted = extract_line_art(adjusted, method=line_method, 
                                   canny_low=canny_low, canny_high=canny_high,
                                   blur_before=blur_before)
    
    return adjusted

def preview_hidden_adjustment(image, brightness=0, contrast=0, saturation=0, gamma=1.0,
                             enable_line_art=False, line_method="canny",
                             canny_low=50, canny_high=150, blur_before=1):
    """隠し画像の調整プレビュー"""
    if image is None:
        return None
    
    adjusted = adjust_image(image, brightness, contrast, saturation, gamma)
    
    if enable_line_art:
        adjusted = extract_line_art(adjusted, method=line_method,
                                   canny_low=canny_low, canny_high=canny_high,
                                   blur_before=blur_before)
    
    return adjusted

def generate_twitter_hidden_image_advanced(
    normal_image, hidden_image,
    normal_brightness=0, normal_contrast=0, normal_saturation=0, normal_gamma=1.0,
    normal_line_art=False, normal_line_method="canny", normal_canny_low=50, normal_canny_high=150, normal_blur_before=1,
    hidden_brightness=0, hidden_contrast=0, hidden_saturation=0, hidden_gamma=1.0,
    hidden_line_art=False, hidden_line_method="canny", hidden_canny_low=50, hidden_canny_high=150, hidden_blur_before=1,
    output_size=900, mask_blur=1, mask_threshold=128, mask_soften=0
):
    """透過PNG生成関数"""
    if normal_image is None or hidden_image is None:
        return None, None, None, None, None
    
    try:
        size = (output_size, output_size)

        # 通常画像の処理
        adjusted_normal = adjust_image(normal_image, normal_brightness, normal_contrast,
                                       normal_saturation, normal_gamma)
        if normal_line_art:
            adjusted_normal = extract_line_art(adjusted_normal, method=normal_line_method,
                                              canny_low=normal_canny_low, canny_high=normal_canny_high,
                                              blur_before=normal_blur_before)
        adjusted_normal = adjusted_normal.resize(size, Image.Resampling.LANCZOS)
        normal_rgb = adjusted_normal.convert('RGB')

        # 隠し画像の処理
        adjusted_hidden = adjust_image(hidden_image, hidden_brightness, hidden_contrast,
                                       hidden_saturation, hidden_gamma)
        if hidden_line_art:
            adjusted_hidden = extract_line_art(adjusted_hidden, method=hidden_line_method,
                                              canny_low=hidden_canny_low, canny_high=hidden_canny_high,
                                              blur_before=hidden_blur_before)
        adjusted_hidden = adjusted_hidden.resize(size, Image.Resampling.LANCZOS)

        # アルファマスク生成
        alpha_mask = create_alpha_mask_from_hidden(adjusted_hidden, threshold=mask_threshold,
                                                   blur_radius=mask_blur, soften=mask_soften)

        # RGBA画像作成
        base_rgba = normal_rgb.convert('RGBA')
        alpha_pil = Image.fromarray(alpha_mask, mode='L')
        base_rgba.putalpha(alpha_pil)

        # プレビュー作成
        h_preview_arr = np.dstack([np.array(adjusted_hidden.convert('RGB')), alpha_mask])
        hidden_layer_preview = Image.fromarray(h_preview_arr, mode='RGBA')

        white_bg = Image.new('RGBA', size, (255, 255, 255, 255))
        light_preview_rgba = Image.alpha_composite(white_bg, base_rgba)
        light_preview = light_preview_rgba.convert('RGB')

        dark_bg = Image.new('RGBA', size, (21, 32, 43, 255))
        dark_preview_rgba = Image.alpha_composite(dark_bg, base_rgba)
        dark_preview = ImageEnhance.Contrast(dark_preview_rgba.convert('RGB')).enhance(1.12)

        result = base_rgba
        download_file = save_transparent_png(result)

        return result, light_preview, dark_preview, hidden_layer_preview, download_file

    except Exception as e:
        print("エラーが発生しました:", e)
        return None, None, None, None, None

# ========================
# 透過ツール機能
# ========================

def rgb_to_hex(rgb):
    """ [r,g,b] or (r,g,b) -> '#rrggbb' """
    r, g, b = int(rgb[0]), int(rgb[1]), int(rgb[2])
    return f"#{r:02x}{g:02x}{b:02x}"

def build_palette_html(colors):
    """色パレットをHTMLで表示"""
    if not colors:
        return "<div style='color:#666;padding:10px;'>パレットは空です。画像をクリックして色を追加してください。</div>"
    parts = []
    for i, c in enumerate(colors):
        parts.append(f"<div style='display:inline-block;margin:2px;padding:2px;text-align:center;'>"
                     f"<div style='width:32px;height:20px;background-color:{c};border:1px solid #ccc;'></div>"
                     f"<div style='font-size:11px;margin-top:2px;'>{i+1}</div>"
                     f"</div>")
    return "<div style='display:flex;flex-wrap:wrap;padding:5px;'>" + "".join(parts) + "</div>"

def create_simple_mask(img_cv, method='simple'):
    """シンプルなマスク生成"""
    height, width = img_cv.shape[:2]
    mask = np.zeros((height, width), np.uint8)
    
    try:
        if method == 'simple':
            hsv = cv2.cvtColor(img_cv, cv2.COLOR_BGR2HSV)
            lower_blue = np.array([100, 50, 30])
            upper_blue = np.array([130, 255, 150])
            blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
            
            border_width = max(3, min(width, height) // 100)
            mask[:border_width, :] = cv2.GC_BGD
            mask[-border_width:, :] = cv2.GC_BGD
            mask[:, :border_width] = cv2.GC_BGD
            mask[:, -border_width:] = cv2.GC_BGD
            
            for y in range(height):
                for x in range(width):
                    if blue_mask[y, x] > 0 and mask[y, x] == cv2.GC_BGD:
                        continue
                    elif mask[y, x] == cv2.GC_BGD:
                        mask[y, x] = cv2.GC_PR_FGD
            
            center_margin = max(20, min(width, height) // 20)
            mask[center_margin:-center_margin, center_margin:-center_margin] = cv2.GC_PR_FGD
            
        elif method == 'minimal':
            border_width = 2
            mask[:border_width, :] = cv2.GC_BGD
            mask[-border_width:, :] = cv2.GC_BGD
            mask[:, :border_width] = cv2.GC_BGD
            mask[:, -border_width:] = cv2.GC_BGD
            mask[mask == 0] = cv2.GC_PR_FGD
            
    except Exception as e:
        print(f"マスク生成エラー: {e}")
        border = max(5, min(width, height) // 50)
        mask[border:-border, border:-border] = cv2.GC_PR_FGD
    
    return mask

def remove_background_grabcut(image, iter_count=5, blur_kernel=3, mask_method='simple'):
    """GrabCutを使用した背景除去"""
    try:
        original_size = image.size
        processed_image = resize_image_for_processing(image, max_size=600)
        
        img_array = np.array(processed_image.convert('RGB'))
        img_cv = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
        height, width = img_cv.shape[:2]
        
        mask = create_simple_mask(img_cv, method=mask_method)
        
        bgd_model = np.zeros((1, 65), np.float64)
        fgd_model = np.zeros((1, 65), np.float64)
        
        iter_count = min(int(iter_count), 8)
        cv2.grabCut(img_cv, mask, None, bgd_model, fgd_model, iter_count, cv2.GC_INIT_WITH_MASK)
        
        mask2 = np.where((mask == cv2.GC_BGD) | (mask == cv2.GC_PR_BGD), 0, 1).astype('uint8')
        
        if blur_kernel > 1:
            k = min(int(blur_kernel), 7)
            if k % 2 == 0:
                k += 1
            mask2_float = cv2.GaussianBlur(mask2.astype(np.float32), (k, k), 0)
            mask2 = np.clip(mask2_float * 255.0, 0, 255).astype(np.uint8)
        else:
            mask2 = mask2 * 255
        
        result_rgba = np.dstack([img_array, mask2])
        result_image = Image.fromarray(result_rgba, 'RGBA')
        
        if result_image.size != original_size:
            result_image = result_image.resize(original_size, Image.LANCZOS)
        
        return result_image
        
    except Exception as e:
        print(f"背景除去エラー: {e}")
        img_array = np.array(image.convert('RGB'))
        alpha = np.full((img_array.shape[0], img_array.shape[1]), 255, dtype=np.uint8)
        result_rgba = np.dstack([img_array, alpha])
        return Image.fromarray(result_rgba, 'RGBA')

def remove_background_by_multiple_colors(pil_image, colors_hex, tolerance=50, feather=5, morph_iter=0):
    """複数色をまとめて除去する関数"""
    if pil_image is None:
        return None

    if not colors_hex or len(colors_hex) == 0:
        rgb = np.array(pil_image.convert('RGB')).astype(np.uint8)
        alpha_full = np.full((rgb.shape[0], rgb.shape[1]), 255, dtype=np.uint8)
        return Image.fromarray(np.dstack([rgb, alpha_full]), mode="RGBA")

    try:
        original_size = pil_image.size
        processed_image = resize_image_for_processing(pil_image, max_size=800)
        
        img_rgb = np.array(processed_image.convert("RGB")).astype(np.float32)
        h, w = img_rgb.shape[:2]

        target_rgbs = np.array([hex_to_rgb(hx).astype(np.float32) for hx in colors_hex])

        img_exp = img_rgb[:, :, np.newaxis, :]
        tgt_exp = target_rgbs[np.newaxis, np.newaxis, :, :]
        diff = img_exp - tgt_exp
        dist = np.sqrt(np.sum(diff ** 2, axis=3))
        mask_bg_any = np.any(dist <= float(tolerance), axis=2).astype(np.uint8)

        if morph_iter and morph_iter > 0:
            kernel = np.ones((3, 3), np.uint8)
            mask_bg_any = cv2.morphologyEx(mask_bg_any, cv2.MORPH_CLOSE, kernel, iterations=int(min(morph_iter, 3)))

        mask_fg = 1 - mask_bg_any

        if feather and feather > 0:
            k = min(int(max(1, round(feather))), 15)
            k = k if k % 2 == 1 else k + 1
            mask_float = mask_fg.astype(np.float32)
            mask_blurred = cv2.GaussianBlur(mask_float, (k, k), 0)
        else:
            mask_blurred = mask_fg.astype(np.float32)

        alpha = np.clip(mask_blurred * 255.0, 0, 255).astype(np.uint8)

        result_rgba = np.dstack([img_rgb.astype(np.uint8), alpha])
        result_image = Image.fromarray(result_rgba, mode="RGBA")
        
        if result_image.size != original_size:
            result_image = result_image.resize(original_size, Image.LANCZOS)
            
        return result_image
        
    except Exception as e:
        print(f"複数色除去エラー: {e}")
        rgb = np.array(pil_image.convert('RGB')).astype(np.uint8)
        alpha_full = np.full((rgb.shape[0], rgb.shape[1]), 255, dtype=np.uint8)
        return Image.fromarray(np.dstack([rgb, alpha_full]), mode="RGBA")

def get_color_from_coordinate(image, x, y):
    """指定座標から色を取得"""
    if image is None:
        return "#ffffff"
    try:
        img_array = np.array(image.convert('RGB'))
        height, width = img_array.shape[:2]
        x, y = int(x), int(y)
        if 0 <= x < width and 0 <= y < height:
            r, g, b = img_array[y, x]
            return f"#{r:02x}{g:02x}{b:02x}"
        else:
            return "#ffffff"
    except Exception:
        return "#ffffff"

def process_image_transparency(image, method, iter_count, blur_kernel, mask_method, palette, tolerance, feather, morph_iter):
    if image is None:
        return None
    
    try:
        if method == "AI自動除去 (GrabCut)":
            return remove_background_grabcut(image, iter_count=int(iter_count), 
                                           blur_kernel=int(blur_kernel), mask_method=mask_method)
        else:
            return remove_background_by_multiple_colors(image, palette, tolerance=tolerance, 
                                                      feather=feather, morph_iter=morph_iter)
    except Exception as e:
        print(f"処理エラー: {e}")
        return None

# ========================
# メインインターフェース
# ========================

def create_integrated_interface():
    with gr.Blocks(title="統合画像処理アプリ", theme=gr.themes.Soft()) as app:
        gr.Markdown("""
        # 🎨 統合画像処理アプリケーション
        **Twitter隠し絵作成**と**透過処理**の2つの機能を1つのアプリで!
        """)
        
        with gr.Tabs():
            # ========================
            # タブ1: Twitter隠し絵ジェネレーター
            # ========================
            with gr.TabItem("🎭 Twitter隠し絵ジェネレーター"):
                gr.Markdown("""
                ## Twitter隠し絵ジェネレーター(透過マスク方式)
                隠し画像部分をアルファ(透明)として出力します。線画抽出機能付きで、写真からも線画を生成できます。
                """)
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### 通常画像(背景になる画像)")
                        normal_image = gr.Image(label="通常画像をアップロード", type="pil")
                        
                        normal_line_art = gr.Checkbox(label="線画抽出を有効にする", value=False)
                        with gr.Accordion("線画抽出設定", open=False):
                            normal_line_method = gr.Dropdown(
                                choices=["canny", "sobel", "laplacian"], 
                                value="canny", 
                                label="抽出方法"
                            )
                            normal_canny_low = gr.Slider(10, 200, 50, step=10, label="Canny低閾値")
                            normal_canny_high = gr.Slider(50, 300, 150, step=10, label="Canny高閾値")
                            normal_blur_before = gr.Slider(0, 5, 1, step=1, label="前処理ぼかし")
                        
                        with gr.Accordion("通常画像の調整", open=False):
                            normal_brightness = gr.Slider(-100, 100, 0, step=5, label="明度")
                            normal_contrast = gr.Slider(-100, 100, 0, step=5, label="コントラスト")
                            normal_saturation = gr.Slider(-100, 100, 0, step=5, label="彩度")
                            normal_gamma = gr.Slider(0.3, 3.0, 1.0, step=0.1, label="ガンマ")
                        
                        normal_preview = gr.Image(label="調整後の通常画像プレビュー", type="pil")
                    
                    with gr.Column():
                        gr.Markdown("### 隠し画像(線画または写真)")
                        hidden_image = gr.Image(label="隠し画像をアップロード", type="pil")
                        
                        hidden_line_art = gr.Checkbox(label="線画抽出を有効にする", value=False)
                        with gr.Accordion("線画抽出設定", open=False):
                            hidden_line_method = gr.Dropdown(
                                choices=["canny", "sobel", "laplacian"], 
                                value="canny", 
                                label="抽出方法"
                            )
                            hidden_canny_low = gr.Slider(10, 200, 50, step=10, label="Canny低閾値")
                            hidden_canny_high = gr.Slider(50, 300, 150, step=10, label="Canny高閾値")
                            hidden_blur_before = gr.Slider(0, 5, 1, step=1, label="前処理ぼかし")
                        
                        with gr.Accordion("隠し画像の調整", open=False):
                            hidden_brightness = gr.Slider(-100, 100, 0, step=5, label="明度")
                            hidden_contrast = gr.Slider(-100, 100, 0, step=5, label="コントラスト")
                            hidden_saturation = gr.Slider(-100, 100, 0, step=5, label="彩度")
                            hidden_gamma = gr.Slider(0.3, 3.0, 1.0, step=0.1, label="ガンマ")
                        
                        hidden_preview = gr.Image(label="調整後の隠し画像プレビュー", type="pil")
                
                with gr.Row():
                    with gr.Column():
                        output_size = gr.Slider(128, 900, 900, step=1, label="出力サイズ(px)(Twitterは900推奨)")
                        mask_threshold = gr.Slider(0, 255, 180, step=1, label="マスク閾値(低=黒が透明)")
                    with gr.Column():
                        mask_blur = gr.Slider(0, 10, 0, step=1, label="マスクぼかし(輪郭を柔らかく)")
                        mask_soften = gr.Slider(0, 128, 50, step=1, label="マスクソフト化幅(0=二値)")
                
                with gr.Row():
                    generate_btn = gr.Button("生成(透過PNG)", variant="primary", size="lg")
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("#### ライトモードでの見え方")
                        light_preview = gr.Image(label="ライトプレビュー")
                    with gr.Column():
                        gr.Markdown("#### ダークモードでの見え方")
                        dark_preview = gr.Image(label="ダークプレビュー")
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("#### 隠しレイヤープレビュー")
                        hidden_layer_preview = gr.Image(label="隠しレイヤープレビュー(アルファ付き)")
                    with gr.Column():
                        gr.Markdown("#### プレビュー表示")
                        result_image = gr.Image(label="結果プレビュー", type="pil")
                
                with gr.Row():
                    gr.Markdown("#### **🎯 透過PNGダウンロード**")
                with gr.Row():
                    download_file = gr.File(label="透過PNG画像をダウンロード", file_count="single")
                    gr.Markdown("**📥 ⬅ このファイルをクリックしてダウンロード**")

                # Twitter隠し絵のイベントハンドラ
                normal_controls = [
                    normal_image, normal_brightness, normal_contrast, normal_saturation, normal_gamma,
                    normal_line_art, normal_line_method, normal_canny_low, normal_canny_high, normal_blur_before
                ]
                for control in normal_controls:
                    control.change(
                        fn=preview_normal_adjustment,
                        inputs=normal_controls,
                        outputs=normal_preview
                    )
                
                hidden_controls = [
                    hidden_image, hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma,
                    hidden_line_art, hidden_line_method, hidden_canny_low, hidden_canny_high, hidden_blur_before
                ]
                for control in hidden_controls:
                    control.change(
                        fn=preview_hidden_adjustment,
                        inputs=hidden_controls,
                        outputs=hidden_preview
                    )
                
                generate_btn.click(
                    fn=generate_twitter_hidden_image_advanced,
                    inputs=[
                        normal_image, hidden_image,
                        normal_brightness, normal_contrast, normal_saturation, normal_gamma,
                        normal_line_art, normal_line_method, normal_canny_low, normal_canny_high, normal_blur_before,
                        hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma,
                        hidden_line_art, hidden_line_method, hidden_canny_low, hidden_canny_high, hidden_blur_before,
                        output_size, mask_blur, mask_threshold, mask_soften
                    ],
                    outputs=[result_image, light_preview, dark_preview, hidden_layer_preview, download_file]
                )

            # ========================
            # タブ2: 透過ツール
            # ========================
            with gr.TabItem("🎨 透過ツール"):
                gr.Markdown("""
                ## 透過ツール(モバイル最適化版)
                - **AI自動除去**: フレーム画像の背景を自動除去
                - **複数色除去**: クリックで色を登録してまとめて除去
                """)

                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("## 📤 入力設定")
                        input_image = gr.Image(label="画像をアップロード", type="pil", format="png", interactive=True)

                        method = gr.Radio(
                            choices=["AI自動除去 (GrabCut)", "複数色除去"],
                            value="AI自動除去 (GrabCut)",
                            label="透過方法"
                        )

                        with gr.Group() as ai_options:
                            gr.Markdown("### 🤖 AI処理設定")
                            mask_method = gr.Radio(
                                choices=["simple", "minimal"],
                                value="simple",
                                label="処理方法",
                                info="simple: 標準 / minimal: 最軽量"
                            )
                            iter_count = gr.Slider(1, 8, value=5, step=1, label="処理回数")
                            blur_kernel = gr.Slider(1, 7, value=3, step=2, label="ぼかし強度")

                        with gr.Group(visible=False) as color_options:
                            gr.Markdown("### 🎯 色登録")
                            click_x = gr.Number(label="X座標", value=0, visible=False)
                            click_y = gr.Number(label="Y座標", value=0, visible=False)
                            
                            current_color = gr.ColorPicker(label="選択した色", value="#ffffff")
                            color_preview = gr.HTML(value="<div style='width:40px;height:20px;background-color:#ffffff;border:1px solid #ccc;display:inline-block;'></div>")
                            
                            with gr.Row():
                                add_color_btn = gr.Button("➕ 追加", size="sm")
                                remove_select = gr.Dropdown(label="削除する色", choices=[], value=None, interactive=True)
                                remove_color_btn = gr.Button("🗑️ 削除", size="sm")
                                clear_palette_btn = gr.Button("🧼 全消去", size="sm")
                            
                            gr.Markdown("### ⚙️ 除去設定")
                            tolerance = gr.Slider(minimum=0, maximum=200, value=60, step=1, label="許容範囲")
                            feather = gr.Slider(minimum=0, maximum=20, value=5, step=1, label="フェザー")
                            morph_iter = gr.Slider(minimum=0, maximum=3, value=0, step=1, label="ノイズ除去")

                        process_btn = gr.Button("🚀 透過処理を実行", variant="primary", size="lg")

                    with gr.Column(scale=1):
                        gr.Markdown("## 📤 色パレット")
                        palette_html = gr.HTML(value="<div style='color:#666;padding:10px;'>パレットは空です。</div>")
                        
                        gr.Markdown("## 📤 処理結果")
                        output_image = gr.Image(label="透過結果", type="pil", format="png", show_download_button=True)

                # 透過ツールのState
                palette_state = gr.State([])

                # 透過ツールのイベントハンドラ
                def toggle_options(selected_method):
                    return (
                        gr.update(visible=(selected_method == "AI自動除去 (GrabCut)")),
                        gr.update(visible=(selected_method == "複数色除去"))
                    )

                method.change(fn=toggle_options, inputs=[method], outputs=[ai_options, color_options])

                def handle_image_click(image, evt: gr.SelectData):
                    try:
                        if evt is not None and getattr(evt, "index", None) is not None:
                            ix, iy = evt.index[0], evt.index[1]
                            color_hex = get_color_from_coordinate(image, ix, iy)
                            preview_html = f"<div style='width:40px;height:20px;background-color:{color_hex};border:1px solid #ccc;display:inline-block;'></div><span style='margin-left:8px;'>{color_hex}</span>"
                            return ix, iy, color_hex, preview_html
                    except Exception:
                        pass
                    return 0, 0, "#ffffff", "<div style='width:40px;height:20px;background-color:#ffffff;border:1px solid #ccc;display:inline-block;'></div>"

                input_image.select(fn=handle_image_click, inputs=[input_image], outputs=[click_x, click_y, current_color, color_preview])

                def add_color(current_color_hex, palette):
                    col = current_color_hex if isinstance(current_color_hex, str) else "#ffffff"
                    if not col.startswith('#'):
                        col = f"#{col}"
                    col = col.lower()
                    
                    palette = list(palette) if palette is not None else []
                    if col not in palette:
                        palette.append(col)
                    
                    html = build_palette_html(palette)
                    choices = palette.copy()
                    return palette, html, gr.update(choices=choices, value=(choices[-1] if choices else None))

                def remove_color(palette, selected_hex):
                    palette = list(palette) if palette is not None else []
                    if selected_hex in palette:
                        palette.remove(selected_hex)
                    html = build_palette_html(palette)
                    choices = palette.copy()
                    return palette, html, gr.update(choices=choices, value=(choices[-1] if choices else None))

                def clear_palette():
                    palette = []
                    html = build_palette_html(palette)
                    return palette, html, gr.update(choices=[], value=None)

                add_color_btn.click(fn=add_color, inputs=[current_color, palette_state],
                                   outputs=[palette_state, palette_html, remove_select])

                remove_color_btn.click(fn=remove_color, inputs=[palette_state, remove_select],
                                      outputs=[palette_state, palette_html, remove_select])

                clear_palette_btn.click(fn=clear_palette, inputs=None, 
                                       outputs=[palette_state, palette_html, remove_select])

                process_btn.click(
                    fn=process_image_transparency,
                    inputs=[input_image, method, iter_count, blur_kernel, mask_method, 
                           palette_state, tolerance, feather, morph_iter],
                    outputs=[output_image]
                )
        
        # 共通の使い方説明
        gr.Markdown("""
        ## 📋 全体の使い方
        
        ### 🎭 Twitter隠し絵ジェネレーター
        1. **通常画像**: 背景として表示される画像をアップロード
        2. **隠し画像**: 隠したい画像をアップロード(写真でも線画でもOK)
        3. **線画抽出**: チェックボックスをONにすると写真から線画を自動抽出
        4. **調整スライダー**: 各画像の明度・コントラスト等を調整
        5. **生成ボタンを押して、ダウンロードファイルから透過PNGを保存**
        
        ### 🎨 透過ツール
        **AI自動除去の場合:**
        - フレーム画像の背景を自動で検出・除去
        
        **複数色除去の場合:**
        1. 画像をクリックして色を取得
        2. 「➕ 追加」でパレットに登録
        3. 複数色を登録後「透過処理を実行」
        
        ## 💡 ポイント
        - 両方のツールとも透過PNG形式で出力されます
        - モバイル環境でも快適に動作するよう最適化済み
        - エラーが発生した場合は設定を調整してお試しください
        """)
    
    return app

if __name__ == "__main__":
    app = create_integrated_interface()
    app.launch(server_name="0.0.0.0", server_port=7860, share=False)