File size: 11,369 Bytes
5a46c95
9dcfc8c
171f52c
9dcfc8c
 
 
5a46c95
9dcfc8c
171f52c
7e96e19
9dcfc8c
 
 
a93dee3
 
 
 
 
 
 
9dcfc8c
3755310
 
 
 
 
 
 
 
 
9dcfc8c
 
 
 
5a46c95
f2d2548
ef5cdc3
ef895ac
9dcfc8c
 
7e96e19
9dcfc8c
7e96e19
9dcfc8c
 
 
171f52c
 
 
 
 
9dcfc8c
 
171f52c
9dcfc8c
171f52c
 
 
 
 
9dcfc8c
 
 
 
 
 
 
 
7e96e19
3755310
 
 
 
 
 
 
7e96e19
9dcfc8c
 
 
7e96e19
a93dee3
 
 
7e96e19
a93dee3
 
7e96e19
171f52c
9dcfc8c
 
 
 
171f52c
9dcfc8c
a93dee3
 
9dcfc8c
171f52c
9dcfc8c
 
 
 
 
 
171f52c
9dcfc8c
171f52c
9dcfc8c
171f52c
9dcfc8c
 
171f52c
9dcfc8c
 
 
 
 
 
 
7e96e19
 
a93dee3
7e96e19
 
a93dee3
171f52c
a93dee3
7e96e19
a93dee3
 
 
 
 
7e96e19
a93dee3
7e96e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93dee3
 
 
 
 
 
 
171f52c
 
9dcfc8c
e680cc7
 
 
9dcfc8c
a93dee3
3755310
9dcfc8c
e680cc7
9dcfc8c
a93dee3
 
 
e680cc7
9dcfc8c
 
e680cc7
171f52c
9dcfc8c
e680cc7
171f52c
9dcfc8c
171f52c
 
 
9dcfc8c
 
 
171f52c
 
9dcfc8c
171f52c
9dcfc8c
171f52c
9dcfc8c
 
171f52c
 
 
 
 
 
9dcfc8c
171f52c
9dcfc8c
171f52c
 
9dcfc8c
171f52c
 
9dcfc8c
171f52c
a93dee3
 
171f52c
e680cc7
3755310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3ddb14
7e96e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import numpy as np
import PIL.Image
import torch
import torchvision.transforms as T
from huggingface_hub import hf_hub_download
import gradio as gr
import time
import cv2

# افزودن مسیر مورد نیاز برای ماژول‌های CelebAMask-HQ
celebamask_path = "/home/user/app/CelebAMask-HQ"
face_parsing_path = os.path.join(celebamask_path, "face_parsing")
sys.path.insert(0, celebamask_path)
sys.path.insert(0, face_parsing_path)

print("Python path:", sys.path)
print("CelebAMask path exists:", os.path.exists(celebamask_path))
print("Face parsing path exists:", os.path.exists(face_parsing_path))

# ایمپورت ماژول‌های مورد نیاز
try:
    from unet import unet
    from utils import generate_label
    IMPORT_SUCCESS = True
    print("✅ Successfully imported CelebAMask-HQ modules")
except ImportError as e:
    IMPORT_SUCCESS = False
    print(f"❌ Failed to import CelebAMask-HQ modules: {e}")

# تنظیمات دستگاه
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

# تنظیم مسیرهای کش
os.environ["HF_HOME"] = "/home/user/app/hf_cache"

# تعریف transform
transform = T.Compose([
    T.Resize((512, 512)),
    T.ToTensor(),
    T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# کلاس‌های Face Parsing
CELEBA_CLASSES = [
    'background', 'skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
    'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat'
]

class FaceParsingModel:
    def __init__(self):
        self.model = None
        self.device = device
        self.load_model()
    
    def load_model(self):
        """لود مدل Face Parsing"""
        try:
            print("📥 Downloading model...")
            model_path = hf_hub_download(
                repo_id="public-data/CelebAMask-HQ-Face-Parsing",
                filename="models/model.pth",
                cache_dir="/home/user/app/hf_cache"
            )
            print(f"✅ Model downloaded to: {model_path}")
            
            # ایجاد مدل با معماری صحیح
            self.model = unet(
                feature_scale=4,
                n_classes=19,
                is_deconv=True,
                in_channels=3,
                is_batchnorm=True
            )
            
            # لود state dict
            state_dict = torch.load(model_path, map_location="cpu")
            
            # اگر state dict از DataParallel باشد، module. را حذف می‌کنیم
            new_state_dict = {}
            for k, v in state_dict.items():
                if k.startswith('module.'):
                    k = k[7:]
                new_state_dict[k] = v
            
            self.model.load_state_dict(new_state_dict)
            self.model.eval()
            self.model.to(self.device)
            
            print("✅ Model loaded successfully")
            
        except Exception as e:
            print(f"❌ Failed to load model: {e}")
            import traceback
            traceback.print_exc()
            self.model = None
    
    def predict(self, image):
        """پردازش تصویر و تولید ماسک"""
        if self.model is None:
            raise ValueError("Model not loaded properly")
        
        # تبدیل به PIL Image اگر لازم است
        if isinstance(image, str):
            image = PIL.Image.open(image).convert('RGB')
        elif isinstance(image, np.ndarray):
            image = PIL.Image.fromarray(image)
        
        # ذخیره تصویر اصلی
        original_image = image.copy()
        
        # پیش‌پردازش
        data = transform(image)
        data = data.unsqueeze(0).to(self.device)

        # پیش‌بینی
        with torch.no_grad():
            out = self.model(data)
            label_out = generate_label(out, 512)
            mask = label_out[0].cpu().numpy()
            
            # رنگ‌آمیزی ماسک
            colored_mask = self.colorize_mask(mask)
            
        # ترکیب تصویر اصلی با ماسک
        resized_image = np.asarray(original_image.resize((512, 512)))
        blended = cv2.addWeighted(resized_image, 0.7, colored_mask, 0.3, 0)

        return colored_mask, blended

    def colorize_mask(self, mask):
        """رنگ‌آمیزی ماسک بر اساس کلاس‌ها"""
        # پالت رنگ برای 19 کلاس (متفاوت برای تشخیص بهتر)
        palette = [
            [0, 0, 0],        # background - سیاه
            [255, 200, 200],  # skin - پوست
            [0, 255, 0],      # l_brow - سبز
            [0, 200, 0],      # r_brow - سبز تیره
            [255, 0, 0],      # l_eye - قرمز
            [200, 0, 0],      # r_eye - قرمز تیره
            [255, 255, 0],    # eye_g - زرد
            [0, 0, 255],      # l_ear - آبی
            [0, 0, 200],      # r_ear - آبی تیره
            [128, 0, 128],    # ear_r - بنفش
            [255, 165, 0],    # nose - نارنجی
            [255, 0, 255],    # mouth - صورتی
            [200, 0, 200],    # u_lip - صورتی تیره
            [165, 42, 42],    # l_lip - قهوه‌ای
            [0, 255, 255],    # neck - فیروزه‌ای
            [0, 200, 200],    # neck_l - فیروزه‌ای تیره
            [128, 128, 128],  # cloth - خاکستری
            [255, 255, 255],  # hair - سفید
            [255, 215, 0]     # hat - طلایی
        ]
        
        colored = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
        for i in range(len(palette)):
            colored[mask == i] = palette[i]
        
        return colored

def initialize_app():
    """Initialize application"""
    print("===== Application Startup at {} =====".format(time.strftime("%Y-%m-%d %H:%M:%S")))
    
    print("[Info] PYTHONPATH:", os.environ.get("PYTHONPATH"))
    print("[Info] CelebAMask-HQ path exists:", os.path.exists(celebamask_path))
    print("[Info] face_parsing folder exists:", os.path.exists(face_parsing_path))
    print("[Info] Module import success:", IMPORT_SUCCESS)
    
    try:
        face_parser = FaceParsingModel()
        success = face_parser.model is not None
        status_msg = "Model loaded successfully" if success else "Model failed to load"
        return success, status_msg, face_parser
    except Exception as e:
        print(f"[Error] Initialization failed: {e}")
        return False, f"Initialization failed: {e}", None

# Initialize the application
success, status_msg, face_parser = initialize_app()

def process_image(input_image):
    """پردازش تصویر ورودی"""
    if input_image is None:
        return None, None, "لطفاً یک تصویر آپلود کنید"
    
    if not success or face_parser is None:
        return None, None, "❌ مدل لود نشده است. لطفاً دوباره تلاش کنید."
    
    try:
        # پردازش تصویر
        mask, blended = face_parser.predict(input_image)
        
        # اطلاعات پردازش
        if isinstance(input_image, str):
            original_img = PIL.Image.open(input_image)
            img_size = original_img.size
        else:
            img_size = input_image.size if hasattr(input_image, 'size') else input_image.shape[:2][::-1]
        
        info_text = f"""
        ✅ پردازش انجام شد!
        - اندازه تصویر ورودی: {img_size}
        - اندازه خروجی: 512x512
        - کلاس‌های تشخیص: {len(CELEBA_CLASSES)}
        - دستگاه پردازش: {device}
        """
        
        return blended, mask, info_text
        
    except Exception as e:
        error_msg = f"❌ خطا در پردازش تصویر: {str(e)}"
        print(error_msg)
        import traceback
        traceback.print_exc()
        return None, None, error_msg

def create_legend():
    """ایجاد لیجند برای کلاس‌ها"""
    import matplotlib.pyplot as plt
    
    legend_html = """
    <div style='max-height: 300px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; border-radius: 5px;'>
    <h4>🎨 Legend - کلاس‌های Face Parsing:</h4>
    """
    
    colors = plt.get_cmap('tab20', len(CELEBA_CLASSES))
    
    for i, class_name in enumerate(CELEBA_CLASSES):
        color = colors(i)
        color_hex = '#%02x%02x%02x' % (int(color[0]*255), int(color[1]*255), int(color[2]*255))
        text_color = 'white' if color[0] * 0.299 + color[1] * 0.587 + color[2] * 0.114 < 0.5 else 'black'
        legend_html += f"""
        <div style='margin: 2px; padding: 5px; background-color: {color_hex}; color: {text_color}; border-radius: 3px;'>
        <strong>{i}:</strong> {class_name}
        </div>
        """
    
    legend_html += "</div>"
    return legend_html

# ایجاد اینترفیس Gradio
with gr.Blocks(title="CelebAMask-HQ Face Parsing", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🎭 CelebAMask-HQ Face Parsing Demo
    **آپلود یک تصویر صورت و دریافت خروجی Face Parsing**
    
    این مدل صورت را به 19 بخش مختلف تقسیم می‌کند (پوست، چشم، ابرو، بینی، دهان، مو و ...)
    """)
    
    with gr.Row():
        with gr.Column():
            input_image = gr.Image(
                label="📷 تصویر ورودی",
                type="filepath",
                sources=["upload"],
                height=300
            )
            process_btn = gr.Button("🚀 پردازش تصویر", variant="primary", size="lg")
            
            with gr.Accordion("ℹ️ وضعیت برنامه", open=False):
                status_display = gr.Markdown(f"""
                **وضعیت:**
                - 🎯 مدل: {'✅ لود شده' if success else '❌ خطا در لود'}
                - 💻 دستگاه: `{device}`
                - 📦 ماژول‌ها: {'✅ ایمپورت شده' if IMPORT_SUCCESS else '❌ خطا در ایمپورت'}
                - 🗂️ کلاس‌ها: {len(CELEBA_CLASSES)}
                """)
        
        with gr.Column():
            output_blended = gr.Image(
                label="🎨 نتیجه ترکیبی (تصویر + ماسک)",
                height=300
            )
            output_mask = gr.Image(
                label="🎭 ماسک سگمنتیشن",
                height=300
            )
    
    with gr.Row():
        info_output = gr.Textbox(
            label="📊 اطلاعات پردازش",
            lines=3,
            max_lines=6
        )
    
    with gr.Row():
        gr.HTML(create_legend())
    
    # اتصال رویدادها
    process_btn.click(
        fn=process_image,
        inputs=[input_image],
        outputs=[output_blended, output_mask, info_output]
    )
    
    input_image.upload(
        fn=process_image,
        inputs=[input_image],
        outputs=[output_blended, output_mask, info_output]
    )

if __name__ == "__main__":
    print("🚀 Starting Face Parsing Application...")
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )