Skip to content

Commit

Permalink
Merge pull request #115 from geneontology/gocam_model_integration
Browse files Browse the repository at this point in the history
Gocam model integration
  • Loading branch information
sierra-moxon authored Jan 6, 2025
2 parents cd0a7b2 + ff2dff8 commit ed0403e
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 2 deletions.
47 changes: 46 additions & 1 deletion app/routers/models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Model API router."""

import logging
from http.client import HTTPException
from pprint import pprint
from typing import List

import requests
from fastapi import APIRouter, Path, Query
from gocam.translation.minerva_wrapper import MinervaWrapper
from oaklib.implementations.sparql.sparql_implementation import SparqlImplementation
from oaklib.resource import OntologyResource

Expand All @@ -20,6 +23,48 @@
logger = logging.getLogger()


@router.get(
"/api/gocam-model/{id}",
tags=["models"],
description="Returns model details in gocam-py format based on a GO-CAM model ID.",
)
async def get_gocam_model_by_id_in_gocam_py_format(
id: str = Path(
...,
description="A GO-CAM identifier (e.g. 581e072c00000820, 581e072c00000295, 5900dc7400000968)",
example="581e072c00000295",
)
) -> dict:
"""
Returns model details in gocam-py format based on a GO-CAM model ID.
:param id: A GO-CAM identifier (e.g. 581e072c00000820, 581e072c00000295, 5900dc7400000968)
:return: model details in gocam-py format based on a GO-CAM model ID.
"""
mw = MinervaWrapper()
stripped_ids = []
if id.startswith("gomodel:"):
model_id = id.replace("gomodel:", "")
stripped_ids.append(model_id)
else:
stripped_ids.append(id)
for stripped_id in stripped_ids:
path_to_s3 = "https://go-public.s3.amazonaws.com/files/go-cam/%s.json" % stripped_id
print(path_to_s3)
try:
response = requests.get(path_to_s3, timeout=30, headers={"User-Agent": USER_AGENT})
print(response.json())
response.raise_for_status()
if response.status_code == 403 or response.status_code == 404:
raise DataNotFoundException("GO-CAM model not found.")
data = response.json()
gocam_reposnse = mw.minerva_object_to_model(data) # convert minerva object to gocam model
pprint(gocam_reposnse)
return gocam_reposnse.model_dump()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Unexpected error: {e}") from e


@router.get("/api/models/go", tags=["models"], description="Returns go term details based on a GO-CAM model ID.")
async def get_goterms_by_model_id(
gocams: List[str] = Query(
Expand Down Expand Up @@ -313,7 +358,7 @@ async def get_pmid_by_model_id(

@router.get(
"/api/go-cam/{id}", tags=["models"], description="Returns model details based on a GO-CAM model ID in JSON format."
)
) # note: this is the endpoint that is currently used by gocam-py to for use in CTX export.
async def get_model_details_by_model_id_json(
id: str = Path(
...,
Expand Down
15 changes: 15 additions & 0 deletions app/utils/sparql_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
"""Utils for SPARQL queries."""

from typing import Any

from fastapi.responses import ORJSONResponse


def create_response(data: Any):
"""
Create a response with the given data.
:param data:
:return:
"""
return ORJSONResponse(content=data.dict())


SEPARATOR = "|" # separator for splitting values


Expand Down
22 changes: 21 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ go-deploy = ">=0.4.1"
biothings-client = "^0.3.0"
email-validator = "^2.0.0.post2"
bmt = "^1.1.2"
gocam = "^0.2.0"

[tool.poetry.dev-dependencies]
pytest = ">=7.4.0"
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/test_models_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from requests import HTTPError

from app.main import app
from tests.integration.step_defs.bioentity_function_steps import response_code

logging.basicConfig(filename="combined_access_error.log", level=logging.INFO, format="%(asctime)s - %(message)s")
logger = logging.getLogger()
Expand Down Expand Up @@ -151,6 +152,16 @@ def test_get_model_details_by_model_id_json(self):
self.assertGreater(len(response.json().get("individuals")), 0)
self.assertGreater(len(response.json().get("facts")), 0)

def test_get_model_details_by_model_id_json_gocam_py(self):
"""
Test the endpoint to retrieve model details by model ID in JSON format from the S3 bucket, check for success.
:return: None
"""
for id in go_cam_ids:
response = test_client.get(f"/api/gocam-model/{id}")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json().get("id"), "gomodel:" + id.replace("gomodel:", ""))

def test_get_model_details_by_model_id_not_found_json(self):
"""
Expand Down

0 comments on commit ed0403e

Please sign in to comment.