File size: 6,564 Bytes
fbf5988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic SVG reference scoring. Candidate raster content is removed before rendering.

This is an artifact scorer, not evidence of which GUI commands were used. A candidate
image cannot substitute for the SVG, and the submitted PNG is checked against a
verifier render of that SVG.
"""
import hashlib, io, json, re, shutil, subprocess, tempfile
import xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
from PIL import Image, ImageFilter

DRAWABLE={'path','rect','circle','ellipse','line','polyline','polygon','text','use'}
REMOVE={'image','foreignObject','script'}
SVG_NS='http://www.w3.org/2000/svg'

def local(tag):return tag.rsplit('}',1)[-1]

def sanitize(source,destination):
    root=ET.parse(source).getroot()
    if local(root.tag)!='svg':raise ValueError('Not an SVG document')
    if '@import' in ET.tostring(root,encoding='unicode'):
        raise ValueError('CSS imports are not allowed in candidate SVG')
    vectors=0;removed=0
    def check_attrs(node):
        for key,val in node.attrib.items():
            if local(key)=='href' and not val.startswith('#'):
                raise ValueError('External SVG references are not allowed')
            for match in re.finditer(r'url\(\s*[\'\"]?([^\'\")\s]+)',val):
                if not match.group(1).startswith('#'):
                    raise ValueError('External SVG URL is not allowed')
    check_attrs(root)
    def walk(node,in_defs=False):
        nonlocal vectors,removed
        for child in list(node):
            kind=local(child.tag)
            if kind in REMOVE:
                node.remove(child);removed+=1;continue
            if kind=='style' and child.text:
                check_attrs(ET.Element('style',{'content':child.text}))
            check_attrs(child)
            if kind in DRAWABLE and not in_defs:vectors+=1
            walk(child,in_defs or kind=='defs')
    walk(root)
    destination.write_bytes(ET.tostring(root,encoding='utf-8',xml_declaration=True))
    def dimension(key):
        value=root.attrib.get(key,'')
        match=re.fullmatch(r'\s*(\d+(?:\.\d+)?)\s*(?:px)?\s*',value)
        return float(match.group(1)) if match else None
    vb=[float(x) for x in re.split(r'[ ,]+',root.attrib.get('viewBox','').strip()) if x]
    page=dimension('width')==1000 and dimension('height')==1000 and (not vb or (len(vb)==4 and vb==[0,0,1000,1000]))
    return {'vectors':vectors,'removed_raster_or_script':removed,'page_1000':page}

def render(svg,out):
    if shutil.which('inkscape'):
        cmd=['inkscape',str(svg),'--export-type=png','--export-filename='+str(out),'--export-width=1000','--export-height=1000']
        p=subprocess.run(cmd,capture_output=True,text=True,timeout=90)
        if p.returncode or not out.exists():raise RuntimeError('SVG render failed: '+p.stderr[-500:])
    else:
        import cairosvg
        cairosvg.svg2png(url=str(svg),write_to=str(out),output_width=1000,output_height=1000)
    # Inkscape and CairoSVG may leave an unpainted page transparent; the task
    # specifies white paper. Flatten before every reference comparison.
    image=Image.open(out).convert('RGBA')
    paper=Image.new('RGBA',image.size,'white');paper.alpha_composite(image)
    paper.convert('RGB').save(out)

def images(rendered,reference):
    def arr(path):
        im=Image.open(path).convert('RGB').resize((384,384),Image.Resampling.LANCZOS)
        return np.asarray(im,dtype=np.float32)/255
    a,b=arr(rendered),arr(reference)
    ma=(1-a.min(axis=2)>0.035).astype(np.float32)
    mb=(1-b.min(axis=2)>0.035).astype(np.float32)
    def blur(mask,radius):
        img=Image.fromarray(np.uint8(mask*255),'L').filter(ImageFilter.GaussianBlur(radius))
        return np.asarray(img,dtype=np.float32)/255
    geometries=[]
    # Two fixed blur scales give modest placement tolerance for thin lines
    # while missing components still lose foreground overlap.
    for radius in (4,10):
        x,y=blur(ma,radius),blur(mb,radius)
        geometries.append(float(2*np.minimum(x,y).sum()/(x.sum()+y.sum()+1e-9)))
    geometry=sum(geometries)/len(geometries)
    union=np.maximum(ma,mb)
    color_error=float((np.abs(a-b).mean(axis=2)*union).sum()/(union.sum()+1e-9))
    color=max(0,1-color_error/0.42)
    return geometry,color

def compare_export(rendered,submitted):
    if not submitted.exists():return 0.
    try:
        a=Image.open(rendered).convert('RGB').resize((384,384),Image.Resampling.LANCZOS)
        b=Image.open(submitted).convert('RGB')
        if b.size!=(1000,1000):return 0.
        b=b.resize((384,384),Image.Resampling.LANCZOS)
        x=np.asarray(a,dtype=np.float32)/255;y=np.asarray(b,dtype=np.float32)/255
        foreground=np.maximum(1-x.min(axis=2)>0.035,1-y.min(axis=2)>0.035)
        if not foreground.any():return 0.
        mae=float(np.abs(x-y).mean(axis=2)[foreground].mean())
        return max(0.,1-mae/.25)
    except Exception:return 0.

def score(output,oracle,cfg,work):
    reference=oracle/cfg['reference']
    if not reference.exists():raise RuntimeError('Missing oracle SVG reference image: '+str(reference))
    if cfg.get('reference_sha256') and hashlib.sha256(reference.read_bytes()).hexdigest()!=cfg['reference_sha256']:
        raise RuntimeError('Oracle reference image changed after calibration')
    if Image.open(reference).size!=(1000,1000):raise RuntimeError('Oracle reference is not 1000x1000')
    svg=output/'final.svg';png=output/'final.png'
    if not svg.exists():return {k:0. for k in ('geometry','structure','styling','visual','delivery')}, {'reason':'Missing final.svg'}
    clean=work/'candidate-sanitized.svg';rendered=work/'candidate-render.png'
    try:
        native=sanitize(svg,clean)
        if native['vectors']==0:return {k:0. for k in ('geometry','structure','styling','visual','delivery')}, {'reason':'No editable vector objects',**native}
        render(clean,rendered)
        geom,color=images(rendered,reference)
        export=compare_export(rendered,png)
        count=min(1,native['vectors']/cfg['min_vectors'])
        scores={
            'geometry':geom*count,
            'structure':geom*count,
            'styling':color*(geom**.5)*count,
            'visual':(.6*geom+.4*color)*count,
            'delivery':(1. if native['page_1000'] else 0.)*export*count,
        }
        return scores,{'geometry_overlap':geom,'color_similarity':color,'export_match':export,**native}
    except (ET.ParseError,ValueError,OverflowError) as e:
        return {k:0. for k in ('geometry','structure','styling','visual','delivery')},{'reason':str(e)}