File size: 3,886 Bytes
6eb86fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import os
from pathlib import Path

REPO_ID = "Gyubeum/AndroidFlux_RM_Eval"
CONFIGS = ["ui_genie_pairwise", "android_flux_recovery_action_preference"]


def get_parquet(config: str, name: str, local_dir: str | None, token: str | None) -> str:
    if local_dir:
        return str(Path(local_dir) / config / name)
    from huggingface_hub import hf_hub_download
    return hf_hub_download(
        repo_id=REPO_ID, repo_type="dataset",
        filename=f"{config}/{name}", token=token,
    )


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", default="ui_genie_pairwise", choices=CONFIGS)
    ap.add_argument("--subset", default="full", choices=["full", "reduced"])
    ap.add_argument("--n", type=int, default=2)
    ap.add_argument("--local_dir", default=None,
                    help="Read the parquet from here instead of the Hub")
    ap.add_argument("--image_dir", default="/tmp/rm_eval_images",
                    help="Where to write screenshots")
    args = ap.parse_args()
    token = os.environ.get("HF_TOKEN")

    import pyarrow.parquet as pq

    print("=" * 68)
    print(f"1. {args.config}/samples.parquet")
    print("=" * 68)
    table = pq.read_table(get_parquet(args.config, "samples.parquet", args.local_dir, token))
    rows = table.to_pylist()
    if args.subset == "reduced":
        rows = [r for r in rows if r["in_reduced"]]
    print(f"   {len(rows)} rows ({args.subset}), {len(table.schema)} columns")
    print(f"   columns: {', '.join(table.schema.names)}")

    rows = rows[: args.n]
    for r in rows:
        print(f"\n   sample_id : {r['sample_id']}")
        print(f"   goal      : {r['goal'][:90]}")
        print(f"   images    : {r['n_images']}  screen: {r['screen_width']}x{r['screen_height']}")
        print(f"   chosen    : {r['chosen_response'][:80].replace(chr(10), ' ')}")
        print(f"   rejected  : {r['rejected_response'][:80].replace(chr(10), ' ')}")
        if args.config != "ui_genie_pairwise":
            print(f"   outcome   : {r['outcome']}  margin: {r['margin']}  {r['model_name']}")

    print("\n" + "=" * 68)
    print("2. Resolving screenshots from images.parquet")
    print("=" * 68)
    wanted: set[str] = set()
    for r in rows:
        wanted |= set(r["image_ids"])
    images_path = get_parquet(args.config, "images.parquet", args.local_dir, token)
    out_dir = Path(args.image_dir) / args.config
    out_dir.mkdir(parents=True, exist_ok=True)

    resolved: dict[str, Path] = {}
    for batch in pq.ParquetFile(images_path).iter_batches(batch_size=32):
        for row in batch.to_pylist():
            if row["image_id"] not in wanted or row["image_id"] in resolved:
                continue
            suffix = ".png" if row["mime_type"] == "image/png" else ".jpg"
            path = out_dir / f"{row['image_id']}{suffix}"
            if not path.is_file():
                path.write_bytes(row["encoded_bytes"])
            resolved[row["image_id"]] = path
        if len(resolved) == len(wanted):
            break
    print(f"   wrote {len(resolved)}/{len(wanted)} screenshots -> {out_dir}")

    print("\n" + "=" * 68)
    print("3. Rebuilding the reward-model prompt")
    print("=" * 68)
    r = rows[0]
    prefix = json.loads(r["prefix_messages_json"])
    for candidate, label in ((r["chosen_response"], "chosen"), (r["rejected_response"], "rejected")):
        messages = prefix + [{"role": "assistant", "content": candidate}]
        print(f"   {label:8} -> {len(messages)} turns, {len(r['image_ids'])} image(s)")
    print(f"   placeholders={r['user_content'].count('<image>')} "
          f"n_images={r['n_images']} image_ids={len(r['image_ids'])}")
    print(f"   image order: {[str(resolved[i].name) for i in r['image_ids']]}")


if __name__ == "__main__":
    main()