Shreyansh1409 commited on
Commit
2e7016d
·
unverified ·
1 Parent(s): e2e284f

Replace Hugging Face API with local Segformer model

Browse files

Refactor Segformer API logic to use local PyTorch model and update styling.

Files changed (1) hide show
  1. app.py +45 -71
app.py CHANGED
@@ -1,6 +1,4 @@
1
  import io
2
- import base64
3
- import requests
4
 
5
  import cv2
6
  import numpy as np
@@ -32,11 +30,7 @@ st.markdown(
32
  header { visibility: hidden; }
33
  footer { visibility: hidden; }
34
 
35
- .app-header {
36
- margin-bottom: 2rem;
37
- padding-bottom: 1rem;
38
- border-bottom: 1px solid rgba(128, 128, 128, 0.2);
39
- }
40
  .app-title { font-weight: 700; font-size: 2.25rem; margin-bottom: 0.25rem; }
41
  .app-subtitle { font-size: 1rem; opacity: 0.7; }
42
  .sidebar-header { font-weight: 600; font-size: 1.1rem; margin-top: 1rem; margin-bottom: 0.5rem; }
@@ -51,10 +45,7 @@ st.markdown(
51
  transition: all 0.2s ease !important;
52
  width: 100%;
53
  }
54
- .stButton > button:hover {
55
- background-color: #4338CA !important;
56
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important;
57
- }
58
 
59
  .stDownloadButton > button {
60
  background-color: #10B981 !important;
@@ -80,72 +71,65 @@ st.markdown(
80
  overflow: hidden;
81
  border: 1px solid rgba(128, 128, 128, 0.2);
82
  }
83
-
84
- .image-card-title {
85
- font-weight: 600;
86
- font-size: 0.9rem;
87
- margin-bottom: 0.75rem;
88
- text-transform: uppercase;
89
- letter-spacing: 0.05em;
90
- opacity: 0.8;
91
- }
92
-
93
- [data-testid="stFileUploaderDropzone"] {
94
- border-radius: 12px;
95
- border: 2px dashed rgba(128, 128, 128, 0.4);
96
- }
97
  </style>
98
  """,
99
  unsafe_allow_html=True,
100
  )
101
 
102
  # ---------------------------------------------------------------------------
103
- # Segformer API Logic
104
  # ---------------------------------------------------------------------------
105
- def hf_segformer_cutout(image_bytes: bytes, hf_token: str, grow_px: int) -> bytes:
106
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
107
 
108
- if not hf_token:
109
- raise ValueError("Hugging Face API Token is missing.")
110
-
111
- # Initialize official client routed to the Segformer clothing model
112
- client = InferenceClient(model="mattmdjaga/segformer_b2_clothes", token=hf_token)
113
 
114
- # Run serverless image segmentation via the official SDK
115
- results = client.image_segmentation(image=image_bytes)
 
 
 
 
 
 
 
 
 
 
116
 
117
- source_img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
118
- target_labels = ["Upper-clothes", "Pants", "Skirt", "Dress", "Coat"]
119
- combined_mask = None
120
 
121
- for item in results:
122
- # Check standard label structures returned by InferenceClient
123
- label = item.get("label", "")
124
- if label in target_labels:
125
- mask_img = item.get("mask").convert("L")
126
- mask_img = mask_img.resize(source_img.size, Image.LANCZOS)
127
-
128
- if combined_mask is None:
129
- combined_mask = np.array(mask_img)
130
- else:
131
- combined_mask = np.maximum(combined_mask, np.array(mask_img))
132
-
133
- if combined_mask is None:
134
- raise ValueError("No garments detected by Segformer.")
135
 
136
  if grow_px > 0:
137
  kernel = np.ones((3, 3), np.uint8)
138
- combined_mask = cv2.erode(combined_mask, kernel, iterations=grow_px)
139
 
140
- mask_final = Image.fromarray(combined_mask)
141
  result = source_img.convert("RGBA")
142
- result.putalpha(mask_final)
143
 
144
  buf = io.BytesIO()
145
  result.save(buf, format="PNG")
146
  return buf.getvalue()
 
147
  # ---------------------------------------------------------------------------
148
- # Local AI Cutout Logic
149
  # ---------------------------------------------------------------------------
150
  AI_MODELS = {
151
  "Clothes ONLY (Deletes Skin & Hair)": "u2net_cloth_seg",
@@ -177,10 +161,7 @@ def ai_cutout(image_bytes: bytes, model_name: str, grow_px: int) -> bytes:
177
 
178
  if model_name == "u2net_cloth_seg":
179
  masks = remove(small, session=load_ai_session(model_name), only_mask=True, return_multiple=True)
180
-
181
  if isinstance(masks, list) and len(masks) >= 3:
182
- # Corrected Mapping based on visual artifacts:
183
- # 0 = Face/Hair, 1 = Lower Body, 2 = Upper Body
184
  lower = np.array(masks[1].convert("L"))
185
  upper = np.array(masks[2].convert("L"))
186
  clothes_only = np.maximum(upper, lower)
@@ -211,7 +192,7 @@ def ai_cutout(image_bytes: bytes, model_name: str, grow_px: int) -> bytes:
211
 
212
 
213
  # ---------------------------------------------------------------------------
214
- # Chroma Key Logic
215
  # ---------------------------------------------------------------------------
216
  def detect_background_hex(img_array: np.ndarray, border: int = 10) -> str:
217
  h, w, _ = img_array.shape
@@ -229,10 +210,8 @@ def chroma_cutout(img_array: np.ndarray, key_hex: str, tola: int, tolb: int, gro
229
  hex_str = key_hex.lstrip('#')
230
  target_color = np.array([int(hex_str[i:i+2], 16) for i in (0, 2, 4)], dtype=np.float32)
231
  distances = np.linalg.norm(img_array.astype(np.float32) - target_color, axis=-1)
232
-
233
  mask = 1.0 - (distances - tola) / max(tolb - tola, 1)
234
  mask = np.clip(mask, 0.0, 1.0)
235
-
236
  alpha_f = 1.0 - mask
237
  final_rgb = img_array.copy()
238
 
@@ -283,12 +262,10 @@ with st.sidebar:
283
  st.markdown("---")
284
 
285
  if method == "Segformer (Pro Garment AI)":
286
- st.info("🚀 **State-of-the-Art Clothing AI.** Uses an advanced transformer API to map 18 garment classes while ignoring skin and backgrounds.")
287
- st.markdown('<div class="sidebar-header">API Configuration</div>', unsafe_allow_html=True)
288
- hf_token = st.text_input("Hugging Face API Token", type="password", help="Get a free API token from your huggingface.co account settings.")
289
 
290
  elif method == "Local AI (Basic & Full Subject)":
291
- st.info("💡 **Local Processing.** Extracts the general silhouette without an internet connection. Struggles with specific garments.")
292
  st.markdown('<div class="sidebar-header">AI Parameters</div>', unsafe_allow_html=True)
293
  model_label = st.selectbox("Model Tier", list(AI_MODELS), index=0, key="ai_model_sel")
294
  model_name = AI_MODELS[model_label]
@@ -334,11 +311,8 @@ with col2:
334
 
335
  try:
336
  if method == "Segformer (Pro Garment AI)":
337
- if not hf_token:
338
- st.warning("A Hugging Face API Token is required for this engine.")
339
- st.stop()
340
- with st.spinner("🧠 Querying Segformer Transformer..."):
341
- extracted_image = Image.open(io.BytesIO(hf_segformer_cutout(image_bytes, hf_token, grow_px)))
342
 
343
  elif method == "Local AI (Basic & Full Subject)":
344
  with st.spinner(f"🤖 Running {model_label.split(' ')[0]} model..."):
 
1
  import io
 
 
2
 
3
  import cv2
4
  import numpy as np
 
30
  header { visibility: hidden; }
31
  footer { visibility: hidden; }
32
 
33
+ .app-header { margin-bottom: 2rem; padding-bottom: 1rem; border-bottom: 1px solid rgba(128, 128, 128, 0.2); }
 
 
 
 
34
  .app-title { font-weight: 700; font-size: 2.25rem; margin-bottom: 0.25rem; }
35
  .app-subtitle { font-size: 1rem; opacity: 0.7; }
36
  .sidebar-header { font-weight: 600; font-size: 1.1rem; margin-top: 1rem; margin-bottom: 0.5rem; }
 
45
  transition: all 0.2s ease !important;
46
  width: 100%;
47
  }
48
+ .stButton > button:hover { background-color: #4338CA !important; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important; }
 
 
 
49
 
50
  .stDownloadButton > button {
51
  background-color: #10B981 !important;
 
71
  overflow: hidden;
72
  border: 1px solid rgba(128, 128, 128, 0.2);
73
  }
74
+ .image-card-title { font-weight: 600; font-size: 0.9rem; margin-bottom: 0.75rem; text-transform: uppercase; opacity: 0.8; }
75
+ [data-testid="stFileUploaderDropzone"] { border-radius: 12px; border: 2px dashed rgba(128, 128, 128, 0.4); }
 
 
 
 
 
 
 
 
 
 
 
 
76
  </style>
77
  """,
78
  unsafe_allow_html=True,
79
  )
80
 
81
  # ---------------------------------------------------------------------------
82
+ # Segformer Local PyTorch Engine
83
  # ---------------------------------------------------------------------------
84
+ @st.cache_resource(show_spinner=False, max_entries=1)
85
+ def load_segformer():
86
+ from transformers import SegformerImageProcessor, AutoModelForSemanticSegmentation
87
+ processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")
88
+ model = AutoModelForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes")
89
+ return processor, model
90
+
91
+ @st.cache_data(show_spinner=False, max_entries=2)
92
+ def local_segformer_cutout(image_bytes: bytes, grow_px: int) -> bytes:
93
+ import torch
94
+ import torch.nn as nn
95
 
96
+ processor, model = load_segformer()
97
+ source_img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
 
 
 
98
 
99
+ # Process image natively via PyTorch tensors
100
+ inputs = processor(images=source_img, return_tensors="pt")
101
+ with torch.no_grad():
102
+ outputs = model(**inputs)
103
+
104
+ logits = outputs.logits.cpu()
105
+ upsampled_logits = nn.functional.interpolate(
106
+ logits,
107
+ size=source_img.size[::-1], # (height, width)
108
+ mode="bilinear",
109
+ align_corners=False,
110
+ )
111
 
112
+ # Convert logits to categorical integer maps
113
+ pred_seg = upsampled_logits.argmax(dim=1)[0].numpy()
 
114
 
115
+ # Model Classes: 4: Upper-clothes, 5: Skirt, 6: Pants, 7: Dress
116
+ target_labels = [4, 5, 6, 7]
117
+ mask_arr = np.isin(pred_seg, target_labels).astype(np.uint8) * 255
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  if grow_px > 0:
120
  kernel = np.ones((3, 3), np.uint8)
121
+ mask_arr = cv2.erode(mask_arr, kernel, iterations=grow_px)
122
 
123
+ mask = Image.fromarray(mask_arr, mode="L")
124
  result = source_img.convert("RGBA")
125
+ result.putalpha(mask)
126
 
127
  buf = io.BytesIO()
128
  result.save(buf, format="PNG")
129
  return buf.getvalue()
130
+
131
  # ---------------------------------------------------------------------------
132
+ # Local AI (rembg) Engine
133
  # ---------------------------------------------------------------------------
134
  AI_MODELS = {
135
  "Clothes ONLY (Deletes Skin & Hair)": "u2net_cloth_seg",
 
161
 
162
  if model_name == "u2net_cloth_seg":
163
  masks = remove(small, session=load_ai_session(model_name), only_mask=True, return_multiple=True)
 
164
  if isinstance(masks, list) and len(masks) >= 3:
 
 
165
  lower = np.array(masks[1].convert("L"))
166
  upper = np.array(masks[2].convert("L"))
167
  clothes_only = np.maximum(upper, lower)
 
192
 
193
 
194
  # ---------------------------------------------------------------------------
195
+ # Chroma Key Engine
196
  # ---------------------------------------------------------------------------
197
  def detect_background_hex(img_array: np.ndarray, border: int = 10) -> str:
198
  h, w, _ = img_array.shape
 
210
  hex_str = key_hex.lstrip('#')
211
  target_color = np.array([int(hex_str[i:i+2], 16) for i in (0, 2, 4)], dtype=np.float32)
212
  distances = np.linalg.norm(img_array.astype(np.float32) - target_color, axis=-1)
 
213
  mask = 1.0 - (distances - tola) / max(tolb - tola, 1)
214
  mask = np.clip(mask, 0.0, 1.0)
 
215
  alpha_f = 1.0 - mask
216
  final_rgb = img_array.copy()
217
 
 
262
  st.markdown("---")
263
 
264
  if method == "Segformer (Pro Garment AI)":
265
+ st.info("🚀 **State-of-the-Art Clothing AI.** Uses an advanced PyTorch transformer to accurately map 18 garment classes locally while strictly ignoring skin and backgrounds.")
 
 
266
 
267
  elif method == "Local AI (Basic & Full Subject)":
268
+ st.info("💡 **Basic Model.** Extracts the general silhouette perfectly. Struggles with internal specific garments.")
269
  st.markdown('<div class="sidebar-header">AI Parameters</div>', unsafe_allow_html=True)
270
  model_label = st.selectbox("Model Tier", list(AI_MODELS), index=0, key="ai_model_sel")
271
  model_name = AI_MODELS[model_label]
 
311
 
312
  try:
313
  if method == "Segformer (Pro Garment AI)":
314
+ with st.spinner("🧠 Downloading & running Segformer (Local PyTorch)..."):
315
+ extracted_image = Image.open(io.BytesIO(local_segformer_cutout(image_bytes, grow_px)))
 
 
 
316
 
317
  elif method == "Local AI (Basic & Full Subject)":
318
  with st.spinner(f"🤖 Running {model_label.split(' ')[0]} model..."):