Download src/generate_data.py from sanidhya1910/northwind-support-lora: direct link, hf CLI and curl.
- Browser
- Download file 7.56 kB
-
https://huggingface.co/spaces/sanidhya1910/northwind-support-lora/resolve/main/src/generate_data.py
- Command line
-
hf download hf://spaces/sanidhya1910/northwind-support-lora/src/generate_data.py
-
curl -L -o generate_data.py https://huggingface.co/spaces/sanidhya1910/northwind-support-lora/resolve/main/src/generate_data.py
7.56 kB
| """Generate the synthetic Northwind Outdoors support dataset. | |
| python src/generate_data.py --train 1400 --val 150 --test 200 | |
| Design notes | |
| ------------ | |
| * Labels are derived by rule in `scenarios.py`, so the gold answers are exact | |
| and the evaluator can score them without an LLM judge. | |
| * One customer phrasing per scenario is reserved for the test split only. The test set therefore contains customer wordings the | |
| model has never been trained on, which keeps the comparison honest. | |
| * Everything is seeded: rerunning produces identical files. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import sys | |
| from collections import Counter | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import templates as T | |
| from scenarios import sample_scenario | |
| ESC_PRIORITY = ["injury", "fraud", "chargeback", "legal", "high_value"] | |
| def _held_index(key, n): | |
| """Deterministically reserve one phrasing per scenario for the test split. | |
| Spread across positions so the test set is not systematically terser or | |
| more formal than the training set. | |
| """ | |
| return sum(ord(c) for c in key[0] + key[1]) % n | |
| def _pick_user_template(rng, key, mood, held_out): | |
| """held_out=True -> use the reserved phrasing, else sample from the rest.""" | |
| options = T.USER[key] | |
| h = _held_index(key, len(options)) | |
| if held_out: | |
| return options[h] | |
| pool = [o for i, o in enumerate(options) if i != h] or options | |
| return rng.choice(pool) | |
| def render_user(rng, scn, held_out): | |
| key = (scn["intent"], scn["variant"]) | |
| text = _pick_user_template(rng, key, scn["mood"], held_out).format(**scn["slots"]) | |
| prefix = rng.choice(T.MOOD_PREFIX[scn["mood"]]) | |
| text = prefix + text | |
| for flag in ("high_value", "chargeback", "legal"): | |
| if flag in scn["flags"]: | |
| text += rng.choice(T.FLAG_SUFFIX[flag]).format(**scn["slots"]) | |
| return text | |
| def render_assistant(rng, scn, labels): | |
| slots = dict(scn["slots"]) | |
| slots["member_fee"] = T.MEMBER_FEE[bool(slots["member"])] | |
| if labels["escalate"]: | |
| flag = next((f for f in ESC_PRIORITY if f in scn["flags"]), None) | |
| bank = T.ESCALATION_BODY[flag] if flag else T.ESCALATION_BODY["out_of_scope"] | |
| prose = rng.choice(bank).format(**slots) | |
| else: | |
| prose = rng.choice(T.BODY[(scn["intent"], scn["variant"])]).format(**slots) | |
| if rng.random() < 0.55: | |
| prose = rng.choice(T.OPENER[scn["mood"]]) + " " + prose | |
| return prose + "\n\n```json\n" + json.dumps(labels) + "\n```" | |
| def pick_followup(rng, scn, labels): | |
| if labels["escalate"]: | |
| return rng.choice(["detail", "thanks"]) | |
| if scn["intent"] in {"damaged_item", "warranty_claim"} and labels["next_action"] != "answer_only": | |
| return rng.choices(["detail", "thanks", "pushback"], weights=[0.6, 0.25, 0.15])[0] | |
| if labels["next_action"] == "answer_only": | |
| return rng.choices(["pushback", "thanks", "escalator"], weights=[0.45, 0.45, 0.10])[0] | |
| # Pushback only makes sense after a "no"; after a resolution it reads odd. | |
| return rng.choices(["thanks", "detail"], weights=[0.7, 0.3])[0] | |
| def followup_labels(kind, labels, scn): | |
| new = json.loads(json.dumps(labels)) | |
| if kind == "escalator": | |
| new["escalate"] = True | |
| new["priority"] = "P1" | |
| new["next_action"] = "escalate_to_specialist" | |
| new["policy_ids"] = sorted(set(new["policy_ids"]) | {"ESC-01"}) | |
| return new | |
| def make_conversation(rng, idx, held_out): | |
| scn = sample_scenario(rng) | |
| labels = scn["labels"] | |
| messages = [ | |
| {"role": "user", "content": render_user(rng, scn, held_out)}, | |
| {"role": "assistant", "content": render_assistant(rng, scn, labels)}, | |
| ] | |
| gold = [labels] | |
| if rng.random() < 0.35: | |
| kind = pick_followup(rng, scn, labels) | |
| options = T.FOLLOWUP[kind] | |
| h = _held_index((kind, kind), len(options)) | |
| pool = options[h:h + 1] if held_out else ([o for i, o in enumerate(options) if i != h] or options) | |
| user2 = rng.choice(pool).format(**scn["slots"]) | |
| labels2 = followup_labels(kind, labels, scn) | |
| if kind == "escalator": | |
| prose = rng.choice(T.FOLLOWUP_REPLY["escalator"]).format(**scn["slots"]) | |
| else: | |
| prose = rng.choice(T.FOLLOWUP_REPLY[kind]).format(**scn["slots"]) | |
| messages.append({"role": "user", "content": user2}) | |
| messages.append({"role": "assistant", "content": prose + "\n\n```json\n" + json.dumps(labels2) + "\n```"}) | |
| gold.append(labels2) | |
| return { | |
| "id": idx, | |
| "intent": scn["intent"], | |
| "variant": scn["variant"], | |
| "flags": scn["flags"], | |
| "mood": scn["mood"], | |
| "messages": messages, | |
| "gold": gold, | |
| } | |
| def build_split(n, seed, held_out, start=0): | |
| rng = random.Random(seed) | |
| seen, out, guard = set(), [], 0 | |
| while len(out) < n and guard < n * 60: | |
| guard += 1 | |
| conv = make_conversation(rng, start + len(out), held_out) | |
| key = tuple(m["content"] for m in conv["messages"] if m["role"] == "user") | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| out.append(conv) | |
| return out | |
| def write(path, rows): | |
| with open(path, "w", encoding="utf-8") as f: | |
| for r in rows: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| def stats(rows): | |
| intents = Counter(r["intent"] for r in rows) | |
| return { | |
| "n": len(rows), | |
| "multi_turn": sum(1 for r in rows if len(r["messages"]) > 2), | |
| "escalating": sum(1 for r in rows if r["gold"][-1]["escalate"]), | |
| "intents": dict(sorted(intents.items())), | |
| "mean_user_chars": round( | |
| sum(len(m["content"]) for r in rows for m in r["messages"] if m["role"] == "user") | |
| / max(1, sum(1 for r in rows for m in r["messages"] if m["role"] == "user")), | |
| 1, | |
| ), | |
| } | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--train", type=int, default=1400) | |
| ap.add_argument("--val", type=int, default=150) | |
| ap.add_argument("--test", type=int, default=200) | |
| ap.add_argument("--out", default="data") | |
| args = ap.parse_args() | |
| os.makedirs(args.out, exist_ok=True) | |
| splits = { | |
| "train": build_split(args.train, seed=11, held_out=False, start=0), | |
| "val": build_split(args.val, seed=22, held_out=False, start=100000), | |
| "test": build_split(args.test, seed=33, held_out=True, start=200000), | |
| } | |
| train_users = {m["content"] for r in splits["train"] for m in r["messages"] if m["role"] == "user"} | |
| leak = sum( | |
| 1 for r in splits["test"] for m in r["messages"] if m["role"] == "user" and m["content"] in train_users | |
| ) | |
| report = {} | |
| for name, rows in splits.items(): | |
| write(os.path.join(args.out, f"{name}.jsonl"), rows) | |
| report[name] = stats(rows) | |
| report["test_user_turns_also_in_train"] = leak | |
| with open(os.path.join(args.out, "stats.json"), "w", encoding="utf-8") as f: | |
| json.dump(report, f, indent=2) | |
| for name in ("train", "val", "test"): | |
| s = report[name] | |
| print(f"{name:5s} n={s['n']:5d} multiturn={s['multi_turn']:4d} escalating={s['escalating']:4d} " | |
| f"mean_user_chars={s['mean_user_chars']}") | |
| print(f"verbatim user turns shared between test and train: {leak}") | |
| if __name__ == "__main__": | |
| main() | |