File size: 4,126 Bytes
6256b19 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | """Validator that keeps synthetic IES Turtle honest.
Rejects anything that (a) doesn't parse, (b) uses an ies: term not in the real
ontology, or (c) is too trivial to be a useful example."""
import json, pathlib, re
from rdflib import Graph, RDF, RDFS, Namespace
ROOT = pathlib.Path("/Users/fabio/projects/qwen-ies-ft")
IES = "http://ies.data.gov.uk/ontology/ies4#"
_vocab = json.loads((ROOT/"data"/"vocab.json").read_text())
REAL = set(_vocab["all_terms"])
CLASSES = set(_vocab["class_names"])
PREFIX_LINE = f"@prefix ies: <{IES}>"
def validate_turtle(ttl: str, min_triples: int = 4):
if PREFIX_LINE not in ttl.replace(" ", " ").replace(" .", ""):
# be lenient about spacing, but the ies namespace must be declared correctly
if IES not in ttl:
return False, "ies namespace not declared", 0, []
g = Graph()
try:
g.parse(data=ttl, format="turtle")
except Exception as e:
return False, f"parse error: {str(e)[:120]}", 0, []
n = len(g)
if n < min_triples:
return False, f"too few triples ({n})", n, []
# every ies: term used must exist in the real ontology
used = set()
for t in g:
for node in t:
s = str(node)
if s.startswith(IES):
used.add(s.split("#")[-1])
bad = sorted(used - REAL)
if bad:
return False, f"unknown ies terms: {bad[:6]}", n, sorted(used)
# must instantiate at least one real IES class
typed_classes = {str(o).split("#")[-1] for _, p, o in g.triples((None, RDF.type, None))
if str(o).startswith(IES)}
if not (typed_classes & CLASSES):
return False, "no rdf:type to a real IES class", n, sorted(used)
return True, "ok", n, sorted(used)
# ---- structural conformance: domain/range checking with subclass closure ----
_PROPS = _vocab["properties"]
_SUPERS = {c: set(d["subClassOf"]) for c, d in _vocab["classes"].items()}
def _ancestors(c, seen=None):
seen = seen or set()
for s in _SUPERS.get(c, ()):
if s not in seen:
seen.add(s); _ancestors(s, seen)
return seen
def _conforms(types, allowed):
"""any of the node's types is the allowed class or a descendant of it"""
for t in types:
if t in allowed: return True
if _ancestors(t) & set(allowed): return True
return False
def structural_conformance(ttl: str):
"""Fraction of checkable ies: property usages whose subject/object types satisfy the
property's declared rdfs:domain/range (with subclass closure). Returns (ratio,
checked, violations)."""
g = Graph()
try: g.parse(data=ttl, format="turtle")
except Exception: return 0.0, 0, ["unparseable"]
types = {}
for s, _, o in g.triples((None, RDF.type, None)):
if str(o).startswith(IES):
types.setdefault(s, set()).add(str(o).split("#")[-1])
checked = 0; bad = []
for s, p, o in g:
ps = str(p)
if not ps.startswith(IES): continue
pn = ps.split("#")[-1]
d = _PROPS.get(pn)
if not d: continue
if d["domain"] and s in types:
checked += 1
if not _conforms(types[s], d["domain"]):
bad.append(f"{pn}: subject {sorted(types[s])} not in domain {d['domain']}")
if d["range"] and o in types:
checked += 1
if not _conforms(types[o], d["range"]):
bad.append(f"{pn}: object {sorted(types[o])} not in range {d['range']}")
ratio = 1.0 if checked == 0 else 1.0 - len(bad)/checked
return ratio, checked, bad[:8]
if __name__ == "__main__":
import sys
# smoke test: a real sample must pass, a hallucinated term must fail
good = (ROOT/"IES4"/"Sample Data"/"hospital.ttl").read_text()
print("REAL hospital.ttl ->", validate_turtle(good)[:3])
bad = good + "\ndata:Fred ies:hasTelepathicLinkTo data:Ghost .\n"
print("HALLUCINATED term ->", validate_turtle(bad)[:2])
broken = "@prefix ies: <http://ies.data.gov.uk/ontology/ies4#> .\ndata:x a ies:Person" # no closing dot
print("BROKEN syntax ->", validate_turtle(broken)[:2])
|