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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -70
app.py CHANGED
@@ -76,92 +76,113 @@ def init_face_parser():
76
  if FACE_PARSING_AVAILABLE:
77
  return True
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):
 
76
  if FACE_PARSING_AVAILABLE:
77
  return True
78
 
79
+ print("[FaceParsing] Attempting to load face parsing model...")
80
 
81
+ # لیست تمام مدل‌های ممکن برای face parsing
82
+ model_candidates = [
83
+ # اول مدل اصلی
84
+ ("jonathandinu/face-parsing", "segformer"),
85
+
86
+ # جایگزین‌های مطمئن
87
+ ("mattmdjaga/segformer_b2_clothes", "segformer"),
88
+ ("nickmuchi/segformer-b0-finetuned-face-parsing", "segformer"),
89
+ ("facebook/detr-resnet-50-panoptic", "detr"),
90
+ ("hustvl/yolos-tiny", "yolos"),
91
+ ]
92
+
93
+ for model_name, model_type in model_candidates:
94
+ print(f"[FaceParsing] Trying {model_name}...")
95
+
96
+ success = try_load_model(model_name, model_type)
97
+ if success:
98
+ FACE_PARSING_AVAILABLE = True
99
+ return True
100
+
101
+ # اگر همه شکست خوردند
102
+ print("[FaceParsing] ✗ All models failed. Using MediaPipe + OpenCV fallback")
103
+
104
+ # استفاده از MediaPipe که از قبل کار می‌کند
105
  try:
106
+ import mediapipe as mp
107
+ mp_face_mesh = mp.solutions.face_mesh
108
+ face_mesh = mp_face_mesh.FaceMesh(
109
+ static_image_mode=True,
110
+ max_num_faces=1,
111
+ refine_landmarks=True,
112
+ min_detection_confidence=0.5
113
+ )
114
 
115
+ FACE_PARSER = {
116
+ 'type': 'mediapipe',
117
+ 'model': face_mesh,
118
+ 'processor': None
119
+ }
120
+ FACE_PARSING_AVAILABLE = True
121
+ print("[FaceParsing] ✓ Using MediaPipe Face Mesh")
122
+ return True
123
 
124
+ except Exception as e:
125
+ print(f"[FaceParsing] MediaPipe failed: {e}")
 
 
 
 
 
126
 
127
+ # نهایتاً OpenCV ساده
128
+ FACE_PARSER = {
129
+ 'type': 'opencv_haar',
130
+ 'model': None,
131
+ 'processor': None
132
+ }
133
+ FACE_PARSING_AVAILABLE = False # تکنیک basic
134
+ print("[FaceParsing] Basic OpenCV face detection only")
135
+ return False
136
+
137
+ def try_load_model(model_name, model_type):
138
+ """سعی کن یک مدل را لود کنی"""
139
+ try:
140
+ if model_type == "segformer":
141
+ from transformers import SegformerForSemanticSegmentation
142
+ from transformers import SegformerImageProcessor
143
+
144
+ model = SegformerForSemanticSegmentation.from_pretrained(model_name)
145
+
146
+ # ایجاد processor مناسب
147
+ processor = SegformerImageProcessor(
148
+ size={"height": 512, "width": 512},
149
+ do_resize=True,
150
+ do_normalize=True,
151
+ image_mean=[0.485, 0.456, 0.406],
152
+ image_std=[0.229, 0.224, 0.225]
153
+ )
 
 
 
 
 
 
 
 
154
 
155
+ elif model_type in ["detr", "yolos"]:
156
+ from transformers import AutoModelForImageSegmentation
157
+ from transformers import AutoImageProcessor
158
+
159
+ model = AutoModelForImageSegmentation.from_pretrained(model_name)
160
+ processor = AutoImageProcessor.from_pretrained(model_name)
 
 
 
161
 
162
+ else:
163
+ # روش عمومی
164
+ from transformers import AutoModelForImageSegmentation
165
+ from transformers import AutoImageProcessor
166
+
167
+ model = AutoModelForImageSegmentation.from_pretrained(
168
+ model_name,
169
+ trust_remote_code=True
170
+ )
171
+ processor = AutoImageProcessor.from_pretrained(model_name)
172
 
173
+ # ذخیره
174
  FACE_PARSER = {
175
  'processor': processor,
176
  'model': model,
177
+ 'model_name': model_name,
178
+ 'model_type': model_type
179
  }
180
 
181
+ print(f"[FaceParsing] Successfully loaded {model_name}")
 
182
  return True
183
 
184
  except Exception as e:
185
+ print(f"[FaceParsing] Failed: {str(e)[:100]}")
 
 
 
 
 
 
186
  return False
187
 
188
  def load_strategy_1(model_name):