Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- ai_stylist.py +326 -0
- app.py +587 -0
- eco_try_products_dataset_fabric_category_fixed.csv +51 -0
- fabric_mapping_1_to_50.json +52 -0
- overrides.json +1 -0
- tryon_hf.py +26 -0
ai_stylist.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# File: ai_stylist.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
import cv2 # type: ignore
|
| 11 |
+
import mediapipe as mp # type: ignore
|
| 12 |
+
import numpy as np # type: ignore
|
| 13 |
+
from sklearn.cluster import KMeans # type: ignore
|
| 14 |
+
except Exception:
|
| 15 |
+
cv2 = None
|
| 16 |
+
np = None
|
| 17 |
+
mp = None
|
| 18 |
+
KMeans = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True)
|
| 22 |
+
class SkinToneResult:
|
| 23 |
+
skin_label: str
|
| 24 |
+
confidence: int
|
| 25 |
+
dominant_hex: str
|
| 26 |
+
dominant_lab: Tuple[float, float, float]
|
| 27 |
+
best_palette: Dict[str, Any]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _palette_db() -> List[Dict[str, Any]]:
|
| 31 |
+
return [
|
| 32 |
+
{
|
| 33 |
+
"id": "warm_neutrals_olive",
|
| 34 |
+
"name": "Warm Neutrals + Olive",
|
| 35 |
+
"tags": ["warm", "everyday", "soft-contrast"],
|
| 36 |
+
"colors_hex": ["#F4E3D7", "#D7B49E", "#A97C50", "#6B7B3E", "#2F2B28"],
|
| 37 |
+
"mean_lab": (190.0, 140.0, 150.0),
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"id": "cool_minimal",
|
| 41 |
+
"name": "Cool Minimal",
|
| 42 |
+
"tags": ["cool", "minimal", "clean"],
|
| 43 |
+
"colors_hex": ["#F6F7FB", "#DDE2EA", "#97A1B2", "#2F3A4C", "#0E0F12"],
|
| 44 |
+
"mean_lab": (205.0, 128.0, 125.0),
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"id": "bold_jewel",
|
| 48 |
+
"name": "Bold Jewel Tones",
|
| 49 |
+
"tags": ["bold", "evening", "high-contrast"],
|
| 50 |
+
"colors_hex": ["#0B3D91", "#0E7C7B", "#7D1538", "#3B1F2B", "#F2E9E4"],
|
| 51 |
+
"mean_lab": (165.0, 135.0, 140.0),
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"id": "earthy_rich",
|
| 55 |
+
"name": "Earthy Rich",
|
| 56 |
+
"tags": ["warm", "earthy", "autumn"],
|
| 57 |
+
"colors_hex": ["#7A4E2D", "#C57B57", "#F1AB86", "#2D3A2E", "#E7D7C1"],
|
| 58 |
+
"mean_lab": (175.0, 145.0, 155.0),
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"id": "deep_contrast",
|
| 62 |
+
"name": "Deep Contrast",
|
| 63 |
+
"tags": ["cool", "deep", "contrast"],
|
| 64 |
+
"colors_hex": ["#111827", "#1F2937", "#0EA5E9", "#DC2626", "#F9FAFB"],
|
| 65 |
+
"mean_lab": (150.0, 130.0, 120.0),
|
| 66 |
+
},
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _lab_to_hex(lab: "np.ndarray") -> str:
|
| 71 |
+
lab_1x1 = lab.reshape(1, 1, 3).astype("uint8")
|
| 72 |
+
bgr = cv2.cvtColor(lab_1x1, cv2.COLOR_LAB2BGR)
|
| 73 |
+
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB).reshape(3)
|
| 74 |
+
return "#{:02x}{:02x}{:02x}".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _skin_label_from_lab(dominant_lab: "np.ndarray") -> str:
|
| 78 |
+
L, a, b = float(dominant_lab[0]), float(dominant_lab[1]), float(dominant_lab[2])
|
| 79 |
+
tone = "Light" if L > 185 else "Medium" if L > 140 else "Deep"
|
| 80 |
+
undertone = "Warm" if b > a else "Cool"
|
| 81 |
+
return f"{undertone} / {tone}"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _recommend_best_palette(dominant_lab: Tuple[float, float, float]) -> Dict[str, Any]:
|
| 85 |
+
db = _palette_db()
|
| 86 |
+
dl = np.array(dominant_lab, dtype=np.float32)
|
| 87 |
+
|
| 88 |
+
scored = []
|
| 89 |
+
for p in db:
|
| 90 |
+
pl = np.array(p["mean_lab"], dtype=np.float32)
|
| 91 |
+
d = float(np.linalg.norm(pl - dl))
|
| 92 |
+
score = float(np.exp(-d / 35.0))
|
| 93 |
+
scored.append((score, p))
|
| 94 |
+
|
| 95 |
+
scored.sort(key=lambda x: -x[0])
|
| 96 |
+
best_score, best = scored[0]
|
| 97 |
+
return {
|
| 98 |
+
"id": best["id"],
|
| 99 |
+
"name": best["name"],
|
| 100 |
+
"score": best_score,
|
| 101 |
+
"tags": best["tags"],
|
| 102 |
+
"colors_hex": best["colors_hex"],
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _expand_bbox(
|
| 107 |
+
x1: int, y1: int, x2: int, y2: int, w: int, h: int, scale: float = 1.5
|
| 108 |
+
) -> Tuple[int, int, int, int]:
|
| 109 |
+
cx = (x1 + x2) / 2.0
|
| 110 |
+
cy = (y1 + y2) / 2.0
|
| 111 |
+
bw = (x2 - x1) * scale
|
| 112 |
+
bh = (y2 - y1) * scale
|
| 113 |
+
nx1 = int(max(0, cx - bw / 2))
|
| 114 |
+
ny1 = int(max(0, cy - bh / 2))
|
| 115 |
+
nx2 = int(min(w - 1, cx + bw / 2))
|
| 116 |
+
ny2 = int(min(h - 1, cy + bh / 2))
|
| 117 |
+
return nx1, ny1, nx2, ny2
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _detect_face_crop(rgb: "np.ndarray") -> Optional["np.ndarray"]:
|
| 121 |
+
h, w, _ = rgb.shape
|
| 122 |
+
detector = mp.solutions.face_detection.FaceDetection(
|
| 123 |
+
model_selection=1, min_detection_confidence=0.35
|
| 124 |
+
)
|
| 125 |
+
res = detector.process(rgb)
|
| 126 |
+
if not res.detections:
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
det = res.detections[0]
|
| 130 |
+
bbox = det.location_data.relative_bounding_box
|
| 131 |
+
x1 = int(bbox.xmin * w)
|
| 132 |
+
y1 = int(bbox.ymin * h)
|
| 133 |
+
x2 = int((bbox.xmin + bbox.width) * w)
|
| 134 |
+
y2 = int((bbox.ymin + bbox.height) * h)
|
| 135 |
+
|
| 136 |
+
x1, y1, x2, y2 = _expand_bbox(x1, y1, x2, y2, w, h, scale=1.50)
|
| 137 |
+
crop = rgb[y1:y2, x1:x2].copy()
|
| 138 |
+
if crop.size == 0:
|
| 139 |
+
return None
|
| 140 |
+
return crop
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _cheek_mask(face_rgb: "np.ndarray", face_landmarks: Any) -> "np.ndarray":
|
| 144 |
+
h, w, _ = face_rgb.shape
|
| 145 |
+
left_ids = [234, 93, 132, 58, 172]
|
| 146 |
+
right_ids = [454, 323, 361, 288, 397]
|
| 147 |
+
|
| 148 |
+
def pts(ids: List[int]) -> "np.ndarray":
|
| 149 |
+
out = []
|
| 150 |
+
for i in ids:
|
| 151 |
+
lm = face_landmarks.landmark[i]
|
| 152 |
+
out.append([int(lm.x * w), int(lm.y * h)])
|
| 153 |
+
return np.array(out, dtype=np.int32)
|
| 154 |
+
|
| 155 |
+
mask = np.zeros((h, w), dtype=np.uint8)
|
| 156 |
+
cv2.fillConvexPoly(mask, pts(left_ids), 255)
|
| 157 |
+
cv2.fillConvexPoly(mask, pts(right_ids), 255)
|
| 158 |
+
return mask
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def detect_skin_tone_pil(selfie_pil: Image.Image) -> SkinToneResult:
|
| 162 |
+
if cv2 is None or np is None or KMeans is None or mp is None:
|
| 163 |
+
raise RuntimeError(
|
| 164 |
+
"Missing deps. Install: pip install numpy opencv-python mediapipe scikit-learn"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
rgb = np.array(selfie_pil.convert("RGB"))
|
| 168 |
+
rgb = np.ascontiguousarray(rgb)
|
| 169 |
+
|
| 170 |
+
face_rgb = _detect_face_crop(rgb)
|
| 171 |
+
if face_rgb is None:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
"Face not detected. Use a clearer front-facing selfie in good light."
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
mesh = mp.solutions.face_mesh.FaceMesh(
|
| 177 |
+
static_image_mode=True,
|
| 178 |
+
refine_landmarks=True,
|
| 179 |
+
max_num_faces=1,
|
| 180 |
+
min_detection_confidence=0.5,
|
| 181 |
+
)
|
| 182 |
+
res = mesh.process(face_rgb)
|
| 183 |
+
if not res.multi_face_landmarks:
|
| 184 |
+
raise ValueError("Face landmarks not detected. Try a clearer selfie.")
|
| 185 |
+
|
| 186 |
+
face = res.multi_face_landmarks[0]
|
| 187 |
+
mask = _cheek_mask(face_rgb, face)
|
| 188 |
+
|
| 189 |
+
bgr = cv2.cvtColor(face_rgb, cv2.COLOR_RGB2BGR)
|
| 190 |
+
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB).astype(np.float32)
|
| 191 |
+
|
| 192 |
+
skin_pixels = lab[mask == 255].reshape(-1, 3)
|
| 193 |
+
if skin_pixels.shape[0] < 180:
|
| 194 |
+
raise ValueError("Not enough cheek pixels. Try brighter lighting.")
|
| 195 |
+
|
| 196 |
+
k = 3 if skin_pixels.shape[0] > 1500 else 2
|
| 197 |
+
km = KMeans(n_clusters=k, n_init=6, random_state=42)
|
| 198 |
+
labels = km.fit_predict(skin_pixels)
|
| 199 |
+
counts = np.bincount(labels)
|
| 200 |
+
dominant_lab = km.cluster_centers_[int(np.argmax(counts))].astype(np.float32)
|
| 201 |
+
|
| 202 |
+
dominant_hex = _lab_to_hex(dominant_lab)
|
| 203 |
+
label = _skin_label_from_lab(dominant_lab)
|
| 204 |
+
confidence = int(min(100, 55 + (skin_pixels.shape[0] / 1500.0) * 45))
|
| 205 |
+
|
| 206 |
+
best_palette = _recommend_best_palette(
|
| 207 |
+
(float(dominant_lab[0]), float(dominant_lab[1]), float(dominant_lab[2]))
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
return SkinToneResult(
|
| 211 |
+
skin_label=label,
|
| 212 |
+
confidence=confidence,
|
| 213 |
+
dominant_hex=dominant_hex,
|
| 214 |
+
dominant_lab=(
|
| 215 |
+
float(dominant_lab[0]),
|
| 216 |
+
float(dominant_lab[1]),
|
| 217 |
+
float(dominant_lab[2]),
|
| 218 |
+
),
|
| 219 |
+
best_palette=best_palette,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _pose_insights(image_pil: Image.Image) -> Dict[str, Any]:
|
| 224 |
+
if cv2 is None or np is None or mp is None:
|
| 225 |
+
return {"pose_detected": False}
|
| 226 |
+
|
| 227 |
+
bgr = cv2.cvtColor(np.array(image_pil.convert("RGB")), cv2.COLOR_RGB2BGR)
|
| 228 |
+
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 229 |
+
|
| 230 |
+
pose = mp.solutions.pose.Pose(static_image_mode=True, model_complexity=1)
|
| 231 |
+
res = pose.process(rgb)
|
| 232 |
+
if not res.pose_landmarks:
|
| 233 |
+
return {"pose_detected": False}
|
| 234 |
+
|
| 235 |
+
lm = res.pose_landmarks.landmark
|
| 236 |
+
L_SH, R_SH = lm[11], lm[12]
|
| 237 |
+
L_HIP, R_HIP = lm[23], lm[24]
|
| 238 |
+
|
| 239 |
+
def dist(a, b) -> float:
|
| 240 |
+
return float(np.hypot(a.x - b.x, a.y - b.y))
|
| 241 |
+
|
| 242 |
+
shoulder_w = dist(L_SH, R_SH)
|
| 243 |
+
hip_w = dist(L_HIP, R_HIP)
|
| 244 |
+
ratio = shoulder_w / (hip_w + 1e-6)
|
| 245 |
+
|
| 246 |
+
if ratio > 1.08:
|
| 247 |
+
shape = "Inverted Triangle (shoulders broader)"
|
| 248 |
+
elif ratio < 0.92:
|
| 249 |
+
shape = "Pear (hips broader)"
|
| 250 |
+
else:
|
| 251 |
+
shape = "Balanced"
|
| 252 |
+
|
| 253 |
+
return {"pose_detected": True, "shoulder_to_hip_ratio": float(ratio), "shape": shape}
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def generate_style_text_suggestions(
|
| 257 |
+
*,
|
| 258 |
+
image_pil: Image.Image,
|
| 259 |
+
skin_label: str,
|
| 260 |
+
dominant_hex: str,
|
| 261 |
+
height_cm: Optional[float],
|
| 262 |
+
body_type: str,
|
| 263 |
+
gender: str,
|
| 264 |
+
) -> Dict[str, List[str]]:
|
| 265 |
+
pose = _pose_insights(image_pil)
|
| 266 |
+
|
| 267 |
+
recs: List[str] = []
|
| 268 |
+
avoid: List[str] = []
|
| 269 |
+
|
| 270 |
+
recs.append("Prefer solid colors + 1 accent piece (premium, clean look).")
|
| 271 |
+
recs.append("Use vertical lines (open jacket, long cardigan, straight seams) to look taller.")
|
| 272 |
+
|
| 273 |
+
if height_cm is not None:
|
| 274 |
+
if height_cm < 160:
|
| 275 |
+
recs.append("Short height: high-waist jeans + shorter jackets elongate legs.")
|
| 276 |
+
avoid.append("Avoid long oversized tops that cut the leg line.")
|
| 277 |
+
elif height_cm > 175:
|
| 278 |
+
recs.append("Tall height: layering (overshirt, long coat) looks balanced.")
|
| 279 |
+
avoid.append("Avoid ultra-short cropped tops if you want a formal silhouette.")
|
| 280 |
+
|
| 281 |
+
bt = (body_type or "Average").lower()
|
| 282 |
+
if bt == "slim":
|
| 283 |
+
recs.append("Slim build: add structure with overshirts/blazers and light layering.")
|
| 284 |
+
recs.append("Bottoms: straight or relaxed jeans work best.")
|
| 285 |
+
elif bt == "athletic":
|
| 286 |
+
recs.append("Athletic build: semi-fitted tops + straight jeans/trousers.")
|
| 287 |
+
avoid.append("Avoid extremely oversized outfits that hide proportions.")
|
| 288 |
+
elif bt == "heavy":
|
| 289 |
+
recs.append("Heavier build: darker solids + vertical patterns + structured outerwear.")
|
| 290 |
+
recs.append("Bottoms: straight-leg or tapered jeans are flattering.")
|
| 291 |
+
avoid.append("Avoid loud horizontal stripes across the midsection.")
|
| 292 |
+
|
| 293 |
+
if pose.get("pose_detected"):
|
| 294 |
+
ratio = float(pose["shoulder_to_hip_ratio"])
|
| 295 |
+
shape = pose["shape"]
|
| 296 |
+
recs.append(f"Body proportion: {shape} (ratio {ratio:.2f}).")
|
| 297 |
+
|
| 298 |
+
if ratio > 1.08:
|
| 299 |
+
recs.append("Patterns: vertical stripes recommended; avoid heavy shoulder details.")
|
| 300 |
+
recs.append("Jeans: straight/wide-leg to balance shoulders.")
|
| 301 |
+
recs.append("Shirt length: hip-length tops balance the frame.")
|
| 302 |
+
avoid.append("Avoid tight crew-necks and shoulder pads.")
|
| 303 |
+
elif ratio < 0.92:
|
| 304 |
+
recs.append("Patterns: texture/stripes on top are okay; keep bottoms simpler/darker.")
|
| 305 |
+
recs.append("Jeans: straight jeans; avoid ultra-skinny if you want balance.")
|
| 306 |
+
recs.append("Tops: structured jackets help balance hips.")
|
| 307 |
+
avoid.append("Avoid heavy prints on bottoms if you want balance.")
|
| 308 |
+
else:
|
| 309 |
+
recs.append("Balanced: you can wear both fitted and relaxed silhouettes confidently.")
|
| 310 |
+
recs.append("Try: straight jeans + either cropped or hip-length tops.")
|
| 311 |
+
else:
|
| 312 |
+
recs.append("Tip: upload a full-body photo for more accurate pattern/fit advice.")
|
| 313 |
+
|
| 314 |
+
if "Warm" in (skin_label or ""):
|
| 315 |
+
recs.append("Warm undertone: olive, cream, tan, warm browns, mustard accents look best.")
|
| 316 |
+
avoid.append("Avoid very icy blues if you want a warm glow.")
|
| 317 |
+
elif "Cool" in (skin_label or ""):
|
| 318 |
+
recs.append("Cool undertone: navy, charcoal, crisp white, emerald, cobalt accents look best.")
|
| 319 |
+
avoid.append("Avoid very yellowish oranges if they dull the skin.")
|
| 320 |
+
|
| 321 |
+
if gender.lower() == "female":
|
| 322 |
+
recs.append("Outfit idea: high-waist jeans + structured top + minimal accessories.")
|
| 323 |
+
elif gender.lower() == "male":
|
| 324 |
+
recs.append("Outfit idea: straight jeans + overshirt/blazer + clean sneakers.")
|
| 325 |
+
|
| 326 |
+
return {"recommendations": recs, "avoid": avoid}
|
app.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# File: app.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import tempfile
|
| 8 |
+
from dataclasses import dataclass, replace
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from flask import (Flask, flash, redirect, render_template, request, session,
|
| 14 |
+
url_for)
|
| 15 |
+
from gradio_client import Client, file
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from ai_stylist import detect_skin_tone_pil, generate_style_text_suggestions
|
| 20 |
+
|
| 21 |
+
DATA_CSV = Path("eco_try_products_dataset_fabric_category_fixed.csv")
|
| 22 |
+
OVERRIDES_JSON = Path("overrides.json")
|
| 23 |
+
|
| 24 |
+
VTON_SPACE_ID = os.environ.get("VTON_SPACE_ID", "").strip()
|
| 25 |
+
VTON_API_NAME = os.environ.get("VTON_API_NAME", "/tryon").strip()
|
| 26 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
|
| 27 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 28 |
+
|
| 29 |
+
_ALLOWED_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
|
| 30 |
+
_VTON_CLIENT: Optional[Client] = None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass(frozen=True)
|
| 34 |
+
class Product:
|
| 35 |
+
product_id: int
|
| 36 |
+
product_name: str
|
| 37 |
+
fabric_type: str
|
| 38 |
+
image_url: str
|
| 39 |
+
water_usage_liters: float
|
| 40 |
+
co2_emission_kg: float
|
| 41 |
+
biodegradability_score: float
|
| 42 |
+
sustainability_score: float
|
| 43 |
+
awareness_text: str
|
| 44 |
+
category: str
|
| 45 |
+
static_filename: str
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def infer_category(product_name: str) -> str:
|
| 49 |
+
if not isinstance(product_name, str) or not product_name.strip():
|
| 50 |
+
return "Other"
|
| 51 |
+
parts = re.sub(r"[^A-Za-z]+", " ", product_name).strip().split()
|
| 52 |
+
if not parts:
|
| 53 |
+
return "Other"
|
| 54 |
+
last = parts[-1].lower()
|
| 55 |
+
mapping = {
|
| 56 |
+
"tshirt": "T-Shirt",
|
| 57 |
+
"tee": "T-Shirt",
|
| 58 |
+
"shirt": "Shirt",
|
| 59 |
+
"jacket": "Jacket",
|
| 60 |
+
"hoodie": "Hoodie",
|
| 61 |
+
"sweater": "Sweater",
|
| 62 |
+
"jeans": "Jeans",
|
| 63 |
+
"pants": "Pants",
|
| 64 |
+
"trouser": "Pants",
|
| 65 |
+
"trousers": "Pants",
|
| 66 |
+
"shorts": "Shorts",
|
| 67 |
+
"dress": "Dress",
|
| 68 |
+
"skirt": "Skirt",
|
| 69 |
+
"coat": "Coat",
|
| 70 |
+
}
|
| 71 |
+
return mapping.get(last, last.capitalize())
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def normalize_static_image_path(image_url_value: Any) -> str:
|
| 75 |
+
if not isinstance(image_url_value, str) or not image_url_value.strip():
|
| 76 |
+
return "images/placeholder.png"
|
| 77 |
+
s = image_url_value.strip().replace("\\", "/").lstrip("/")
|
| 78 |
+
if s.startswith("static/"):
|
| 79 |
+
s = s[len("static/") :]
|
| 80 |
+
return s
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def load_overrides() -> Dict[str, Dict[str, Any]]:
|
| 84 |
+
if not OVERRIDES_JSON.exists():
|
| 85 |
+
OVERRIDES_JSON.write_text("{}", encoding="utf-8")
|
| 86 |
+
return {}
|
| 87 |
+
try:
|
| 88 |
+
return json.loads(OVERRIDES_JSON.read_text(encoding="utf-8") or "{}")
|
| 89 |
+
except json.JSONDecodeError:
|
| 90 |
+
return {}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def save_overrides(overrides: Dict[str, Dict[str, Any]]) -> None:
|
| 94 |
+
OVERRIDES_JSON.write_text(
|
| 95 |
+
json.dumps(overrides, ensure_ascii=False, indent=2),
|
| 96 |
+
encoding="utf-8",
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def apply_overrides(p: Product, overrides: Dict[str, Dict[str, Any]]) -> Product:
|
| 101 |
+
override = overrides.get(str(p.product_id))
|
| 102 |
+
if not override:
|
| 103 |
+
return p
|
| 104 |
+
|
| 105 |
+
allowed = {"product_name", "fabric_type", "category"}
|
| 106 |
+
data = {
|
| 107 |
+
k: v
|
| 108 |
+
for k, v in override.items()
|
| 109 |
+
if k in allowed and isinstance(v, str) and v.strip()
|
| 110 |
+
}
|
| 111 |
+
if not data:
|
| 112 |
+
return p
|
| 113 |
+
|
| 114 |
+
return replace(
|
| 115 |
+
p,
|
| 116 |
+
product_name=data.get("product_name", p.product_name),
|
| 117 |
+
fabric_type=data.get("fabric_type", p.fabric_type),
|
| 118 |
+
category=data.get("category", p.category),
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _get_vton_client() -> Client:
|
| 123 |
+
global _VTON_CLIENT
|
| 124 |
+
if _VTON_CLIENT is not None:
|
| 125 |
+
return _VTON_CLIENT
|
| 126 |
+
if not VTON_SPACE_ID:
|
| 127 |
+
raise RuntimeError("Set VTON_SPACE_ID, e.g. EcoTry/IDM-VTON")
|
| 128 |
+
_VTON_CLIENT = Client(VTON_SPACE_ID)
|
| 129 |
+
return _VTON_CLIENT
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _secure_ext(filename: str) -> str:
|
| 133 |
+
ext = Path(filename or "").suffix.lower()
|
| 134 |
+
return ext if ext in _ALLOWED_IMAGE_EXTS else ".png"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _open_result_as_image(result: Any) -> Image.Image:
|
| 138 |
+
if isinstance(result, Image.Image):
|
| 139 |
+
return result.convert("RGBA")
|
| 140 |
+
if isinstance(result, str):
|
| 141 |
+
return Image.open(result).convert("RGBA")
|
| 142 |
+
if isinstance(result, dict) and "path" in result:
|
| 143 |
+
return Image.open(result["path"]).convert("RGBA")
|
| 144 |
+
raise ValueError(f"Unexpected VTON result format: {type(result)} => {result}")
|
| 145 |
+
|
| 146 |
+
# ✅ FIRST FUNCTION (OUTSIDE)
|
| 147 |
+
def _get_vton_client() -> Client:
|
| 148 |
+
global _VTON_CLIENT
|
| 149 |
+
|
| 150 |
+
if _VTON_CLIENT is not None:
|
| 151 |
+
return _VTON_CLIENT
|
| 152 |
+
|
| 153 |
+
if not VTON_SPACE_ID:
|
| 154 |
+
raise RuntimeError("Set VTON_SPACE_ID, e.g. EcoTry/IDM-VTON")
|
| 155 |
+
|
| 156 |
+
# optional token
|
| 157 |
+
if HF_TOKEN:
|
| 158 |
+
os.environ["HF_TOKEN"] = HF_TOKEN
|
| 159 |
+
|
| 160 |
+
_VTON_CLIENT = Client(VTON_SPACE_ID)
|
| 161 |
+
return _VTON_CLIENT
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# ✅ SECOND FUNCTION (SEPARATE)
|
| 165 |
+
def call_vton_space(person_image_path: str, cloth_image_path: str, garment_description: str) -> Image.Image:
|
| 166 |
+
client = _get_vton_client()
|
| 167 |
+
|
| 168 |
+
result = client.predict(
|
| 169 |
+
dict={
|
| 170 |
+
"background": file(person_image_path),
|
| 171 |
+
"layers": [],
|
| 172 |
+
"composite": None,
|
| 173 |
+
},
|
| 174 |
+
garm_img=file(cloth_image_path),
|
| 175 |
+
garment_des=f"high quality realistic photo of person wearing {garment_description}",
|
| 176 |
+
is_checked=True,
|
| 177 |
+
is_checked_crop=True,
|
| 178 |
+
denoise_steps=40,
|
| 179 |
+
seed=1234,
|
| 180 |
+
api_name=VTON_API_NAME,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
return _open_result_as_image(result[0])
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
_VTON_CLIENT = Client(VTON_SPACE_ID)
|
| 188 |
+
|
| 189 |
+
return _VTON_CLIENT
|
| 190 |
+
result = client.predict(
|
| 191 |
+
dict={
|
| 192 |
+
"background": file(person_image_path),
|
| 193 |
+
"layers": [],
|
| 194 |
+
"composite": None,
|
| 195 |
+
},
|
| 196 |
+
garm_img=file(cloth_image_path),
|
| 197 |
+
garment_des=f"high quality realistic photo of person wearing {garment_description}",
|
| 198 |
+
is_checked=True,
|
| 199 |
+
is_checked_crop=True,
|
| 200 |
+
denoise_steps=40,
|
| 201 |
+
seed=1234,
|
| 202 |
+
api_name=VTON_API_NAME,
|
| 203 |
+
)
|
| 204 |
+
return _open_result_as_image(result[0])
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def create_app() -> Flask:
|
| 208 |
+
app = Flask(__name__)
|
| 209 |
+
app.config["SECRET_KEY"] = os.environ.get("ECOTRY_SECRET_KEY", "change-this-secret")
|
| 210 |
+
app.config["ADMIN_PASSWORD"] = os.environ.get("ECOTRY_ADMIN_PASSWORD", "admin123")
|
| 211 |
+
|
| 212 |
+
df = pd.read_csv(DATA_CSV)
|
| 213 |
+
df["category"] = df["product_name"].apply(infer_category)
|
| 214 |
+
df["static_filename"] = df["image_url"].apply(normalize_static_image_path)
|
| 215 |
+
|
| 216 |
+
base_products: List[Product] = []
|
| 217 |
+
for row in df.to_dict(orient="records"):
|
| 218 |
+
base_products.append(
|
| 219 |
+
Product(
|
| 220 |
+
product_id=int(row["product_id"]),
|
| 221 |
+
product_name=str(row["product_name"]),
|
| 222 |
+
fabric_type=str(row["fabric_type"]),
|
| 223 |
+
image_url=str(row["image_url"]),
|
| 224 |
+
water_usage_liters=float(row["water_usage_liters"]),
|
| 225 |
+
co2_emission_kg=float(row["co2_emission_kg"]),
|
| 226 |
+
biodegradability_score=float(row["biodegradability_score"]),
|
| 227 |
+
sustainability_score=float(row["sustainability_score"]),
|
| 228 |
+
awareness_text=str(row["awareness_text"]),
|
| 229 |
+
category=str(row["category"]),
|
| 230 |
+
static_filename=str(row["static_filename"]),
|
| 231 |
+
)
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
base_by_id: Dict[int, Product] = {p.product_id: p for p in base_products}
|
| 235 |
+
|
| 236 |
+
def get_cart() -> Dict[str, int]:
|
| 237 |
+
cart = session.get("cart", {})
|
| 238 |
+
if not isinstance(cart, dict):
|
| 239 |
+
return {}
|
| 240 |
+
cleaned: Dict[str, int] = {}
|
| 241 |
+
for k, v in cart.items():
|
| 242 |
+
try:
|
| 243 |
+
qty = int(v)
|
| 244 |
+
except (TypeError, ValueError):
|
| 245 |
+
continue
|
| 246 |
+
if qty > 0:
|
| 247 |
+
cleaned[str(k)] = qty
|
| 248 |
+
return cleaned
|
| 249 |
+
|
| 250 |
+
def save_cart(cart: Dict[str, int]) -> None:
|
| 251 |
+
session["cart"] = cart
|
| 252 |
+
session.modified = True
|
| 253 |
+
|
| 254 |
+
def cart_count(cart: Dict[str, int]) -> int:
|
| 255 |
+
return sum(cart.values())
|
| 256 |
+
|
| 257 |
+
def build_category_counts(items: List[Product]) -> List[Tuple[str, int]]:
|
| 258 |
+
counts: Dict[str, int] = {}
|
| 259 |
+
for p in items:
|
| 260 |
+
counts[p.category] = counts.get(p.category, 0) + 1
|
| 261 |
+
return sorted(counts.items(), key=lambda x: x[1], reverse=True)
|
| 262 |
+
|
| 263 |
+
def apply_filters(items: List[Product], *, category: Optional[str], q: Optional[str], sort: str) -> List[Product]:
|
| 264 |
+
filtered = items
|
| 265 |
+
|
| 266 |
+
if category and category != "All":
|
| 267 |
+
filtered = [p for p in filtered if p.category == category]
|
| 268 |
+
|
| 269 |
+
if q:
|
| 270 |
+
query = q.strip().lower()
|
| 271 |
+
if query:
|
| 272 |
+
filtered = [
|
| 273 |
+
p
|
| 274 |
+
for p in filtered
|
| 275 |
+
if query in p.product_name.lower() or query in p.fabric_type.lower()
|
| 276 |
+
]
|
| 277 |
+
|
| 278 |
+
if sort == "eco_desc":
|
| 279 |
+
filtered = sorted(filtered, key=lambda p: p.sustainability_score, reverse=True)
|
| 280 |
+
elif sort == "eco_asc":
|
| 281 |
+
filtered = sorted(filtered, key=lambda p: p.sustainability_score)
|
| 282 |
+
elif sort == "name_desc":
|
| 283 |
+
filtered = sorted(filtered, key=lambda p: p.product_name.lower(), reverse=True)
|
| 284 |
+
else:
|
| 285 |
+
filtered = sorted(filtered, key=lambda p: p.product_name.lower())
|
| 286 |
+
|
| 287 |
+
return filtered
|
| 288 |
+
|
| 289 |
+
def get_products_with_overrides() -> List[Product]:
|
| 290 |
+
overrides = load_overrides()
|
| 291 |
+
return [apply_overrides(p, overrides) for p in base_products]
|
| 292 |
+
|
| 293 |
+
def render_tryon_page(product: Product, *, result_image_url: Optional[str] = None) -> str:
|
| 294 |
+
return render_template(
|
| 295 |
+
"tryon.html",
|
| 296 |
+
product={
|
| 297 |
+
"product_id": product.product_id,
|
| 298 |
+
"product_name": product.product_name,
|
| 299 |
+
"image_src": url_for("static", filename=product.static_filename),
|
| 300 |
+
},
|
| 301 |
+
result_image_url=result_image_url,
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def admin_authed() -> bool:
|
| 305 |
+
return session.get("is_admin") is True
|
| 306 |
+
|
| 307 |
+
@app.context_processor
|
| 308 |
+
def inject_globals() -> Dict[str, Any]:
|
| 309 |
+
cart = get_cart()
|
| 310 |
+
return {"cart_items_count": cart_count(cart), "brand_logo": url_for("static", filename="assets/ecotry-logo.png")}
|
| 311 |
+
|
| 312 |
+
@app.route("/")
|
| 313 |
+
def home():
|
| 314 |
+
selected_category = request.args.get("category", "All")
|
| 315 |
+
q = request.args.get("q", "")
|
| 316 |
+
sort = request.args.get("sort", "name_asc")
|
| 317 |
+
|
| 318 |
+
products = get_products_with_overrides()
|
| 319 |
+
filtered = apply_filters(products, category=selected_category, q=q, sort=sort)
|
| 320 |
+
|
| 321 |
+
view_products: List[Dict[str, Any]] = []
|
| 322 |
+
for p in filtered:
|
| 323 |
+
view_products.append(
|
| 324 |
+
{
|
| 325 |
+
"product_id": p.product_id,
|
| 326 |
+
"product_name": p.product_name,
|
| 327 |
+
"fabric_type": p.fabric_type,
|
| 328 |
+
"sustainability_score": p.sustainability_score,
|
| 329 |
+
"water_usage_liters": p.water_usage_liters,
|
| 330 |
+
"co2_emission_kg": p.co2_emission_kg,
|
| 331 |
+
"biodegradability_score": p.biodegradability_score,
|
| 332 |
+
"awareness_text": p.awareness_text,
|
| 333 |
+
"category": p.category,
|
| 334 |
+
"image_src": url_for("static", filename=p.static_filename),
|
| 335 |
+
}
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
return render_template(
|
| 339 |
+
"index.html",
|
| 340 |
+
products=view_products,
|
| 341 |
+
categories_with_counts=build_category_counts(products),
|
| 342 |
+
total_count=len(products),
|
| 343 |
+
selected_category=selected_category,
|
| 344 |
+
q=q,
|
| 345 |
+
sort=sort,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
# ---- CART ROUTES (fixes cart_page BuildError) ----
|
| 349 |
+
@app.route("/add-to-cart/<int:product_id>", methods=["POST"])
|
| 350 |
+
def add_to_cart(product_id: int):
|
| 351 |
+
if product_id not in base_by_id:
|
| 352 |
+
flash("Product not found.", "error")
|
| 353 |
+
return redirect(url_for("home"))
|
| 354 |
+
|
| 355 |
+
cart = get_cart()
|
| 356 |
+
key = str(product_id)
|
| 357 |
+
cart[key] = cart.get(key, 0) + 1
|
| 358 |
+
save_cart(cart)
|
| 359 |
+
flash("Added to cart.", "success")
|
| 360 |
+
return redirect(request.referrer or url_for("home"))
|
| 361 |
+
|
| 362 |
+
@app.route("/cart")
|
| 363 |
+
def cart_page():
|
| 364 |
+
cart = get_cart()
|
| 365 |
+
overrides = load_overrides()
|
| 366 |
+
lines: List[Dict[str, Any]] = []
|
| 367 |
+
for pid_str, qty in cart.items():
|
| 368 |
+
p = base_by_id.get(int(pid_str))
|
| 369 |
+
if not p:
|
| 370 |
+
continue
|
| 371 |
+
p = apply_overrides(p, overrides)
|
| 372 |
+
lines.append(
|
| 373 |
+
{
|
| 374 |
+
"product_id": p.product_id,
|
| 375 |
+
"product_name": p.product_name,
|
| 376 |
+
"fabric_type": p.fabric_type,
|
| 377 |
+
"category": p.category,
|
| 378 |
+
"qty": qty,
|
| 379 |
+
"eco": p.sustainability_score,
|
| 380 |
+
"image_src": url_for("static", filename=p.static_filename),
|
| 381 |
+
}
|
| 382 |
+
)
|
| 383 |
+
return render_template("cart.html", lines=lines)
|
| 384 |
+
|
| 385 |
+
@app.route("/cart/update", methods=["POST"])
|
| 386 |
+
def cart_update():
|
| 387 |
+
cart = get_cart()
|
| 388 |
+
for k, v in request.form.to_dict().items():
|
| 389 |
+
if not k.startswith("qty_"):
|
| 390 |
+
continue
|
| 391 |
+
pid = k.replace("qty_", "").strip()
|
| 392 |
+
try:
|
| 393 |
+
qty = int(v)
|
| 394 |
+
except ValueError:
|
| 395 |
+
qty = 1
|
| 396 |
+
if qty <= 0:
|
| 397 |
+
cart.pop(pid, None)
|
| 398 |
+
else:
|
| 399 |
+
cart[pid] = min(qty, 99)
|
| 400 |
+
save_cart(cart)
|
| 401 |
+
flash("Cart updated.", "success")
|
| 402 |
+
return redirect(url_for("cart_page"))
|
| 403 |
+
|
| 404 |
+
@app.route("/cart/remove/<int:product_id>", methods=["POST"])
|
| 405 |
+
def cart_remove(product_id: int):
|
| 406 |
+
cart = get_cart()
|
| 407 |
+
cart.pop(str(product_id), None)
|
| 408 |
+
save_cart(cart)
|
| 409 |
+
flash("Removed from cart.", "success")
|
| 410 |
+
return redirect(url_for("cart_page"))
|
| 411 |
+
|
| 412 |
+
@app.route("/checkout", methods=["GET", "POST"])
|
| 413 |
+
def checkout():
|
| 414 |
+
cart = get_cart()
|
| 415 |
+
if not cart:
|
| 416 |
+
flash("Your cart is empty.", "error")
|
| 417 |
+
return redirect(url_for("home"))
|
| 418 |
+
|
| 419 |
+
overrides = load_overrides()
|
| 420 |
+
lines: List[Dict[str, Any]] = []
|
| 421 |
+
for pid_str, qty in cart.items():
|
| 422 |
+
p = base_by_id.get(int(pid_str))
|
| 423 |
+
if not p:
|
| 424 |
+
continue
|
| 425 |
+
p = apply_overrides(p, overrides)
|
| 426 |
+
lines.append({"product_id": p.product_id, "product_name": p.product_name, "qty": qty, "eco": p.sustainability_score})
|
| 427 |
+
|
| 428 |
+
eco_avg = round(sum(line["eco"] * line["qty"] for line in lines) / max(1, sum(line["qty"] for line in lines)), 2)
|
| 429 |
+
|
| 430 |
+
if request.method == "POST":
|
| 431 |
+
name = request.form.get("name", "").strip()
|
| 432 |
+
email = request.form.get("email", "").strip()
|
| 433 |
+
address = request.form.get("address", "").strip()
|
| 434 |
+
if not name or not email or not address:
|
| 435 |
+
flash("Please fill in name, email, and address.", "error")
|
| 436 |
+
return render_template("checkout.html", lines=lines, eco_avg=eco_avg)
|
| 437 |
+
|
| 438 |
+
session["last_order"] = {"name": name, "email": email, "address": address, "items": lines, "eco_avg": eco_avg}
|
| 439 |
+
save_cart({})
|
| 440 |
+
return redirect(url_for("order_success"))
|
| 441 |
+
|
| 442 |
+
return render_template("checkout.html", lines=lines, eco_avg=eco_avg)
|
| 443 |
+
|
| 444 |
+
@app.route("/order-success")
|
| 445 |
+
def order_success():
|
| 446 |
+
order = session.get("last_order")
|
| 447 |
+
if not order:
|
| 448 |
+
return redirect(url_for("home"))
|
| 449 |
+
return render_template("success.html", order=order)
|
| 450 |
+
|
| 451 |
+
# ---- AI STYLIST PAGE ----
|
| 452 |
+
@app.route("/stylist", methods=["GET", "POST"])
|
| 453 |
+
def stylist_page():
|
| 454 |
+
if request.method == "GET":
|
| 455 |
+
return render_template("stylist.html", result=None)
|
| 456 |
+
|
| 457 |
+
selfie = request.files.get("selfie")
|
| 458 |
+
if not selfie or not selfie.filename:
|
| 459 |
+
flash("Please upload an image.", "error")
|
| 460 |
+
return render_template("stylist.html", result=None)
|
| 461 |
+
|
| 462 |
+
height_cm_raw = (request.form.get("height_cm") or "").strip()
|
| 463 |
+
body_type = (request.form.get("body_type") or "Average").strip()
|
| 464 |
+
gender = (request.form.get("gender") or "Unspecified").strip()
|
| 465 |
+
|
| 466 |
+
height_cm: Optional[float] = None
|
| 467 |
+
if height_cm_raw:
|
| 468 |
+
try:
|
| 469 |
+
height_cm = float(height_cm_raw)
|
| 470 |
+
except ValueError:
|
| 471 |
+
height_cm = None
|
| 472 |
+
|
| 473 |
+
try:
|
| 474 |
+
img = Image.open(selfie.stream).convert("RGB")
|
| 475 |
+
|
| 476 |
+
generated_dir = Path(app.root_path) / "static" / "generated"
|
| 477 |
+
generated_dir.mkdir(parents=True, exist_ok=True)
|
| 478 |
+
filename = "stylist_user.png"
|
| 479 |
+
img.save(generated_dir / filename)
|
| 480 |
+
|
| 481 |
+
skin = detect_skin_tone_pil(img)
|
| 482 |
+
style = generate_style_text_suggestions(
|
| 483 |
+
image_pil=img,
|
| 484 |
+
skin_label=skin.skin_label,
|
| 485 |
+
dominant_hex=skin.dominant_hex,
|
| 486 |
+
height_cm=height_cm,
|
| 487 |
+
body_type=body_type,
|
| 488 |
+
gender=gender,
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
result = {
|
| 492 |
+
"image_url": url_for("static", filename=f"generated/{filename}"),
|
| 493 |
+
"skin": {"label": skin.skin_label, "confidence": skin.confidence, "dominant_hex": skin.dominant_hex},
|
| 494 |
+
"palette": skin.best_palette,
|
| 495 |
+
"style": style,
|
| 496 |
+
}
|
| 497 |
+
return render_template("stylist.html", result=result)
|
| 498 |
+
except Exception as exc:
|
| 499 |
+
flash(f"AI Stylist failed: {exc}", "error")
|
| 500 |
+
return render_template("stylist.html", result=None)
|
| 501 |
+
|
| 502 |
+
# Placeholder for your friend's feature
|
| 503 |
+
@app.route("/size", methods=["GET"])
|
| 504 |
+
def size_page():
|
| 505 |
+
flash("Size Recommendation page is under development.", "success")
|
| 506 |
+
return redirect(url_for("home"))
|
| 507 |
+
@app.route("/api/ai/style", methods=["POST"])
|
| 508 |
+
def ai_style():
|
| 509 |
+
try:
|
| 510 |
+
vibe = request.form.get("vibe", "minimal")
|
| 511 |
+
|
| 512 |
+
recs = []
|
| 513 |
+
|
| 514 |
+
# simple recommendation logic
|
| 515 |
+
for p in base_products[:5]:
|
| 516 |
+
recs.append({
|
| 517 |
+
"product": {
|
| 518 |
+
"product_id": p.product_id,
|
| 519 |
+
"product_name": p.product_name,
|
| 520 |
+
"category": p.category,
|
| 521 |
+
"image_src": url_for("static", filename=p.static_filename)
|
| 522 |
+
},
|
| 523 |
+
"score": round(p.sustainability_score, 3)
|
| 524 |
+
})
|
| 525 |
+
|
| 526 |
+
return {"ok": True, "recs": recs}
|
| 527 |
+
|
| 528 |
+
except Exception as e:
|
| 529 |
+
return {"ok": False, "error": str(e)}
|
| 530 |
+
|
| 531 |
+
@app.route("/tryon/<int:product_id>", methods=["GET", "POST"])
|
| 532 |
+
def tryon_product(product_id: int):
|
| 533 |
+
product = base_by_id.get(product_id)
|
| 534 |
+
if not product:
|
| 535 |
+
flash("Product not found.", "error")
|
| 536 |
+
return redirect(url_for("home"))
|
| 537 |
+
|
| 538 |
+
cloth_path = Path(app.root_path) / "static" / product.static_filename
|
| 539 |
+
|
| 540 |
+
if request.method == "GET":
|
| 541 |
+
return render_tryon_page(product, result_image_url=None)
|
| 542 |
+
|
| 543 |
+
if "person_image" not in request.files:
|
| 544 |
+
flash("Please upload your photo.", "error")
|
| 545 |
+
return render_tryon_page(product, result_image_url=None)
|
| 546 |
+
|
| 547 |
+
if not cloth_path.exists():
|
| 548 |
+
flash(f"Cloth image file not found: {cloth_path}", "error")
|
| 549 |
+
return render_tryon_page(product, result_image_url=None)
|
| 550 |
+
|
| 551 |
+
person_file = request.files["person_image"]
|
| 552 |
+
if not person_file.filename:
|
| 553 |
+
flash("Invalid person image.", "error")
|
| 554 |
+
return render_tryon_page(product, result_image_url=None)
|
| 555 |
+
|
| 556 |
+
person_ext = _secure_ext(person_file.filename)
|
| 557 |
+
|
| 558 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 559 |
+
tmp_path = Path(tmp_dir)
|
| 560 |
+
person_path = tmp_path / f"person{person_ext}"
|
| 561 |
+
person_file.save(person_path)
|
| 562 |
+
|
| 563 |
+
try:
|
| 564 |
+
out_img = call_vton_space(
|
| 565 |
+
person_image_path=str(person_path),
|
| 566 |
+
cloth_image_path=str(cloth_path),
|
| 567 |
+
garment_description=product.product_name,
|
| 568 |
+
)
|
| 569 |
+
except Exception as exc:
|
| 570 |
+
flash(f"Try-on failed: {exc}", "error")
|
| 571 |
+
return render_tryon_page(product, result_image_url=None)
|
| 572 |
+
|
| 573 |
+
generated_dir = Path(app.root_path) / "static" / "generated"
|
| 574 |
+
generated_dir.mkdir(parents=True, exist_ok=True)
|
| 575 |
+
|
| 576 |
+
output_filename = f"tryon_{product_id}.png"
|
| 577 |
+
out_img.save(generated_dir / output_filename)
|
| 578 |
+
|
| 579 |
+
return render_tryon_page(product, result_image_url=url_for("static", filename=f"generated/tryon_{product_id}.png"))
|
| 580 |
+
|
| 581 |
+
return app
|
| 582 |
+
|
| 583 |
+
app = create_app()
|
| 584 |
+
|
| 585 |
+
if __name__ == "__main__":
|
| 586 |
+
port = int(os.environ.get("PORT", "7860"))
|
| 587 |
+
app.run(host="0.0.0.0", port=port, debug=True)
|
eco_try_products_dataset_fabric_category_fixed.csv
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
product_id,product_name,fabric_type,image_url,water_usage_liters,co2_emission_kg,biodegradability_score,sustainability_score,awareness_text,category
|
| 2 |
+
1,Hemp Sweater,Cotton jersey,static/images/1.jpeg,1272.8,1.05,9,9.3,"Hemp has water usage ~1272.8L/kg, CO2 emission ~1.05kg/kg, biodegradability 9/10.",Sweater
|
| 3 |
+
2,Recycled Polyester Jeans,Wool knit / wool blend,static/images/2.jpeg,1938.5,2.6,3,6.3,"Recycled Polyester has water usage ~1938.5L/kg, CO2 emission ~2.6kg/kg, biodegradability 3/10.",Jeans
|
| 4 |
+
3,Recycled Polyester Shirt,Satin (polyester or silk satin),static/images/3.jpeg,1924.1,2.58,4,6.6,"Recycled Polyester has water usage ~1924.1L/kg, CO2 emission ~2.58kg/kg, biodegradability 4/10.",Shirt
|
| 5 |
+
4,Silk Jeans,Cotton jersey,static/images/4.jpeg,2800.0,3.25,7,6.7,"Silk has water usage ~2800.0L/kg, CO2 emission ~3.25kg/kg, biodegradability 7/10.",Jeans
|
| 6 |
+
5,Silk Shirt,"Denim (cotton denim, maybe elastane)",static/images/5.jpeg,2267.2,3.98,8,7.3,"Silk has water usage ~2267.2L/kg, CO2 emission ~3.98kg/kg, biodegradability 8/10.",Shirt
|
| 7 |
+
6,Wool Dress,Denim / cotton twill,static/images/6.jpeg,4689.9,10.61,7,3.0,"Wool has water usage ~4689.9L/kg, CO2 emission ~10.61kg/kg, biodegradability 7/10.",Dress
|
| 8 |
+
7,Silk Dress,Fleece (cotton/poly blend),static/images/7.jpeg,2910.0,3.26,8,7.0,"Silk has water usage ~2910.0L/kg, CO2 emission ~3.26kg/kg, biodegradability 8/10.",Dress
|
| 9 |
+
8,Polyester Dress,Fleece (cotton/poly blend),static/images/8.jpeg,2595.5,5.32,1,4.3,"Polyester has water usage ~2595.5L/kg, CO2 emission ~5.32kg/kg, biodegradability 1/10.",Dress
|
| 10 |
+
9,Silk Hoodie,Wool / wool blend (coat wool),static/images/9.jpeg,2326.6,3.84,6,6.6,"Silk has water usage ~2326.6L/kg, CO2 emission ~3.84kg/kg, biodegradability 6/10.",Hoodie
|
| 11 |
+
10,Linen T-shirt,Satin (polyester or silk satin),static/images/10.jpeg,1741.6,1.18,9,8.9,"Linen has water usage ~1741.6L/kg, CO2 emission ~1.18kg/kg, biodegradability 9/10.",Shirt
|
| 12 |
+
11,Linen Shirt,Linen / linen-blend,static/images/11.jpeg,1477.1,1.31,9,9.0,"Linen has water usage ~1477.1L/kg, CO2 emission ~1.31kg/kg, biodegradability 9/10.",Shirt
|
| 13 |
+
12,Silk Hoodie,Polyester (performance knit),static/images/12.jpeg,2068.6,3.58,6,6.9,"Silk has water usage ~2068.6L/kg, CO2 emission ~3.58kg/kg, biodegradability 6/10.",Hoodie
|
| 14 |
+
13,Silk Sweater,Cotton poplin / cotton-linen blend,static/images/13.jpeg,2231.3,3.66,6,6.7,"Silk has water usage ~2231.3L/kg, CO2 emission ~3.66kg/kg, biodegradability 6/10.",Sweater
|
| 15 |
+
14,Wool Jacket,Cotton jersey (or blend),static/images/14.jpeg,4112.6,10.72,7,3.4,"Wool has water usage ~4112.6L/kg, CO2 emission ~10.72kg/kg, biodegradability 7/10.",Jacket
|
| 16 |
+
15,Polyester Hoodie,Nylon/Polyester (synthetic shell),static/images/15.jpeg,2536.6,5.31,3,5.0,"Polyester has water usage ~2536.6L/kg, CO2 emission ~5.31kg/kg, biodegradability 3/10.",Hoodie
|
| 17 |
+
16,Polyester Hoodie,Wool knit / wool blend,static/images/16.jpeg,2742.2,5.97,1,4.0,"Polyester has water usage ~2742.2L/kg, CO2 emission ~5.97kg/kg, biodegradability 1/10.",Hoodie
|
| 18 |
+
17,Hemp Hoodie,Satin (polyester or silk satin),static/images/17.jpeg,953.7,1.1,9,9.5,"Hemp has water usage ~953.7L/kg, CO2 emission ~1.1kg/kg, biodegradability 9/10.",Hoodie
|
| 19 |
+
18,Recycled Polyester Dress,Linen / linen-blend,static/images/18.jpeg,2080.6,2.74,3,6.1,"Recycled Polyester has water usage ~2080.6L/kg, CO2 emission ~2.74kg/kg, biodegradability 3/10.",Dress
|
| 20 |
+
19,Linen Jeans,Polyester-heavy fleece / poly blend,static/images/19.jpeg,1385.8,1.59,9,9.0,"Linen has water usage ~1385.8L/kg, CO2 emission ~1.59kg/kg, biodegradability 9/10.",Jeans
|
| 21 |
+
20,Recycled Polyester Shirt,Cotton jersey,static/images/20.jpeg,1897.9,2.27,5,7.1,"Recycled Polyester has water usage ~1897.9L/kg, CO2 emission ~2.27kg/kg, biodegradability 5/10.",Shirt
|
| 22 |
+
21,Recycled Polyester Hoodie,Cotton jersey,static/images/21.jpeg,1819.8,2.99,5,6.9,"Recycled Polyester has water usage ~1819.8L/kg, CO2 emission ~2.99kg/kg, biodegradability 5/10.",Hoodie
|
| 23 |
+
22,Silk Shirt,Wool / wool blend (coat wool),static/images/22.jpeg,2151.6,3.36,6,6.9,"Silk has water usage ~2151.6L/kg, CO2 emission ~3.36kg/kg, biodegradability 6/10.",Shirt
|
| 24 |
+
23,Silk Jacket,"Denim (cotton denim, maybe elastane)",static/images/23.jpeg,2782.8,3.96,7,6.5,"Silk has water usage ~2782.8L/kg, CO2 emission ~3.96kg/kg, biodegradability 7/10.",Jacket
|
| 25 |
+
24,Wool Jacket,Denim / cotton twill,static/images/24.jpeg,4598.6,10.02,9,3.9,"Wool has water usage ~4598.6L/kg, CO2 emission ~10.02kg/kg, biodegradability 9/10.",Jacket
|
| 26 |
+
25,Wool Dress,Denim / cotton twill,static/images/25.jpeg,4008.0,11.95,7,3.1,"Wool has water usage ~4008.0L/kg, CO2 emission ~11.95kg/kg, biodegradability 7/10.",Dress
|
| 27 |
+
26,Hemp Hoodie,Cotton jersey,static/images/26.jpeg,1073.0,1.12,9,9.4,"Hemp has water usage ~1073.0L/kg, CO2 emission ~1.12kg/kg, biodegradability 9/10.",Hoodie
|
| 28 |
+
27,Polyester Jacket,Satin (polyester or silk satin),static/images/27.jpeg,2941.1,5.81,2,4.2,"Polyester has water usage ~2941.1L/kg, CO2 emission ~5.81kg/kg, biodegradability 2/10.",Jacket
|
| 29 |
+
28,Polyester Sweater,Linen / linen-blend (or cotton-linen),static/images/28.jpeg,2838.0,5.1,3,4.8,"Polyester has water usage ~2838.0L/kg, CO2 emission ~5.1kg/kg, biodegradability 3/10.",Sweater
|
| 30 |
+
29,Recycled Polyester T-shirt,Wool knit / wool blend,static/images/29.jpeg,2085.9,2.5,4,6.5,"Recycled Polyester has water usage ~2085.9L/kg, CO2 emission ~2.5kg/kg, biodegradability 4/10.",Shirt
|
| 31 |
+
30,Polyester Sweater,Fleece (cotton/poly blend),static/images/30.jpeg,2922.3,5.23,1,4.0,"Polyester has water usage ~2922.3L/kg, CO2 emission ~5.23kg/kg, biodegradability 1/10.",Sweater
|
| 32 |
+
31,Hemp T-shirt,Cotton jersey,static/images/31.jpeg,1185.4,1.33,9,9.3,"Hemp has water usage ~1185.4L/kg, CO2 emission ~1.33kg/kg, biodegradability 9/10.",Shirt
|
| 33 |
+
32,Silk T-shirt,Wool / wool blend (coat wool),static/images/32.jpeg,2347.6,3.65,6,6.6,"Silk has water usage ~2347.6L/kg, CO2 emission ~3.65kg/kg, biodegradability 6/10.",Shirt
|
| 34 |
+
33,Silk Sweater,"Denim (cotton denim, maybe elastane)",static/images/33.jpeg,2682.4,3.99,7,6.6,"Silk has water usage ~2682.4L/kg, CO2 emission ~3.99kg/kg, biodegradability 7/10.",Sweater
|
| 35 |
+
34,Hemp T-shirt,Denim / cotton twill,static/images/34.jpeg,1184.9,1.39,10,9.6,"Hemp has water usage ~1184.9L/kg, CO2 emission ~1.39kg/kg, biodegradability 10/10.",Shirt
|
| 36 |
+
35,Linen Hoodie,Denim / cotton twill,static/images/35.jpeg,1157.0,1.0,8,9.0,"Linen has water usage ~1157.0L/kg, CO2 emission ~1.0kg/kg, biodegradability 8/10.",Hoodie
|
| 37 |
+
36,Silk Sweater,Cotton jersey,static/images/36.jpeg,2856.4,3.75,6,6.2,"Silk has water usage ~2856.4L/kg, CO2 emission ~3.75kg/kg, biodegradability 6/10.",Sweater
|
| 38 |
+
37,Hemp Hoodie,Satin (polyester or silk satin),static/images/37.jpeg,1053.7,1.43,10,9.7,"Hemp has water usage ~1053.7L/kg, CO2 emission ~1.43kg/kg, biodegradability 10/10.",Hoodie
|
| 39 |
+
38,Wool Shirt,Linen / linen-blend (or cotton-linen),static/images/38.jpeg,4600.9,11.45,8,3.2,"Wool has water usage ~4600.9L/kg, CO2 emission ~11.45kg/kg, biodegradability 8/10.",Shirt
|
| 40 |
+
39,Polyester Jacket,Wool knit / wool blend,static/images/39.jpeg,2904.3,5.04,1,4.1,"Polyester has water usage ~2904.3L/kg, CO2 emission ~5.04kg/kg, biodegradability 1/10.",Jacket
|
| 41 |
+
40,Hemp T-shirt,Fleece (cotton/poly blend),static/images/40.jpeg,1174.9,1.36,10,9.6,"Hemp has water usage ~1174.9L/kg, CO2 emission ~1.36kg/kg, biodegradability 10/10.",Shirt
|
| 42 |
+
41,Polyester Hoodie,Satin (polyester or silk satin),static/images/41.jpeg,2800.6,5.49,2,4.4,"Polyester has water usage ~2800.6L/kg, CO2 emission ~5.49kg/kg, biodegradability 2/10.",Hoodie
|
| 43 |
+
42,Polyester Jacket,Linen / linen-blend,static/images/42.jpeg,2638.2,5.84,2,4.4,"Polyester has water usage ~2638.2L/kg, CO2 emission ~5.84kg/kg, biodegradability 2/10.",Jacket
|
| 44 |
+
43,Hemp T-shirt,Wool knit / wool blend,static/images/43.jpeg,1004.2,1.5,9,9.4,"Hemp has water usage ~1004.2L/kg, CO2 emission ~1.5kg/kg, biodegradability 9/10.",Shirt
|
| 45 |
+
44,Polyester Sweater,Polyester (performance knit),static/images/44.jpeg,2598.4,5.92,3,4.7,"Polyester has water usage ~2598.4L/kg, CO2 emission ~5.92kg/kg, biodegradability 3/10.",Sweater
|
| 46 |
+
45,Linen Jeans,Fleece (cotton/poly blend),static/images/45.jpeg,1470.5,1.41,8,8.7,"Linen has water usage ~1470.5L/kg, CO2 emission ~1.41kg/kg, biodegradability 8/10.",Jeans
|
| 47 |
+
46,Polyester Dress,Fleece (cotton/poly blend),static/images/46.jpeg,2689.3,5.58,1,4.1,"Polyester has water usage ~2689.3L/kg, CO2 emission ~5.58kg/kg, biodegradability 1/10.",Dress
|
| 48 |
+
47,Hemp T-shirt,Linen / linen-blend,static/images/47.jpeg,1315.2,1.36,9,9.1,"Hemp has water usage ~1315.2L/kg, CO2 emission ~1.36kg/kg, biodegradability 9/10.",Shirt
|
| 49 |
+
48,Recycled Polyester Jacket,Satin (polyester or silk satin),static/images/48.jpeg,2009.6,2.1,5,7.0,"Recycled Polyester has water usage ~2009.6L/kg, CO2 emission ~2.1kg/kg, biodegradability 5/10.",Jacket
|
| 50 |
+
49,Linen Jeans,Polyester/Nylon (synthetic shell),static/images/49.jpeg,1234.5,1.96,7,8.4,"Linen has water usage ~1234.5L/kg, CO2 emission ~1.96kg/kg, biodegradability 7/10.",Jeans
|
| 51 |
+
50,Hemp T-shirt,Cotton jersey,static/images/50.jpeg,2138.9,2.27,5,6.9,"Hemp has water usage ~2138.9L/kg, CO2 emission ~2.27kg/kg, biodegradability 5/10.",Shirt
|
fabric_mapping_1_to_50.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"1": "Cotton jersey",
|
| 3 |
+
"2": "Wool knit / wool blend",
|
| 4 |
+
"3": "Satin (polyester or silk satin)",
|
| 5 |
+
"4": "Cotton jersey",
|
| 6 |
+
"5": "Denim (cotton denim, maybe elastane)",
|
| 7 |
+
"6": "Denim / cotton twill",
|
| 8 |
+
"7": "Fleece (cotton/poly blend)",
|
| 9 |
+
"8": "Fleece (cotton/poly blend)",
|
| 10 |
+
"9": "Wool / wool blend (coat wool)",
|
| 11 |
+
"10": "Satin (polyester or silk satin)",
|
| 12 |
+
"11": "Linen / linen-blend",
|
| 13 |
+
"12": "Polyester (performance knit)",
|
| 14 |
+
"13": "Cotton poplin / cotton-linen blend",
|
| 15 |
+
"14": "Cotton jersey (or blend)",
|
| 16 |
+
"15": "Nylon/Polyester (synthetic shell)",
|
| 17 |
+
"16": "Wool knit / wool blend",
|
| 18 |
+
"17": "Satin (polyester or silk satin)",
|
| 19 |
+
"18": "Linen / linen-blend",
|
| 20 |
+
"19": "Polyester-heavy fleece / poly blend",
|
| 21 |
+
"20": "Cotton jersey",
|
| 22 |
+
"21": "Cotton jersey",
|
| 23 |
+
"22": "Wool / wool blend (coat wool)",
|
| 24 |
+
"23": "Denim (cotton denim, maybe elastane)",
|
| 25 |
+
"24": "Denim / cotton twill",
|
| 26 |
+
"25": "Denim / cotton twill",
|
| 27 |
+
"26": "Cotton jersey",
|
| 28 |
+
"27": "Satin (polyester or silk satin)",
|
| 29 |
+
"28": "Linen / linen-blend (or cotton-linen)",
|
| 30 |
+
"29": "Wool knit / wool blend",
|
| 31 |
+
"30": "Fleece (cotton/poly blend)",
|
| 32 |
+
"31": "Cotton jersey",
|
| 33 |
+
"32": "Wool / wool blend (coat wool)",
|
| 34 |
+
"33": "Denim (cotton denim, maybe elastane)",
|
| 35 |
+
"34": "Denim / cotton twill",
|
| 36 |
+
"35": "Denim / cotton twill",
|
| 37 |
+
"36": "Cotton jersey",
|
| 38 |
+
"37": "Satin (polyester or silk satin)",
|
| 39 |
+
"38": "Linen / linen-blend (or cotton-linen)",
|
| 40 |
+
"39": "Wool knit / wool blend",
|
| 41 |
+
"40": "Fleece (cotton/poly blend)",
|
| 42 |
+
"41": "Satin (polyester or silk satin)",
|
| 43 |
+
"42": "Linen / linen-blend",
|
| 44 |
+
"43": "Wool knit / wool blend",
|
| 45 |
+
"44": "Polyester (performance knit)",
|
| 46 |
+
"45": "Fleece (cotton/poly blend)",
|
| 47 |
+
"46": "Fleece (cotton/poly blend)",
|
| 48 |
+
"47": "Linen / linen-blend",
|
| 49 |
+
"48": "Satin (polyester or silk satin)",
|
| 50 |
+
"49": "Polyester/Nylon (synthetic shell)",
|
| 51 |
+
"50": "Cotton jersey"
|
| 52 |
+
}
|
overrides.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{}
|
tryon_hf.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from gradio_client import Client, file
|
| 3 |
+
|
| 4 |
+
VTON_SPACE_ID = "EcoTry/IDM-VTON"
|
| 5 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # env se lo (best)
|
| 6 |
+
|
| 7 |
+
# ✅ single clean client
|
| 8 |
+
client = Client(VTON_SPACE_ID, hf_token=HF_TOKEN)
|
| 9 |
+
|
| 10 |
+
def run_tryon(person_img_path, cloth_img_path, prompt="t-shirt"):
|
| 11 |
+
result = client.predict(
|
| 12 |
+
dict={
|
| 13 |
+
"background": file(person_img_path),
|
| 14 |
+
"layers": [],
|
| 15 |
+
"composite": None
|
| 16 |
+
},
|
| 17 |
+
garm_img=file(cloth_img_path),
|
| 18 |
+
garment_des=f"high quality photo of person wearing {prompt}",
|
| 19 |
+
is_checked=True,
|
| 20 |
+
is_checked_crop=False,
|
| 21 |
+
denoise_steps=30,
|
| 22 |
+
seed=42,
|
| 23 |
+
api_name="/tryon"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
return result[0]
|