"""Turn correct-by-construction IES graphs into training pairs. 1. Normalise each graph's instance IRIs to clean sequential data:iN (learnable targets). 2. Emit a deterministic (description -> turtle) pair for every graph. 3. For a fraction, add a local-Qwen paraphrase of the description (linguistic diversity). All turtle is re-validated after normalisation. Runs under .venv311.""" import sys, json, pathlib, argparse, urllib.request, re sys.path.insert(0, str(pathlib.Path(__file__).parent)) from rdflib import Graph, URIRef, Namespace from iesval import validate_turtle ROOT = pathlib.Path("/Users/fabio/projects/qwen-ies-ft") TESTDATA = "http://data.gov.uk/testdata#" DATA = Namespace(TESTDATA) IES = Namespace("http://ies.data.gov.uk/ontology/ies4#") ISO = Namespace("http://iso.org/iso8601#") URL = "http://localhost:8080/v1/chat/completions" MODEL = "mlx-community/Qwen3.6-35B-A3B-8bit" SYS = ("You are an expert in the UK Government Information Exchange Standard (IES4), " "a 4D RDF ontology. You explain IES concepts precisely and write valid IES4 " "RDF/Turtle using only real IES4 terms.") def _slug(v): s = re.sub(r"[^0-9A-Za-z]+", "_", v.strip().lower()).strip("_") return s[:40] or "x" def normalise(ttl: str) -> str: """Rename instance IRIs to human-plausible slugs: named entities get name-based IRIs (data:fred_smith), unnamed nodes get type-based ones (data:boundingstate_1).""" g = Graph(); g.parse(data=ttl, format="turtle") from rdflib import RDF HASNAME = IES["hasName"]; REPVAL = IES["representationValue"] inst = sorted({str(n) for t in g for n in t if isinstance(n, URIRef) and str(n).startswith(TESTDATA)}) # collect name values per entity names = {} for s, _, o in g.triples((None, HASNAME, None)): v = g.value(o, REPVAL) if v: names.setdefault(str(s), []).append(str(v)) remap = {}; used = {} def assign(u, base): n = used.get(base, 0) + 1; used[base] = n remap[URIRef(u)] = DATA[base if n == 1 else f"{base}_{n}"] for u in inst: if u in names: assign(u, _slug("_".join(sorted(names[u])[:2]))) for u in inst: if URIRef(u) in remap: continue t = g.value(URIRef(u), RDF.type) base = _slug(str(t).split("#")[-1]) if t else "node" # name nodes get tied to their value where possible v = g.value(URIRef(u), REPVAL) if v and "name" in base: base = _slug(str(v)) + "_name" elif v: base = base + "_" + _slug(str(v))[:20] assign(u, base) ng = Graph() ng.bind("data", DATA); ng.bind("ies", IES); ng.bind("iso8601", ISO) for s, p, o in g: ng.add((remap.get(s, s), remap.get(p, p), remap.get(o, o))) return ng.serialize(format="turtle") ALT_NS = ["http://example.org/case#", "http://ops.example.com/data#", "http://records.example.gov.uk/inv#", "http://intel.example.net/kg#"] def vary_namespace(ttl, desc, i): """For ~35% of records swap the instance namespace and instruct the model to use it — teaches namespace-following instead of hardcoding testdata.""" if i % 20 >= 7: return ttl, desc, None ns = ALT_NS[i % len(ALT_NS)] return ttl.replace(TESTDATA, ns), desc, ns _CAPWORD = re.compile(r"\b[A-Z][a-z]+\b") def paraphrase_ok(facts, para): """Every proper noun and every year in the facts must survive the paraphrase.""" need = set(_CAPWORD.findall(facts)) | set(re.findall(r"\b(?:19|20)\d\d\b", facts)) have = para # substring check is enough return all(w in have for w in need) def user_turn(desc, ns=None): ns_line = (f" Use <{ns}> as the namespace for instance IRIs." if ns else "") return ("Encode the following scenario as IES4 RDF/Turtle. Use only real IES4 terms and " f"the 4D state/period pattern where relevant.{ns_line} Output only Turtle.\n\n" f"Scenario: {desc}") def rec(desc, ttl, ns=None): return {"messages":[{"role":"system","content":SYS}, {"role":"user","content":user_turn(desc, ns)}, {"role":"assistant","content":ttl.strip()}]} def qwen(prompt, max_tokens=200, temperature=0.8): body=json.dumps({"model":MODEL,"messages":[{"role":"user","content":prompt}], "max_tokens":max_tokens,"temperature":temperature, "chat_template_kwargs":{"enable_thinking":False}}).encode() req=urllib.request.Request(URL, body, {"Content-Type":"application/json"}) with urllib.request.urlopen(req, timeout=180) as r: return json.loads(r.read())["choices"][0]["message"].get("content","").strip() def main(): ap=argparse.ArgumentParser(); ap.add_argument("--frac", type=float, default=0.6) args=ap.parse_args() rows=[json.loads(l) for l in (ROOT/"data"/"ground.jsonl").open()] log=(ROOT/"data"/"describe.log").open("w") # --- pass 1: normalise + write ALL deterministic pairs (fast, no LLM) --- norm=[]; det=0; bad=0; varied=0 with (ROOT/"data"/"pairs_ies.jsonl").open("w") as out: for i,r in enumerate(rows): try: ttl=normalise(r["turtle"]) except Exception: bad+=1; continue if not validate_turtle(ttl,5)[0]: bad+=1; continue vttl, desc, ns = vary_namespace(ttl, r["facts"], i) if ns: varied+=1 out.write(json.dumps(rec(desc, vttl, ns))+"\n"); det+=1 norm.append((r["facts"], vttl, ns)) log.write(f"pass1 deterministic={det} bad={bad} ns-varied={varied}\n"); log.flush() print(f"pass1: {det} deterministic pairs written (bad={bad}, ns-varied={varied})") # --- pass 2: append Qwen paraphrases for diversity (interruptible) --- para=0; rejected=0 with (ROOT/"data"/"pairs_ies.jsonl").open("a") as out: for i,(facts,ttl,ns) in enumerate(norm): if (i % 1000)/1000.0 >= args.frac: continue try: p=qwen("Rewrite this factual statement as a natural, plainly-worded sentence or two " "for a case file. Keep every fact identical; keep all names and years exactly " "as written; do not add or remove facts; do not mention RDF or ontologies. " f"Output only the rewrite.\n\n{facts}") p=p.strip().strip('"') if 15 < len(p) < 400 and p.lower()!=facts.lower() and paraphrase_ok(facts, p): out.write(json.dumps(rec(p, ttl, ns))+"\n"); out.flush(); para+=1 else: rejected+=1 except Exception as e: log.write(f"{i} qwen err {e}\n") if i%25==0: log.write(f"pass2 {i}/{len(norm)} para={para} rej={rejected}\n"); log.flush() print(f"IES pairs: deterministic={det} paraphrased={para} (rejected {rejected}) total={det+para}") if __name__=="__main__": main()