"""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='.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'],cfg['min_vectors']) 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