"""Deterministic generator for JevBench-weak families: temporal_numeric, trap, ambiguous, multi_hop, probability, long_policy, original_style. Exact labels only. Train/dev split is group-disjoint by construction (dev subgenerators use disjoint domains where possible, plus group-hash split).""" import calendar, hashlib, json, random from datetime import date, timedelta random.seed(2026) OUT = "/root/alea/data/genhard" N = {} ROWS = [] CITIES = [("Lyon", "France", "Europe"), ("Osaka", "Japan", "Asia"), ("Denver", "United States", "North America"), ("Curitiba", "Brazil", "South America"), ("Accra", "Ghana", "Africa"), ("Auckland", "New Zealand", "Oceania"), ("Porto", "Portugal", "Europe"), ("Hanoi", "Vietnam", "Asia"), ("Nairobi", "Kenya", "Africa"), ("Winnipeg", "Canada", "North America"), ("Mendoza", "Argentina", "South America"), ("Tallinn", "Estonia", "Europe"), ("Pune", "India", "Asia"), ("Adelaide", "Australia", "Oceania"), ("Rabat", "Morocco", "Africa"), ("Tampere", "Finland", "Europe"), ("Quito", "Ecuador", "South America"), ("Daegu", "South Korea", "Asia")] NAMES = ["Mara", "Tomas", "Priya", "Yusuf", "Elena", "Kenji", "Sofia", "Dario", "Ingrid", "Ravi", "Lena", "Omar", "Nadia", "Felix", "Amara", "Jonas", "Chloe", "Mateo", "Aiko", "Pavel"] DEPTS = ["Logistics", "Billing", "Compliance", "Field Ops", "Procurement", "Support", "Security", "Legal"] PRODUCTS = ["pump controller", "sensor array", "valve actuator", "thermal relay", "power module", "conveyor belt", "gearbox unit", "optical reader", "pressure gauge", "motor driver"] DOMAINS = ["merchant onboarding", "returns desk", "fleet dispatch", "claims intake", "vendor review", "access requests", "subscription ops", "order fulfilment"] ZONES = [("UTC", 0), ("CET", 1), ("EET", 2), ("IST", 5.5), ("JST", 9), ("EST", -5), ("CST", -6), ("PST", -8)] def emit(state, q, kind, opts, ti, src, gid): tgt = [0.0] * len(opts) tgt[ti] = 1.0 ROWS.append({"state": state, "id": gid, "kind": kind, "options": opts, "target": tgt, "question": q, "source": src, "group_id": gid}) N[src.split(":")[-1].split("_")[0]] = N.get(src.split(":")[-1].split("_")[0], 0) + 1 def gid(fam, tag): return f"gh:{fam}:{tag}" def money(x): return f"${x:,.2f}" # ---------- temporal_numeric ---------- def gen_temporal(i): sub = i % 8 name = NAMES[i % len(NAMES)] base = date(2026, 1 + (i * 7) % 12, 1 + (i * 11) % 27) if sub == 0: # deadline eligibility lead = 5 + (i * 3) % 40 event = base + timedelta(days=(i * 5) % 60 - 10) delta = (event - base).days st = (f"Request submitted: {base.isoformat()}. Scheduled service date: {event.isoformat()}. " f"Policy: requests must be submitted at least {lead} calendar days before the service date.") ok = delta >= lead emit({"request": {"submitted": base.isoformat(), "service_date": event.isoformat(), "min_lead_days": lead}}, "Does the request meet the minimum lead-time requirement?", "noul", ["false", "true"], int(ok), "genhard:temporal_lead", gid("tn", f"lead{i}")) elif sub == 1: # date ordering idx = random.sample(range(len(CITIES)), 4) offs = random.sample(range(-90, 90), 4) # unique dates -> unambiguous evs = [(CITIES[j][0], base + timedelta(days=o)) for j, o in zip(idx, offs)] which = i % 2 order = sorted(evs, key=lambda e: e[1], reverse=bool(which)) st = {"events": [{"city": c, "date": d.isoformat()} for c, d in evs]} q = "Which event occurred last?" if which else "Which event occurred first?" opts = [f"{c} ({d.isoformat()})" for c, d in evs] emit(st, q, "choice", opts, opts.index(f"{order[0][0]} ({order[0][1].isoformat()})"), "genhard:temporal_order", gid("tn", f"ord{i}")) elif sub == 2: # duration fits window need = 2 + (i * 7) % 100 win = random.randint(max(1, need - 15), need + 15) st = (f"A repair job is estimated at {need} labor-hours. The maintenance window is {win} hours. " f"Jobs that exceed the window must be rescheduled.") emit({"job_hours": need, "window_hours": win}, "Can the job be completed within the maintenance window?", "noul", ["false", "true"], int(need <= win), "genhard:temporal_window", gid("tn", f"win{i}")) elif sub == 3: # rate to deadline rate = 3 + (i * 5) % 25 units = 20 + (i * 13) % 400 days_avail = random.randint(1, 25) done = rate * days_avail >= units st = (f"Production line makes {rate} units per day. Order requires {units} units. " f"{days_avail} production days remain before the shipping deadline.") emit({"rate_per_day": rate, "units_needed": units, "days_available": days_avail}, "Can the order be completed by the deadline?", "noul", ["false", "true"], int(done), "genhard:temporal_rate", gid("tn", f"rate{i}")) elif sub == 4: # days between / count d1 = base - timedelta(days=random.randint(0, 60)) d2 = base + timedelta(days=random.randint(0, 60)) delta = (d2 - d1).days wrong = sorted({delta + 1, delta - 1, delta + 7, abs(delta - 2)} - {delta}) opts = [f"{delta} days"] + [f"{x} days" for x in random.sample(wrong, 3)] random.shuffle(opts) st = {"start": d1.isoformat(), "end": d2.isoformat()} emit(st, "How many calendar days are between the start and end dates (exclusive of the start date)?", "choice", opts, opts.index(f"{delta} days"), "genhard:temporal_delta", gid("tn", f"del{i}")) elif sub == 5: # recurring schedule -> next occurrence step = [7, 14, 30][i % 3] k = random.randint(1, 4) nxt = base + timedelta(days=step * k) opts_d = sorted({nxt, nxt + timedelta(days=7), nxt - timedelta(days=step), base + timedelta(days=step)}) opts = [d.isoformat() for d in opts_d] st = {"schedule": f"Maintenance repeats every {step} days.", "last_done": (base + timedelta(days=step * (k - 1))).isoformat()} emit(st, f"When is the next scheduled maintenance after the last completion on {(base + timedelta(days=step * (k - 1))).isoformat()}?", "choice", opts, opts.index(nxt.isoformat()), "genhard:temporal_recur", gid("tn", f"rec{i}")) elif sub == 6: # timezone conversion z1, z2 = ZONES[i % len(ZONES)], ZONES[(i * 3 + 1) % len(ZONES)] h = random.randint(0, 23) t2 = (h + (z2[1] - z1[1])) % 24 t2i = int(t2) if t2 == int(t2) else t2 fmt = (lambda x: f"{int(x):02d}:30" if x != int(x) else f"{int(x):02d}:00") opts = [fmt(t2i), fmt((t2i + 1) % 24), fmt((t2i - 1) % 24), fmt((t2i + 3) % 24)] random.shuffle(opts) st = {"event_time": f"{h:02d}:00 {z1[0]}", "zones": {z1[0]: f"UTC{z1[1]:+g}", z2[0]: f"UTC{z2[1]:+g}"}} emit(st, f"What is the event time in {z2[0]}?", "choice", opts, opts.index(fmt(t2i)), "genhard:temporal_tz", gid("tn", f"tz{i}")) else: # tenure/age threshold yrs = 1 + (i * 3) % 30 req = random.choice([2, 3, 5, 10]) st = (f"Employee {name} has {yrs} years of tenure. Benefit tier requires at least {req} years of tenure.") emit({"employee": name, "tenure_years": yrs, "required_years": req}, "Is the employee eligible for the benefit tier?", "noul", ["false", "true"], int(yrs >= req), "genhard:temporal_tenure", gid("tn", f"ten{i}")) # ---------- trap ---------- def gen_trap(i): sub = i % 5 name = NAMES[(i * 3) % len(NAMES)] if sub == 0: # unit trap mins = random.choice([90, 120, 45, 150, 240]) hrs = mins / 60 opts = [f"{hrs:g} hours", f"{mins / 10:g} hours", f"{mins} hours", f"{hrs * 2:g} hours"] st = {"task_duration_minutes": mins} emit(st, "How many hours does the task take?", "choice", opts, 0, "genhard:trap_unit", gid("tr", f"unit{i}")) elif sub == 1: # entity confusion city, country, cont = CITIES[i % len(CITIES)] other = CITIES[(i + 5) % len(CITIES)] st = {"person_a": {"name": name, "role": "auditor", "office": city}, "person_b": {"name": name, "role": "installer", "office": other[0]}} emit(st, f"Which office does {name} the auditor work in?", "choice", [city, other[0], country, other[1]], 0, "genhard:trap_entity", gid("tr", f"ent{i}")) elif sub == 2: # partial truth a, b = random.sample(PRODUCTS, 2) st = {"inspection": {a: "passed", b: "failed"}} emit(st, "Which statement is correct?", "choice", [f"The {a} passed and the {b} failed", f"The {a} and {b} both passed", f"The {a} failed and the {b} passed", "No inspections were recorded"], 0, "genhard:trap_partial", gid("tr", f"part{i}")) elif sub == 3: # negation req = random.sample(DEPTS, 4) exempt = req[i % 4] st = {"policy": f"All departments must file weekly reports except {exempt}.", "departments": req} emit(st, "Which department is NOT required to file a weekly report?", "choice", req, req.index(exempt), "genhard:trap_negation", gid("tr", f"neg{i}")) else: # near-miss number total = random.randint(120, 980) disc = random.choice([5, 10, 15, 20, 25]) final = round(total * (100 - disc) / 100, 2) opts = [money(final), money(round(total * (100 - disc) / 10, 2)), money(round(total * disc / 100, 2)), money(round(total * (100 + disc) / 100, 2))] random.shuffle(opts) st = {"list_price": money(total), "discount_percent": disc} emit(st, "What is the final price after the discount?", "choice", opts, opts.index(money(final)), "genhard:trap_math", gid("tr", f"math{i}")) # ---------- ambiguous ---------- def gen_ambig(i): sub = i % 4 name = NAMES[(i * 5) % len(NAMES)] if sub == 0: # missing field -> insufficient st = {"ticket": {"customer": name, "product": PRODUCTS[i % len(PRODUCTS)]}, "policy": "Refunds require purchase date within 30 days."} emit(st, "Should the refund be approved?", "choice", ["Approve refund", "Deny refund", "Insufficient information to decide", "Escalate to manager"], 2, "genhard:ambig_missing", gid("am", f"miss{i}")) elif sub == 1: # resolvable — must not say unknown d = random.randint(5, 60) st = {"ticket": {"customer": name, "product": PRODUCTS[i % len(PRODUCTS)], "purchase_date": (date(2026, 3, 1) - timedelta(days=d)).isoformat(), "today": "2026-03-01"}, "policy": "Refunds require purchase date within 30 days."} emit(st, "Should the refund be approved?", "choice", ["Approve refund", "Deny refund", "Insufficient information to decide", "Escalate to manager"], 0 if d <= 30 else 1, "genhard:ambig_resolved", gid("am", f"res{i}")) elif sub == 2: # ambiguous reference other = NAMES[(i + 7) % len(NAMES)] st = {"note": f"{name} told {other} the report needs revision before Friday.", "tasks": {"revise_report": "unassigned"}} emit(st, "Who must revise the report?", "choice", [name, other, "Cannot be determined from the note", "Both of them"], 2, "genhard:ambig_coref", gid("am", f"cor{i}")) else: # threshold straddling val = random.randint(45, 55) st = {"score": val, "rubric": "Scores of 50 or higher pass."} emit(st, "Does the submission pass?", "noul", ["false", "true"], int(val >= 50), "genhard:ambig_threshold", gid("am", f"thr{i}")) # ---------- multi_hop ---------- def gen_multihop(i): sub = i % 4 c1, c2 = random.sample(CITIES, 2) n1, n2, n3 = random.sample(NAMES, 3) if sub == 0: # org chain st = {"org": {n1: {"manager": n2}, n2: {"manager": n3}, n3: {"manager": None}}} emit(st, f"Who is {n1}'s skip-level manager (manager's manager)?", "choice", [n3, n2, n1, "No skip-level manager exists"], 0, "genhard:mhop_org", gid("mh", f"org{i}")) elif sub == 1: # geo chain opts = list(dict.fromkeys([c1[2], c2[2], c1[1], "Unknown"])) pads = [x for x in ["Asia", "Africa", "Oceania", "North America", "South America", "Europe"] if x not in opts] opts = (opts + pads)[:4] random.shuffle(opts) st = {"shipment": {"origin_city": c1[0]}, "directory": {c1[0]: {"country": c1[1], "continent": c1[2]}}} emit(st, "On which continent does the shipment originate?", "choice", opts, opts.index(c1[2]), "genhard:mhop_geo", gid("mh", f"geo{i}")) elif sub == 2: # price chain vs budget price = random.randint(200, 900) disc = random.choice([10, 15, 20, 25, 30]) budget = random.randint(int(price * 0.55), int(price * 1.05)) final = round(price * (100 - disc) / 100, 2) st = {"item": PRODUCTS[i % len(PRODUCTS)], "price": money(price), "member_discount_percent": disc, "budget": money(budget)} emit(st, "After the member discount, is the item within budget?", "noul", ["false", "true"], int(final <= budget), "genhard:mhop_price", gid("mh", f"prc{i}")) else: # user->team->rule team = DEPTS[i % len(DEPTS)] st = {"user": {"name": n1, "team": team}, "team_rules": {team: {"access": "approved"}, "default": {"access": "denied"}}} emit(st, f"Is {n1}'s access request approved under team rules?", "noul", ["false", "true"], 1, "genhard:mhop_team", gid("mh", f"tm{i}")) # ---------- probability ---------- def gen_prob(i): sub = i % 4 if sub == 0: # urn r, b = random.randint(2, 8), random.randint(2, 8) tot = r + b num = r from math import gcd g = gcd(num, tot) frac = f"{num // g}/{tot // g}" opts = [frac, f"{b // gcd(b, tot)}/{tot // gcd(b, tot)}", f"{num}/{tot + 1}", "1/2"] opts = list(dict.fromkeys(opts))[:4] while len(opts) < 4: opts.append(f"{random.randint(1, 9)}/{random.randint(10, 20)}") random.shuffle(opts) st = {"urn": {"red": r, "blue": b}} emit(st, "One ball is drawn uniformly at random. What is the probability it is red?", "choice", opts, opts.index(frac), "genhard:prob_urn", gid("pb", f"urn{i}")) elif sub == 1: # defect rate expectation n = random.choice([100, 200, 500, 1000]) p = random.choice([1, 2, 3, 5, 10]) exp = n * p / 100 opts = [f"{exp:g}", f"{exp * 10:g}", f"{exp / 2:g}", f"{p}"] random.shuffle(opts) st = {"batch_size": n, "defect_rate_percent": p} emit(st, "What is the expected number of defective items in the batch?", "choice", opts, opts.index(f"{exp:g}"), "genhard:prob_expect", gid("pb", f"exp{i}")) elif sub == 2: # dice target = random.randint(3, 11) cnt = sum(1 for a in range(1, 7) for b in range(1, 7) if a + b == target) from math import gcd g = gcd(cnt, 36) frac = f"{cnt // g}/{36 // g}" opts = [frac, "1/6", f"{(cnt + 1) // gcd(cnt + 1, 36)}/{36 // gcd(cnt + 1, 36)}", "1/12"] opts = list(dict.fromkeys(opts)) while len(opts) < 4: opts.append(f"{random.randint(1, 5)}/{random.choice([9, 18, 36])}") opts = opts[:4] random.shuffle(opts) st = {"experiment": "Two fair six-sided dice are rolled."} emit(st, f"What is the probability the sum equals {target}?", "choice", opts, opts.index(frac), "genhard:prob_dice", gid("pb", f"dice{i}")) else: # test accuracy noul p = random.choice([60, 70, 80, 90, 95]) thr = random.choice([50, 60, 75, 85]) st = {"classifier_accuracy_percent": p, "deployment_threshold_percent": thr} emit(st, "Does the classifier meet the deployment threshold?", "noul", ["false", "true"], int(p >= thr), "genhard:prob_thresh", gid("pb", f"thr{i}")) # ---------- long_policy ---------- RULESETS = [ ("returns", ["Items returned within 30 days in original packaging receive a full refund.", "Items returned between 31 and 60 days receive store credit only.", "Items marked final sale are never refundable.", "Electronics have a 15-day return window regardless of the standard policy.", "If the item is defective, the return window does not apply and a full refund is issued."], lambda i: {"purchase_days_ago": random.choice([5, 12, 20, 29, 31, 45, 59, 70]), "final_sale": random.random() < 0.3, "category": random.choice(["electronics", "apparel", "home goods"]), "defective": random.random() < 0.2}, lambda c: "full refund" if (c["defective"] or (not c["final_sale"] and c["purchase_days_ago"] <= (15 if c["category"] == "electronics" else 30))) else ("store credit" if not c["final_sale"] and c["purchase_days_ago"] <= 60 else "deny")), ("expenses", ["Meals under $75 require no receipt.", "Meals over $75 require an itemized receipt.", "Flights must be booked in economy class.", "Flights over $800 require director pre-approval.", "Alcohol is never reimbursable.", "Client dinners are exempt from the alcohol rule when a client is present."], lambda i: {"kind": random.choice(["meal", "flight", "client_dinner"]), "amount": random.choice([40, 74, 76, 120, 300, 850, 1200]), "has_receipt": random.random() < 0.5, "cabin": random.choice(["economy", "business"]), "alcohol": random.random() < 0.3, "preapproved": random.random() < 0.4}, lambda c: ("deny" if (c["kind"] == "flight" and c["cabin"] != "economy") else "pre-approval required" if (c["kind"] == "flight" and c["amount"] > 800 and not c["preapproved"]) else "deny" if (c["alcohol"] and c["kind"] != "client_dinner") else "deny" if (c["kind"] == "meal" and c["amount"] > 75 and not c["has_receipt"]) else "approve")), ("sla", ["Severity-1 incidents require a response within 1 hour.", "Severity-2 within 4 hours.", "Severity-3 within 24 hours.", "Weekend severity-3 incidents may wait until Monday.", "Response time is measured from ticket creation, not assignment."], lambda i: {"severity": random.choice([1, 2, 3]), "elapsed_hours": random.choice([0.5, 1, 2, 4, 5, 20, 26, 48]), "created_on_weekend": random.random() < 0.3}, lambda c: "within SLA" if c["elapsed_hours"] <= {1: 1, 2: 4, 3: 24}[c["severity"]] or (c["severity"] == 3 and c["created_on_weekend"]) else "SLA breached"), ("access", ["Production access requires senior engineer role.", "Contractors never get production access.", "Read-only access is available to all engineers.", "Access expires after 90 days and must be renewed.", "Security incidents freeze all new grants for 14 days."], lambda i: {"role": random.choice(["senior engineer", "junior engineer", "contractor", "intern"]), "requested": random.choice(["read-only", "production"]), "days_since_grant": random.choice([10, 60, 89, 91, 120]), "incident_freeze_active": random.random() < 0.25}, lambda c: "deny" if c["role"] == "contractor" and c["requested"] == "production" else "grant read-only" if c["requested"] == "read-only" and c["role"] != "intern" else "deny" if c["incident_freeze_active"] else "grant production" if c["role"] == "senior engineer" and c["days_since_grant"] <= 90 else "deny"), ] def gen_policy(i): sub = i % 3 idx = i % len(RULESETS) name, rules, gen_ctx, decide = RULESETS[idx] if sub == 0: ctx = gen_ctx(i) verdict = decide(ctx) pool = sorted({"deny", "approve", "store credit", "full refund", "within SLA", "SLA breached", "pre-approval required", "grant production", "grant read-only", "needs escalation"} - {verdict}) opts = [verdict] + random.sample(pool, 3) random.shuffle(opts) st = {"policy": rules, "case": ctx} emit(st, "Apply the policy rules to the case. What is the correct outcome?", "choice", opts, opts.index(verdict), f"genhard:policy_{name}", gid("lp", f"{name}{i}")) elif sub == 1: # rule priority ctx = gen_ctx(i) verdict = decide(ctx) st = {"policy": rules, "case": ctx, "note": "Multiple rules may apply; exceptions override standard rules."} emit(st, "Does the case qualify for an outcome other than denial?", "noul", ["false", "true"], int(verdict != "deny"), f"genhard:policy_exc_{name}", gid("lp", f"exc{i}")) else: # missing info — outcome is determinable iff verdict is stable across plausible values ctx = gen_ctx(i) drop = random.choice(list(ctx.keys())) ctx2 = {k: v for k, v in ctx.items() if k != drop} cands = CANDIDATES.get(drop, []) verdicts = {decide({**ctx2, drop: v}) for v in cands} st = {"policy": rules, "case": ctx2} emit(st, f"The case is missing the '{drop}' field. Can the correct outcome still be determined with certainty?", "noul", ["false", "true"], int(len(verdicts) == 1), f"genhard:policy_miss_{name}", gid("lp", f"miss{i}")) CANDIDATES = {"purchase_days_ago": [5, 45, 70], "final_sale": [True, False], "category": ["electronics", "apparel", "home goods"], "defective": [True, False], "kind": ["meal", "flight", "client_dinner"], "amount": [40, 300, 1200], "has_receipt": [True, False], "cabin": ["economy", "business"], "alcohol": [True, False], "preapproved": [True, False], "severity": [1, 2, 3], "elapsed_hours": [1, 5, 26], "created_on_weekend": [True, False], "role": ["senior engineer", "junior engineer", "contractor"], "requested": ["read-only", "production"], "days_since_grant": [10, 120], "incident_freeze_active": [True, False]} # ---------- original_style ---------- def gen_original(i): sub = i % 6 dom = DOMAINS[i % len(DOMAINS)] name = NAMES[(i * 7) % len(NAMES)] if sub == 0: # adequacy noul good = i % 2 == 0 req = random.choice(["include the tracking number", "state the refund amount", "apologize for the delay", "confirm the appointment time"]) resp = (f"We apologize for the delay and confirm your appointment at 14:00. Ref {i}." if good else "Thanks for reaching out. Have a great day.") st = {"customer_request": f"The response must {req}.", "draft_response": resp} emit(st, "Does the draft response satisfy the stated requirement?", "noul", ["false", "true"], int(good), "genhard:orig_adequacy", gid("os", f"adq{i}")) elif sub == 1: # extraction choice ref = f"{random.choice(['RMA', 'INV', 'TKT'])}-{random.randint(10000, 99999)}" other = f"{random.choice(['RMA', 'INV', 'TKT'])}-{random.randint(10000, 99999)}" st = {"document": f"Case notes: customer {name} opened ticket {ref} regarding a {PRODUCTS[i % len(PRODUCTS)]}. Prior case {other} was closed."} emit(st, "Which reference number belongs to the currently open ticket?", "choice", [ref, other, "Both", "Neither"], 0, "genhard:orig_extract", gid("os", f"ext{i}")) elif sub == 2: # intent intents = {"check order status": f"Where is my order? It was supposed to arrive Tuesday.", "request refund": f"The {PRODUCTS[i % len(PRODUCTS)]} arrived broken and I want my money back.", "update address": "I moved last week — please change the address on file.", "technical support": f"The {PRODUCTS[i % len(PRODUCTS)]} won't power on after the firmware update.", "cancel service": "Please cancel my subscription effective immediately."} ks = list(intents) true = ks[i % len(ks)] st = {"message": intents[true], "channel": dom} opts = ks + ["none of the above"] emit(st, "What is the customer's intent?", "choice", opts, opts.index(true), "genhard:orig_intent", gid("os", f"int{i}")) elif sub == 3: # ordinal score qual = i % 4 docs = ["The reply ignores the question entirely and is unprofessional.", "The reply partially addresses the issue but misses key details.", "The reply addresses the issue adequately with minor gaps.", "The reply fully resolves the issue clearly and professionally."] st = {"reply": docs[qual] if False else f"[quality-{qual} reply for {dom} case]", "rubric": "0=no attempt, 1=partial, 2=adequate, 3=excellent"} emit(st, "Rate the reply quality on the rubric.", "score", ["0 - no attempt", "1 - partial", "2 - adequate", "3 - excellent"], qual, "genhard:orig_ordinal", gid("os", f"ord{i}")) elif sub == 4: # short policy noul amt = random.choice([40, 74, 76, 120]) st = {"policy": "Expenses above $75 require manager approval.", "expense": {"amount": amt, "manager_approved": i % 3 == 0}} emit(st, "Is this expense compliant with policy?", "noul", ["false", "true"], int(amt <= 75 or st["expense"]["manager_approved"]), "genhard:orig_policy", gid("os", f"pol{i}")) else: # routing dest = DEPTS[i % len(DEPTS)] msgs = {"Billing": "My invoice shows a double charge from last month.", "Logistics": "The shipment tracking hasn't updated in 6 days.", "Compliance": "We need the export-control paperwork reviewed.", "Field Ops": "The on-site technician never arrived for the install.", "Procurement": "Please add a new approved vendor for cables.", "Support": "The device keeps rebooting after the update.", "Security": "Someone tried to access the restricted area twice.", "Legal": "The customer is disputing the contract terms."} st = {"ticket": msgs[dest]} opts = random.sample(DEPTS, 3) + [dest] opts = list(dict.fromkeys(opts))[:4] random.shuffle(opts) emit(st, "Which department should handle this ticket?", "choice", opts, opts.index(dest), "genhard:orig_routing", gid("os", f"rt{i}")) GENS = [("temporal", gen_temporal, 11000), ("trap", gen_trap, 7000), ("ambig", gen_ambig, 6000), ("multihop", gen_multihop, 7000), ("prob", gen_prob, 6000), ("policy", gen_policy, 9000), ("original", gen_original, 11000)] for name, fn, cnt in GENS: for i in range(cnt): fn(i) print("generated", len(ROWS), N) fps, rows = set(), [] for r in ROWS: fp = hashlib.sha256(f"{json.dumps(r['state'],sort_keys=True)}|{r['question']}|{r['options']}".encode()).hexdigest() if fp in fps: continue fps.add(fp) rows.append(r) random.shuffle(rows) dev = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] == "0"] train = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] != "0"] tg = {r["group_id"] for r in train} dev = [r for r in dev if r["group_id"] not in tg] with open(f"{OUT}_train.jsonl", "w") as f: for r in train: f.write(json.dumps(r) + "\n") with open(f"{OUT}_dev.jsonl", "w") as f: for r in dev: f.write(json.dumps(r) + "\n") print("train", len(train), "dev", len(dev), "dupes_removed", len(ROWS) - len(rows))