Download validator.py from RegalFire/GCC-InvoiceMath-Verified: direct link, hf CLI and curl.
- Browser
- Download file 6.73 kB
-
https://huggingface.co/datasets/RegalFire/GCC-InvoiceMath-Verified/resolve/main/validator.py
- Command line
-
hf download hf://datasets/RegalFire/GCC-InvoiceMath-Verified/validator.py
-
curl -L -o validator.py https://huggingface.co/datasets/RegalFire/GCC-InvoiceMath-Verified/resolve/main/validator.py
6.73 kB
| """Independent rational-arithmetic oracle. Never imports generator code.""" | |
| from __future__ import annotations | |
| import argparse, hashlib, json, re | |
| from fractions import Fraction | |
| from pathlib import Path | |
| from collections import Counter, defaultdict | |
| from jsonschema import Draft202012Validator | |
| SCALES={'SAR':2,'AED':2,'QAR':2,'KWD':3,'BHD':3,'OMR':3} | |
| COUNTRIES={'SAR':'SA','AED':'AE','QAR':'QA','KWD':'KW','BHD':'BH','OMR':'OM'} | |
| FIELDS=('net','tax','gross','due') | |
| def parse(text,style): | |
| """Reject mixed alphabets, malformed grouping, exponent notation and bidi controls.""" | |
| if not isinstance(text,str) or len(text)>80: raise ValueError('invalid number type/length') | |
| arabic='arabic' in style | |
| digits=''.join(chr(0x0660+i) for i in range(10)) if arabic else '0123456789' | |
| dot=chr(0x066B) if arabic else '.'; group=chr(0x066C) if arabic else ',' | |
| integer=rf'[{digits}]{{1,3}}(?:{re.escape(group)}[{digits}]{{3}})*' if 'grouped' in style else rf'[{digits}]+' | |
| pattern=rf'-?{integer}(?:{re.escape(dot)}[{digits}]+)?' | |
| if re.fullmatch(pattern,text) is None: raise ValueError('number violates declared grammar') | |
| # Decode each digit individually rather than sharing generator formatting helpers. | |
| negative=text.startswith('-'); body=text[1:] if negative else text | |
| sides=body.split(dot); whole=sides[0].replace(group,''); tail=sides[1] if len(sides)==2 else '' | |
| n=0 | |
| for ch in whole+tail: n=n*10+digits.index(ch) | |
| return Fraction(-n if negative else n,10**len(tail)) | |
| def rounded_minor(value,scale): | |
| scaled=value*10**scale | |
| a,b=abs(scaled.numerator),scaled.denominator | |
| q,r=divmod(a,b) | |
| return (-1 if scaled<0 else 1)*(q+(2*r>=b)) | |
| def money(n,scale): | |
| sign='-' if n<0 else ''; n=abs(n); div=10**scale | |
| return f'{sign}{n//div}.{n%div:0{scale}d}' | |
| def oracle(invoice): | |
| scale=SCALES[invoice['currency']]; style=invoice['numeric_style']; unit=10**scale | |
| nets=[]; taxes=[] | |
| for line in invoice['lines']: | |
| q,p,a,c,r=[parse(line[k],style) for k in ['quantity','unit_price','allowance','charge','rate']] | |
| if q<=0 or any(x<0 for x in (p,a,c,r)) or r>1: raise ValueError('impossible source line') | |
| raw=q*p-a+c | |
| if raw<0: raise ValueError('negative line net') | |
| net=rounded_minor(raw,scale); nets.append(net) | |
| taxes.append(rounded_minor(Fraction(net,unit)*r,scale)) | |
| net=sum(nets); tax=sum(taxes); gross=net+tax | |
| pre=parse(invoice['prepaid'],style)*unit | |
| if pre.denominator!=1 or pre<0 or pre>gross: raise ValueError('invalid prepaid') | |
| if invoice['document_type']=='credit_note' and pre: raise ValueError('credit prepayment forbidden in this contract') | |
| sign=-1 if invoice['document_type']=='credit_note' else 1 | |
| amounts=dict(net=sign*net,tax=sign*tax,gross=sign*gross,due=sign*(gross-int(pre))) | |
| expected={k:money(v,scale) for k,v in amounts.items()} | |
| errors=[] | |
| for k in FIELDS: | |
| obs=parse(invoice['claimed_totals'][k],style)*unit | |
| if obs.denominator!=1 or obs!=amounts[k]: errors.append(k) | |
| return dict(valid=not errors,totals=expected,error_fields=errors) | |
| def canonical(x): return json.dumps(x,sort_keys=True,separators=(',',':'),ensure_ascii=False) | |
| def sha(x): return hashlib.sha256(canonical(x).encode()).hexdigest() | |
| def validate(rows,schema): | |
| checker=Draft202012Validator(schema); ids=set(); content=set(); pairs=defaultdict(list); evidence=[] | |
| for row in rows: | |
| checker.validate(row) | |
| if row['id'] in ids: raise ValueError('duplicate ID') | |
| ids.add(row['id']) | |
| d=sha(row['invoice']) | |
| if d in content: raise ValueError('duplicate invoice') | |
| content.add(d) | |
| if row['id']!=d[:32]: raise ValueError('id mismatch') | |
| body={k:v for k,v in row.items() if k!='fingerprint_sha256'} | |
| if sha(body)!=row['fingerprint_sha256']: raise ValueError('fingerprint mismatch') | |
| if row['country']!=COUNTRIES[row['invoice']['currency']]: raise ValueError('currency-country mismatch') | |
| computed=oracle(row['invoice']) | |
| if computed!=row['expected']: raise ValueError(f'oracle disagreement {row["id"]}') | |
| if row['provenance']['copied_records']!=0 or not row['provenance']['synthetic']: raise ValueError('provenance mismatch') | |
| pairs[row['pair_id']].append(row) | |
| evidence.append(dict(id=row['id'],independent_oracle=computed,fingerprint_sha256=row['fingerprint_sha256'],pass_all=True)) | |
| # Validate pairing and leakage at semantic input level, beyond IDs. | |
| base_hashes=set() | |
| for pair_id,pair in pairs.items(): | |
| if len(pair)!=2 or sum(x['expected']['valid'] for x in pair)!=1: raise ValueError('pair label/count failure') | |
| a,b=sorted(pair,key=lambda x:not x['expected']['valid']) | |
| if a['split']!=b['split']: raise ValueError('split leakage') | |
| src_a={k:v for k,v in a['invoice'].items() if k!='claimed_totals'} | |
| src_b={k:v for k,v in b['invoice'].items() if k!='claimed_totals'} | |
| if src_a!=src_b or sha(src_a)[:24]!=pair_id: raise ValueError('pair inputs differ') | |
| changes=[k for k in FIELDS if a['invoice']['claimed_totals'][k]!=b['invoice']['claimed_totals'][k]] | |
| if changes!=b['expected']['error_fields'] or len(changes)!=1: raise ValueError('not a causal single-field mutation') | |
| field=changes[0]; style=a['invoice']['numeric_style']; scale=SCALES[a['invoice']['currency']] | |
| delta=parse(b['invoice']['claimed_totals'][field],style)-parse(a['invoice']['claimed_totals'][field],style) | |
| if abs(delta)!=Fraction(1,10**scale): raise ValueError('incorrect mutation delta') | |
| if b['mutation']['path']!='claimed_totals.'+field or parse(b['mutation']['delta'],'ascii')!=delta: raise ValueError('mutation trace mismatch') | |
| if a['mutation'] is not None: raise ValueError('valid record has mutation') | |
| semantic=src_a.copy(); semantic.pop('numeric_style') | |
| semantic['lines']=[{k:str(parse(v,style)) for k,v in l.items()} for l in semantic['lines']] | |
| semantic['prepaid']=str(parse(semantic['prepaid'],style)) | |
| normalized=sha(semantic) | |
| if normalized in base_hashes: raise ValueError('semantic duplicate source') | |
| base_hashes.add(normalized) | |
| return evidence | |
| if __name__=='__main__': | |
| p=argparse.ArgumentParser(); p.add_argument('dataset',type=Path); p.add_argument('--schema',type=Path,required=True); p.add_argument('--log',type=Path) | |
| a=p.parse_args(); rows=[json.loads(x) for x in a.dataset.read_text(encoding='utf-8').splitlines()] | |
| log=validate(rows,json.loads(a.schema.read_text(encoding='utf-8'))) | |
| if a.log: a.log.write_text(''.join(canonical(r)+'\n' for r in log),encoding='utf-8') | |
| print(json.dumps(dict(validated=len(log),status='PASS'))) | |