Upload build_canonical_corpus.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Build canonical-convention training corpus for Q3B v8.
Sources: - data/src/partner_graph/output/scenarios/*.json (134 scenarios, ~550 turns) All speaker="atc" turns (ATC-to-ownship + ambient + broadcast for breadth) - data/flights/_reports/report-strict_fast_*.json deduped (~800 turns) Per-turn dimensions provide canonical intent + parameters
Conventions (matches `just baseline` measurement): - intent: 50-enum slug (lowercase, e.g., "landing_clearance") - slots: dict with LOWERCASE keys ("runway", "altitude", "call_sign", etc.) - slots are FMM-relevant SUBSET (not all extractable values)
Output: poc/llm-finetune/training/data_canonical/{train,valid,test}.jsonl"""from __future__ import annotationsimport jsonimport randomfrom collections import defaultdictfrom pathlib import Path
ROOT = Path("/Users/jean-patricksmith/digital/kingly/apps/production/naac")
INTENTS = sorted(json.loads((ROOT / "poc/deberta_intent/checkpoints-base/label_mapping.json").read_text())["intent2id"].keys())SLOTS_LOWER = ["altimeter_setting", "altitude", "approach_type", "call_sign", "clock_position", "direction", "distance", "facility", "fix", "frequency", "heading", "pattern_leg", "route", "runway", "speed", "taxiway", "time", "transponder_code", "turn_direction"]
SYSTEM_PROMPT = ( "You are an ATC parser. Parse the air traffic control transmission into a JSON object.\n" "OUTPUT FORMAT: {\"intent\": <one-of-enum>, \"slots\": {<lowercase_slot_key>: <value>}}\n" "\nIntent must be one of these 50 values: " + ", ".join(INTENTS) + "\n" "\nSlot keys (LOWERCASE): " + ", ".join(SLOTS_LOWER) + "\n" "\nSlots is the FMM-relevant subset only — do NOT include callsign, facility, " "or other context unless it is required for the action. Output ONLY the JSON object.")
def to_chat(text: str, intent: str, slots: dict) -> dict: gold = json.dumps({"intent": intent, "slots": slots}, ensure_ascii=False) return { "messages": [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": text.strip()}, {"role": "assistant", "content": gold}, ] }
def walk_scenarios(): """Yield (text, intent, params) per ATC turn from canonical scenario gold.""" scenario_dir = ROOT / "data/src/partner_graph/output/scenarios" for path in sorted(scenario_dir.glob("*.json")): try: scn = json.loads(path.read_text()) except Exception: continue for turn in scn.get("turns", []): if turn.get("speaker", "").lower() != "atc": continue text = (turn.get("expected_transcript") or "").strip() intent = turn.get("expected_intent") params = turn.get("expected_parameters") or {} if not text or not intent or intent not in INTENTS: continue slots = {k.lower(): str(v) for k, v in params.items() if v is not None and str(v) != ""} yield text, intent, slots
def walk_flight_reports(): """Walk data/flights/_reports/report-strict_fast_*.json; yield per-turn (text, intent, slots).
Each turn has dimensions.intent.expected, dimensions.slots.expected, etc. """ reports_dir = ROOT / "data/flights/_reports" for path in sorted(reports_dir.glob("report-strict_fast_*.json")): try: r = json.loads(path.read_text()) except Exception: continue # report shape: {scenarios: [{turns: [{...dimensions...}]}], ...} for scn in r.get("scenarios") or r.get("scenario_results") or []: for turn in scn.get("turns") or scn.get("turn_results") or []: text = turn.get("text") or turn.get("input_text") or turn.get("transcript") if not text: continue dims = turn.get("dimensions") or {} intent_dim = dims.get("intent") or {} slots_dim = dims.get("slots") or {} intent = intent_dim.get("expected") if isinstance(intent_dim, dict) else None slots_exp = slots_dim.get("expected") if isinstance(slots_dim, dict) else None if not intent or intent not in INTENTS: continue if not isinstance(slots_exp, dict): slots_exp = {} slots = {k.lower(): str(v) for k, v in slots_exp.items() if v is not None and str(v) != ""} yield text, intent, slots
def main(): out = ROOT / "poc/llm-finetune/training/data_canonical" out.mkdir(parents=True, exist_ok=True)
rows = [] counts = defaultdict(int)
print("walking output/scenarios/...") for text, intent, slots in walk_scenarios(): rows.append({"text": text, "intent": intent, "slots": slots, "_source": "canonical_scenarios"}) counts["canonical_scenarios"] += 1
print("walking _reports/strict_fast/...") for text, intent, slots in walk_flight_reports(): rows.append({"text": text, "intent": intent, "slots": slots, "_source": "flight_reports"}) counts["flight_reports"] += 1
print(f"total raw: {len(rows)}") print(f" source counts: {dict(counts)}")
# Dedupe by (text, intent) seen = set() dedup = [] for r in rows: k = (r["text"], r["intent"]) if k in seen: continue seen.add(k) dedup.append(r) print(f"deduped: {len(dedup)}")
rng = random.Random(42) rng.shuffle(dedup) n = len(dedup) n_valid = max(20, int(n * 0.05)) n_test = max(20, int(n * 0.05)) n_train = n - n_valid - n_test splits = {"train": dedup[:n_train], "valid": dedup[n_train:n_train+n_valid], "test": dedup[n_train+n_valid:]}
for name, items in splits.items(): path = out / f"{name}.jsonl" with path.open("w") as f: for r in items: f.write(json.dumps(to_chat(r["text"], r["intent"], r["slots"]), ensure_ascii=False) + "\n") print(f"{name}: {len(items)} -> {path}")
print(f"\nintent distribution (top 15):") intent_counts = defaultdict(int) for r in dedup: intent_counts[r["intent"]] += 1 for intent, n_i in sorted(intent_counts.items(), key=lambda kv: -kv[1])[:15]: print(f" {intent}: {n_i}") print(f" ...{len(intent_counts)} unique intents")
if __name__ == "__main__": main()build_canonical_corpus.pyAdded+156