fabsssss's picture
Upload scripts/gen_obo.py with huggingface_hub
8fcdf55 verified
Raw
History Blame Contribute Delete
3.2 kB
"""OBO term-grounding pairs (candidate-based entity normalization).
Given a mention + a shortlist of REAL candidate ontology terms, the model selects the correct
CURIE and emits a typed RDF/Turtle triple. Candidate-based => no identifier hallucination:
the model links, it does not invent IDs. Every candidate and answer is a real OBO term."""
import sys, json, pathlib, random
from rdflib import Graph
sys.path.insert(0, str(pathlib.Path(__file__).parent))
import bioseed as S
random.seed(404)
ROOT = pathlib.Path("/Users/fabio/projects/qwen-bio-ft")
BL = S.PREFIX["biolink"]; RDFS = "http://www.w3.org/2000/01/rdf-schema#"
SYS = ("You are a biomedical entity-normalisation assistant. Given a mention and a list of "
"candidate ontology terms, you select the single correct term and emit a typed RDF/Turtle "
"triple (Biolink category + rdfs:label). You choose only from the CURIEs provided and never "
"invent identifiers. Output only Turtle.")
# ontology -> (pool key or GO aspect, Biolink category CamelCase, human domain word)
DOMAINS = [
("GO_BP", "BiologicalProcess", "biological process"),
("GO_MF", "MolecularActivity", "molecular function"),
("GO_CC", "CellularComponent", "cellular component"),
("MONDO", "Disease", "disease"),
("HP", "PhenotypicFeature", "phenotype"),
("CHEBI", "ChemicalEntity", "chemical entity"),
("CL", "Cell", "cell type"),
]
def draw(key):
if key.startswith("GO_"): return random.choice(S.GO_SPLIT[key[3:]])
cid, lab, _ = random.choice(S.OBO_POOL[key]); return cid, lab
def iri(curie): p, l = curie.split(":", 1); return S.PREFIX[p]+l
def build_one():
key, cat, dom = random.choice(DOMAINS)
cid, lab = draw(key)
# distractors from the same ontology (all real), then shuffle
cands = [(cid, lab)]
seen = {cid}
while len(cands) < 4:
d_c, d_l = draw(key)
if d_c in seen: continue
seen.add(d_c); cands.append((d_c, d_l))
random.shuffle(cands)
cand_str = "; ".join(f"{c} = {l}" for c, l in cands)
ttl = (f"@prefix biolink: <{BL}> .\n@prefix rdfs: <{RDFS}> .\n\n"
f'<{iri(cid)}> a biolink:{cat} ;\n rdfs:label "{lab}" .')
try: Graph().parse(data=ttl, format="turtle")
except Exception: return None
if S.label_of(cid) != lab: return None # membership + label gate
user = (f"Mention: \"{lab}\" (a {dom}).\n"
f"Candidate ontology terms: {cand_str}.\n"
f"Select the correct term and emit the typed grounding as Turtle. Output only Turtle.")
return {"messages": [{"role": "system", "content": SYS},
{"role": "user", "content": user},
{"role": "assistant", "content": ttl}], "_dom": dom}
def main(n=1000):
out = (ROOT/"data"/"pairs_obo.jsonl").open("w")
kept = 0; per = {}; tries = 0
while kept < n and tries < n*6:
tries += 1
r = build_one()
if not r: continue
out.write(json.dumps(r)+"\n"); kept += 1
per[r["_dom"]] = per.get(r["_dom"], 0)+1
out.close()
print(f"obo grounding pairs kept={kept} by domain: {dict(sorted(per.items()))}")
if __name__ == "__main__":
main()