Download task_027/tests/report_contract.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 6.08 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_027/tests/report_contract.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_027/tests/report_contract.py
-
curl -L -o report_contract.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_027/tests/report_contract.py
6.08 kB
| """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') | |