File size: 8,727 Bytes
e33425b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Offline Harbor grader. Hidden oracle configuration supplies reviewed measurements.
Unconfigured criteria are evaluator errors, never candidate zeros.
"""
import argparse,json,subprocess,sys,math,hashlib,xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
from PIL import Image,ImageOps

def probe(path):
 r=subprocess.run(['ffprobe','-v','error','-show_format','-show_streams','-of','json',str(path)],capture_output=True,text=True)
 if r.returncode: return {'valid':False,'error':r.stderr[-500:]}
 return {'valid':True,**json.loads(r.stdout)}
def xml_features(path):
 root=ET.parse(path).getroot();els=[]
 for e in root.iter():
  els.append({'tag':e.tag.split('}')[-1],'attrs':dict(e.attrib),'text':''.join(e.itertext()).strip() if e.tag.split('}')[-1] in ['text','tspan','property'] else ''})
 return {'root':dict(root.attrib),'elements':els,'counts':{t:sum(e['tag']==t for e in els) for t in set(e['tag'] for e in els)}}
def inspect(path,kind,work):
 if kind=='blend':
  out=work/'native.json';p=subprocess.run(['blender','-b','-Y',str(path),'--python','/tests/inspect_blend.py','--',str(out)],capture_output=True,text=True,timeout=240);(work/'blender.log').write_text(p.stdout+p.stderr)
  if p.returncode or not out.exists():return {'valid':False,'error':p.stderr[-500:]}
  return {'valid':True,**json.loads(out.read_text())}
 if kind in ['svg','kdenlive','lmms']:
  try:return {'valid':True,**xml_features(path)}
  except ET.ParseError as e:return {'valid':False,'error':str(e)}
 if kind=='audacity':
  import sqlite3
  try:
   db=sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True);tables=[r[0] for r in db.execute("select name from sqlite_master where type='table'")];rows={t:db.execute('select count(*) from '+chr(34)+t.replace(chr(34),chr(34)*2)+chr(34)).fetchone()[0] for t in tables};db.close();return {'valid':bool(tables),'tables':tables,'row_counts':rows,'note':'AUP3 track semantics require Audacity reopening/export, not SQLite row counts.'}
  except sqlite3.DatabaseError as e:return {'valid':False,'error':str(e)}
 if kind=='xcf':
  b=path.read_bytes()[:64];return {'valid':b.startswith(b'gimp xcf '),'bytes':path.stat().st_size,'note':'Layer topology must be inspected with a calibrated GIMP export/inspection hook; byte count is not layer correctness.'}
 return {'valid':False,'error':'Unknown format'}
def lookup(data,pointer):
 cur=data
 for key in pointer.split('/')[1:]:cur=cur[int(key)] if isinstance(cur,list) else cur[key.replace('~1','/').replace('~0','~')]
 return cur
def similarity(a,b,tol):
 if isinstance(b,dict):return float(np.mean([similarity(a.get(k),v,tol) for k,v in b.items()])) if isinstance(a,dict) and b else float(a==b)
 if isinstance(b,list):return float(np.mean([similarity(x,y,tol) for x,y in zip(a,b)])) if isinstance(a,list) and len(a)==len(b) and b else float(a==b)
 if isinstance(b,(int,float)) and not isinstance(b,bool):return max(0,1-abs(float(a)-b)/tol) if isinstance(a,(int,float)) and tol>0 else float(a==b)
 return float(a==b)
def image_score(a,b,cfg):
 a=Image.open(a).convert('RGB');b=Image.open(b).convert('RGB')
 if cfg.get('candidate_crop'):a=a.crop(cfg['candidate_crop'])
 if cfg.get('reference_crop'):b=b.crop(cfg['reference_crop'])
 # A frozen crop/scale policy, never per-candidate best-match search.
 a=ImageOps.pad(a,(512,512),color='white');b=ImageOps.pad(b,(512,512),color='white')
 x=np.asarray(a,dtype=float)/255;y=np.asarray(b,dtype=float)/255
 error=float(np.mean(abs(x-y)));return max(0,1-error/float(cfg['max_mae']))
def audio_features(p,work):
 out=work/'audio.wav';r=subprocess.run(['ffmpeg','-v','error','-y','-i',str(p),'-ac','1','-ar','16000',str(out)],capture_output=True,text=True)
 if r.returncode:return {'valid':False}
 import wave
 with wave.open(str(out)) as w:a=np.frombuffer(w.readframes(w.getnframes()),dtype='<i2').astype(float)/32768
 size=1600;rms=[float(np.sqrt(np.mean(a[i:i+size]**2))) for i in range(0,len(a),size) if len(a[i:i+size])]
 return {'valid':True,'duration':len(a)/16000,'rms':rms,'peak':float(np.max(abs(a))) if len(a) else 0,'non_silent':bool(len(a) and np.max(abs(a))>.001),'clipped_fraction':float(np.mean(abs(a)>.999)) if len(a) else 0}
def run(task,output,log):
 log.mkdir(parents=True,exist_ok=True);(log/'reward.txt').unlink(missing_ok=True)
 rubric=json.loads((task/'rubric.json').read_text());config=json.loads((task/'oracle/config.json').read_text())
 if 'REVIEW_REQUIRED' in json.dumps(config) or any(v is None for v in config.get('checks',{}).values()):raise RuntimeError('Review-required oracle bindings remain.')
 if config.get('status')!='calibrated':raise RuntimeError('Oracle is not calibrated/reviewed. Complete /tests/oracle/config.json before running agents.')
 for c in rubric['criteria']:
  if c['id'] not in config.get('checks',{}):raise RuntimeError('Unconfigured criterion: '+c['id'])
 report={'rubric_version':rubric['version'],'checks':[]};work=log/'artifacts';work.mkdir(exist_ok=True)
 nativepath=output/rubric['native_file'];native=inspect(nativepath,rubric['kind'],work) if nativepath.exists() else {'valid':False,'missing':True}
 (work/'inspection.json').write_text(json.dumps(native,indent=2,allow_nan=False));data={'native':native,'files':{p.name:{'exists':True,'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in output.iterdir() if p.is_file()}}
 if rubric.get('media_file'):
  media=output/rubric['media_file'];data['media']=probe(media) if media.exists() else {'valid':False}
  if rubric['kind'] in ['lmms','audacity'] and media.exists():data['audio']=audio_features(media,work)
 svg_cache={}
 def evaluate(cfg,check_id):
  typ=cfg['type'];score=0.;detail=''
  if typ=='group':
   sub=cfg.get('checks',[])
   if not sub:raise RuntimeError('Empty check group: '+check_id)
   results=[evaluate(v,check_id+'-'+str(i))[0] for i,v in enumerate(sub)]
   return float(np.mean(results)),str(results)
  elif typ=='feature':
   try:score=similarity(lookup(data,cfg['pointer']),cfg['expected'],cfg.get('tolerance',0))
   except (KeyError,IndexError,TypeError):score=0.;detail='Candidate feature missing'
  elif typ=='svg_reference':
   from svg_reference import score as score_svg
   key=cfg['reference']
   if key not in svg_cache:svg_cache[key]=score_svg(output,task/'oracle',cfg,work)
   scores,evidence=svg_cache[key]
   raw=scores[cfg['metric']]
   baseline=cfg.get('positive_baseline',1.)
   if not 0<baseline<=1:raise RuntimeError('Invalid positive baseline for '+check_id)
   score=min(1.,raw/baseline)
   detail=json.dumps({'raw_score':raw,'positive_baseline':baseline,**evidence},sort_keys=True)
  elif typ=='image':
   a=output/cfg['candidate'];b=task/'oracle'/cfg['reference']
   if not b.exists():raise RuntimeError('Missing oracle reference '+str(b))
   if a.exists():score=image_score(a,b,cfg)
   else:detail='Candidate image missing'
  elif typ=='video_frames':
   scores=[]
   for i,pair in enumerate(cfg['pairs']):
    ref=task/'oracle'/pair['reference'];img=work/f'frame-{check_id}-{i}.png'
    if not ref.exists():raise RuntimeError('Missing oracle frame '+str(ref))
    media=output/cfg['candidate']
    if media.exists():
     r=subprocess.run(['ffmpeg','-v','error','-y','-ss',str(pair['time']),'-i',str(media),'-frames:v','1',str(img)],capture_output=True,text=True)
     scores.append(image_score(img,ref,pair) if r.returncode==0 and img.exists() else 0.)
    else:scores.append(0.)
   if not scores:raise RuntimeError('No temporal samples configured')
   score=float(np.mean(scores))
  else:raise RuntimeError('Unsupported check type: '+typ)

  return score,detail
 for c in rubric['criteria']:
  score,detail=evaluate(config['checks'][c['id']],c['id'])
  report['checks'].append({'id':c['id'],'description':c['description'],'weight':c['weight'],'score':score,'earned':score*c['weight'],'detail':detail})
 report['reward']=min(1.,max(0.,sum(c['earned'] for c in report['checks'])));report['evidence_only_references']=rubric.get('reference_note')
 (log/'score-report.json').write_text(json.dumps(report,indent=2,allow_nan=False));(log/'reward.txt').write_text(f'{report["reward"]:.6f}\n');return report
if __name__=='__main__':
 a=argparse.ArgumentParser();a.add_argument('--task',type=Path,default=Path('/tests'));a.add_argument('--output',type=Path,default=Path('/root/output'));a.add_argument('--log',type=Path,default=Path('/logs/verifier'));args=a.parse_args()
 try:print(json.dumps(run(args.task,args.output,args.log),indent=2))
 except Exception as e:
  args.log.mkdir(parents=True,exist_ok=True);(args.log/'reward.txt').unlink(missing_ok=True);(args.log/'evaluation-error.json').write_text(json.dumps({'evaluation_error':str(e),'reward':None},indent=2));print(str(e),file=sys.stderr);sys.exit(1)