yang1232009's picture
Add shot beats and the seven-dimension evaluation package
aa7162d verified
Raw History Blame Contribute Delete
9.05 kB
#!/usr/bin/env python3
"""Standalone Easyapi Gemini-native seven-dimension video evaluator."""
import argparse
import base64
import hashlib
import json
import mimetypes
import os
from pathlib import Path
import re
import time
import requests
DIMS = ["entity_consistency", "scene_consistency", "transition_smoothness",
"semantic_alignment", "cinematic_aesthetics", "narrative_coherence", "action_staging"]
PREVIOUS = re.compile(r"(?:前一(?:个)?|上一(?:个)?|前序)(?:镜头|片段|shot|视频)|(?<!当)前片段|上一段(?:视频|片段|镜头)|(?:承接|延续|接续|衔接)(?:了|着)?前段")
def save(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_suffix(".tmp")
temp.write_text(json.dumps(value, ensure_ascii=False, indent=2))
temp.replace(path)
def media(path, default_mime):
data = path.read_bytes()
if not data:
raise ValueError(f"Empty media file: {path}")
return {"inlineData": {"mimeType": mimetypes.guess_type(path.name)[0] or default_mime,
"data": base64.b64encode(data).decode()}}
def parse_scores(raw, sample):
text = raw.strip()
if text.startswith("```"):
text = re.sub(r"^\`\`\`(?:json)?\s*|\s*\`\`\`$", "", text).strip()
scores = json.loads(text)
if set(scores) != set(DIMS):
raise ValueError("Expected exactly seven dimensions")
for dim, item in scores.items():
value = item["score"]
if value is not None and (type(value) is not int or not 0 <= value <= 5):
raise ValueError(f"Invalid score: {dim}")
if not isinstance(item.get("reason"), str) or len(item["reason"]) < 8:
raise ValueError(f"Missing evidence reason: {dim}")
if dim != "transition_smoothness" and PREVIOUS.search(item["reason"]):
raise ValueError(f"Predecessor evidence outside transition: {dim}")
if not sample.get("previous_video") and scores["transition_smoothness"]["score"] is not None:
raise ValueError("First-shot transition must be null")
transition = scores["transition_smoothness"]
if sample.get("require_boundary_anchors") and transition["score"] is not None:
if not all(anchor in transition["reason"] for anchor in ("前视频末尾", "当前视频开头")):
raise ValueError("Transition reason must identify both cross-shot boundary anchors")
for field, dim in [("entity_refs", "entity_consistency"), ("scene_refs", "scene_consistency")]:
if not sample.get(field) and scores[dim]["score"] is not None:
raise ValueError(f"No actual references: {dim} must be null")
return scores
def build_request(sample, root, rubric, model, entity_scope):
contents = []
for field, caption in [("previous_video", "前视频,仅用于跨shot转场,禁止用于其他六维"),
("current_video", "当前视频,本次评分对象")]:
if sample.get(field):
contents.append({"role": "user", "parts": [
{"text": caption}, media(root / sample[field], "video/mp4"), {"text": "以上视频结束"}]})
parts = contents[-1]["parts"]
for field, role in [("entity_refs", "角色/实体参考图,仅用于实体一致性"),
("scene_refs", "场景参考图,仅用于场景一致性,比较固定空间结构")]:
for ref in sample.get(field, []):
if entity_scope == "characters" and field == "entity_refs" and ref.get("kind") != "character":
raise ValueError("Character-only evaluation requires kind=character for every entity reference")
parts.extend([{"text": role + ";身份/状态:" + ref["label"]},
media(root / ref["path"], "image/png")])
prompt = ("当前初始事件/beat,唯一文本目标:\n" + sample["initial_beat"]
+ "\n严格遵守七维证据使用合同。只返回七个维度对象,每维包含score和reason。")
if not sample.get("previous_video"):
prompt += "\n本镜为首镜,转场必须null。"
elif sample.get("require_boundary_anchors"):
prompt += ("\n转场自然度只评前视频最后一段画面/声音到当前视频最开始画面/声音的唯一边界。"
"当前片段的内部切镜完全不计入本维。有数值时,理由须用“前视频末尾”和“当前视频开头”"
"明确标出两个独立可见或可听的锚点,再说明它们如何衔接。")
if not sample.get("entity_refs"):
prompt += "\n未提供实际实体参考,实体一致性必须null。"
if not sample.get("scene_refs"):
prompt += "\n未提供实际场景参考,场景一致性必须null。"
if entity_scope == "characters":
prompt += "\n实体一致性仅评角色,物品不计入。"
parts.append({"text": prompt})
return {"systemInstruction": {"parts": [{"text": rubric}]}, "contents": contents,
"generationConfig": {"temperature": 0.2, "maxOutputTokens": 8192}}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("manifest", type=Path)
parser.add_argument("--out", type=Path, default=Path("evaluation_results"))
parser.add_argument("--base-url", default=os.getenv("EASYAPI_BASE_URL", "https://easymax.ai"))
parser.add_argument("--model", default="gemini-3.8-flash")
parser.add_argument("--entity-scope", choices=["all", "characters"], default="all")
parser.add_argument("--retry-seconds", type=float, default=10)
parser.add_argument("--max-attempts", type=int, default=0, help="0 means retry indefinitely")
args = parser.parse_args()
key = os.environ.get("EASYAPI_API_KEY")
if not key:
parser.error("Set EASYAPI_API_KEY")
rubric = Path(__file__).with_name("rubric.txt").read_text()
samples = json.loads(args.manifest.read_text())
ids = [s["id"] for s in samples]
if len(ids) != len(set(ids)) or any(not re.fullmatch(r"[A-Za-z0-9_.-]+", s) for s in ids):
parser.error("Sample IDs must be unique safe filenames")
base_url = args.base_url.rstrip("/")
for suffix in ["/v1beta", "/v1"]:
if base_url.endswith(suffix):
base_url = base_url[:-len(suffix)]
break
url = base_url + "/v1beta/models/" + args.model + ":generateContent"
for sample in samples:
if not sample.get("current_video") or not sample.get("initial_beat"):
raise ValueError("Every sample requires current_video and initial_beat")
payload = build_request(sample, args.manifest.resolve().parent, rubric, args.model, args.entity_scope)
fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
result_path = args.out / "scores" / (sample["id"] + ".json")
if result_path.exists():
previous = json.loads(result_path.read_text())
if previous["input_sha256"] != fingerprint:
raise ValueError(f"Changed input for {sample['id']}; use a new output directory")
print("REUSE", sample["id"], flush=True)
continue
attempt = 0
while True:
attempt += 1
folder = args.out / "attempts" / sample["id"] / str(time.time_ns())
folder.mkdir(parents=True)
try:
response = requests.post(url, headers={"Authorization": "Bearer " + key,
"x-goog-api-key": key, "Content-Type": "application/json"},
json=payload, stream=False, timeout=(20, 300))
# Store the provider body for diagnosing 403/quota and 429 errors.
(folder / "response.json").write_text(response.text.replace(key, "[REDACTED]"))
response.raise_for_status()
body = response.json()
candidate = body["candidates"][0]
if candidate.get("finishReason") != "STOP":
raise ValueError("Incomplete output: " + str(candidate.get("finishReason")))
raw = "".join(p.get("text", "") for p in candidate["content"]["parts"] if not p.get("thought"))
(folder / "response.txt").write_text(raw)
scores = parse_scores(raw, sample)
save(result_path, {"id": sample["id"], "provider": "Easyapi", "model": args.model,
"stream": False, "input_sha256": fingerprint, "scores": scores,
"usage": body.get("usageMetadata"), "raw_response": raw})
print("OK", sample["id"], flush=True)
break
except Exception as error:
save(folder / "error.json", {"type": type(error).__name__, "error": str(error).replace(key, "[REDACTED]")})
print("RETRY", sample["id"], type(error).__name__, flush=True)
if args.max_attempts and attempt >= args.max_attempts:
raise
time.sleep(args.retry_seconds)
if __name__ == "__main__":
main()