ies4-turtle-instruct / scripts /build_multistd.py
fabsssss's picture
Upload folder using huggingface_hub
6256b19 verified
Raw
History Blame Contribute Delete
3.61 kB
"""Multi-standard generalization slice from Text2KGBench (Wikidata-TekGen).
Builds ontology-CONDITIONED pairs: the prompt supplies the target ontology's relations,
the target Turtle uses ONLY those relations (conformance, parallel to the IES validator).
Teaches the general 'conform to the ontology you are given' skill. No LLM; rdflib-checked."""
import json, pathlib, re, random, glob
from rdflib import Graph
random.seed(7)
ROOT = pathlib.Path("/Users/fabio/projects/qwen-ies-ft")
BASE = ROOT/"Text2KGBench"/"data"/"wikidata_tekgen"
PER_DOMAIN = 45
SYS = ("You extract ontology-conformant RDF/Turtle knowledge graphs from text. "
"You use only the relations of the target ontology you are given, and you never "
"invent relations outside it.")
def slug(s):
s = re.sub(r"[^0-9A-Za-z]+", "_", s.strip()).strip("_")
return s or "x"
DATEISH = re.compile(r"\d{1,2}\s+\w+\s+\d{4}|\d{4}(-\d\d-\d\d)?$|^\d[\d.,]*$")
def to_turtle(triples, rel_slugs):
by_sub = {}
used_ok = True
for t in triples:
r = slug(t["rel"])
if r not in rel_slugs: # keep it conformant: skip out-of-ontology relations
continue
by_sub.setdefault(slug(t["sub"]), []).append((r, t["obj"]))
if not by_sub: return None
lines = ["@prefix ex: <http://example.org/kg#> .", ""]
for sub, pos in by_sub.items():
parts = []
for r, obj in pos:
if DATEISH.match(obj.strip()):
parts.append(f'ex:{r} "{obj.strip()}"')
else:
parts.append(f"ex:{r} ex:{slug(obj)}")
lines.append(f"ex:{sub} " + " ;\n ".join(parts) + " .")
return "\n".join(lines)
def main():
onts = {}
for f in glob.glob(str(BASE/"ontologies"/"*.json")):
d = json.load(open(f))
onts[d["id"]] = d
pairs = []
for gt in sorted(glob.glob(str(BASE/"ground_truth"/"*.jsonl"))):
oid = "ont_" + re.search(r"ont_(\d+_\w+?)_", pathlib.Path(gt).name).group(1)
# match ontology by id prefix
ont = next((o for k,o in onts.items() if k==oid or k.replace("ont_","")==oid.replace("ont_","")), None)
if not ont: continue
rels = [r["label"] for r in ont["relations"]]
rel_slugs = {slug(r) for r in rels}
concepts = [c["label"] for c in ont["concepts"]][:20]
rows = [json.loads(l) for l in open(gt)]
random.shuffle(rows)
kept = 0
for row in rows:
if kept >= PER_DOMAIN: break
ttl = to_turtle(row.get("triples",[]), rel_slugs)
if not ttl: continue
try: Graph().parse(data=ttl, format="turtle")
except Exception: continue
user = (f"Target ontology '{ont['title']}'.\n"
f"Allowed relations: {', '.join(rels)}.\n"
f"Example concepts: {', '.join(concepts)}.\n\n"
f"Extract a knowledge graph from this sentence as RDF/Turtle, using ONLY the "
f"allowed relations and the ex: <http://example.org/kg#> namespace. Output only Turtle.\n\n"
f"Sentence: {row['sent']}")
pairs.append({"messages":[{"role":"system","content":SYS},
{"role":"user","content":user},
{"role":"assistant","content":ttl}]})
kept += 1
out = ROOT/"data"/"pairs_multistd.jsonl"
with out.open("w") as f:
for p in pairs: f.write(json.dumps(p)+"\n")
print(f"multi-standard pairs: {len(pairs)} across {len(onts)} ontologies -> {out}")
if __name__=="__main__":
main()