Spaces:
Sleeping
Sleeping
Download scripts/prepare_fresh_test.py from xstard/decision-model: direct link, hf CLI and curl.
- Browser
- Download file 5.43 kB
-
https://huggingface.co/spaces/xstard/decision-model/resolve/main/scripts/prepare_fresh_test.py
- Command line
-
hf download hf://spaces/xstard/decision-model/scripts/prepare_fresh_test.py
-
curl -L -o prepare_fresh_test.py https://huggingface.co/spaces/xstard/decision-model/resolve/main/scripts/prepare_fresh_test.py
5.43 kB
| """Prepare an unseen balanced stress test; paid generation needs a model lock. | |
| All calls use the ORIGINAL lifetime ledger. No keys or raw texts are published. | |
| """ | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import random | |
| from rapidfuzz import fuzz,process | |
| from decision_model.artifacts import sha256 | |
| from decision_model.budget import BudgetLedger | |
| from decision_model.data import normalize,read_jsonl,write_jsonl | |
| from decision_model.generation import Generator,DATASET_FILE,run_batches,persisted_batches | |
| import decision_model.generation as generation | |
| from decision_model.settings import ROOT,load_env | |
| from decision_model.holdout import bind_selection_lock,verify_lifetime_budget | |
| parser=argparse.ArgumentParser() | |
| parser.add_argument('--generate',action='store_true') | |
| parser.add_argument('--directory',type=Path,default=Path('data/fresh-test')) | |
| parser.add_argument('--selection-lock',type=Path,default=Path('artifacts/v2-selection-lock.json')) | |
| parser.add_argument('--seed',type=int,default=20261124) | |
| args=parser.parse_args();load_env() | |
| # A separate evaluation protocol includes the short, colloquial messages that | |
| # motivated this improvement. Do not modify the original training generator. | |
| generation.GENERATOR_VERSION='support-v4-evaluation' | |
| generation.RUBRIC=generation.RUBRIC.replace('15-65 words','5-45 words') | |
| generation.RUBRIC+='\nFollow the additional_requirement field as a controlled evaluation stratum. Include short natural messages and preserve negation exactly in both languages.' | |
| directory=ROOT/args.directory;directory.mkdir(parents=True,exist_ok=True) | |
| seed_path=directory/'seeds.json' | |
| if seed_path.exists(): | |
| seeds=json.loads(seed_path.read_text(encoding='utf-8')) | |
| else: | |
| old=json.loads((ROOT/'data/generated/seeds.json').read_text(encoding='utf-8')) | |
| for previous in (ROOT/'data').glob('fresh-test*/seeds.json'): | |
| if previous.resolve()!=seed_path.resolve():old+=json.loads(previous.read_text(encoding='utf-8')) | |
| known=[normalize(s['text']) for s in old] | |
| seen={s['id'] for s in old} | |
| with (ROOT/'data/raw'/DATASET_FILE).open(encoding='utf-8-sig',newline='') as f: | |
| pool=list(csv.DictReader(f)) | |
| random.Random(args.seed).shuffle(pool) | |
| seeds=[] | |
| for row in pool: | |
| text=row['instruction'];identifier='bitext-'+hashlib.sha256(text.encode()).hexdigest()[:20] | |
| normalized=normalize(text) | |
| if identifier in seen or process.extractOne(normalized,known,scorer=fuzz.ratio,score_cutoff=92): | |
| continue | |
| i=len(seeds);refund=i%2==0 | |
| department='billing' if refund else ['technical','sales','other','billing'][(i//2)%4] | |
| requirement='Use varied natural, sometimes colloquial language; avoid stock support templates.' | |
| if refund: | |
| requirement+=' Directly ask for money back, using varied paraphrases. Ukrainian may use «верніть гроші», «поверніть оплату» or «відшкодуйте сплачену суму».' | |
| elif department=='billing': | |
| requirement+=' Ask ONLY about the STATUS of an already submitted refund. Do not request a new refund or demand money back.' | |
| else: | |
| requirement+=' Explicitly say a refund is NOT requested, then clearly ask for the target department action. Negating a refund is not a financial request.' | |
| if i%5==4: | |
| requirement+=(' Use a direct aggressive insult, without a legal ultimatum.' if i%2==0 | |
| else ' Explicitly threaten to leave or cancel if the issue is ignored.') | |
| seed={'id':identifier,'text':text,'department':department,'wants_refund':refund, | |
| 'frustration':i%5,'additional_requirement':requirement} | |
| seeds.append(seed);seen.add(identifier);known.append(normalized) | |
| if len(seeds)==160:break | |
| if len(seeds)!=160:raise ValueError('Недостатньо незалежних нових джерел.') | |
| seed_path.write_text(json.dumps(seeds,ensure_ascii=False,indent=2),encoding='utf-8') | |
| if not args.generate: | |
| print('Prepared160 unseen source families; no API calls. --generate requires immutable selection lock.') | |
| raise SystemExit(0) | |
| lock_path=ROOT/args.selection_lock | |
| if not lock_path.exists():raise ValueError('Спочатку зафіксуйте модель за validation, не відкриваючи новий test.') | |
| lock=json.loads(lock_path.read_text(encoding='utf-8')) | |
| lock['checkpoint']=str((ROOT/lock['checkpoint']).resolve()) | |
| anchor=ROOT/'data/generated/budget-anchor-v1.json' | |
| ledger_path=ROOT/'data/generated/cost.sqlite' | |
| verify_lifetime_budget(ledger_path,anchor) | |
| bind_selection_lock(directory/'selection-lock.json',lock,{'seeds_sha256':sha256(seed_path), | |
| 'rubric_sha256':hashlib.sha256(generation.RUBRIC.encode()).hexdigest(), | |
| 'generator_version':generation.GENERATOR_VERSION,'model':generation.MODEL, | |
| 'budget_anchor_sha256':sha256(anchor)}) | |
| ledger=BudgetLedger(ledger_path,5,existing_only=True) | |
| generator=Generator(os.getenv('OPENROUTER_API_KEY',''),ledger) | |
| completed=persisted_batches(directory,seeds) | |
| pilot=completed.get(0) | |
| if pilot is None: | |
| pilot=generator.generate(seeds[:10]);write_jsonl(directory/'batch-00000.jsonl',pilot) | |
| completed[0]=pilot | |
| run_batches(seeds[10:],generator,directory,pilot,initial_completed=completed) | |
| print(json.dumps({'generated_pairs':160,'lifetime_committed_usd':ledger.committed,'budget_usd':5})) | |