File size: 6,075 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 | """Rendered table associations and tick-calibrated, genuinely painted scatter plots."""
import json
import math
import os
import re
from collections import Counter
from pathlib import Path
from PIL import Image
from report_values import number
DIRECTORY=Path(os.environ.get('REPORT_REVIEW_DIR','/logs/verifier/report-review'))
def load_report():
return json.loads((DIRECTORY/'rendered.json').read_text())
def numeric(value):
return float(number(str(value)))
def matching_rows(report,aliases):
for table in report['tables']:
for index,row in enumerate(table):
columns=[next((i for i,text in enumerate(row) if any(re.search(pattern,text.lower()) for pattern in choices)),None) for choices in aliases]
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):
wanted={tuple(str(key).strip().lower() for key in row[:key_count]):row[key_count:] for row in expected}
for rows in matching_rows(report,aliases):
try:
parsed={}
for row in rows:
key=tuple(cell.strip().lower() for cell in row[:key_count])
if key not in wanted and key[0] in ('total','合计','总计'): continue
assert key not in parsed, 'duplicate category'
parsed[key]=[numeric(cell) for cell in row[key_count:]]
if set(parsed)==set(wanted) and all(len(parsed[key])==len(values) and all(abs(actual-expected)<=tolerance for actual,expected in zip(parsed[key],values)) for key,values in wanted.items()): return
except (ValueError,AssertionError):
continue
raise AssertionError(f'Visible table values are missing or misassociated: {aliases}')
def ink(image,x,y,radius=4):
"""Inspect actual pixels against the plot's dominant background, including hollow markers."""
width,height=image.size
x,y=int(round(x)),int(round(y)); radius=int(math.ceil(min(radius,24)))
if not 0<=x<width or not 0<=y<height:return False
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(image.getpixel((u,v)),background))>4
for u in range(max(0,x-radius),min(width,x+radius+1))
for v in range(max(0,y-radius),min(height,y+radius+1)))
def tick_fits(texts,axis):
"""Infer scale only from visible numeric axis ticks, not from submitted point positions."""
numeric_texts=[]
for text in texts:
try:numeric_texts.append((text,numeric(text['text'])))
except (ValueError,AssertionError):pass
fits=[]
for a,av in numeric_texts:
for b,bv in numeric_texts:
if bv<=av:continue
aligned=abs(a['y']-b['y'])<8 if axis=='x' else any(abs(a.get(anchor,a['x'])-b.get(anchor,b['x']))<8 for anchor in ('left','right','x'))
if not aligned:continue
for anchor in (('x','left','right') if axis=='x' else ('y',)):
ap=a.get(anchor,a['x']); bp=b.get(anchor,b['x'])
scale=(bp-ap)/(bv-av)
if (axis=='x' and scale<=0) or (axis=='y' and scale>=0) or abs(bp-ap)<50:continue
fits.append((scale,ap-scale*av,min(ap,bp),max(ap,bp),a,b))
return fits
def affine_scatter(report,expected):
expected=list(dict.fromkeys(expected)) # coincident opaque points have identical visible geometry
for plot in report['plots']:
texts=plot['texts']
if not any(re.search(r'carat|克拉',t['text'],re.I) for t in texts):continue
if not any(re.search(r'price|价格',t['text'],re.I) for t in texts):continue
image=Image.open(DIRECTORY/plot['image']).convert('RGB')
# Deduplicate fill+stroke logs without erasing distinct data coordinates.
points=[]
for point in plot['points']:
if ink(image,*point) and not any(math.dist(point[:2],other[:2])<.1 for other in points):points.append(point)
if not len(expected)<=len(points)<=2000:continue
for sx,ox,xlo,xhi,xa,xb in tick_fits(texts,'x'):
for sy,oy,ylo,yhi,ya,yb in tick_fits(texts,'y'):
targets=[(ox+sx*x,oy+sy*y) for x,y in expected]
if max(x for x,y in targets)-min(x for x,y in targets)<50 or max(y for x,y in targets)-min(y for x,y in targets)<50:continue
# X ticks are below the data and y ticks to its left or right.
if min(xa['y'],xb['y'])<max(y for x,y in targets)-8:continue
if min(ya['x'],yb['x'])>min(x for x,y in targets)+8 and max(ya['x'],yb['x'])<max(x for x,y in targets)-8:continue
choices=[[i for i,p in enumerate(points) if math.dist(target,p[:2])<=3] for target in targets]
if any(not options for options in choices):continue
assigned={}
def match(target,seen):
for index in choices[target]:
if index in seen:continue
seen.add(index)
if index not in assigned or match(assigned[index],seen):assigned[index]=target;return True
return False
if not all(match(i,set()) for i in range(len(targets))):continue
# A wrong extra point inside the plotted data region is not a decorative legend.
xlo=min(xlo,min(x for x,y in targets));xhi=max(xhi,max(x for x,y in targets))
ylo=min(ylo,min(y for x,y in targets));yhi=max(yhi,max(y for x,y in targets))
extra=[p for i,p in enumerate(points) if i not in assigned and xlo-3<=p[0]<=xhi+3 and ylo-3<=p[1]<=yhi+3]
if extra:continue
return
raise AssertionError('Painted scatter points do not agree with source data and visible linear axis ticks')
|