File size: 8,311 Bytes
f91d9a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reusable prompt builders for LSV benchmark tasks."""

from __future__ import annotations

import json
from typing import Any, Literal

ProtocolStyle = Literal["json", "flat_numbered", "substeps", "substeps_with_details"]

MONITORING_DELTA_SCHEMA: dict[str, Any] = {
    "current_step": "step_id string or null",
    "new_notes": [
        {
            "t": "number  # start time of the action in seconds",
            "note": "string  # concise natural-language observation",
        }
    ],
    "errors": [
        {
            "t": "number",
            "error_type": (
                "step_skipped | step_reordered | reagent_wrong | volume_wrong | "
                "technique_error | contamination_risk | timing_error | none"
            ),
            "step_ref": "step_id string or null",
            "description": "string",
        }
    ],
    "suggestion": "string or null  # brief next-action hint for the user",
}


def compact_json(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def response_format_block(skeleton: Any) -> str:
    rendered = skeleton.strip() if isinstance(skeleton, str) else json.dumps(skeleton, ensure_ascii=False, sort_keys=True, indent=2)
    return f"Return strict JSON only.\n\n## Response Format\n{rendered}"


def render_monitoring_delta_prompt(state: dict[str, Any]) -> str:
    instructions = [
        "You are a real-time lab assistant monitoring a scientist's wet-lab procedure from short video windows.",
        "The current protocol state/history is provided below. Watch the current window and update the state.",
        "Report protocol errors only when supported by the visible time window or state.",
        "Ignore irrelevant unknown keys in the state JSON.",
        "Given the protocol being followed, the history of completed steps, and a new video window, update the monitoring state by returning a delta JSON.",
    ]
    return "\n\n".join(
        [
            *instructions,
            f"STATE:\n{compact_json(state)}",
            response_format_block(MONITORING_DELTA_SCHEMA),
            "Return a delta JSON for only the watched lab video window.",
        ]
    )


def _load_protocol(protocol: dict[str, Any] | str) -> dict[str, Any]:
    return json.loads(protocol) if isinstance(protocol, str) and protocol.strip() else (protocol if isinstance(protocol, dict) else {})


def executable_steps(protocol: dict[str, Any] | str) -> list[dict[str, Any]]:
    payload = _load_protocol(protocol)
    return [
        step
        for step in list(payload.get("steps") or [])
        if isinstance(step, dict) and str(step.get("text") or "").strip()
    ]


def protocol_to_text(protocol: dict[str, Any] | str, style: ProtocolStyle = "flat_numbered") -> str:
    payload = _load_protocol(protocol)
    if style == "json":
        return compact_json(payload)
    if style == "flat_numbered":
        return "\n".join(
            f"{idx}. {step.get('text', '')}"
            for idx, step in enumerate(executable_steps(payload), start=1)
        )
    title = str(payload.get("title") or "Demonstrated procedure").strip()
    lines = [f"1. {title}"]
    include_details = style == "substeps_with_details"
    for idx, step in enumerate(executable_steps(payload), start=1):
        suffix = ""
        if include_details:
            details = []
            if step.get("demonstrated") is not None:
                details.append(f"demonstrated={bool(step.get('demonstrated'))}")
            if step.get("t_start") is not None and step.get("t_end") is not None:
                details.append(f"time={float(step['t_start']):.1f}-{float(step['t_end']):.1f}s")
            suffix = f" ({'; '.join(details)})" if details else ""
        lines.append(f"  1.{idx}. {step.get('text', '')}{suffix}")
    return "\n".join(lines)


def protocol_response_format(output_style: ProtocolStyle = "flat_numbered", include_flat_lists: bool = False) -> str:
    if output_style == "json":
        return response_format_block(
            {
                "title": "string",
                "summary": "string or null",
                "steps": [
                    {
                        "step_id": "string",
                        "order": "number or null",
                        "text": "string",
                        "reagents": ["string"],
                        "equipment": ["string"],
                        "objects": ["string"],
                    }
                ],
            }
        )
    if output_style == "flat_numbered":
        lists = "\n\nReagent List:\n1. <observed reagent or material>\n\nTools Used:\n1. <observed tool or equipment>" if include_flat_lists else ""
        return "\n".join(
            [
                "Please respond with the following format:",
                "",
                "## Response Format",
                "1. <observed action step with no substeps>",
                "2. <observed action step with no substeps>",
                lists,
                "",
                "Use simple flat numbered protocol steps. Do not include step IDs, substeps, bullets, or JSON.",
                "",
                "## Question",
            ]
        )
    return "\n".join(
        [
            "Please respond with the following format:",
            "",
            "## Response Format",
            "1. <section or procedure title>",
            "  1.1. <observed action>",
            "  1.2. <observed action>",
            "",
            "Use numbered sections and substeps. Do not include JSON.",
            "",
            "## Question",
        ]
    )


def _timed_steps(protocol: dict[str, Any] | str) -> list[dict[str, Any]]:
    rows = [
        step
        for step in executable_steps(protocol)
        if step.get("t_start") is not None and step.get("t_end") is not None
    ]
    return sorted(rows, key=lambda row: (float(row["t_start"]), float(row["t_end"])))


def step_timeline_text(protocol: dict[str, Any] | str) -> str:
    """Render demonstrated protocol steps as timestamped timeline lines."""
    lines = []
    for step in _timed_steps(protocol):
        start = float(step["t_start"])
        end = float(step["t_end"])
        step_id = str(step.get("step_id") or "?")
        text = str(step.get("text") or "")
        lines.append(f"[{start:.1f}-{end:.1f}s] step {step_id}: {text}")
    return "\n".join(lines)


def monitoring_state(protocol: dict[str, Any] | str, t: float) -> dict[str, Any]:
    """Return completed/current/remaining timed protocol steps at timestamp ``t``."""
    completed: list[dict[str, Any]] = []
    current: list[dict[str, Any]] = []
    remaining: list[dict[str, Any]] = []
    for step in _timed_steps(protocol):
        start = float(step["t_start"])
        end = float(step["t_end"])
        item = {
            "step_id": str(step.get("step_id") or "?"),
            "text": str(step.get("text") or ""),
            "t_start": start,
            "t_end": end,
        }
        if end <= t:
            completed.append(item)
        elif start <= t <= end:
            current.append(item)
        else:
            remaining.append(item)
    return {"t": float(t), "completed": completed, "current": current, "remaining": remaining}


def error_summary(row: dict[str, Any]) -> str:
    """Summarize the flat benchmark error fields from a parquet row."""
    if not row.get("has_error"):
        return "No annotated procedural error."
    error = str(row.get("error") or "").strip()
    return f"Error: {error}" if error else "Annotated procedural error present."


def row_video_context(row: dict[str, Any], include_timeline: bool = True) -> str:
    operation = str(row.get("operation") or row.get("protocol_title") or "the demonstrated wet-lab procedure").strip()
    lines = [f"Reconstruct the demonstrated protocol for {operation}."]
    if row.get("error"):
        lines.append("If an error is visible, include only the observed action sequence; do not add diagnostic commentary.")
    if include_timeline and row.get("protocol_json"):
        timeline = step_timeline_text(row["protocol_json"])
        if timeline:
            lines.extend(["", "Visible timeline:", timeline])
    return "\n".join(line for line in lines if str(line).strip())