| |
| from __future__ import annotations |
|
|
| import argparse |
| import glob |
| import json |
| import os |
| from pathlib import Path |
| from collections import Counter, defaultdict |
| import tarfile |
| from typing import BinaryIO |
| import re |
|
|
|
|
| class MultiFileReader: |
| def __init__(self, paths: list[Path]): |
| self.paths = paths |
| self.index = 0 |
| self.current: BinaryIO | None = None |
| self._open_next() |
|
|
| def _open_next(self) -> None: |
| if self.current is not None: |
| self.current.close() |
| if self.index >= len(self.paths): |
| self.current = None |
| return |
| self.current = self.paths[self.index].open("rb") |
| self.index += 1 |
|
|
| def read(self, size: int = -1) -> bytes: |
| if self.current is None: |
| return b"" |
| chunks: list[bytes] = [] |
| remaining = size |
| while self.current is not None: |
| data = self.current.read(remaining if remaining >= 0 else -1) |
| if data: |
| chunks.append(data) |
| if remaining >= 0: |
| remaining -= len(data) |
| if remaining <= 0: |
| break |
| else: |
| self._open_next() |
| if remaining == 0: |
| break |
| return b"".join(chunks) |
|
|
| def close(self) -> None: |
| if self.current is not None: |
| self.current.close() |
| self.current = None |
|
|
|
|
| def load_split_maps(split_dir: Path) -> dict[str, str]: |
| split_map: dict[str, str] = {} |
| standard = split_dir / "standard.json" |
| if not standard.exists(): |
| return split_map |
| data = json.loads(standard.read_text()) |
| for split_name, ids in data.items(): |
| for episode_id in ids: |
| split_map[str(episode_id)] = split_name |
| return split_map |
|
|
|
|
| def is_gmail_payload(payload: dict) -> bool: |
| goal = str(payload.get("goal_info", "")).lower() |
| activity = str(payload.get("current_activity", "")).lower() |
| |
| |
| |
| gmail_package = re.search(r"(^|[^a-z0-9_.])com\.google\.android\.gm([^a-z0-9_.]|$)", activity) |
| gmail_word = re.search(r"\bgmail\b", " ".join([goal, activity])) is not None |
| return bool(gmail_package or gmail_word) |
|
|
|
|
| def member_domain(name: str) -> str: |
| parts = name.split("/") |
| if len(parts) >= 2 and parts[0] == "processed": |
| return parts[1] |
| return "unknown" |
|
|
|
|
| def scan(args: argparse.Namespace) -> None: |
| part_re = re.compile(r"a\.tar\.part-\d{3}$") |
| parts = [Path(p) for p in sorted(glob.glob(args.parts_glob)) if part_re.search(Path(p).name)] |
| if not parts: |
| raise SystemExit(f"No tar parts matched: {args.parts_glob}") |
| out = Path(args.out) |
| out.parent.mkdir(parents=True, exist_ok=True) |
| stats_path = Path(args.stats_out) if args.stats_out else out.with_suffix(".stats.json") |
| split_map = load_split_maps(Path(args.split_dir)) |
|
|
| counts = Counter() |
| gmail_episodes: dict[str, dict] = {} |
| goals = Counter() |
| activities = Counter() |
| domains = Counter() |
| split_counts = Counter() |
|
|
| reader = MultiFileReader(parts) |
| try: |
| with tarfile.open(fileobj=reader, mode="r|") as tf, out.open("w") as fout: |
| for member in tf: |
| if not member.isfile() or not member.name.endswith("_payload.txt"): |
| continue |
| counts["payload_total"] += 1 |
| domain = member_domain(member.name) |
| counts[f"payload_domain:{domain}"] += 1 |
| if args.domain and domain != args.domain: |
| continue |
| f = tf.extractfile(member) |
| if f is None: |
| counts["payload_no_file"] += 1 |
| continue |
| try: |
| payload = json.loads(f.read().decode("utf-8")) |
| except Exception: |
| counts["payload_json_error"] += 1 |
| continue |
| if not is_gmail_payload(payload): |
| continue |
| episode_id = str(payload.get("episode_id", "")) |
| step_id = int(payload.get("step_id", -1)) |
| split = split_map.get(episode_id, "unknown") |
| record = { |
| "tar_member": member.name, |
| "domain": domain, |
| "episode_id": episode_id, |
| "step_id": step_id, |
| "split": split, |
| "goal_info": payload.get("goal_info", ""), |
| "current_activity": payload.get("current_activity", ""), |
| "action_text": payload.get("action_text", ""), |
| "ex_action_type": payload.get("ex_action_type"), |
| "touch_x": payload.get("touch_x"), |
| "touch_y": payload.get("touch_y"), |
| "lift_x": payload.get("lift_x"), |
| "lift_y": payload.get("lift_y"), |
| "type_text": payload.get("type_text", ""), |
| "image_height": payload.get("image_height"), |
| "image_width": payload.get("image_width"), |
| } |
| fout.write(json.dumps(record, ensure_ascii=False) + "\n") |
| counts["gmail_payload_total"] += 1 |
| domains[domain] += 1 |
| split_counts[split] += 1 |
| goals[str(payload.get("goal_info", ""))] += 1 |
| activities[str(payload.get("current_activity", ""))] += 1 |
| ep = gmail_episodes.setdefault( |
| episode_id, |
| { |
| "episode_id": episode_id, |
| "domain": domain, |
| "split": split, |
| "goal_info": payload.get("goal_info", ""), |
| "steps": 0, |
| "min_step": step_id, |
| "max_step": step_id, |
| }, |
| ) |
| ep["steps"] += 1 |
| ep["min_step"] = min(ep["min_step"], step_id) |
| ep["max_step"] = max(ep["max_step"], step_id) |
| if args.max_matches and counts["gmail_payload_total"] >= args.max_matches: |
| break |
| finally: |
| reader.close() |
|
|
| episodes_path = out.with_name(out.stem + "_episodes.jsonl") |
| with episodes_path.open("w") as f: |
| for ep in sorted(gmail_episodes.values(), key=lambda x: (x["split"], x["episode_id"])): |
| f.write(json.dumps(ep, ensure_ascii=False) + "\n") |
| stats = { |
| "parts": [str(p) for p in parts], |
| "part_count": len(parts), |
| "counts": dict(counts), |
| "gmail_episode_count": len(gmail_episodes), |
| "domains": dict(domains), |
| "split_counts": dict(split_counts), |
| "top_goals": goals.most_common(50), |
| "top_activities": activities.most_common(50), |
| "episodes_manifest": str(episodes_path), |
| } |
| stats_path.write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n") |
| print(json.dumps(stats, ensure_ascii=False, indent=2)) |
|
|
|
|
| def main() -> None: |
| p = argparse.ArgumentParser() |
| p.add_argument("--parts-glob", default="/data/gmail_aitw/raw/aitw_parts/a.tar.part-*") |
| p.add_argument("--split-dir", default="/data/gmail_aitw/manifests/official") |
| p.add_argument("--domain", default="google_apps") |
| p.add_argument("--out", default="/data/gmail_aitw/manifests/gmail_payloads.jsonl") |
| p.add_argument("--stats-out", default="") |
| p.add_argument("--max-matches", type=int, default=0) |
| scan(p.parse_args()) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|