File size: 10,838 Bytes
d7786d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""SVG outcome grading, version 2. No XML-count or duplicated overlap scores."""
import hashlib
import json
import re
import shutil
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
from PIL import Image, ImageFilter

VERSION='svg-outcome-v2'
SLUGS=['rosette','hierarchy','rlc-circuit','four-bar','gear','bicycle','isometric-house','floor-plan','flowchart']
WEIGHTS={'geometry':.40,'structure':.30,'styling':.20,'delivery':.10}
def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def tag(node):return node.tag.rsplit('}',1)[-1]
def dimension(value):
    m=re.fullmatch(r'\s*([+]?(?:\d+(?:\.\d*)?|\.\d+))\s*(px|mm|cm|in|pt|pc|q)?\s*',value or '')
    if not m:return None
    return float(m[1])*{'px':1,'mm':96/25.4,'cm':96/2.54,'in':96,'pt':96/72,'pc':16,'q':96/101.6,None:1}[m[2]]

def sanitize(source,destination):
    data=Path(source).read_bytes()
    if len(data)>32*1024*1024:raise ValueError('SVG exceeds 32 MiB bounded parser limit')
    if b'<!ENTITY' in data.upper():raise ValueError('Entity declarations are unsupported')
    root=ET.fromstring(data)
    if tag(root)!='svg':raise ValueError('Not an SVG document')
    if len(list(root.iter()))>100000:raise ValueError('SVG exceeds bounded element limit')
    removed=[]
    def walk(node):
        for child in list(node):
            if tag(child) in {'image','foreignObject','script'}:
                removed.append(tag(child));node.remove(child);continue
            walk(child)
        for k,v in node.attrib.items():
            if k.rsplit('}',1)[-1].lower().startswith('on'):raise ValueError('SVG event handlers unsupported')
            if k.rsplit('}',1)[-1]=='href' and not v.startswith('#'):raise ValueError('External references unsupported')
        content=' '.join(node.attrib.values())+' '+(node.text or '')
        if '@import' in content:raise ValueError('CSS imports unsupported')
        for target in re.findall(r'url\(\s*[\'\"]?([^\'\")\s]+)',content):
            if not target.startswith('#'):raise ValueError('External paint references unsupported')
    walk(root)
    vb=root.get('viewBox')
    if vb:
        values=[float(v) for v in re.split('[ ,]+',vb.strip())]
        if len(values)!=4 or not all(np.isfinite(values)) or min(values[2:])<=0:raise ValueError('Invalid viewBox')
    w,h=dimension(root.get('width')),dimension(root.get('height'))
    page=w is not None and h is not None and abs(w-1000)<.1 and abs(h-1000)<.1
    # Drawing count is diagnostic only; visible raster-stripped output is decisive.
    count=sum(tag(n) in {'path','rect','circle','ellipse','line','polyline','polygon','text','use'} for n in root.iter())
    destination.write_bytes(ET.tostring(root,encoding='utf-8',xml_declaration=True))
    return {'page_1000':page,'page_css_px':[w,h],'removed_elements':removed,'drawable_count_diagnostic':count}

def render(svg,out,drawing=False):
    exe=shutil.which('inkscape')
    if not exe:raise RuntimeError('Verifier dependency missing: Inkscape')
    cmd=[exe,str(svg),'--export-type=png','--export-filename='+str(out),'--export-width=1000']
    if drawing:cmd.append('--export-area-drawing')
    else:cmd.extend(['--export-area-page','--export-height=1000'])
    p=subprocess.run(cmd,capture_output=True,text=True,timeout=90)
    if p.returncode or not out.exists():raise RuntimeError('Renderer failed: '+p.stderr[-1000:])
    image=Image.open(out).convert('RGBA')
    if drawing:
        bbox=image.getbbox()
        if not bbox:raise RuntimeError('Reference SVG has no visible drawing')
        image=image.crop(bbox)
        scale=800/max(image.size)
        image=image.resize(tuple(max(1,round(v*scale)) for v in image.size),Image.Resampling.LANCZOS)
        paper=Image.new('RGBA',(1000,1000),'white')
        paper.alpha_composite(image,((1000-image.width)//2,(1000-image.height)//2))
    else:
        paper=Image.new('RGBA',image.size,'white');paper.alpha_composite(image)
    paper.convert('RGB').save(out)

def normalize_reference(source,destination):
    """Preserve source coordinate mapping; fit Inkscape's evaluated drawing bounds."""
    p=subprocess.run(['inkscape',str(source),'--query-all'],capture_output=True,text=True,timeout=90)
    if p.returncode:raise RuntimeError('Reference bounds failed: '+p.stderr[-1000:])
    try:x,y,w,h=map(float,p.stdout.splitlines()[0].split(',')[-4:])
    except (ValueError,IndexError) as exc:raise RuntimeError('Reference drawing bounds unavailable') from exc
    if not all(np.isfinite([x,y,w,h])) or min(w,h)<=0:raise RuntimeError('Reference bounds invalid')
    scale=800/max(w,h)
    root=ET.parse(source).getroot()
    outer=ET.Element('{http://www.w3.org/2000/svg}svg',{'width':'1000','height':'1000','viewBox':'0 0 1000 1000'})
    group=ET.SubElement(outer,'{http://www.w3.org/2000/svg}g',{'transform':f'matrix({scale},0,0,{scale},{500-scale*(x+w/2)},{500-scale*(y+h/2)})'})
    group.append(root);destination.write_bytes(ET.tostring(outer))

def foreground(rgb):return np.min(rgb,axis=2)<245
def boundary(mask):
    eroded=np.asarray(Image.fromarray(mask.astype('uint8')*255).filter(ImageFilter.MinFilter(3)))>0
    return mask&~eroded
def distances(source,target,max_distance=30):
    remaining=source.copy();values=np.full(source.shape,max_distance,dtype=np.float32)
    grown=target.copy()
    for d in range(max_distance+1):
        hit=remaining&grown;values[hit]=d;remaining[hit]=False
        if not remaining.any():break
        grown=np.asarray(Image.fromarray(grown.astype('uint8')*255).filter(ImageFilter.MaxFilter(3)))>0
    return values[source]
def geometry(a,b):
    ma,mb=foreground(a),foreground(b)
    if not ma.any():return 0.,{'reason':'No visible editable vector drawing'}
    # Boundary distance at half resolution; no registration to hide placement errors.
    small=lambda x:np.asarray(Image.fromarray(x.astype('uint8')*255).resize((500,500),Image.Resampling.NEAREST))>0
    ea,eb=boundary(small(ma)),boundary(small(mb))
    ds=np.concatenate([distances(ea,eb),distances(eb,ea)])*2
    mean=float(ds.mean());p95=float(np.percentile(ds,95))
    ramp=lambda x,full,zero:max(0.,min(1.,(zero-x)/(zero-full)))
    score=.6*ramp(mean,3,18)+.4*ramp(p95,7,35)
    return score,{'mean_boundary_distance_px':mean,'p95_boundary_distance_px':p95,'distance_metric':'bidirectional Chebyshev raster boundary distance; no alignment','full_credit_px':[3,7],'zero_credit_px':[18,35]}

def appearance(a,b):
    # Local median color measures surface fills, excluding texture residual and
    # edge placement. Geometry/structure own missing or displaced regions.
    common=foreground(a)&foreground(b)
    support=np.asarray(Image.fromarray(common.astype('uint8')*255).filter(ImageFilter.MinFilter(5)))>0
    errors=[]
    for y in range(0,1000,50):
        for x in range(0,1000,50):
            roi=support[y:y+50,x:x+50]
            if roi.sum()<20:continue
            ac=a[y:y+50,x:x+50][roi];bc=b[y:y+50,x:x+50][roi]
            errors.append(float(np.abs(np.median(ac,axis=0)-np.median(bc,axis=0)).mean()/255))
    if not errors:
        # Thin black lines have no five-pixel interior; use shared painted samples.
        if common.any():errors=[float(np.abs(a[common].astype(float).mean(axis=0)-b[common].astype(float).mean(axis=0)).mean()/255)]
        else:return 0.,{'reason':'No corresponding painted support'}
    err=float(np.mean(errors))
    return max(0.,min(1.,(0.20-err)/(0.20-.015))),{'local_median_rgb_error':err,'sampled_tiles':len(errors),'texture_policy':'Flat vector fills accepted; high-frequency raster texture is not required','full_credit_rgb_error':.015,'zero_credit_rgb_error':.20}

def export_match(rendered,submitted):
    if not submitted.exists():return 0.,{'reason':'Missing final.png'}
    try:
        image=Image.open(submitted).convert('RGBA')
        if image.size!=(1000,1000):return 0.,{'reason':'PNG must be 1000x1000'}
        paper=Image.new('RGBA',image.size,'white');paper.alpha_composite(image)
        a=np.asarray(Image.open(rendered).convert('RGB'),dtype=float)/255
        b=np.asarray(paper.convert('RGB'),dtype=float)/255
        support=np.maximum(1-a.min(axis=2),1-b.min(axis=2))>.035
        err=float(np.abs(a-b).mean(axis=2)[support].mean()) if support.any() else 0.
        return max(0.,min(1.,(.10-err)/(.10-.005))),{'foreground_mae':err,'full_credit_mae':.005,'zero_credit_mae':.10}
    except (OSError,ValueError) as exc:return 0.,{'reason':str(exc)}

def run(task,output,log):
    from features import structure
    task,output,log=map(Path,(task,output,log));log.mkdir(parents=True,exist_ok=True)
    (log/'reward.txt').unlink(missing_ok=True)
    cfg=json.loads((task/'svg-v2.json').read_text());slug=cfg['task']
    oracle=task/'oracle';reference=oracle/'canonical-v2.png';source=oracle/'source.svg'
    if sha(reference)!=cfg['reference_sha256'] or sha(source)!=cfg['source_sha256']:raise RuntimeError('Reference provenance mismatch')
    work=log/'artifacts';work.mkdir(exist_ok=True)
    svg=output/'final.svg';scores=dict.fromkeys(WEIGHTS,0.);details={}
    if svg.exists():
        clean=work/'candidate-vector.svg';rendered=work/'candidate-render.png'
        try:native=sanitize(svg,clean)
        except (ET.ParseError,ValueError,OverflowError) as exc:details={'invalid_candidate':str(exc)}
        else:
            render(clean,rendered)
            a=np.asarray(Image.open(rendered).convert('RGB'));b=np.asarray(Image.open(reference).convert('RGB'))
            if foreground(a).any():
                scores['geometry'],details['geometry']=geometry(a,b)
                scores['structure'],details['structure']=structure(a,b,cfg['manifest'])
                scores['styling'],details['styling']=appearance(a,b)
            export,ed=export_match(rendered,output/'final.png')
            scores['delivery']=.5*float(native['page_1000'])+.5*export
            details.update(native=native,delivery=ed)
            overlay=np.stack([foreground(b)*200,foreground(a)*180,np.zeros((1000,1000))],axis=2).astype('uint8')
            Image.fromarray(overlay).save(work/'boundary-overlay.png')
    else:details['reason']='Missing final.svg'
    report={'version':VERSION,'task':slug,'checks':[{'id':k,'weight':v,'score':float(scores[k]),'earned':float(scores[k])*v} for k,v in WEIGHTS.items()],
        'reward':sum(scores[k]*v for k,v in WEIGHTS.items()),'details':details,'reference_svg_sha256':sha(source),'reference_render_sha256':sha(reference),'scorer_sha256':sha(__file__),
        'calibration':'Versioned initial policy; equivalent-construction and defect fixtures tested. Human pen-tool tolerance calibration remains a limitation.'}
    (log/'score-report.json').write_text(json.dumps(report,indent=2,allow_nan=False)+'\n')
    (log/'reward.txt').write_text(f"{report['reward']:.6f}\n")
    return report