File size: 10,832 Bytes
44a7ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
287
288
#!/usr/bin/env python3
"""Process MultiID-2M for MVEB: crop, build annotations from split JSON, pack parquet."""

from __future__ import annotations

import argparse
import json
import shutil
import sys
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Dict, List, Sequence, Tuple

from PIL import Image
from tqdm import tqdm

_SCRIPTS_ROOT = Path(__file__).resolve().parent.parent
if str(_SCRIPTS_ROOT) not in sys.path:
    sys.path.insert(0, str(_SCRIPTS_ROOT))
from pack_media_parquet import pack_dataset_with_media, resolve_split_output_dir

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent

QUERY_INSTRUCTION = "You are a helpful assistant."
QUERY_TEXT = "Represent the face in the given image."
CANDIDATE_INSTRUCTION = "You are a helpful assistant."
CANDIDATE_TEXT = "Represent all faces in the given image."


def crop_faces(source_dir: Path, *, num_workers: int = 10, force: bool = False) -> None:
    """Crop faces from train_cp json/jpg pairs into cropped_grounding_cp_images."""
    train_cp_dir = source_dir / "train_cp"
    cropped_dir = source_dir / "cropped_grounding_cp_images"
    if not train_cp_dir.is_dir():
        raise FileNotFoundError(f"Missing train_cp dir: {train_cp_dir}")

    cropped_dir.mkdir(parents=True, exist_ok=True)
    subdirs = sorted(d.name for d in train_cp_dir.iterdir() if d.is_dir())
    if not subdirs:
        raise FileNotFoundError(f"No extracted shards under {train_cp_dir}")

    lock = threading.Lock()
    fail_count = 0

    def process_subdir(subdir: str) -> int:
        local_fail = 0
        anno_files = sorted((train_cp_dir / subdir).glob("*.json"))
        for anno_file in tqdm(anno_files, desc=f"crop {subdir}", leave=False):
            try:
                anno = json.loads(anno_file.read_text(encoding="utf-8"))
                img_path = anno_file.with_suffix(".jpg")
                if not img_path.is_file():
                    local_fail += 1
                    continue
                crop_box = anno["crop"]
                img = Image.open(img_path)
                for i, bbox in enumerate(anno["bboxes"]):
                    inst_id = str(anno["name"][i])
                    out_name = f"{img_path.stem}_{inst_id}.jpg"
                    out_path = cropped_dir / subdir / out_name
                    if out_path.is_file() and not force:
                        continue
                    face_bbox = [
                        bbox[0] - crop_box[0],
                        bbox[1] - crop_box[1],
                        bbox[2] - crop_box[0],
                        bbox[3] - crop_box[1],
                    ]
                    out_path.parent.mkdir(parents=True, exist_ok=True)
                    img.crop(face_bbox).save(out_path)
            except Exception:
                local_fail += 1
        return local_fail

    with ThreadPoolExecutor(max_workers=num_workers) as executor:
        futures = {executor.submit(process_subdir, subdir): subdir for subdir in subdirs}
        for future in tqdm(as_completed(futures), total=len(futures), desc="Cropping shards"):
            local_fail = future.result()
            with lock:
                fail_count += local_fail

    if fail_count:
        print(f"[warn] crop failed samples: {fail_count}")


def _parse_query_instance_id(query_rel_path: str) -> str:
    # cropped_grounding_cp_images/re_x/000010_000434.jpg -> 000434
    stem = Path(query_rel_path).stem
    if "_" not in stem:
        raise ValueError(f"Invalid query filename (expect *_<instance>): {query_rel_path}")
    return stem.rsplit("_", 1)[1]


def _candidate_json_rel_path(candidate_rel_path: str) -> str:
    # train_cp/re_x/000010.jpg -> train_cp/re_x/000010.json
    return str(Path(candidate_rel_path).with_suffix(".json")).replace("\\", "/")


def _load_split(split_json: Path) -> Dict[str, List[str]]:
    data = json.loads(split_json.read_text(encoding="utf-8"))
    for key in ("train", "test"):
        if key not in data or not isinstance(data[key], list):
            raise ValueError(f"{split_json} must contain {key!r} list")
    return data


def _build_annotations_for_split(
    split_name: str,
    split_paths: Sequence[str],
    source_dir: Path,
) -> Tuple[List[dict], List[dict]]:
    """Build annotations from split JSON per user-specified logic.

    - candidates: all `train_cp/...` images in split
    - query: all `cropped_grounding_cp_images/...` images in split
    - candidate instance mapping: parse corresponding train_cp/*.json `name` list
    - query pos_ids: mapping_dict[query_instance_id]
    """
    candidate_paths = sorted({p.replace("\\", "/") for p in split_paths if p.startswith("train_cp/")})
    query_paths = sorted(
        {p.replace("\\", "/") for p in split_paths if p.startswith("cropped_grounding_cp_images/")}
    )
    if not candidate_paths or not query_paths:
        raise ValueError(
            f"[{split_name}] split must contain both train_cp and cropped_grounding_cp_images paths"
        )

    candidate_rows: List[dict] = []
    inst_to_candidate_ids: Dict[str, List[str]] = {}

    for idx, rel_path in tqdm(enumerate(candidate_paths), total=len(candidate_paths), desc="Building candidate rows"):
        abs_path = source_dir / rel_path
        if not abs_path.is_file():
            raise FileNotFoundError(f"[{split_name}] missing candidate image: {abs_path}")

        anno_rel = _candidate_json_rel_path(rel_path)
        anno_abs = source_dir / anno_rel
        if not anno_abs.is_file():
            raise FileNotFoundError(f"[{split_name}] missing candidate json: {anno_abs}")

        anno = json.loads(anno_abs.read_text(encoding="utf-8"))
        instance_ids = [str(x) for x in anno.get("name", [])]
        if not instance_ids:
            continue

        candidate_rows.append(
            {
                "id": rel_path,
                # multi-person image: keep all ids in one field for audit
                "instance_id": "|".join(sorted(set(instance_ids))),
                "image_path": rel_path,
                "instruction": CANDIDATE_INSTRUCTION,
                "text": CANDIDATE_TEXT,
            }
        )
        for inst_id in set(instance_ids):
            inst_to_candidate_ids.setdefault(inst_id, []).append(rel_path)

    query_rows: List[dict] = []
    missing_pos = 0
    for rel_path in tqdm(query_paths, total=len(query_paths), desc="Building query rows"):
        abs_path = source_dir / rel_path
        if not abs_path.is_file():
            raise FileNotFoundError(f"[{split_name}] missing query image: {abs_path}")

        inst_id = _parse_query_instance_id(rel_path)
        pos_ids = inst_to_candidate_ids.get(inst_id, [])
        if not pos_ids:
            missing_pos += 1
            continue

        query_rows.append(
            {
                "id": rel_path,
                "instance_id": inst_id,
                "image_path": rel_path,
                "instruction": QUERY_INSTRUCTION,
                "text": QUERY_TEXT,
                "pos_ids": sorted(set(pos_ids)),
            }
        )

    if missing_pos:
        print(f"[{split_name}] warn: {missing_pos} query images have no matched candidate")
    if not query_rows or not candidate_rows:
        raise ValueError(f"[{split_name}] empty query/candidate after building")
    return query_rows, candidate_rows


def _process_one_split(
    split_name: str,
    split_paths: Sequence[str],
    source_dir: Path,
    output_root: Path,
    overwrite: bool,
    media_rows_per_shard: int,
    row_group_size: int,
    num_workers: int,
) -> None:
    out_dir = resolve_split_output_dir(output_root, split_name, "MultiID")
    if overwrite and out_dir.exists():
        shutil.rmtree(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    query_rows, candidate_rows = _build_annotations_for_split(split_name, split_paths, source_dir)
    stats = pack_dataset_with_media(
        query_annotations=query_rows,
        candidate_annotations=candidate_rows,
        image_dir=str(source_dir),
        output_dir=str(out_dir),
        media_rows_per_shard=media_rows_per_shard,
        row_group_size=row_group_size,
        num_workers=num_workers,
        dataset_name="MultiID",
        data_split=split_name,
        write_subset_readme=True,
        show_progress=True,
    )
    print(
        f"[{split_name}] done: media={stats['num_media']}, "
        f"query={stats['num_query']}, candidate={stats['num_candidate']}, "
        f"shards={stats['num_shards']} -> {out_dir}"
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--source-dir",
        type=Path,
        default=ROOT_DIR / "source" / "MultiID-2M",
        help="Root containing train_cp/ and cropped_grounding_cp_images/.",
    )
    parser.add_argument(
        "--split-json",
        type=Path,
        default=SCRIPT_DIR / "train_test_split.json",
        help="JSON with split image paths (train_cp + cropped_grounding_cp_images).",
    )
    parser.add_argument(
        "--skip-crop",
        action="store_true",
        help="Skip face cropping; require existing cropped images + anno file.",
    )
    parser.add_argument(
        "--force-crop",
        action="store_true",
        help="Re-crop even if cropped jpg already exists.",
    )
    parser.add_argument("--crop-workers", type=int, default=10)
    parser.add_argument("--output-root", type=Path, default=ROOT_DIR)
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--media-rows-per-shard", type=int, default=5000)
    parser.add_argument("--row-group-size", type=int, default=100)
    parser.add_argument("--num-workers", type=int, default=1)
    parser.add_argument("--splits", nargs="+", default=["train", "test"], choices=["train", "test"])
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    source_dir = args.source_dir
    if not source_dir.exists():
        raise FileNotFoundError(f"source dir not found: {source_dir}")

    if not args.skip_crop:
        print(f"==> Crop faces from {source_dir / 'train_cp'}")
        crop_faces(source_dir, num_workers=args.crop_workers, force=args.force_crop)

    split_data = _load_split(args.split_json)
    for split_name in args.splits:
        _process_one_split(
            split_name=split_name,
            split_paths=split_data[split_name],
            source_dir=source_dir,
            output_root=args.output_root,
            overwrite=args.overwrite,
            media_rows_per_shard=args.media_rows_per_shard,
            row_group_size=args.row_group_size,
            num_workers=args.num_workers,
        )


if __name__ == "__main__":
    main()