SpatialEvidenceBench / code /run_real.py
spatial-evidence-bench's picture
Upload folder using huggingface_hub
a863f79 verified
Raw History Blame Contribute Delete
4.58 kB
import argparse
import hashlib
import json
import re
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from run_models import MODEL_REGISTRY, load, run_one, yes_no_ids
CONDITIONS = ("T0", "Tpos", "Tneg", "Tabs", "Tunk")
STATUS = {"Tpos": "ASSERTED", "Tneg": "NEGATED", "Tabs": "ABSENT", "Tunk": "UNKNOWN"}
TRAILING = re.compile(r"\s*Answer only yes or no\.?\s*$", re.IGNORECASE)
MANIFESTS = {
"spatialsense": "runs/n_evidence_v1/gate0/source_manifest.jsonl",
"vsr": "runs/n_evidence_v1/gate3/manifest_vsr.jsonl",
}
def clean_question(text):
return TRAILING.sub("", text).strip()
def evidence_block(subject, obj, predicate, condition):
entities = [
{"id": "e1", "name": subject, "category": subject},
{"id": "e2", "name": obj, "category": obj},
]
if condition in ("Tabs", "Tunk"):
relation = {
"subject_id": "e1",
"object_id": "e2",
"predicate": None,
"claim_status": STATUS[condition],
}
else:
relation = {
"subject_id": "e1",
"object_id": "e2",
"predicate": f"not {predicate}" if condition == "Tneg" else predicate,
"claim_status": STATUS[condition],
}
return json.dumps({"entities": entities, "relation_evidence": relation}, ensure_ascii=False, indent=2)
def build_prompt(question, condition, subject, obj, predicate):
if condition == "T0":
return f"Look at the image.\n{question}\nRespond with exactly one word: yes or no."
evidence = evidence_block(subject, obj, predicate, condition)
return (
f"Look at the image.\n{question}\n"
f"A previous step produced this relation evidence:\n{evidence}\n"
"Respond with exactly one word: yes or no."
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--root", default="/mnt/f70f6709-366e-49a0-861f-497645d98975/lyz/GraphEvolve")
parser.add_argument("--collection", required=True, choices=sorted(MANIFESTS))
parser.add_argument("--model-key", required=True, choices=sorted(MODEL_REGISTRY))
parser.add_argument("--out", required=True)
parser.add_argument("--shard", type=int, default=0)
parser.add_argument("--shards", type=int, default=1)
parser.add_argument("--limit", type=int, default=0)
args = parser.parse_args()
root = Path(args.root)
rows = [json.loads(line) for line in (root / MANIFESTS[args.collection]).open(encoding="utf-8")]
rows = [r for i, r in enumerate(rows) if i % args.shards == args.shard]
if args.limit:
rows = rows[: args.limit]
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
processor, model = load(args.model_key)
ids = yes_no_ids(processor)
written = 0
started = time.time()
with out.open("w", encoding="utf-8") as fh:
for row in rows:
image_path = Path(row["image_path"])
if not image_path.is_absolute():
image_path = root / image_path
if not image_path.exists():
raise FileNotFoundError(str(image_path))
question = clean_question(row["question"])
subject = row["object_a"]
obj = row["object_b"]
predicate = row["predicate"]
for condition in CONDITIONS:
prompt = build_prompt(question, condition, subject, obj, predicate)
result = run_one(processor, model, ids, image_path, prompt)
record = {
"collection": args.collection,
"model": args.model_key,
"annotation_id": row["annotation_id"],
"image_path": str(image_path),
"question": question,
"subject": subject,
"object": obj,
"predicate": predicate,
"gold": row["gold"],
"condition": condition,
"prompt": prompt,
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
**result,
}
fh.write(json.dumps(record, ensure_ascii=False) + "\n")
fh.flush()
written += 1
if written % 50 == 0:
rate = written / max(1e-6, time.time() - started)
print(f"PROGRESS {written} rows {rate:.2f}/s", flush=True)
print(f"WROTE {out} rows={written}")
if __name__ == "__main__":
main()