File size: 9,138 Bytes
295e5db
5ee2642
295e5db
 
 
5ee2642
 
 
295e5db
 
5ee2642
 
 
 
295e5db
5ee2642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295e5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ee2642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295e5db
 
5ee2642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295e5db
 
 
 
 
5ee2642
295e5db
 
 
 
5ee2642
295e5db
 
 
5ee2642
295e5db
 
 
 
 
 
 
 
 
 
5ee2642
295e5db
 
 
 
 
5ee2642
 
295e5db
5ee2642
295e5db
5ee2642
 
 
 
295e5db
5ee2642
 
 
 
 
 
 
 
 
295e5db
 
5ee2642
295e5db
5ee2642
295e5db
5ee2642
 
 
295e5db
5ee2642
 
 
 
 
 
 
 
 
295e5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ee2642
 
 
 
 
 
 
 
 
 
295e5db
5ee2642
 
 
 
 
 
 
 
 
 
 
 
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
"""Build a pre-processed sample wardrobe from HuggingFace datasets.

Supports multiple dataset sources:
  - fashion-1k: Codatta/Fashion-1K (flat lays, needs detection)
  - second-hand: fnauman/fashion-second-hand-front-only-rgb (individual garments)

Usage:
    cd packages/wardrobe-us
    .venv/bin/python scripts/build_sample_wardrobe.py --dataset second-hand
    .venv/bin/python scripts/build_sample_wardrobe.py --dataset fashion-1k

Requires: datasets>=2.18.0 (pip install datasets)
"""

import argparse
import io
import json
import logging
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from PIL import Image

from src.detector import detect_and_crop
from src.vision import _extract_single_garment

logging.basicConfig(level=logging.INFO, format="%(name)s | %(message)s")
logger = logging.getLogger("build_sample")

SAMPLES_DIR = Path(__file__).resolve().parent.parent / "data" / "samples"
GARMENTS_DIR = SAMPLES_DIR / "garments"
CATALOG_PATH = SAMPLES_DIR / "catalog.json"

DEFAULT_TARGET = 50
TARGET_GARMENTS = DEFAULT_TARGET

DATASETS = {
    "second-hand": {
        "hf_id": "fnauman/fashion-second-hand-front-only-rgb",
        "description": "31K individual garments on uniform background (no detection needed)",
        "needs_detection": False,
    },
    "fashion-1k": {
        "hf_id": "Codatta/Fashion-1K",
        "description": "1K flat lay outfits (multi-garment, needs detection + cropping)",
        "needs_detection": True,
    },
}

# Curated indices for Fashion-1K variety
FASHION_1K_INDICES = [
    0, 5, 12, 18, 25, 33, 41, 50, 58, 67,
    75, 83, 91, 100, 110, 120, 130, 140, 150, 160,
    170, 180, 190, 200, 220, 240, 260, 280, 300, 320,
    350, 380, 400, 430, 460, 500, 550, 600, 650, 700,
]


def save_crop(garment_id: str, crop_bytes: bytes) -> str:
    """Save a crop to the samples garments directory."""
    GARMENTS_DIR.mkdir(parents=True, exist_ok=True)
    filename = f"{garment_id}.jpg"
    path = GARMENTS_DIR / filename
    path.write_bytes(crop_bytes)
    return filename


def process_with_detection(image: Image.Image, image_idx: int, catalog: list, garment_counter: int) -> int:
    """Process a flat lay image through detection + VLM. Returns updated garment counter."""
    with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
        image.save(tmp, format="JPEG", quality=90)
        tmp_path = tmp.name

    try:
        crops = detect_and_crop(tmp_path)
    except Exception as e:
        logger.warning("Detection failed for image %d: %s", image_idx, e)
        return garment_counter

    if not crops:
        logger.info("Image %d: no garments detected, skipping", image_idx)
        return garment_counter

    logger.info("Image %d: %d crops detected", image_idx, len(crops))

    for crop_bytes in crops:
        if garment_counter >= TARGET_GARMENTS:
            break

        garment = _extract_single_garment(crop_bytes)
        if not garment:
            logger.debug("  Crop failed VLM extraction, skipping")
            continue

        garment_counter += 1
        garment_id = f"garment_{garment_counter:03d}"
        garment["id"] = garment_id

        image_ref = save_crop(garment_id, crop_bytes)
        garment["image_ref"] = image_ref

        catalog.append(garment)
        logger.info(
            "  [%d/%d] %s: %s %s (%s)",
            garment_counter, TARGET_GARMENTS,
            garment_id, garment.get("color", "?"), garment.get("type", "?"),
            garment.get("pattern", "?"),
        )

    Path(tmp_path).unlink(missing_ok=True)
    return garment_counter


def process_individual(image: Image.Image, image_idx: int, catalog: list, garment_counter: int) -> int:
    """Process a single-garment image directly with VLM (no detection needed)."""
    buf = io.BytesIO()
    image.save(buf, format="JPEG", quality=90)
    crop_bytes = buf.getvalue()

    garment = _extract_single_garment(crop_bytes)
    if not garment:
        logger.debug("Image %d: VLM extraction failed, skipping", image_idx)
        return garment_counter

    garment_counter += 1
    garment_id = f"garment_{garment_counter:03d}"
    garment["id"] = garment_id

    image_ref = save_crop(garment_id, crop_bytes)
    garment["image_ref"] = image_ref

    catalog.append(garment)
    logger.info(
        "  [%d/%d] %s: %s %s (%s)",
        garment_counter, TARGET_GARMENTS,
        garment_id, garment.get("color", "?"), garment.get("type", "?"),
        garment.get("pattern", "?"),
    )

    return garment_counter


def build_from_fashion_1k(ds) -> list[dict]:
    """Build sample wardrobe from Fashion-1K (multi-garment flat lays)."""
    catalog: list[dict] = []
    garment_counter = 0
    max_images = 40

    for i, idx in enumerate(FASHION_1K_INDICES):
        if garment_counter >= TARGET_GARMENTS:
            break
        if idx >= len(ds):
            continue
        if i >= max_images:
            break

        sample = ds[idx]
        image = sample["image"]
        if not isinstance(image, Image.Image):
            continue
        if image.mode != "RGB":
            image = image.convert("RGB")

        logger.info("--- Processing image %d (dataset idx %d) ---", i + 1, idx)
        garment_counter = process_with_detection(image, idx, catalog, garment_counter)

    # Fill remaining with sequential if needed
    if garment_counter < TARGET_GARMENTS:
        processed = set(FASHION_1K_INDICES[:max_images])
        for idx in range(len(ds)):
            if garment_counter >= TARGET_GARMENTS:
                break
            if idx in processed:
                continue

            sample = ds[idx]
            image = sample["image"]
            if not isinstance(image, Image.Image):
                continue
            if image.mode != "RGB":
                image = image.convert("RGB")

            logger.info("--- Processing image (dataset idx %d) ---", idx)
            garment_counter = process_with_detection(image, idx, catalog, garment_counter)

    return catalog


def build_from_second_hand(ds) -> list[dict]:
    """Build sample wardrobe from second-hand dataset (individual garments)."""
    catalog: list[dict] = []
    garment_counter = 0

    # Spread indices across the dataset for variety
    step = max(1, len(ds) // (TARGET_GARMENTS * 2))
    indices = list(range(0, len(ds), step))[:TARGET_GARMENTS * 2]

    for i, idx in enumerate(indices):
        if garment_counter >= TARGET_GARMENTS:
            break

        sample = ds[idx]
        image = sample.get("image") or sample.get("img")
        if not isinstance(image, Image.Image):
            continue
        if image.mode != "RGB":
            image = image.convert("RGB")

        # Resize large images to max 512px to save VLM time
        if max(image.size) > 512:
            image.thumbnail((512, 512), Image.LANCZOS)

        logger.info("--- Processing image %d/%d (dataset idx %d) ---", i + 1, len(indices), idx)
        garment_counter = process_individual(image, idx, catalog, garment_counter)

    return catalog


def main():
    parser = argparse.ArgumentParser(description="Build sample wardrobe from HuggingFace dataset")
    parser.add_argument(
        "--dataset",
        choices=list(DATASETS.keys()),
        default="second-hand",
        help="Dataset source to use (default: second-hand)",
    )
    parser.add_argument(
        "--target",
        type=int,
        default=DEFAULT_TARGET,
        help=f"Number of garments to generate (default: {DEFAULT_TARGET})",
    )
    args = parser.parse_args()

    global TARGET_GARMENTS
    TARGET_GARMENTS = args.target

    ds_config = DATASETS[args.dataset]
    logger.info("=== Building Sample Wardrobe ===")
    logger.info("Dataset: %s (%s)", args.dataset, ds_config["description"])
    logger.info("Target: %d garments", TARGET_GARMENTS)

    try:
        from datasets import load_dataset
    except ImportError:
        logger.error("'datasets' package not installed. Run: pip install datasets")
        sys.exit(1)

    logger.info("Loading %s...", ds_config["hf_id"])
    ds = load_dataset(ds_config["hf_id"], split="train")
    logger.info("Dataset loaded: %d images", len(ds))

    SAMPLES_DIR.mkdir(parents=True, exist_ok=True)
    GARMENTS_DIR.mkdir(parents=True, exist_ok=True)

    if args.dataset == "fashion-1k":
        catalog = build_from_fashion_1k(ds)
    else:
        catalog = build_from_second_hand(ds)

    # Save catalog
    with open(CATALOG_PATH, "w", encoding="utf-8") as f:
        json.dump(catalog, f, indent=2, ensure_ascii=False)

    logger.info("=== Done ===")
    logger.info("Total garments: %d", len(catalog))
    logger.info("Catalog saved: %s", CATALOG_PATH)
    logger.info("Garment images: %s", GARMENTS_DIR)

    # Summary by type
    types: dict[str, int] = {}
    for g in catalog:
        t = g.get("type", "unknown")
        types[t] = types.get(t, 0) + 1

    logger.info("Distribution by type:")
    for t, count in sorted(types.items(), key=lambda x: -x[1]):
        logger.info("  %s: %d", t, count)


if __name__ == "__main__":
    main()