SceneBench / code /evaluate_openrouter.py
EgoF0102's picture
SceneBench v1: frozen source-derived test benchmark and verified artifacts
7735593 verified
Raw History Blame Contribute Delete
6.63 kB
"""Resumable, image-only baseline. Credentials never enter the dataset or logs."""
import argparse,asyncio,base64,json,time,random,re,hashlib,collections,os
from pathlib import Path
import httpx
from common import read_jsonl,write_json
SYSTEM='You are answering a multiple-choice question about laparoscopic cholecystectomy images. Use the provided image or images. For spatial questions, left/right/above/below refer to bounding-box centers in image coordinates; image y increases downward. For CVS, use the Cholec80-CVS scoring convention: each of the three criteria has score 0, 1, or 2, and overall CVS is achieved when their sum is at least 5. Return only the single uppercase letter of the correct option. Do not include an explanation.'
def parse_answer(content,n):
if not isinstance(content,str):return None
s=content.strip()
m=re.fullmatch(r'[\s*`]*(?:\(?)([A-D])(?:\)?)[.\s*`]*',s)
if not m:m=re.fullmatch(r'(?:Answer|Final answer|Option)\s*[::]?\s*\(?([A-D])\)?[.\s]*',s,re.I)
return m.group(1).upper() if m and ord(m.group(1).upper())-65<n else None
def payload(item,release,model):
content=[]
for i,rel in enumerate(item['images']):
content.append({'type':'text','text':f'Frame {i+1}:' if len(item['images'])>1 else 'Image:'})
data=base64.b64encode((release/rel).read_bytes()).decode('ascii')
content.append({'type':'image_url','image_url':{'url':'data:image/jpeg;base64,'+data,'detail':'high'}})
text=item['question']+'\n'+'\n'.join(f'{chr(65+i)}. {o}' for i,o in enumerate(item['options']))+'\nReturn only the answer letter.'
content.append({'type':'text','text':text})
return {'model':model,'messages':[{'role':'system','content':SYSTEM},{'role':'user','content':content}],'temperature':0,'max_tokens':64,'seed':20260922,'stream':False}
async def run(args):
root=Path(args.root);release=root/'release';cfg=json.loads((root/'config.json').read_text());credentials=json.loads(Path(args.credentials).read_text());model=cfg['model'];items=list(read_jsonl(release/'benchmark.jsonl'))
assert (release/'FROZEN.json').exists(),'Freeze and validate benchmark before evaluating'
frozen=json.loads((release/'FROZEN.json').read_text());assert hashlib.sha256((release/'benchmark.jsonl').read_bytes()).hexdigest()==frozen['benchmark_sha256']
out=root/'evaluation';out.mkdir(exist_ok=True);path=out/'predictions.jsonl';done={r['id']:r for r in read_jsonl(path)} if path.exists() else {};todo=[r for r in items if r['id'] not in done or args.retry_errors and done[r['id']].get('status')!='ok']
if args.limit:todo=todo[:args.limit]
protocol=dict(model=model,benchmark_sha256=frozen['benchmark_sha256'],system_prompt=SYSTEM,temperature=0,max_tokens=64,seed=20260922,input='exported benchmark images + question + options only; no source graphs, GT, video IDs or timestamps',calls_per_question=1,retries='HTTP transport/429/5xx only, at most 5 attempts',parser='strict option letter, optionally prefixed by Answer/Final answer/Option',started_unix=time.time())
write_json(out/'protocol.json',protocol);sem=asyncio.Semaphore(args.concurrency);lock=asyncio.Lock();start=time.time();n=0
async with httpx.AsyncClient(timeout=httpx.Timeout(180,connect=30),limits=httpx.Limits(max_connections=args.concurrency,max_keepalive_connections=args.concurrency),headers={'Authorization':'Bearer '+credentials['openrouter'],'Content-Type':'application/json','X-Title':'SceneBench zero-shot evaluation'}) as client:
async def one(item):
nonlocal n
async with sem:
body=payload(item,release,model);t0=time.time();result=None;error=None
for attempt in range(5):
try:
response=await client.post('https://openrouter.ai/api/v1/chat/completions',json=body)
if response.status_code in [429,500,502,503,504]:
error=f'HTTP {response.status_code}'
if attempt<4:await asyncio.sleep(min(30,2**attempt+random.random()));continue
if response.status_code!=200:
error=f'HTTP {response.status_code}: '+response.text[:600];break
result=response.json()
if result.get('error'):error=str(result['error'])[:600];result=None
break
except (httpx.TimeoutException,httpx.TransportError) as ex:
error=type(ex).__name__
if attempt<4:await asyncio.sleep(min(30,2**attempt+random.random()))
record={'id':item['id'],'task':item['task'],'family':item['family'],'video_id':item['video_id'],'gold':item['answer'],'gold_text':item['answer_text'],'latency_s':time.time()-t0,'attempts':attempt+1,'model_requested':model,'timestamp_unix':time.time()}
if result:
choice=(result.get('choices') or [{}])[0];msg=choice.get('message') or {};content=msg.get('content','');pred=parse_answer(content,len(item['options']))
record.update(status='ok',prediction=pred,correct=pred==item['answer'],content=content,finish_reason=choice.get('finish_reason'),response_id=result.get('id'),model_returned=result.get('model'),provider=result.get('provider'),usage=result.get('usage',{}))
else:record.update(status='api_error',prediction=None,correct=False,error=error)
async with lock:
with path.open('a') as f:f.write(json.dumps(record,ensure_ascii=False)+'\n')
done[item['id']]=record;n+=1
if n%25==0 or n==len(todo):
rr=[done[x['id']] for x in items if x['id'] in done];progress={'completed':len(rr),'total':len(items),'ok':sum(r['status']=='ok' for r in rr),'correct':sum(r['correct'] for r in rr),'elapsed_s':round(time.time()-start,1)};write_json(out/'progress.json',progress);print(json.dumps(progress),flush=True)
await asyncio.gather(*(one(r) for r in todo))
write_json(out/'completion.json',{'completed':sum(x['id'] in done for x in items),'total':len(items),'finished_unix':time.time()})
def main():
p=argparse.ArgumentParser();p.add_argument('--root',default='/home/ach18533cl/workspace/SceneBench');p.add_argument('--credentials',default='/home/ach18533cl/.cache/scenebench-auth/credentials.json');p.add_argument('--concurrency',type=int,default=8);p.add_argument('--limit',type=int);p.add_argument('--retry-errors',action='store_true');a=p.parse_args();asyncio.run(run(a))
if __name__=='__main__':main()