"""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<=x4 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'])min(x for x,y in targets)+8 and max(ya['x'],yb['x'])