File size: 1,504 Bytes
6e9bb07
87c5f3b
 
 
 
6e9bb07
87c5f3b
 
6e9bb07
87c5f3b
 
6e9bb07
87c5f3b
 
 
 
 
 
 
 
 
 
6e9bb07
87c5f3b
 
 
 
 
 
 
 
 
 
6e9bb07
87c5f3b
 
 
 
 
 
 
 
 
 
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
# genesis/ontology.py
"""
Ontology Expansion for GENESIS-AI
Uses UMLS & BioPortal to find related terms, synonyms, and hierarchies.
"""

import os
import requests

UMLS_API_KEY = os.getenv("UMLS_API_KEY")
BIOPORTAL_API_KEY = os.getenv("BIOPORTAL_API_KEY")

def expand_with_bioportal(term):
    """Expand term using BioPortal ontology search."""
    try:
        url = f"https://data.bioontology.org/search?q={term}&apikey={BIOPORTAL_API_KEY}"
        r = requests.get(url)
        r.raise_for_status()
        data = r.json()
        return list({res["prefLabel"] for res in data.get("collection", []) if "prefLabel" in res})
    except Exception as e:
        return {"error": str(e)}

def expand_with_umls(term):
    """Expand term using UMLS API."""
    try:
        url = f"https://uts-ws.nlm.nih.gov/rest/search/current?string={term}&apiKey={UMLS_API_KEY}"
        r = requests.get(url)
        r.raise_for_status()
        data = r.json()
        return [res["name"] for res in data.get("result", {}).get("results", []) if "name" in res]
    except Exception as e:
        return {"error": str(e)}

def expand_terms_with_ontology(term):
    """Combine BioPortal and UMLS expansions."""
    bioportal_terms = expand_with_bioportal(term)
    umls_terms = expand_with_umls(term)
    results = set()
    if isinstance(bioportal_terms, list):
        results.update(bioportal_terms)
    if isinstance(umls_terms, list):
        results.update(umls_terms)
    return list(results) if results else [term]