Download videoagent/code/prepare_gpt_trajectory_pilot.py from ppppppz/video_agent_trace: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/ppppppz/video_agent_trace/resolve/main/videoagent/code/prepare_gpt_trajectory_pilot.py
- Command line
-
hf download hf://datasets/ppppppz/video_agent_trace/videoagent/code/prepare_gpt_trajectory_pilot.py
-
curl -L -o prepare_gpt_trajectory_pilot.py https://huggingface.co/datasets/ppppppz/video_agent_trace/resolve/main/videoagent/code/prepare_gpt_trajectory_pilot.py
10.7 kB
| #!/usr/bin/env python3 | |
| """Prepare a non-destructive H3 pilot from GPT-verified trajectory texts.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import shutil | |
| from collections import Counter | |
| from datetime import UTC, datetime | |
| from pathlib import Path | |
| from typing import Any | |
| REPO_ROOT = Path(__file__).resolve().parents[2] | |
| DEFAULT_TRAJECTORIES = REPO_ROOT / "runs" / "trajectory_text" / "friday_h3_rewrite_v5_final" | |
| DEFAULT_SOURCE_CAMPAIGN = REPO_ROOT / "runs" / "injection" / "pilot_full_200_v1" | |
| DEFAULT_OUTPUT = REPO_ROOT / "runs" / "injection" / "pilot_gpt_v5_5seed_v1" | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as stream: | |
| for chunk in iter(lambda: stream.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def sha256_text(value: str) -> str: | |
| return hashlib.sha256(value.encode("utf-8")).hexdigest() | |
| def canonical_digest(value: Any) -> str: | |
| payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) | |
| return sha256_text(payload) | |
| def load_json(path: Path) -> Any: | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def model_fingerprint(model_root: Path) -> tuple[str, dict[str, str]]: | |
| inputs = { | |
| "ref2va_model_index_sha256": sha256_file(model_root / "Ref2VA" / "model_index.json"), | |
| "ref2va_transformer_index_sha256": sha256_file( | |
| model_root / "Ref2VA" / "transformer" / "model.safetensors.index.json" | |
| ), | |
| "ref2va_text_encoder_index_sha256": sha256_file( | |
| model_root / "Ref2VA" / "text_encoder" / "model.safetensors.index.json" | |
| ), | |
| } | |
| return canonical_digest(inputs), inputs | |
| def prepare( | |
| *, | |
| trajectory_root: Path, | |
| source_campaign: Path, | |
| model_root: Path, | |
| output: Path, | |
| seeds_per_case: int, | |
| seed_start: int | None = None, | |
| ) -> Path: | |
| if seeds_per_case < 1: | |
| raise ValueError("seeds_per_case must be positive") | |
| if seed_start is not None and seed_start < 1: | |
| raise ValueError("seed_start must be positive when provided") | |
| if output.exists(): | |
| raise FileExistsError(f"refusing to overwrite campaign: {output}") | |
| text_manifest = load_json(trajectory_root / "manifest.json") | |
| corpus_verifier = load_json(trajectory_root / "corpus_verifier.json") | |
| trajectories = load_json(trajectory_root / "all_trajectories.json") | |
| expected_count = int(text_manifest["case_count"]) | |
| if expected_count < 1 or corpus_verifier["verdict"] != "PASS": | |
| raise ValueError("trajectory text bundle is not a verified final release") | |
| if len(trajectories) != expected_count: | |
| raise ValueError( | |
| f"trajectory count mismatch: manifest={expected_count}, actual={len(trajectories)}" | |
| ) | |
| fingerprint, fingerprint_inputs = model_fingerprint(model_root) | |
| output.mkdir(parents=True) | |
| rows: list[dict[str, Any]] = [] | |
| for case_index, trajectory in enumerate(trajectories, start=1): | |
| case_id = trajectory["case_id"] | |
| old_spec = load_json(source_campaign / "cases" / case_id / "spec.json") | |
| old_source = Path(old_spec["source_path"]) | |
| case_dir = output / "cases" / case_id | |
| source_dir = case_dir / "private_source" | |
| source_dir.mkdir(parents=True) | |
| copied_source = source_dir / old_source.name | |
| shutil.copy2(old_source, copied_source) | |
| prompt = trajectory["h3_execution_prompt"].strip() | |
| benchmark_edit = trajectory["benchmark_edit_instruction"].strip() | |
| prompt_path = case_dir / "prompt.txt" | |
| prompt_path.write_text(prompt + "\n", encoding="utf-8") | |
| spec = { | |
| "schema_version": "trace-repair.h3-gpt-trajectory-pilot-spec.v1", | |
| "case_id": case_id, | |
| "parent_campaign": str(source_campaign.resolve()), | |
| "trajectory_text_release": str(trajectory_root.resolve()), | |
| "family": trajectory["family"], | |
| "source": old_spec["source"], | |
| "source_path": str(copied_source.resolve()), | |
| "source_sha256": sha256_file(copied_source), | |
| "source_observation": trajectory["source_observation"], | |
| "structured_trajectory": trajectory["structured_trajectory"], | |
| "counterfactual_delta": trajectory["counterfactual_delta"], | |
| "benchmark_edit_instruction": benchmark_edit, | |
| "h3_execution_prompt": prompt, | |
| "prompt_sha256": sha256_text(prompt), | |
| "text_verifier": trajectory["text_verifier"], | |
| "corpus_verifier": "PASS", | |
| "candidate_count": seeds_per_case, | |
| } | |
| (case_dir / "spec.json").write_text( | |
| json.dumps(spec, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| for candidate_index in range(1, seeds_per_case + 1): | |
| # The historical per-case layout is retained by default. Large campaigns | |
| # opt into one contiguous range to prevent collisions once a case has | |
| # 100 or more candidates. | |
| seed = ( | |
| seed_start + len(rows) | |
| if seed_start is not None | |
| else 200_000 + case_index * 100 + candidate_index | |
| ) | |
| candidate_dir = case_dir / "candidates" / f"seed_{seed}" | |
| candidate_dir.mkdir(parents=True) | |
| request = { | |
| "model": "MiniMaxAI/MiniMax-H3", | |
| "prompt": prompt, | |
| "seconds": 5, | |
| "task": "ref2va", | |
| "conditions": [ | |
| { | |
| "type": "video_audio", | |
| "uri": copied_source.resolve().as_uri(), | |
| "role": "reference", | |
| "start_time_seconds": 0.0, | |
| } | |
| ], | |
| "target": { | |
| "short_edge": 768, | |
| "aspect_ratio": ( | |
| "9:16" if old_spec["source"] == "fashion-glasses-ad.mp4" else "16:9" | |
| ), | |
| "duration_seconds": 5.0, | |
| }, | |
| "num_outputs_per_prompt": 1, | |
| "num_inference_steps": 50, | |
| "flow_shift": 12.0, | |
| "audio_flow_shift": 3.0, | |
| "seed": seed, | |
| } | |
| request_path = candidate_dir / "request.json" | |
| request_path.write_text( | |
| json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| provenance = { | |
| "schema_version": "trace-repair.h3-gpt-trajectory-pilot-provenance.v1", | |
| "campaign_id": output.name, | |
| "case_id": case_id, | |
| "candidate_index": candidate_index, | |
| "seed": seed, | |
| "status": "prepared", | |
| "pilot_only": True, | |
| "benchmark_eligible": False, | |
| "created_at": datetime.now(UTC).isoformat(), | |
| "backend": "MiniMax-H3-Base-Ref2VA-local", | |
| "model_root": str(model_root.resolve()), | |
| "model_fingerprint": fingerprint, | |
| "model_fingerprint_inputs": fingerprint_inputs, | |
| "trajectory_text_release": str(trajectory_root.resolve()), | |
| "target_error_family": trajectory["family"], | |
| "target_error": benchmark_edit, | |
| "structured_trajectory": trajectory["structured_trajectory"], | |
| "counterfactual_delta": trajectory["counterfactual_delta"], | |
| "protected_facts": trajectory["structured_trajectory"]["protected_facts"], | |
| "text_verifier_verdict": trajectory["text_verifier"]["verdict"], | |
| "corpus_verifier_verdict": "PASS", | |
| "source_asset_sha256": spec["source_sha256"], | |
| "prompt_sha256": spec["prompt_sha256"], | |
| "sampling_config_sha256": canonical_digest(request), | |
| "request_path": str(request_path.resolve()), | |
| } | |
| (candidate_dir / "provenance.json").write_text( | |
| json.dumps(provenance, ensure_ascii=False, indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| rows.append( | |
| { | |
| "case_id": case_id, | |
| "family": trajectory["family"], | |
| "seed": seed, | |
| "candidate_dir": str(candidate_dir.resolve()), | |
| "request_path": str(request_path.resolve()), | |
| } | |
| ) | |
| family_counts = Counter(row["family"] for row in rows) | |
| manifest = { | |
| "schema_version": "trace-repair.h3-gpt-trajectory-pilot-manifest.v1", | |
| "campaign_id": output.name, | |
| "created_at": datetime.now(UTC).isoformat(), | |
| "pilot_only": True, | |
| "benchmark_eligible": False, | |
| "non_destructive": True, | |
| "source_campaign": str(source_campaign.resolve()), | |
| "trajectory_text_release": str(trajectory_root.resolve()), | |
| "trajectory_text_corpus_verifier": "PASS", | |
| "source_project_count": len({trajectory["source"] for trajectory in trajectories}), | |
| "injection_spec_count": len(trajectories), | |
| "candidates_per_spec": seeds_per_case, | |
| "candidate_count": len(rows), | |
| "seed_start": seed_start, | |
| "target_counts": dict(sorted(family_counts.items())), | |
| "candidates": rows, | |
| } | |
| manifest_path = output / "manifest.json" | |
| manifest_path.write_text( | |
| json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| return manifest_path | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--trajectory-root", type=Path, default=DEFAULT_TRAJECTORIES) | |
| parser.add_argument("--source-campaign", type=Path, default=DEFAULT_SOURCE_CAMPAIGN) | |
| parser.add_argument("--model-root", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) | |
| parser.add_argument("--seeds-per-case", type=int, default=5) | |
| parser.add_argument( | |
| "--seed-start", | |
| type=int, | |
| help="Use a contiguous global seed range starting here; required for more than 99 seeds per case.", | |
| ) | |
| return parser.parse_args() | |
| def main() -> int: | |
| args = parse_args() | |
| manifest = prepare( | |
| trajectory_root=args.trajectory_root, | |
| source_campaign=args.source_campaign, | |
| model_root=args.model_root, | |
| output=args.output, | |
| seeds_per_case=args.seeds_per_case, | |
| seed_start=args.seed_start, | |
| ) | |
| print(manifest.resolve()) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |