File size: 8,932 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Visible report semantics and shape-independent affine scatter checks."""
import json
import math
import os
import re
from collections import Counter
from pathlib import Path
from PIL import Image

DIRECTORY = Path(os.environ.get('REPORT_AUDIT_DIR', '/logs/verifier/report-review'))


def load_report():
    return json.loads((DIRECTORY / 'rendered.json').read_text())


def numeric(value):
    value = str(value).strip().replace('\u00a0', '').replace('\u202f', '').replace(',', '')
    percent = value.endswith('%')
    value = re.sub(r'^[¥¥$]\s*', '', value).removesuffix('%').strip()
    number = float(value)
    assert math.isfinite(number), f'nonfinite report value {value}'
    return number / 100 if percent else number


def matching_rows(report, aliases):
    for table in report['tables']:
        for index, row in enumerate(table):
            columns = []
            for choices in aliases:
                columns.append(next((i for i, text in enumerate(row)
                                     if any(re.search(pattern, text.lower()) for pattern in choices)), None))
            if None not in columns and len(set(columns)) == len(columns):
                yield [[row[i] for i in columns] for row in table[index+1:] if len(row)>max(columns)]
                break


def assert_rows(report, aliases, expected, key_count=1, tolerance=.0051, allow_extra=False):
    """Require correctly associated visible rows; table IDs and column order are free."""
    for rows in matching_rows(report, aliases):
        if len(rows) < len(expected) or (not allow_extra and len(rows) != len(expected)):
            continue
        try:
            parsed = {}
            for row in rows:
                key=tuple(format(float(cell), '.12g') if re.fullmatch(r'[+-]?\d+(?:\.\d+)?',cell.strip()) else cell.strip().lower() for cell in row[:key_count])
                assert key not in parsed
                parsed[key]=[numeric(cell) for cell in row[key_count:]]
            wanted={tuple(str(k).lower() for k in row[:key_count]):row[key_count:] for row in expected}
            keys_match=set(wanted)<=set(parsed) if allow_extra else set(parsed)==set(wanted)
            if keys_match and all(len(parsed[k])==len(values) and all(abs(a-b)<=tolerance for a,b in zip(parsed[k],values)) for k,values in wanted.items()):
                return
        except (ValueError,AssertionError):
            continue
    raise AssertionError(f'Missing or misassociated visible report rows: {aliases}; expected={expected}')


def ink(image, x, y, radius=4):
    """A reported geometry location must have actual non-background pixels."""
    w,h=image.size
    x,y=int(round(x)),int(round(y))
    if not (0<=x<w and 0<=y<h): return False
    colors=[image.getpixel((u,v)) for u in range(max(0,x-radius),min(w,x+radius+1))
            for v in range(max(0,y-radius),min(h,y+radius+1))]
    if 'audit_background' not in image.info:
        image.info['audit_background']=Counter(image.resize((100,100)).getdata()).most_common(1)[0][0]
    background=image.info['audit_background']
    return any(max(abs(a-b) for a,b in zip(c,background))>4 for c in colors)


def affine_scatter(report, expected, trend=None):
    """Accept SVG and Canvas, arbitrary translation/scale, point shapes and ordering."""
    a=min(expected,key=lambda p:p[0]); b=max(expected,key=lambda p:p[0])
    assert a[0]!=b[0] and a[1]!=b[1], 'fixture requires separated affine anchors'
    for plot in report['plots']:
        labels={t['text'].strip().lower() for t in plot['texts']}
        if not {'rm','medv'} <= labels: continue
        image=Image.open(DIRECTORY/plot['image']).convert('RGB')
        points=[p for p in plot['points'] if ink(image,*p, radius=12)]
        if len(points)<len(expected) or len(points)>2000: continue
        for p in points:
            for q in points:
                sx=(q[0]-p[0])/(b[0]-a[0]); sy=(q[1]-p[1])/(b[1]-a[1])
                if sx<=0 or sy>=0 or q[0]-p[0]<50 or abs(sy)*(max(y for _,y in expected)-min(y for _,y in expected))<50: continue
                ox=p[0]-sx*a[0]; oy=p[1]-sy*a[1]
                targets=[(ox+sx*x,oy+sy*y) for x,y in expected]
                choices=[[i for i,(u,v) in enumerate(points) if math.hypot(x-u,y-v)<=3] for x,y in targets]
                if any(not options for options in choices): continue
                assigned={}
                def match(target,seen):
                    for i in choices[target]:
                        if i in seen: continue
                        seen.add(i)
                        if i not in assigned or match(assigned[i],seen):
                            assigned[i]=target;return True
                    return False
                if not all(match(i,set()) for i in range(len(targets))): continue
                # Extra in-plot observations (including the filtered outlier) are not data.
                if any(i not in assigned for i in range(len(points))): continue
                if not calibrated_axes(plot, sx, sy, ox, oy, expected): continue
                if trend:
                    slope,intercept=trend
                    def line_ok(line):
                        x,y,u,v=line
                        if abs(u-x)<.7*(q[0]-p[0]): return False
                        target_y=lambda xx: oy+sy*(slope*((xx-ox)/sx)+intercept)
                        painted=all(ink(image,x+(u-x)*fraction,y+(v-y)*fraction,2) for fraction in (.05,.15,.25,.35,.45,.55,.65,.75,.85,.95))
                        return abs(y-target_y(x))<=3 and abs(v-target_y(u))<=3 and painted
                    if not any(line_ok(line) for line in plot['lines']): continue
                return
    raise AssertionError('Rendered scatter/trend geometry does not match independently recomputed data')


def calibrated_axes(plot, sx, sy, ox, oy, expected):
    """Bind the inferred data map to visible numeric ticks, not arbitrary geometry."""
    left=ox+sx*min(x for x,_ in expected)
    bottom=oy+sy*min(y for _,y in expected)
    ticks={'x':[], 'y':[]}
    for text in plot['texts']:
        try:
            value=numeric(text['text'])
        except (ValueError, AssertionError):
            continue
        if text['y']>bottom and abs(text['x']-(ox+sx*value))<=4:
            ticks['x'].append(value)
        if text['x']<left and abs(text['y']-(oy+sy*value))<=4:
            ticks['y'].append(value)
    return all(len(set(values))>=2 for values in ticks.values())


def survival_bars(report,rates):
    for plot in report['plots']:
        texts=plot['texts']; bars=plot['bars']
        if not bars: continue
        maximum=max(b['height'] for b in bars)
        if maximum<30: continue
        image=Image.open(DIRECTORY/plot['image']).convert('RGB')
        left=min(b['x']-b['width']/2 for b in bars)
        categories={str(value).lower() for key in rates for value in key}
        label_positions=[text['x'] for text in texts if categories & set(re.findall(r'\w+',text['text'].lower()))]
        if label_positions: left=min(left,min(label_positions))
        ticks={}
        for text in texts:
            if text['x']>=left: continue
            try:
                value=numeric(text['text'])
            except (ValueError, AssertionError):
                continue
            if value in (0,1): ticks[value]=text['y']
        if set(ticks)!={0,1} or ticks[0]-ticks[1]<30: continue
        scale=ticks[0]-ticks[1]
        success=True
        for (sex,category),rate in rates.items():
            labels=[t for t in texts if t['y']>ticks[0] and sex.lower() in re.findall(r'\w+',t['text'].lower()) and category.lower() in re.findall(r'\w+',t['text'].lower())]
            if not labels:
                sex_labels=[t for t in texts if sex.lower() in re.findall(r'\w+',t['text'].lower()) and t['y']>ticks[0]]
                class_labels=[t for t in texts if category.lower() in re.findall(r'\w+',t['text'].lower()) and t['y']>ticks[0]]
                labels=[a for a in sex_labels if any(abs(a['x']-b['x'])<=6 and abs(a['y']-b['y'])<=40 for b in class_labels)]
            if not labels: success=False;break
            label=labels[0]
            nearby=[b for b in bars if abs(b['x']-label['x'])<max(6,b['width']/2)]
            if rate==0:
                if any(b['height']>2 for b in nearby): success=False;break
            elif not any(abs(b['height']-rate*scale)<=3 and abs(b['y']+b['height']-ticks[0])<=4 and visible_bar(image,b) for b in nearby):
                success=False;break
        if success: return
    raise AssertionError('Visible sex/class labels and bar heights do not match survival rates')


def visible_bar(image, bar):
    """Check painted height at multiple levels, allowing filled and outlined bars."""
    return all(any(ink(image,bar['x']+offset,bar['y']+bar['height']*fraction,1)
                   for offset in (-bar['width']/2+1,0,bar['width']/2-1))
               for fraction in (.1,.25,.5,.75,.9))