File size: 5,425 Bytes
b6ae5c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""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}))