|
a |
|
b/aiagents4pharma/talk2biomodels/api/ols.py |
|
|
1 |
""" |
|
|
2 |
This module contains the API for fetching ols database |
|
|
3 |
""" |
|
|
4 |
from typing import List, Dict |
|
|
5 |
import requests |
|
|
6 |
|
|
|
7 |
def fetch_from_ols(term: str) -> str: |
|
|
8 |
""" |
|
|
9 |
Fetch the label for a single term from OLS. |
|
|
10 |
|
|
|
11 |
Args: |
|
|
12 |
term (str): The term in the format "ONTOLOGY:TERM_ID". |
|
|
13 |
|
|
|
14 |
Returns: |
|
|
15 |
str: The label for the term or an error message. |
|
|
16 |
""" |
|
|
17 |
try: |
|
|
18 |
ontology, _ = term.split(":") |
|
|
19 |
base_url = f"https://www.ebi.ac.uk/ols4/api/ontologies/{ontology.lower()}/terms" |
|
|
20 |
params = {"obo_id": term} |
|
|
21 |
response = requests.get( |
|
|
22 |
base_url, |
|
|
23 |
params=params, |
|
|
24 |
headers={"Accept": "application/json"}, |
|
|
25 |
timeout=10 |
|
|
26 |
) |
|
|
27 |
response.raise_for_status() |
|
|
28 |
data = response.json() |
|
|
29 |
label = '-' |
|
|
30 |
# Extract and return the label |
|
|
31 |
if "_embedded" in data and "terms" in data["_embedded"] \ |
|
|
32 |
and len(data["_embedded"]["terms"]) > 0: |
|
|
33 |
label = data["_embedded"]["terms"][0].get("label", "Label not found") |
|
|
34 |
return label |
|
|
35 |
except (requests.exceptions.RequestException, KeyError, IndexError) as e: |
|
|
36 |
return f"Error: {str(e)}" |
|
|
37 |
|
|
|
38 |
def fetch_ols_labels(terms: List[str]) -> Dict[str, str]: |
|
|
39 |
""" |
|
|
40 |
Fetch labels for multiple terms from OLS. |
|
|
41 |
|
|
|
42 |
Args: |
|
|
43 |
terms (List[str]): A list of terms in the format "ONTOLOGY:TERM_ID". |
|
|
44 |
|
|
|
45 |
Returns: |
|
|
46 |
Dict[str, str]: A mapping of term IDs to their labels or error messages. |
|
|
47 |
""" |
|
|
48 |
results = {} |
|
|
49 |
for term in terms: |
|
|
50 |
results[term] = fetch_from_ols(term) |
|
|
51 |
return results |
|
|
52 |
|
|
|
53 |
def search_ols_labels(data: List[Dict[str, str]]) -> Dict[str, Dict[str, str]]: |
|
|
54 |
""" |
|
|
55 |
Fetch OLS annotations grouped by ontology type. |
|
|
56 |
|
|
|
57 |
Args: |
|
|
58 |
data (List[Dict[str, str]]): A list of dictionaries containing 'Id' and 'Database'. |
|
|
59 |
|
|
|
60 |
Returns: |
|
|
61 |
Dict[str, Dict[str, str]]: A mapping of ontology type to term labels. |
|
|
62 |
""" |
|
|
63 |
grouped_data = {} |
|
|
64 |
for entry in data: |
|
|
65 |
ontology = entry["Database"].lower() |
|
|
66 |
grouped_data.setdefault(ontology, []).append(entry["Id"]) |
|
|
67 |
|
|
|
68 |
results = {} |
|
|
69 |
for ontology, terms in grouped_data.items(): |
|
|
70 |
results[ontology] = fetch_ols_labels(terms) |
|
|
71 |
|
|
|
72 |
return results |