File size: 3,241 Bytes
1836fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NVIDIA-OneWay-Noncommercial

"""Prompts, benchmark loading and result files shared by the three stages."""
from __future__ import annotations

import json
import os
import sys

PROMPTS_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "..", "prompts"
)


def load_prompt(name: str) -> str:
    """Read a prompt text file from the top-level ``prompts/`` directory."""
    with open(os.path.join(PROMPTS_DIR, name), "r", encoding="utf-8") as f:
        return f.read()


PRINCIPLES = load_prompt("eval_principles.txt")
DEFAULT_QUESTION = load_prompt("eval_question_default.txt")
JUDGE_SYSTEM_PROMPT = load_prompt("eval_judge_overall_system.txt")
JUDGE_USER_TEMPLATE = load_prompt("eval_judge_overall_user.txt")

# The four prompt conditions of the paper: a 2 x 2 of task instruction
# (absent / present) and safety principles (absent / present).
PROMPT_TYPE_NAMES = ("default", "task", "principles", "task_principles")


def build_question(prompt_type: str, task: str) -> str:
    question = DEFAULT_QUESTION
    if prompt_type == "default":
        return question
    if prompt_type == "task":
        return f"You are instructed to {task}. \n" + question
    if prompt_type == "principles":
        return PRINCIPLES + "\n" + question
    if prompt_type == "task_principles":
        return (
            PRINCIPLES + "\n"
            f"You are instructed to {task}. \n" + question
        )
    raise ValueError(f"Unknown prompt type: {prompt_type}")


def load_eval_items(path: str) -> list[dict]:
    """One item per benchmark entry; ``scenario_index`` is the entry's position."""
    with open(path, "r", encoding="utf-8") as f:
        rows = json.load(f)
    if not isinstance(rows, list):
        print("Scenario JSON must be an array.", file=sys.stderr)
        sys.exit(1)
    items: list[dict] = []
    for i, row in enumerate(rows):
        if not isinstance(row, dict) or not row.get("video_path"):
            continue
        items.append({
            "scenario_index": i,
            "side": row.get("side", ""),
            "video_path": row["video_path"],
            "task": row.get("task", ""),
            "robot": row.get("robot", ""),
        })
    return items


def model_slug(model: str) -> str:
    return model.replace("/", "_").replace(" ", "_")


def result_path(output_dir: str, stage: str, model: str, prompt_type: str,
                scenario_idx: int, side: str) -> str:
    """``<output_dir>/<stage>/<model_slug>/<prompt_type>/idx_NNNN_<side>.json``."""
    d = os.path.join(output_dir, stage, model_slug(model), prompt_type)
    return os.path.join(d, f"idx_{scenario_idx:04d}_{side}.json")


def save_result(path: str, data: dict) -> None:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
        f.write("\n")
    os.replace(tmp, path)


def load_result(path: str) -> dict | None:
    if not os.path.isfile(path):
        return None
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)