Download generator.py from RegalFire/GCC-InvoiceMath-Verified: direct link, hf CLI and curl.
- Browser
- Download file 6.91 kB
-
https://huggingface.co/datasets/RegalFire/GCC-InvoiceMath-Verified/resolve/main/generator.py
- Command line
-
hf download hf://datasets/RegalFire/GCC-InvoiceMath-Verified/generator.py
-
curl -L -o generator.py https://huggingface.co/datasets/RegalFire/GCC-InvoiceMath-Verified/resolve/main/generator.py
6.91 kB
| """Original procedural invoice arithmetic fixtures. Python >=3.11, standard library.""" | |
| from __future__ import annotations | |
| import argparse, copy, hashlib, json, random | |
| from decimal import Decimal, ROUND_HALF_UP, localcontext | |
| from pathlib import Path | |
| PROFILES = [('SA','SAR',2),('AE','AED',2),('QA','QAR',2),('KW','KWD',3),('BH','BHD',3),('OM','OMR',3)] | |
| FAMILIES = ['half_up_tie','line_vs_document_rounding','line_allowance','line_charge','prepayment','credit_note','large_amount_stress','zero_rate','mixed_rates','zero_due'] | |
| STYLES = ['ascii','arabic_indic','grouped_ascii','grouped_arabic_indic'] | |
| SOURCES = ['https://zatca.gov.sa/en/E-Invoicing/Introduction/LawsAndRegulations/Pages/default.aspx','https://mof.gov.ae/en/about-us/initiatives/einvoicing/','https://www.six-group.com/en/products-services/financial-information/market-reference-data/data-standards.html','https://arxiv.org/abs/2602.18776'] | |
| def canonical(x): return json.dumps(x,sort_keys=True,separators=(',',':'),ensure_ascii=False) | |
| def digest(x): return hashlib.sha256(canonical(x).encode()).hexdigest() | |
| def fmt(x,scale): return format(x,f'.{scale}f') | |
| def render(s,style): | |
| sign = '' | |
| if s.startswith('-'): | |
| sign = '-' | |
| s = s[1:] | |
| if 'grouped' in style: | |
| whole, sep, frac = s.partition('.') | |
| whole = f'{int(whole):,}' | |
| s = whole + (sep + frac if sep else '') | |
| s = sign + s | |
| if 'arabic' in style: | |
| trans = str.maketrans({ | |
| '0': chr(0x0660), '1': chr(0x0661), '2': chr(0x0662), | |
| '3': chr(0x0663), '4': chr(0x0664), '5': chr(0x0665), | |
| '6': chr(0x0666), '7': chr(0x0667), '8': chr(0x0668), | |
| '9': chr(0x0669), '.': chr(0x066B), ',': chr(0x066C) | |
| }) | |
| s = s.translate(trans) | |
| return s | |
| def calculate(lines,prepaid,scale,credit=False): | |
| """Generator oracle uses Decimal; validator must not import this function.""" | |
| step=Decimal(1).scaleb(-scale) | |
| nets=[(l['quantity']*l['unit_price']-l['allowance']+l['charge']).quantize(step,rounding=ROUND_HALF_UP) for l in lines] | |
| taxes=[(n*l['rate']).quantize(step,rounding=ROUND_HALF_UP) for n,l in zip(nets,lines)] | |
| net=sum(nets,Decimal(0)); tax=sum(taxes,Decimal(0)); gross=net+tax | |
| sign=-1 if credit else 1 | |
| return {k:fmt(v*sign,scale) for k,v in dict(net=net,tax=tax,gross=gross,due=gross-prepaid).items()} | |
| def make_pair(currency_index,family_index,variation,seed): | |
| country,currency,scale=PROFILES[currency_index] | |
| family=FAMILIES[family_index] | |
| unit=Decimal(1).scaleb(-scale) | |
| local_seed=seed+currency_index*100000+family_index*1000+variation | |
| rng=random.Random(local_seed) | |
| lines=[dict(quantity=Decimal(rng.randint(1,9)),unit_price=Decimal(rng.randint(100000,900000))/1000,allowance=Decimal(0),charge=Decimal(0),rate=Decimal('0.05')) for _ in range(rng.randint(2,5))] | |
| if family in ('half_up_tie','line_vs_document_rounding'): | |
| # Even minor-unit base distinguishes half-up from ties-to-even. | |
| lines=[dict(quantity=Decimal(1),unit_price=Decimal(rng.randrange(10000,90000,2))*unit+unit/2,allowance=Decimal(0),charge=Decimal(0),rate=Decimal(0)) for _ in range(2 if family=='line_vs_document_rounding' else 1)] | |
| if family=='line_allowance': | |
| for l in lines: l['allowance']=Decimal(rng.randint(1,900))*unit | |
| if family=='line_charge': | |
| for l in lines: l['charge']=Decimal(rng.randint(1,900))*unit | |
| if family=='large_amount_stress': | |
| lines[0]['unit_price']=Decimal(10**14+rng.randint(100,99999))+Decimal(7)*unit | |
| if family=='zero_rate': | |
| for l in lines: l['rate']=Decimal(0) | |
| if family=='mixed_rates': | |
| for i,l in enumerate(lines): l['rate']=[Decimal(0),Decimal('.05'),Decimal('.15')][i%3] | |
| prepaid=Decimal(0) | |
| totals=calculate(lines,prepaid,scale,False) | |
| if family=='prepayment': prepaid=(Decimal(totals['gross'])/3).quantize(unit,rounding=ROUND_HALF_UP) | |
| if family=='zero_due': prepaid=Decimal(totals['gross']) | |
| totals=calculate(lines,prepaid,scale,family=='credit_note') | |
| style=STYLES[(currency_index*50+family_index*5+variation)%4] | |
| invoice=dict(currency=currency,document_type='credit_note' if family=='credit_note' else 'invoice',numeric_style=style, | |
| lines=[{k:render(fmt(v,scale+3 if k=='unit_price' else scale if k in ('allowance','charge') else 2),style) for k,v in l.items()} for l in lines], | |
| prepaid=render(fmt(prepaid,scale),style)) | |
| pair_id=digest(invoice)[:24] | |
| split='train' if variation<3 else 'validation' if variation==3 else 'test' | |
| field=['net','tax','gross','due'][(currency_index+family_index+variation)%4] | |
| # Signed, one-minor-unit mutation. Both directions occur within each slice. | |
| bad=copy.deepcopy(totals) | |
| delta=unit * (-1 if (currency_index+variation)%2 else 1) | |
| bad[field]=fmt(Decimal(bad[field])+delta,scale) | |
| pair=[] | |
| for claimed,valid in [(totals,True),(bad,False)]: | |
| candidate=copy.deepcopy(invoice) | |
| candidate['claimed_totals']={k:render(v,style) for k,v in claimed.items()} | |
| record=dict(id=digest(candidate)[:32],pair_id=pair_id,seed=local_seed,split=split,country=country,family=family, | |
| contract_id='gcc-invoice-math-1.0',invoice=candidate, | |
| expected=dict(valid=valid,totals=totals,error_fields=[] if valid else [field]), | |
| provenance=dict(synthetic=True,external_sources_used_for_research=SOURCES,copied_records=0,generation_method='procedural Decimal oracle plus single claimed-total perturbation',license_reviewed=True,license_review_scope='Original code and fixtures; no external records/code reused. Not a legal opinion.',model=None), | |
| mutation=None if valid else dict( | |
| path='claimed_totals.'+field, | |
| delta=fmt( | |
| Decimal(claimed[field]) - Decimal(totals[field]), | |
| scale | |
| ), | |
| single_change=True | |
| )) | |
| record['fingerprint_sha256']=digest(record) | |
| pair.append(record) | |
| return pair | |
| def generate(seed=20260930,variations=5): | |
| if variations!=5: raise ValueError('v1 pilot is fixed at five parameter variants per currency/family; custom scaling requires new QA') | |
| with localcontext() as ctx: | |
| ctx.prec=50 | |
| rows=[r for c in range(6) for f in range(10) for v in range(variations) for r in make_pair(c,f,v,seed)] | |
| return sorted(rows,key=lambda x:x['id']) | |
| def write_jsonl(path,rows): | |
| Path(path).write_text(''.join(canonical(r)+'\n' for r in rows),encoding='utf-8',newline='\n') | |
| if __name__=='__main__': | |
| p=argparse.ArgumentParser(); p.add_argument('--output',type=Path,required=True); p.add_argument('--seed',type=int,default=20260930) | |
| a=p.parse_args(); a.output.parent.mkdir(parents=True,exist_ok=True); rows=generate(a.seed); write_jsonl(a.output,rows) | |
| print(json.dumps(dict(records=len(rows),sha256=hashlib.sha256(a.output.read_bytes()).hexdigest()))) | |