File size: 16,550 Bytes
498228a
e01c86c
498228a
 
 
 
 
 
 
 
 
 
 
 
e01c86c
 
498228a
 
 
 
 
 
e01c86c
498228a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e01c86c
498228a
 
 
e01c86c
498228a
 
e01c86c
498228a
 
 
 
 
 
e01c86c
498228a
 
e01c86c
498228a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e01c86c
498228a
 
 
e01c86c
498228a
 
 
 
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""
Construct the candidate paired-view pool for VisAlloc training.

Usage:
    python scripts/prepare_data.py --data-dir ./cache/visalloc

This script:
1. Downloads the Vision-OPD-6K dataset from HuggingFace
   (train.jsonl, student images, teacher crops)
2. Generates the negative teacher views: a red box drawn at a displaced
   position (IoU < 0.1 vs the ground-truth box), using the exact recovered
   positive crop window size, within-crop box, Pillow stroke, and 2x resize.
   The official positive is reconstructed pixel-exactly before generation
3. Converts train.jsonl to train.parquet and attaches the `neg_bbox_images`
   column for all source candidates; this script does not run paired-teacher
   filtering or select the final 5,795 training samples

Outputs (under --data-dir):
    images/           official student images (red-box full image)
    teacher_images/   official positive teacher crops
    teacher_neg/      generated negative teacher crops
    results.json      per-sample generation metadata (boxes, IoU)
    train.parquet     candidate pool with local image paths, before sample filtering
"""

from __future__ import annotations

import argparse
import hashlib
import itertools
import json
import os
import random
import subprocess
import sys
import time
from multiprocessing import Pool
from typing import Any

import cv2
import datasets
import numpy as np
from PIL import Image, ImageDraw

FRAME_WIDTH = 5     # verified against every official teacher image
NEG_IOU_LIMIT = 0.1
UPSTREAM_REVISION = "eb5c1c2e7b9a7b6a619efe4161c7369c71bf8af4"


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Prepare the VisAlloc candidate paired-view pool.")
    parser.add_argument("--data-dir", default="./cache/visalloc", help="Output directory")
    parser.add_argument("--hf-repo", default="yuanqianhao/Vision-OPD-6K", help="HuggingFace dataset repo")
    parser.add_argument("--revision", default=UPSTREAM_REVISION, help="Pinned upstream dataset revision")
    parser.add_argument("--skip-download", action="store_true", help="Skip downloading, only preprocess")
    parser.add_argument("--nproc", type=int, default=16, help="Worker processes for negative-view generation")
    return parser.parse_args()


# ---------------------------------------------------------------- download --
def download_dataset(repo_id: str, data_dir: str, revision: str = UPSTREAM_REVISION) -> None:
    print(f"Downloading dataset from {repo_id} ...")
    from huggingface_hub import snapshot_download
    snapshot_download(repo_id, repo_type="dataset", revision=revision, local_dir=data_dir)

    # Extract every shipped image bundle (multi-part tars are cat-joined).
    for sub, prefix in (("images", "images.tar.gz"),
                        ("teacher_images", "teacher_images.tar.gz"),
                        ("original_images", "original_images.tar.gz")):
        d = os.path.join(data_dir, sub)
        if not os.path.isdir(d):
            print(f"Warning: {d} not present in the download", file=sys.stderr)
            continue
        tars = sorted(f for f in os.listdir(d) if f.startswith(prefix))
        if not tars:
            continue
        print(f"Extracting {sub} ...")
        cat_process = subprocess.Popen(["cat", *tars], cwd=d, stdout=subprocess.PIPE)
        try:
            subprocess.run(["tar", "-xf", "-", "-C", "."], cwd=d, stdin=cat_process.stdout, check=True)
        finally:
            if cat_process.stdout is not None:
                cat_process.stdout.close()
            cat_returncode = cat_process.wait()
        if cat_returncode != 0:
            raise subprocess.CalledProcessError(cat_process.returncode, cat_process.args)
        for f in tars:
            os.remove(os.path.join(d, f))

    print("Image extraction complete.")


# ------------------------------------------------------- negative  views --
def iou(a, b):
    ix0, iy0 = max(a[0], b[0]), max(a[1], b[1])
    ix1, iy1 = min(a[2], b[2]), min(a[3], b[3])
    inter = max(0, ix1 - ix0) * max(0, iy1 - iy0)
    ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    return inter / ua if ua else 0.0


def project_bands(values):
    indices = np.flatnonzero(values >= values.max() * 0.65)
    return [group for group in np.split(indices, np.flatnonzero(np.diff(indices) > 1) + 1) if len(group)]


def recover_geometry(original, official, gt):
    w, h = official.size
    if w % 2 or h % 2:
        raise ValueError("Official teacher dimensions must match the verified 2x pipeline")
    cw, ch = w // 2, h // 2
    pixels = np.array(official)
    red = (pixels[:, :, 0] > 245) & (pixels[:, :, 1] < 25) & (pixels[:, :, 2] < 25)
    xb, yb = project_bands(red.sum(0)), project_bands(red.sum(1))
    if len(xb) < 2 or len(yb) < 2:
        return recover_difficult(original, official, gt)
    box = [int(xb[0][0]) // 2, int(yb[0][0]) // 2, int(xb[-1][-1]) // 2, int(yb[-1][-1]) // 2]
    if xb[-1][-1] == w - 1:
        box[2] = cw
    if yb[-1][-1] == h - 1:
        box[3] = ch
    x = max(0, min(original.width - cw, int((gt[0] + gt[2] - cw) / 2)))
    y = max(0, min(original.height - ch, int((gt[1] + gt[3] - ch) / 2)))
    small = np.array(official.resize((cw, ch), Image.Resampling.BOX))
    strong = (
        (small[:, :, 0].astype(int) > small[:, :, 1] * 1.5)
        & (small[:, :, 0].astype(int) > small[:, :, 2] * 1.5)
        & (small[:, :, 0] > 150)
    )
    valid = 1 - cv2.dilate(strong.astype("uint8"), np.ones((7, 7), np.uint8))
    sx, sy = max(0, x - 4), max(0, y - 4)
    ex, ey = min(original.width, x + cw + 5), min(original.height, y + ch + 5)
    if valid.sum() == 0:
        return recover_difficult(original, official, gt)
    scores = cv2.matchTemplate(
        np.array(original.crop((sx, sy, ex, ey))).astype("float32"),
        small.astype("float32"),
        cv2.TM_SQDIFF,
        mask=np.repeat(valid[:, :, None], 3, axis=2),
    )
    _, _, loc, _ = cv2.minMaxLoc(scores)
    ox, oy = sx + loc[0], sy + loc[1]
    source_crop = original.crop((ox, oy, ox + cw, oy + ch))

    def compare(candidate):
        drawn = source_crop.copy()
        ImageDraw.Draw(drawn).rectangle(candidate, outline=(255, 0, 0), width=FRAME_WIDTH)
        return np.array(drawn.resize((w, h), Image.Resampling.LANCZOS))

    rebuilt = compare(box)
    if not np.array_equal(rebuilt, pixels):
        # Natural red content can move a threshold edge by one pixel.
        choices = [[v, v - 1, v + 1] for v in box]
        for candidate in itertools.product(*choices):
            if np.array_equal(compare(candidate), pixels):
                box = list(candidate)
                break
        else:
            return recover_difficult(original, official, gt)
    return {
        "positive_crop_window": [ox, oy, ox + cw, oy + ch],
        "frame_box_in_crop": box,
        "source_crop_size": [cw, ch],
        "output_size": [w, h],
        "resize_scale": [2, 2],
        "frame_width": FRAME_WIDTH,
        "reconstruction_exact": True,
    }


def recover_difficult(original, official, gt):
    w, h = official.size
    cw, ch = w // 2, h // 2
    pixels = np.array(official)
    x = max(0, min(original.width - cw, int((gt[0] + gt[2] - cw) / 2)))
    y = max(0, min(original.height - ch, int((gt[1] + gt[3] - ch) / 2)))
    offsets = [0, 1, -1, 2, -2]
    for ox, oy in itertools.product(
        [x + v for v in offsets if 0 <= x + v <= original.width - cw],
        [y + v for v in offsets if 0 <= y + v <= original.height - ch],
    ):
        crop = original.crop((ox, oy, ox + cw, oy + ch))
        bw, bh = gt[2] - gt[0], gt[3] - gt[1]
        estimate = [
            int(gt[0] - bw * 0.05) - ox,
            int(gt[1] - bh * 0.05) - oy,
            int(gt[2] + bw * 0.05) - ox,
            int(gt[3] + bh * 0.05) - oy,
        ]
        options = [[v + d for d in [0, 1, -1, 2, -2]] for v in estimate]
        for box in itertools.product(*options):
            if box[2] < box[0] or box[3] < box[1]:
                continue
            drawn = crop.copy()
            ImageDraw.Draw(drawn).rectangle(box, outline="red", width=FRAME_WIDTH)
            if np.array_equal(np.array(drawn.resize((w, h), Image.Resampling.LANCZOS)), pixels):
                return {
                    "positive_crop_window": [ox, oy, ox + cw, oy + ch],
                    "frame_box_in_crop": list(box),
                    "source_crop_size": [cw, ch],
                    "output_size": [w, h],
                    "resize_scale": [2, 2],
                    "frame_width": FRAME_WIDTH,
                    "reconstruction_exact": True,
                }
    raise ValueError("No exact transform found for difficult sample")


_ROWS = None
_DATA_DIR = None


def _init_worker(rows, data_dir):
    """Pool initializer: safe under both fork and spawn start methods."""
    global _ROWS, _DATA_DIR
    _ROWS = rows
    _DATA_DIR = data_dir


def render_teacher(original, window, geometry):
    crop = original.crop(window)
    if list(crop.size) != geometry["source_crop_size"]:
        raise ValueError("Crop size differs from the official positive template")
    ImageDraw.Draw(crop).rectangle(geometry["frame_box_in_crop"], outline=(255, 0, 0), width=FRAME_WIDTH)
    return crop.resize(tuple(geometry["output_size"]), Image.Resampling.LANCZOS)


def sample_negative_window(gt, positive_window, image_size, rng):
    """Translate the whole official crop, preserving every within-crop coordinate."""
    W, H = image_size
    px, py, x2, y2 = positive_window
    cw, ch = x2 - px, y2 - py
    candidates = ((rng.randint(0, W - cw), rng.randint(0, H - ch)) for _ in range(2000))
    corners = itertools.product((0, W - cw), (0, H - ch))
    for x, y in itertools.chain(candidates, corners):
        negative = [gt[0] + x - px, gt[1] + y - py, gt[2] + x - px, gt[3] + y - py]
        if iou(negative, gt) < NEG_IOU_LIMIT:
            return [x, y, x + cw, y + ch], negative
    raise ValueError("No geometry-preserving negative window satisfies IoU < 0.1")


def _worker(i):
    h = _ROWS[i]
    try:
        data_dir = _DATA_DIR
        src_tpos = os.path.join(data_dir, h["teacher_images"][0])
        with Image.open(os.path.join(data_dir, h["original_images"][0])) as image:
            original = image.convert("RGB")
        with Image.open(src_tpos) as image:
            official = image.convert("RGB")
        gt = h["bbox"]
        geometry = recover_geometry(original, official, gt)
        positive_window = geometry["positive_crop_window"]
        reconstructed = render_teacher(original, positive_window, geometry)
        if not np.array_equal(np.asarray(reconstructed), np.asarray(official)):
            raise ValueError("Official positive reconstruction is not pixel-exact")
        negative_window, negative_bbox = sample_negative_window(
            gt, positive_window, original.size, random.Random(9000 + i)
        )
        negative = render_teacher(original, negative_window, geometry)
        path = os.path.join(data_dir, "teacher_neg", f"{i:06d}.png")
        negative.save(path, compress_level=1)
        frame = Image.new("L", tuple(geometry["source_crop_size"]), 0)
        ImageDraw.Draw(frame).rectangle(geometry["frame_box_in_crop"], outline=255, width=FRAME_WIDTH)
        frame = frame.resize(official.size, Image.Resampling.LANCZOS)
        with open(src_tpos, "rb") as stream:
            positive_sha256 = hashlib.sha256(stream.read()).hexdigest()
        with open(path, "rb") as stream:
            negative_sha256 = hashlib.sha256(stream.read()).hexdigest()
        return {
            "idx": i,
            "ok": True,
            "gt_bbox": list(gt),
            "neg_bbox": negative_bbox,
            "iou": iou(negative_bbox, gt),
            "crop_size": list(official.size),
            "negative_crop_window": negative_window,
            "original_size": list(original.size),
            "target_bbox_in_crop": [
                gt[0] - positive_window[0],
                gt[1] - positive_window[1],
                gt[2] - positive_window[0],
                gt[3] - positive_window[1],
            ],
            "positive_sha256": positive_sha256,
            "negative_sha256": negative_sha256,
            "shared_frame_mask_sha256": hashlib.sha256(frame.tobytes()).hexdigest(),
            "generation_version": "2.0.0",
            "resampling": "PIL.LANCZOS",
            "renderer": "PIL.ImageDraw.rectangle",
            **geometry,
        }
    except Exception as e:
        return {"idx": i, "ok": False, "reason": f"exc:{type(e).__name__}:{str(e)[:180]}"}

def generate_negative_views(data_dir: str, nproc: int) -> list:
    with open(os.path.join(data_dir, "train.jsonl"), encoding="utf-8") as f:
        rows = [json.loads(line) for line in f]
    os.makedirs(os.path.join(data_dir, "teacher_neg"), exist_ok=True)

    t0 = time.time()
    results = []
    with Pool(nproc, initializer=_init_worker, initargs=(rows, data_dir)) as pool:
        for n, r in enumerate(pool.imap_unordered(_worker, range(len(rows)), chunksize=16), 1):
            results.append(r)
            if n % 500 == 0:
                ok = sum(1 for x in results if x.get("ok"))
                print(f"[{n}/{len(rows)}] ok={ok} elapsed={time.time() - t0:.0f}s", flush=True)
    results.sort(key=lambda r: r["idx"])
    with open(os.path.join(data_dir, "results.json"), "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=1)
    ok = sum(1 for r in results if r.get("ok"))
    success_rate = 100 * ok / len(results) if results else 0.0
    print(f"Negative views: {ok}/{len(results)} ({success_rate:.1f}%) "
          f"in {(time.time() - t0) / 60:.1f} min")
    if ok != len(results):
        raise RuntimeError("Negative generation incomplete; inspect results.json before using the dataset")
    return results


# ---------------------------------------------------------------- parquet --
def clean_question(problem: str) -> str:
    text = (problem or "").replace("<image>", "").strip()
    hint = ("Only focus on the objects inside the red bounding box in the image "
            "to answer this question.")
    text = text.replace(f"\n\n{hint}", "").replace(hint, "")
    return text.strip()


def build_record(item: dict[str, Any], data_dir: str, neg_path: str | None) -> dict[str, Any]:
    record = {
        "data_source": "zwz_rl_vqa_bbox_teacher",
        "prompt": [{"role": "user", "content": item["problem"]}],
        "images": [{"path": os.path.join(data_dir, item["images"][0])}],
        "bbox_images": [{"path": os.path.join(data_dir, item["teacher_images"][0])}],
        "ability": "visual_question_answering",
        "reward_model": {"style": "none", "ground_truth": item.get("answer", "")},
        "extra_info": {
            "answer": item.get("answer", ""),
            "question": clean_question(item.get("problem", "")),
            "source_extra_info": item.get("extra_info", {}),
        },
    }
    record["neg_bbox_images"] = [{"path": neg_path}] if neg_path is not None else []
    return record


def convert_to_parquet(data_dir: str, results: list) -> None:
    jsonl_path = os.path.join(data_dir, "train.jsonl")
    if not os.path.exists(jsonl_path):
        print(f"Error: {jsonl_path} not found", file=sys.stderr)
        sys.exit(1)

    by_idx_ok = {r["idx"]: r.get("ok", False) for r in results}
    print("Converting train.jsonl to train.parquet ...")
    records = []
    with open(jsonl_path, encoding="utf-8") as f:
        for i, line in enumerate(f):
            item = json.loads(line)
            neg = os.path.join(data_dir, "teacher_neg", f"{i:06d}.png") if by_idx_ok.get(i) else None
            records.append(build_record(item, data_dir, neg))

    dataset = datasets.Dataset.from_list(records)
    output_path = os.path.join(data_dir, "train.parquet")
    dataset.to_parquet(output_path)
    n_neg = sum(1 for r in records if "neg_bbox_images" in r)
    print(f"Saved {len(records)} records ({n_neg} with negative views) to {output_path}")


def main() -> None:
    args = parse_args()
    data_dir = os.path.abspath(args.data_dir)
    os.makedirs(data_dir, exist_ok=True)

    if not args.skip_download:
        download_dataset(args.hf_repo, data_dir, args.revision)

    results = generate_negative_views(data_dir, args.nproc)
    convert_to_parquet(data_dir, results)
    print(f"\nCandidate pool preparation complete. Apply sample selection before training: {data_dir}/train.parquet")


if __name__ == "__main__":
    main()