danicor commited on
Commit
fcaa717
·
verified ·
1 Parent(s): 3016887

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -19
app.py CHANGED
@@ -78,27 +78,91 @@ def init_face_parser():
78
 
79
  model_name = "jonathandinu/face-parsing"
80
 
81
- # لیست استراتژی‌های مختلف لود
82
- strategies = [
83
- # استراتژی ۱: لود مستقیم با تنظیمات بهینه
84
- lambda: load_strategy_1(model_name),
85
 
86
- # استراتژی ۲: لود با معماری مشخص
87
- lambda: load_strategy_2(model_name),
 
 
88
 
89
- # استراتژی ۳: دانلود و لود مجدد
90
- lambda: load_strategy_3(model_name),
91
- ]
92
-
93
- for i, strategy in enumerate(strategies, 1):
94
- print(f"[FaceParsing] Trying strategy {i}...")
95
- success = strategy()
96
- if success:
97
- FACE_PARSING_AVAILABLE = True
98
- return True
99
-
100
- print("[FaceParsing] All strategies failed, using CV2 fallback")
101
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  def load_strategy_1(model_name):
104
  """استراتژی ۱: لود استاندارد با تنظیمات پیشرفته"""
 
78
 
79
  model_name = "jonathandinu/face-parsing"
80
 
81
+ try:
82
+ print("[FaceParsing] Creating custom image processor...")
 
 
83
 
84
+ from transformers import AutoModelForImageSegmentation
85
+ import torch
86
+ from PIL import Image
87
+ import numpy as np
88
 
89
+ # ۱. اول model را بدون processor لود کن
90
+ print("[FaceParsing] Loading model (without processor)...")
91
+ model = AutoModelForImageSegmentation.from_pretrained(
92
+ model_name,
93
+ trust_remote_code=True,
94
+ ignore_mismatched_sizes=True
95
+ )
96
+
97
+ # ۲.创建一个 custom processor
98
+ class CustomImageProcessor:
99
+ def __init__(self):
100
+ self.size = {"height": 512, "width": 512}
101
+ self.do_resize = True
102
+ self.do_normalize = True
103
+ self.image_mean = [0.485, 0.456, 0.406]
104
+ self.image_std = [0.229, 0.224, 0.225]
105
+
106
+ def __call__(self, images, return_tensors="pt"):
107
+ # تبدیل PIL Image به tensor
108
+ if isinstance(images, Image.Image):
109
+ images = [images]
110
+
111
+ processed_images = []
112
+ for img in images:
113
+ # resize
114
+ img = img.resize((self.size["width"], self.size["height"]))
115
+
116
+ # به numpy array تبدیل کن
117
+ img_array = np.array(img).astype(np.float32) / 255.0
118
+
119
+ # normalize
120
+ if self.do_normalize:
121
+ img_array = (img_array - self.image_mean) / self.image_std
122
+
123
+ # از HWC به CHW تغییر بده
124
+ img_array = np.transpose(img_array, (2, 0, 1))
125
+
126
+ processed_images.append(img_array)
127
+
128
+ # به tensor تبدیل کن
129
+ if return_tensors == "pt":
130
+ return {"pixel_values": torch.tensor(np.stack(processed_images))}
131
+ return {"pixel_values": np.stack(processed_images)}
132
+
133
+ def post_process_semantic_segmentation(self, outputs, target_sizes=None):
134
+ # پردازش خروجی مدل
135
+ logits = outputs.logits
136
+
137
+ if target_sizes is not None:
138
+ # resize به اندازه اصلی
139
+ pass
140
+
141
+ return logits.argmax(dim=1)
142
+
143
+ # ۳. ایجاد processor
144
+ processor = CustomImageProcessor()
145
+
146
+ # ۴. ذخیره
147
+ FACE_PARSER = {
148
+ 'processor': processor,
149
+ 'model': model,
150
+ 'type': 'custom'
151
+ }
152
+
153
+ FACE_PARSING_AVAILABLE = True
154
+ print("[FaceParsing] ✓ Model loaded with custom processor!")
155
+ return True
156
+
157
+ except Exception as e:
158
+ print(f"[FaceParsing] Failed: {str(e)[:200]}")
159
+
160
+ # لاگ کامل خطا
161
+ import traceback
162
+ print(f"[FaceParsing] Traceback: {traceback.format_exc()[:500]}")
163
+
164
+ print("[FaceParsing] ⚠ Using CV2 fallback")
165
+ return False
166
 
167
  def load_strategy_1(model_name):
168
  """استراتژی ۱: لود استاندارد با تنظیمات پیشرفته"""