File size: 12,654 Bytes
7ec48b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference-bound regional structure checks; no SVG element-count requirements.

Regions are human-labelled against the retained reference, then mapped to the
actual canonical SVG render's foreground bounding box. They describe visible
roles, not DOM identities. Raster checks cannot prove electrical/mechanical
function or recover hidden geometry. Exact label recognition is not claimed.
"""
from pathlib import Path
import hashlib
import json
import math
import numpy as np
from PIL import Image, ImageFilter, ImageDraw

# Coordinates measured on the supplied 1000-square reference PNGs. Every ROI is
# rebound to the canonical reference render's foreground box by build_manifest.
ANNOTATIONS = {
 'rosette': [('central junction',(.46,.46,.54,.54)),('upper petal',(.43,.16,.57,.44)),('lower petal',(.43,.56,.57,.84))],
 'hierarchy': [('leaf '+s,(x-.055,.175,x+.055,.265)) for s,x in zip('abcdef',[.15,.29,.43,.57,.71,.85])] + [('bc merge',(.31,.315,.415,.405)),('de merge',(.59,.315,.70,.405)),('def merge',(.59,.46,.70,.55)),('bcdef merge',(.285,.60,.445,.68)),('root abcdef',(.13,.735,.33,.815))],
 'rlc-circuit': [('resistor zigzag',(.35,.28,.51,.37)),('capacitor plates',(.58,.47,.73,.55)),('inductor coils',(.80,.43,.855,.565)),('voltage source plates',(.10,.49,.29,.55)),('R label',(.335,.38,.39,.445)),('C label',(.505,.48,.565,.57)),('L label',(.86,.47,.905,.545)),('V label',(.28,.525,.335,.59))],
 'four-bar': [('drag-link mechanism',(.17,.397,.35,.526)),('crank-rocker mechanism',(.36,.395,.575,.525)),('double-rocker mechanism',(.595,.40,.735,.525)),('parallelogram mechanism',(.755,.465,.90,.525)),('four captions',(.21,.545,.90,.605)),('rotation guide',(.10,.40,.30,.56))],
 'gear': [('central bore',(.39,.33,.61,.43)),('top face inner ring',(.25,.225,.75,.50)),('upper tooth lobes',(.29,.145,.72,.24)),('left tooth contour',(.10,.28,.24,.61)),('right tooth contour',(.76,.29,.90,.62)),('front extrusion',(.28,.575,.72,.845))],
 'bicycle': [('rear wheel',(.22,.45,.43,.675)),('front wheel',(.585,.45,.805,.675)),('frame triangle',(.36,.40,.63,.565)),('handlebar and fork',(.59,.31,.70,.56)),('saddle',(.35,.32,.455,.365)),('crank drivetrain',(.435,.53,.555,.61)),('rear drivetrain',(.305,.56,.41,.64)),('part labels left',(.13,.345,.27,.715)),('part labels right',(.77,.51,.90,.64)),('part labels upper',(.495,.28,.83,.40))],
 'isometric-house': [('roof left slope',(.20,.15,.52,.41)),('roof middle slope',(.45,.31,.65,.52)),('roof right slope',(.66,.44,.82,.58)),('front wall',(.145,.34,.44,.64)),('right facade',(.65,.60,.85,.82)),('entrance',(.30,.67,.41,.80)),('left dormer',(.24,.23,.31,.305)),('middle dormer',(.38,.33,.45,.40)),('right dormer',(.56,.43,.64,.515))],
 'floor-plan': [('green side room',(.105,.47,.21,.64)),('yellow main room',(.21,.47,.69,.74)),('pink right room',(.69,.47,.90,.74)),('blue upper room',(.695,.26,.90,.47)),('toilet symbol',(.153,.56,.194,.62)),('central magenta fixture',(.37,.57,.455,.633)),('right L fixture',(.645,.54,.76,.735)),('orange right fixture',(.82,.61,.875,.735)),('upper fixtures',(.69,.26,.785,.455)),('north wall opening',(.85,.25,.885,.28)),('bottom door gap',(.27,.725,.37,.75))],
 'flowchart': [('start circle',(.421,.10,.504,.184))] + [('process '+str(i),(.40,y,.525,y+.055)) for i,y in enumerate([.209,.285,.362,.44,.846],1)] + [('decision '+str(i),(.41,y,.515,y+.09)) for i,y in enumerate([.515,.625,.738],1)] + [('left branch process',(.263,.533,.388,.587)),('right branch process',(.611,.533,.734,.587)),('right second process',(.611,.61,.734,.664)),('right end circle',(.625,.688,.713,.781))],
}
# Connections checked along their visible middle, away from labels/nodes. Paths
# represent pixel-supported strokes, not a claim that the SVG is a semantic graph.
CONNECTIONS = {
 'hierarchy': [('b to bc',[(.31,.266),(.35,.318)]),('c to bc',[(.411,.26),(.387,.316)]),('d to de',[(.59,.265),(.618,.315)]),('e to de',[(.69,.26),(.66,.32)]),('de to def',[(.64,.402),(.64,.461)]),('f to def',[(.825,.259),(.674,.473)]),('bc to bcdef',[(.36,.408),(.36,.598)]),('def to bcdef',[(.59,.52),(.427,.61)]),('a to root',[(.157,.266),(.220,.73)]),('bcdef to root',[(.323,.675),(.266,.739)])],
 'rlc-circuit': [('top left wire',[(.20,.36),(.20,.475)]),('top resistor lead',[(.24,.329),(.342,.329)]),('upper right bus',[(.52,.329),(.813,.329)]),('capacitor upper lead',[(.656,.35),(.656,.475)]),('capacitor lower lead',[(.656,.56),(.656,.69)]),('bottom bus',[(.22,.704),(.811,.704)]),('right lower lead',[(.828,.59),(.828,.69)]),('source lower lead',[(.20,.555),(.20,.69)])],
 'flowchart': [('main stem '+str(i),[(.462,y0),(.462,y1)]) for i,(y0,y1) in enumerate([(.186,.206),(.264,.284),(.34,.36),(.415,.438),(.49,.513),(.600,.625),(.715,.738),(.825,.846)],1)] + [('right branch',[(.514,.559),(.61,.559)]),('right continuation',[(.674,.589),(.674,.61)]),('right end connector',[(.673,.666),(.673,.689)]),('left decision branch',[(.414,.669),(.322,.669),(.322,.590)]),('left lower branch',[(.415,.780),(.322,.780),(.322,.67)])],
}

def rgb(value):
 if isinstance(value,(str,Path)):
  im=Image.open(value).convert('RGBA'); bg=Image.new('RGBA',im.size,'white');bg.alpha_composite(im);return np.asarray(bg.convert('RGB'))
 return np.asarray(value,dtype=np.uint8)[...,:3]

def foreground(a): return a.min(axis=2)<242

def bbox(a):
 y,x=np.where(foreground(a))
 if not len(x): raise ValueError('Reference has no visible foreground')
 return [int(x.min()),int(y.min()),int(x.max()+1),int(y.max()+1)]

def _map_point(p,old,new):
 return [new[0]+(p[0]*1000-old[0])/(old[2]-old[0])*(new[2]-new[0]),new[1]+(p[1]*1000-old[1])/(old[3]-old[1])*(new[3]-new[1])]


def _component_boxes(mask,min_area):
 seen=np.zeros_like(mask,dtype=bool);boxes=[];h,w=mask.shape
 for y,x in zip(*np.where(mask)):
  if seen[y,x]:continue
  stack=[(int(y),int(x))];seen[y,x]=True;pts=[]
  while stack:
   yy,xx=stack.pop();pts.append((yy,xx))
   for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
    cy,cx=yy+dy,xx+dx
    if 0<=cy<h and 0<=cx<w and mask[cy,cx] and not seen[cy,cx]:seen[cy,cx]=True;stack.append((cy,cx))
  if len(pts)>=min_area:
   ys,xs=zip(*pts);boxes.append([min(xs),min(ys),max(xs)+1,max(ys)+1])
 return sorted(boxes,key=lambda b:(b[1],b[0]))

def build_manifest(slug,reference_svg,reference_render):
 if slug not in ANNOTATIONS: raise ValueError('Unknown SVG reproduction task '+slug)
 ref=rgb(reference_render); targetbox=bbox(ref)
 # Original annotations use the supplied PNG's figure bounding box, not its XML.
 original=Path(reference_svg).with_name('reference.png')
 if not original.exists(): raise ValueError('Adjacent original reference.png required for annotation mapping')
 oldbox=bbox(rgb(original)); regions=[]
 for name,r in ANNOTATIONS[slug]:
  a=_map_point(r[:2],oldbox,targetbox);b=_map_point(r[2:],oldbox,targetbox)
  regions.append({'name':name,'box':[round(v,4) for v in a+b],'method':'local_edge_profile'})
 if slug=='isometric-house':
  # Dark blue glazing is used only to locate the reference's visible features.
  # Candidate scoring then uses boundary geometry, accepting different SVG code
  # and different colours without counting DOM nodes.
  navy=(ref[:,:,2].astype(int)-ref[:,:,0]>10)&(ref[:,:,1].astype(int)-ref[:,:,0]>8)&(ref.mean(axis=2)<125)
  for i,box in enumerate(_component_boxes(navy,min_area=100),1):
   regions.append({'name':'glazing region '+str(i),'box':[max(0,box[0]-5),max(0,box[1]-5),min(ref.shape[1],box[2]+5),min(ref.shape[0],box[3]+5)],'method':'local_edge_profile','grounding':'Connected navy area in reference only; not a candidate object-count requirement.'})
 paths=[{'name':name,'points':[_map_point(p,oldbox,targetbox) for p in points],'method':'visible_stroke_support'} for name,points in CONNECTIONS.get(slug,[])]
 return {'schema':'svg-structure-v1','task':slug,'source_sha256':hashlib.sha256(Path(reference_svg).read_bytes()).hexdigest(),'reference_sha256':hashlib.sha256(Path(reference_render).read_bytes()).hexdigest(),'render_size':[ref.shape[1],ref.shape[0]],'reference_foreground_bbox':targetbox,'regions':regions,'connections':paths,'symmetry':{'order':6,'center':[(targetbox[0]+targetbox[2])/2,(targetbox[1]+targetbox[3])/2],'radius':min(targetbox[2]-targetbox[0],targetbox[3]-targetbox[1])/2} if slug=='rosette' else None,'limits':['Checks visible regional boundaries and connection stroke support; does not infer hidden topology, functional mechanics or exact text transcription.','Structure is an independent regional allocation; it does not multiply other grade categories.','No SVG object-count gate.']}

def _edges(a):
 # Smooth away texture and antialiasing, leaving shape/color-region boundaries.
 im=Image.fromarray(a).filter(ImageFilter.GaussianBlur(3))
 f=np.asarray(im,dtype=np.float32);out=np.zeros(f.shape[:2],np.float32)
 out[:,1:]=np.maximum(out[:,1:],np.max(np.abs(f[:,1:]-f[:,:-1]),axis=2))
 out[1:]=np.maximum(out[1:],np.max(np.abs(f[1:]-f[:-1]),axis=2))
 return np.minimum(np.maximum(out-3,0)/8,1)

def _profile(a,box):
 x0,y0,x1,y1=box;x0=max(0,int(x0));y0=max(0,int(y0));x1=min(a.shape[1],int(math.ceil(x1)));y1=min(a.shape[0],int(math.ceil(y1)))
 if x1<=x0 or y1<=y0:return np.zeros(64)
 crop=a[y0:y1,x0:x1]; out=[]
 for yy in np.array_split(crop,8,axis=0):
  for cell in np.array_split(yy,8,axis=1):out.append(float(cell.mean()) if cell.size else 0)
 return np.asarray(out)

def _ratio(c,r):
 if r.sum()<1e-5:return 1. if c.sum()<1e-5 else 0.
 # Symmetric regional edge-mass similarity; extra boundaries are penalized.
 return float(2*np.minimum(c,r).sum()/(c.sum()+r.sum()+1e-12))

def _stroke_support(mask,points):
 vals=[];h,w=mask.shape
 for p,q in zip(points,points[1:]):
  n=max(2,int(math.hypot(q[0]-p[0],q[1]-p[1])/2))
  for t in np.linspace(0,1,n):
   x=int(round(p[0]*(1-t)+q[0]*t));y=int(round(p[1]*(1-t)+q[1]*t));r=4
   win=mask[max(0,y-r):min(h,y+r+1),max(0,x-r):min(w,x+r+1)]
   vals.append(float(win.any()) if win.size else 0.)
 return float(np.mean(vals)) if vals else 0.

def _polar(a,center,radius):
 # Compare six sector occupancy signatures to reference; filling white gaps,
 # losing a petal or making an asymmetric flower changes these signatures.
 h,w=a.shape;angles=np.linspace(0,2*math.pi,720,endpoint=False);radii=np.linspace(.06,.94,60)*radius
 xx=np.rint(center[0]+np.cos(angles)[:,None]*radii).astype(int);yy=np.rint(center[1]+np.sin(angles)[:,None]*radii).astype(int)
 xx=np.clip(xx,0,w-1);yy=np.clip(yy,0,h-1);return a[yy,xx].astype(float)

def structure(candidateRGB,referenceRGB,manifest):
 c=rgb(candidateRGB);r=rgb(referenceRGB)
 if c.shape!=r.shape or list(c.shape[:2][::-1])!=manifest['render_size']:raise ValueError('Canonical render dimensions differ')
 ce,re=_edges(c),_edges(r);regions=[]
 for item in manifest['regions']:
  a,b=_profile(ce,item['box']),_profile(re,item['box']);s=_ratio(a,b)
  regions.append({'name':item['name'],'score':s,'candidate_edge_mass':float(a.sum()),'reference_edge_mass':float(b.sum()),'box':item['box']})
 connections=[];cf,rf=foreground(c),foreground(r)
 for item in manifest['connections']:
  a,b=_stroke_support(ce>0,item['points']),_stroke_support(re>0,item['points'])
  # Only positions actually grounded by the reference contribute.
  connections.append({'name':item['name'],'score':min(1.,a/max(b,.001)) if b>=.5 else None,'candidate_support':a,'reference_support':b,'points':item['points']})
 parts=[float(np.mean([x['score'] for x in regions]))]
 active=[x['score'] for x in connections if x['score'] is not None]
 if active:parts.append(float(np.mean(active)))
 symmetry=None
 if manifest.get('symmetry'):
  spec=manifest['symmetry'];cp=_polar(cf,spec['center'],spec['radius']);rp=_polar(rf,spec['center'],spec['radius'])
  sector_scores=[float(1-np.abs(a-b).mean()) for a,b in zip(np.split(cp,6),np.split(rp,6))]
  symmetry={'sector_scores':sector_scores,'reference_sector_match':float(np.mean(sector_scores)),'candidate_rotation_agreement':float(1-np.abs(cp-np.roll(cp,120,axis=0)).mean()),'reference_rotation_agreement':float(1-np.abs(rp-np.roll(rp,120,axis=0)).mean())}
  # Joint positive and negative space comparison; symmetry alone cannot pass a disk.
  parts.append(symmetry['reference_sector_match'])
 return float(np.mean(parts)),{'method':'reference_bound_regional_structure','regions':regions,'connections':connections,'symmetry':symmetry,'limits':manifest['limits']}

def save_overlay(reference_render,manifest,path):
 im=Image.fromarray(rgb(reference_render));d=ImageDraw.Draw(im)
 for r in manifest['regions']:
  d.rectangle(r['box'],outline='#f000c0',width=2);d.text((r['box'][0],r['box'][1]),r['name'],fill='#b00090')
 for p in manifest['connections']:d.line([tuple(q) for q in p['points']],fill='red',width=2)
 im.save(path)