odubench / evaluation /tests /test_protocol.py
qc316's picture
init (part 10)
f996af6 verified
Raw History Blame Contribute Delete
14.4 kB
import copy
import json
from pathlib import Path
import pytest
from odu_eval import runner
from odu_eval.cli import main
from odu_eval.core import scoring, scene, transport
from odu_eval.dataset import Dataset
from odu_eval.io import file_digest, read_jsonl, write_json, write_jsonl
from odu_eval.parsing import api, local
from odu_eval.providers import APIError, Service
@pytest.fixture
def dataset(tmp_path):
root = tmp_path / "data"
root.mkdir()
rows = []
for index, (modality, label, clips) in enumerate([
("audio-only", "positive", 1), ("audio-only", "negative", 2),
("audio-visual", "positive", 2), ("audio-visual", "negative", 1),
]):
sid = f"example_{index}"
folder = root / modality / label / sid
folder.mkdir(parents=True)
ext = "wav" if modality == "audio-only" else "mp4"
media = []
for clip in range(1, clips + 1):
name = f"clip_v{clip}.{ext}"
(folder / name).write_bytes(b"fixture-media-" + str(clip).encode())
media.append(name)
seg = {"start_ms": 0, "end_ms": 1000, "transcript": "Turn down the volume.",
"structured_intent": "Reduce the volume.", "required_context": [],
"user_gender": "unknown", "user_age_group": "adult",
"key_points": [{"qid": "kp01", "point": "Reduce volume", "tiers": ["T1"], "source": "intent"},
{"qid": "kp02", "point": "A television", "tiers": ["T1", "T2"], "source": "dialogue_history"},
{"qid": "kp03", "point": "Background music", "tier": 2, "source": "audio"}]}
if modality == "audio-visual":
seg["user_in_frame"] = False
write_json(folder / "annotation_en.json", {"scene_id": sid, "evaluation_targets": {
"has_demand": label == "positive", "segments": [seg] if label == "positive" else []}})
write_json(folder / "metadata.json", {"scene_id": sid, "agent_replies": [
{"after_clip_id": "v0", "content": "excluded before first clip"},
{"after_clip_id": "v1", "content": "Earlier assistant reply"},
{"after_clip_id": "v2", "content": "excluded after final clip"}]})
rows.append({"scene_id": sid, "modality": modality, "label": label, "source": "generated", "n_clips": clips,
"rel_path": folder.relative_to(root).as_posix(), "media": media, "metadata": "metadata.json",
"annotations": {"en": "annotation_en.json"}, "annotation": "annotation_en.json"})
write_jsonl(root / "manifest.jsonl", rows)
write_jsonl(root / "subsets/main.jsonl", rows)
sums = [f"{file_digest(root / r['rel_path'] / name)} {r['rel_path']}/{name}" for r in rows for name in r["media"]]
(root / "checksums.sha256").write_text("\n".join(sums) + "\n")
return Dataset(root)
def test_inputs_keep_multiclip_order_without_reference_answer(dataset):
assert dataset.validate(checksums=True)["checksums_verified"] == 6
sample = dataset.sample(dataset.rows[2])
assert [m["role"] for m in sample["messages"]] == ["system", "user"]
parts = sample["messages"][1]["content"]
assert [p["clip_id"] for p in parts if p["type"] == "video"] == ["v1", "v2"]
text = " ".join(p["text"] for p in parts if p["type"] == "text")
assert "Earlier assistant reply" in text
assert "excluded" not in text
assert "local timestamps within the final video clip" in text
assert "key_points" not in json.dumps(sample)
assert all(not Path(p["path"]).is_absolute() and p["use_audio"] for p in parts if p["type"] == "video")
def test_dataset_escape_and_duplicate_ids_are_rejected(dataset):
row = copy.deepcopy(dataset.rows[0])
row["media"] = ["../../escape.wav"]
with pytest.raises(ValueError, match="inside"):
dataset.sample(row)
rows = dataset.rows + [dataset.rows[0]]
write_jsonl(dataset.root / "manifest.jsonl", rows)
with pytest.raises(ValueError, match="unique"):
Dataset(dataset.root)
def test_parsers_keep_their_historical_difference(monkeypatch):
monkeypatch.setattr(api, "_JSON_REPAIR_ENABLED", False)
tagged = "<has_demand>false</has_demand><segments></segments>"
assert api.parse_model_output(tagged) is None
parsed, mode = local.parse_model_output_with_mode(tagged)
assert mode == "tagged"
assert parsed["evaluation_targets"] == {"has_demand": False, "segments": []}
raw = '<think>reasoning</think>```json\n{"has_demand":true,"segments":[{"start_ms":"1.2s","end_ms":"2.5s"}]}\n```'
assert api.parse_model_output(raw) == local.parse_model_output(raw)
def test_final_clip_scopes_each_side_independently():
pred = {"has_demand": True, "segments": [{"clip_id": "v1"}, {"clip_id": "v3"}, {"transcript": "keep"}]}
gt = {"has_demand": True, "segments": [{"clip_id": "v2"}, {"clip_id": "v4"}]}
p, g, final = scoring.apply_multiturn_scope(pred, gt, "example")
assert final == "v4"
assert [x.get("clip_id") for x in p["segments"]] == ["v3", None]
assert g["segments"] == [{"clip_id": "v4"}]
def test_union_keypoints_and_judge_failures(dataset):
gt = dataset.gt(dataset.rows[0])["evaluation_targets"]
pred = copy.deepcopy(gt)
for seg in pred["segments"]:
seg.pop("key_points")
transport.set_llm_call(lambda **kwargs: '[{"qid":"kp01","hit":true},{"qid":"kp02","hit":true},{"qid":"kp03","hit":false}]')
try:
result = scene.evaluate_scene(pred, gt, run_m4_llm=True, audio_only=True)
assert result["scores"]["verification_qa"] == .6667
assert result["details"]["verification_qa"]["t1_hit_rate"] == 1
assert result["details"]["verification_qa"]["point_stats"] == {"hit": 2, "total": 3}
def fail(**kwargs):
raise RuntimeError("OpenAIError")
transport.set_llm_call(fail)
failed = scene.evaluate_scene(copy.deepcopy(pred), copy.deepcopy(gt), run_m4_llm=True, m4_max_retries=1, audio_only=True)
assert failed["overall"] is None
assert failed["details"]["verification_qa"]["incomplete"]
finally:
transport.set_llm_call(None)
def test_wire_protocols_keep_media_order(dataset, monkeypatch):
monkeypatch.delenv("ODU_QWEN_OMNI_MODEL", raising=False)
sample = dataset.sample(dataset.rows[2])
qwen = Service("qwen3.5-omni-plus")
body = qwen.inference_payload(sample, dataset.root)
assert set(body) == {"model", "messages", "stream", "stream_options", "modalities"}
assert body["modalities"] == ["text"] and body["stream"] is True
assert [p["type"] for p in body["messages"][1]["content"]] == [p["type"].replace("video", "video_url") for p in sample["messages"][1]["content"]]
gemini = Service("gemini-3.1-pro")
native = gemini.inference_payload(sample, dataset.root)
assert set(native) == {"systemInstruction", "contents"}
assert native["contents"][0]["role"] == "user"
assert len([p for p in native["contents"][0]["parts"] if "inlineData" in p]) == 2
assert "path" not in json.dumps(native)
audio = qwen.inference_payload(dataset.sample(dataset.rows[0]), dataset.root)
assert audio["messages"][1]["content"][0]["input_audio"]["data"].startswith("data:audio/")
assert Service("qwen3.6-flash", thinking="true").text_payload("s", "u")["enable_thinking"] is True
openai = Service("gpt-5.4", reasoning="high").text_payload("s", "u")
assert openai["reasoning_effort"] == "high" and "enable_thinking" not in openai
def test_streaming_collects_answer_only(monkeypatch):
class Response:
headers = {"Content-Type": "text/event-stream; charset=utf-8"}
def __enter__(self): return self
def __exit__(self, *args): return False
def iter_lines(self):
yield b'data: {"choices":[{"delta":{"reasoning_content":"hidden"}}]}'
yield b'data: {"choices":[{"delta":{"content":"ans"}}]}'
yield b'data: {"choices":[{"delta":{"content":"wer"}}]}'
yield b'data: {"choices":[],"usage":{"total_tokens":10}}'
yield b'data: [DONE]'
service = Service("gpt-5.4")
monkeypatch.setattr(service, "request", lambda *a, **k: Response())
assert service.call_text("s", "u") == "answer"
assert service.stats["reasoning_chunks"] == 1
def test_server_errors_do_not_echo_credentials(monkeypatch):
class Response:
ok, status_code = False, 401
def json(self): return {"error": {"code": "invalid_api_key", "message": "secret-value https://private.example/"}}
def close(self): pass
class Session:
def request(self, *a, **k): return Response()
service = Service("gpt-5.4")
service.key = "test-key"
service._session = Session()
with pytest.raises(APIError) as err:
service.request("POST", "https://example.test")
assert "401" in str(err.value)
assert "secret-value" not in str(err.value) and "private.example" not in str(err.value)
def test_gemini_files_upload_wire_contract(dataset, monkeypatch):
service = Service("gemini-3.1-pro")
media = dataset.scene_file(dataset.rows[2], dataset.rows[2]["media"][0])
calls = []
class Response:
def __init__(self, body=None, headers=None):
self.body, self.headers = body, headers or {}
def __enter__(self): return self
def __exit__(self, *args): return False
def json(self): return self.body
def request(method, url, **kwargs):
calls.append((method, url, kwargs))
if len(calls) == 1:
assert kwargs["json"] == {"file": {"display_name": "evaluation-media"}}
assert kwargs["headers"]["X-Goog-Upload-Protocol"] == "resumable"
return Response(headers={"X-Goog-Upload-URL": "https://upload.example.test/session"})
if len(calls) == 2:
assert kwargs["headers"]["X-Goog-Upload-Command"] == "upload, finalize"
assert kwargs["data"].read() == media.read_bytes()
return Response({"file": {"name": "files/example", "state": "PROCESSING"}})
return Response({"name": "files/example", "state": "ACTIVE", "uri": "https://files.example.test/example"})
monkeypatch.setattr(service, "request", request)
monkeypatch.setattr("odu_eval.providers.time.sleep", lambda n: None)
uploaded = service._upload_gemini(media, "video/mp4")
assert uploaded["state"] == "ACTIVE" and len(calls) == 3
sample = dataset.sample(dataset.rows[2])
key = next(p["path"] for p in sample["messages"][1]["content"] if p["type"] == "video")
payload = service.inference_payload(sample, dataset.root, files={key: uploaded})
files = [p["fileData"] for p in payload["contents"][0]["parts"] if "fileData" in p]
assert files == [{"mimeType": "video/mp4", "fileUri": uploaded["uri"]}]
def test_moving_dataset_keeps_inputs_and_fingerprint(dataset, tmp_path):
import shutil
destination = tmp_path / "relocated"
shutil.copytree(dataset.root, destination)
moved = Dataset(destination)
assert dataset.fingerprint(dataset.rows) == moved.fingerprint(moved.rows)
assert [dataset.sample(r) for r in dataset.rows] == [moved.sample(r) for r in moved.rows]
def test_readme_flow_and_offline_replay(dataset, tmp_path, monkeypatch):
monkeypatch.setenv("DASHSCOPE_API_KEY", "test-key")
def fake_infer(self, sample, root):
row = next(r for r in dataset.rows if r["scene_id"] == sample["scene_id"])
gt = copy.deepcopy(dataset.gt(row)["evaluation_targets"])
for seg in gt["segments"]:
seg.pop("key_points")
return json.dumps(gt)
monkeypatch.setattr(Service, "infer", fake_infer)
monkeypatch.setattr(Service, "call_text", lambda *a, **kw: '[{"qid":"kp01","hit":true},{"qid":"kp02","hit":true},{"qid":"kp03","hit":false}]')
data = ["--data-root", str(dataset.root)]
inputs, predictions = tmp_path / "inputs.jsonl", tmp_path / "model"
assert main(["validate", *data, "--checksums"]) == 0
assert main(["export-inputs", *data, "--smoke", "--output", str(inputs)]) == 0
command = ["infer", *data, "--smoke", "--model", "qwen3.5-omni-plus", "--output-dir", str(predictions)]
assert main(command) == 0
assert main(command) == 0 # Resume must not change the raw rows.
score = tmp_path / "score"
score_args = ["score", *data, "--predictions", str(predictions / "predictions.jsonl"), "--judge", "qwen3.6-flash"]
assert main([*score_args, "--output-dir", str(score)]) == 0
recorded = json.loads((score / "run_manifest.json").read_text())
assert len(recorded["judge_prompt_sha256"]) == 64
assert recorded["protocol"]["judge_prompt_sha256"] == recorded["judge_prompt_sha256"]
monkeypatch.delenv("DASHSCOPE_API_KEY")
monkeypatch.setenv("DASHSCOPE_BASE_URL", "https://different.example/v1")
monkeypatch.setattr(Service, "call_text", lambda *a, **kw: pytest.fail("offline sent a request"))
replay = tmp_path / "replay"
assert main([*score_args, "--judge-cache", str(score / "judge_cache"), "--offline", "--output-dir", str(replay)]) == 0
assert read_jsonl(score / "scores.jsonl") == read_jsonl(replay / "scores.jsonl")
assert (score / "comparison.csv").read_bytes() == (replay / "comparison.csv").read_bytes()
assert str(dataset.root) not in (score / "run_manifest.json").read_text()
assert main(["aggregate", "--runs", str(score), str(replay), "--output-dir", str(tmp_path / "report")]) == 0
def test_custom_submission_and_coverage(dataset, tmp_path, monkeypatch):
monkeypatch.setenv("DASHSCOPE_API_KEY", "test-key")
monkeypatch.setattr(Service, "call_text", lambda *a, **k: pytest.fail("negative answer should not require a judge"))
inputs, raw, pred = tmp_path / "inputs.jsonl", tmp_path / "raw.jsonl", tmp_path / "predictions.jsonl"
runner.export_inputs(dataset, dataset.rows, inputs)
write_jsonl(raw, [{"scene_id": dataset.rows[0]["scene_id"], "raw_output": '{"has_demand":false,"segments":[]}'}])
assert main(["parse", "--input", str(raw), "--inputs", str(inputs), "--output", str(pred), "--profile", "local"]) == 0
out = tmp_path / "partial"
assert main(["score", "--data-root", str(dataset.root), "--predictions", str(pred), "--judge", "qwen3.6-flash", "--output-dir", str(out)]) == 1
coverage = json.loads((out / "coverage.json").read_text())
assert coverage["expected"] == 4 and coverage["missing_predictions"] == 3