diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3df88855a76da515ac43c17a3adfdb4d65037b9 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,11 @@ +import logging +import logging.config as logging_config +import os + +logging_config.fileConfig("logging.conf", disable_existing_loggers=False) +logger = logging.getLogger(__name__) + +if os.getenv("DEBUG"): + logger.setLevel(logging.DEBUG) + +REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/1") diff --git a/app/annotations/__init__.py b/app/annotations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/annotations/annotations.py b/app/annotations/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..69da878b12fcab5b845055422ec7db604eae8729 --- /dev/null +++ b/app/annotations/annotations.py @@ -0,0 +1,122 @@ +from typing import Any, Optional + +from fastapi import Path, Query +from fastapi.responses import JSONResponse +from fastapi.routing import APIRouter +from starlette import status + +from app import logger +from app.annotations.schema import Annotation, FeatureType +from app.config import get_base_service_url, get_services +from app.constants import UNIPROT_ID_PARAM, UNIPROT_QUAL_DESC, UNIPROT_RANGE_DESC +from app.utils import clean_args, get_final_service_url, send_async_requests + +annotations_route = APIRouter() + + +@annotations_route.get( + "/{uniprot_qualifier}.json", + status_code=status.HTTP_200_OK, + summary="Get annotations for a UniProt residue range", + description="Get annotations for a range of UniProt residues.", + response_model=Annotation, + tags=["Annotations"], + response_model_exclude_unset=True, + include_in_schema=True, + response_model_exclude_none=True, +) +async def get_annotations_api( + uniprot_qualifier: Any = Path( + ..., + description=UNIPROT_QUAL_DESC, + openapi_examples={ + "default": { + "summary": "Example UniProt accession", + "value": UNIPROT_ID_PARAM, + } + }, + ), + annotation_type: FeatureType = Query( + ..., description="Annotation type", alias="type" + ), + provider: Optional[Any] = Query( + None, enum=[x["provider"] for x in get_services("annotations")] + ), + res_range: Any = Query(None, alias="range", description=UNIPROT_RANGE_DESC), +): + f"""Returns annotation details for a UniProt accession + + Args: + uniprot_qualifier (Any): {UNIPROT_QUAL_DESC} + range (Any, optional): {UNIPROT_RANGE_DESC} Defaults to None. + provider (str, optional): Data provider + annotation_type (FeatureType, optional): Annotation type. + + Raises: + HTTPException: Raised when there are validation issues with parameters + + Returns: + Result: A Annotations model + """ + + uniprot_qualifier = uniprot_qualifier.upper() + + results = await get_annotations_api_helper( + uniprot_qualifier, annotation_type, provider, res_range + ) + + if not results: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + + return results + + +@clean_args() +async def get_annotations_api_helper( + uniprot_qualifier: str, + annotation_type: str, + provider: Optional[str] = None, + res_range: Optional[str] = None, +): + """Helper function for get_annotations_api""" + qualifier = uniprot_qualifier.upper() + services = get_services( + service_type="annotations", + provider=provider, + ) + calls = [] + for service in services: + base_url = get_base_service_url(service["provider"]) + final_url = get_final_service_url( + base_url, service["accessPoint"], f"{qualifier}.json" + ) + final_url = f"{final_url}&type={annotation_type}" + if res_range: + final_url = f"{final_url}&range={res_range}" + + calls.append(final_url) + + result = await send_async_requests(calls) + final_result = [] + + for x in result: + if x and x.status_code == status.HTTP_200_OK: + try: + final_result.append(dict(x.json())) + except Exception: + logger.error(f"Error parsing response from {x.url}") + + if not final_result: + return None + + annotations = [] + + for result in final_result: + annotations.extend(result["annotation"]) + + return Annotation( + accession=uniprot_qualifier, + id=final_result[0]["id"], + sequence=final_result[0]["sequence"], + annotation=annotations, + ) diff --git a/app/annotations/schema.py b/app/annotations/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..0beef769fbe15903f9a74a045f004c84e7cf4ee3 --- /dev/null +++ b/app/annotations/schema.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from enum import Enum +from typing import List, Optional + +from pydantic import BaseModel, Field + + +class FeatureType(Enum): + CARBOHYD = "CARBOHYD" + DOMAIN = "DOMAIN" + ACT_SITE = "ACT_SITE" + METAL = "METAL" + BINDING = "BINDING" + NON_STD = "NON_STD" + MOD_RES = "MOD_RES" + DISULFID = "DISULFID" + MUTAGEN = "MUTAGEN" + HELIX = "HELIX" + STRAND = "STRAND" + DISORDERED = "DISORDERED" + INTERFACE = "INTERFACE" + CHANNEL = "CHANNEL" + + def __str__(self) -> str: + return self.value + + +class Region(BaseModel): + start: int = Field( + ..., + description="The first position of the annotation", + json_schema_extra={"example": 23}, + ) + end: int = Field( + ..., + description="The last position of the annotation", + json_schema_extra={"example": 42}, + ) + annotation_value: str = Field( + None, + description="The value of the annotation", + json_schema_extra={"example": "0.9"}, + ) + unit: str = Field( + None, + description="The unit of the annotation value, if applicable", + json_schema_extra={"example": "mmol"}, + ) + + +class Evidence(Enum): + EXPERIMENTALLY_DETERMINED = "EXPERIMENTALLY DETERMINED" + COMPUTATIONAL_PREDICTED = "COMPUTATIONAL/PREDICTED" + FROM_LITERATURE = "FROM LITERATURE" + + +class FeatureItem(BaseModel): + type: FeatureType = Field( + ..., + description="Type of the annotation", + json_schema_extra={"example": "ACT_SITE"}, + ) + description: str = Field( + ..., + description="Description/Label of the annotation", + json_schema_extra={"example": "Pfam N1221 (PF07923})"}, + ) + source_name: Optional[str] = Field( + None, + description="Name of the source of the annotations, i.e. where is " + "the data from", + ) + source_url: Optional[str] = Field( + None, + description="URL of the source of the annotation, i.e. where to find more data", + ) + evidence: Optional[Evidence] = Field( + None, description="Evidence category of the annotation" + ) + residues: Optional[List[int]] = Field( + None, description="An array of residue indices" + ) + regions: Optional[List[Region]] = Field(None) + + +class Annotation(BaseModel): + accession: str = Field( + ..., description="A UniProt accession", json_schema_extra={"example": "P00734"} + ) + id: Optional[str] = Field( + None, + description="A UniProt identifier", + json_schema_extra={"example": "FGFR2_HUMAN"}, + ) + sequence: str = Field( + ..., + description="The sequence of the protein", + json_schema_extra={"example": "AFFGVAATRKL"}, + ) + annotation: Optional[List[FeatureItem]] = None diff --git a/app/app.py b/app/app.py new file mode 100644 index 0000000000000000000000000000000000000000..f4969980ea40a1d425ed39f302d8d140f2ca1e2d --- /dev/null +++ b/app/app.py @@ -0,0 +1,129 @@ +import time +from contextlib import asynccontextmanager +import os + +from uvicorn.workers import UvicornWorker +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.gzip import GZipMiddleware +from fastapi.openapi.utils import get_openapi +from prometheus_fastapi_instrumentator import Instrumentator +from starlette.requests import Request + +from app import REDIS_URL +from app.annotations.annotations import annotations_route +from app.ensembl.ensembl import ensembl_route +from app.health.health import health_route +from app.sequence.sequence import sequence_route +from app.uniprot.uniprot import uniprot_route +from app.version import __version__ as schema_version + +instrumentator = Instrumentator( + should_group_status_codes=True, + should_ignore_untemplated=True, + should_respect_env_var=False, + excluded_handlers=[".*admin.*", "/metrics"], + env_var_name="ENABLE_METRICS", +) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Async context manager for FastAPI lifespan events.""" + # Startup: load configs + from app.config import load_data_file + from worker.cache.redis_cache import RedisCache + + RedisCache.init_redis(REDIS_URL, "utf-8") + load_data_file() + + yield + + # Shutdown: clear caches + from app.config import get_providers, read_data_file + + read_data_file.cache_clear() + load_data_file.cache_clear() + get_providers.cache_clear() + + +app = FastAPI( + lifespan=lifespan, + docs_url="/", + title="3D Beacons HUB API", + description="The 3D-Beacons Network provides unified programmatic access to " + "experimentally determined and predicted structure models.", + contact={ + "name": "3D-Beacons Network", + "url": "https://3dbeacons.org", + "email": "pdbekb_help@ebi.ac.uk", + }, + license_info={ + "name": "CC BY 4.0", + "url": "https://creativecommons.org/licenses/by/4.0/", + }, + redoc_url=None, + version=schema_version, +) +app.include_router(uniprot_route, prefix="/uniprot") +app.include_router(ensembl_route, prefix="/ensembl") +app.include_router(sequence_route, prefix="/sequence") +app.include_router(annotations_route, prefix="/annotations") +app.include_router(health_route, prefix="/health") + +origins = ["*"] + +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) +app.add_middleware(GZipMiddleware) + +instrumentator.instrument(app) +instrumentator.expose(app, include_in_schema=False, should_gzip=False) + + +@app.middleware("http") +async def add_extra_headers(request: Request, call_next): + start_time = time.time() + response = await call_next(request) + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + response.headers["X-3DBeacons-API-Version"] = schema_version + return response + + +class CustomUvicornWorker(UvicornWorker): + CONFIG_KWARGS = {} + root_path = os.environ.get("ROOT_PATH", "") + if root_path: + CONFIG_KWARGS.update({"root_path": root_path}) + + +def custom_openapi(): + if not app.openapi_schema: + app.openapi_schema = get_openapi( + title=app.title, + version=app.version, + openapi_version=app.openapi_version, + description=app.description, + terms_of_service=app.terms_of_service, + contact=app.contact, + license_info=app.license_info, + routes=app.routes, + tags=app.openapi_tags, + servers=app.servers, + ) + for _, method_item in app.openapi_schema.get("paths").items(): + for _, param in method_item.items(): + responses = param.get("responses") + # remove 422 response, also can remove other status code + if "422" in responses: + del responses["422"] + return app.openapi_schema + + +app.openapi = custom_openapi diff --git a/app/cli.py b/app/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..047ea21487ffe6396d62ff2dcd1d445473ac0fa1 --- /dev/null +++ b/app/cli.py @@ -0,0 +1,11 @@ +import click + + +@click.group("CLI", help="CLI application for 3d-Beacons Hub API") +def main(): + """The main CLI application + + Returns: + int: An integer value as exit status. + """ + return 0 diff --git a/app/config/__init__.py b/app/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20e09c1fabacd019b9a3cc1a5137aa1e69bb8b4b --- /dev/null +++ b/app/config/__init__.py @@ -0,0 +1,124 @@ +import json +import os +from functools import lru_cache + +from fastapi.params import Query + +from app import logger + +DATA_FILE = "data.json" +ENV = os.getenv("ENVIRONMENT", "DEV") +MAX_POST_LIMIT = int(os.getenv("MAX_POST_LIMIT", 10)) +GIFTS_API = os.getenv("GIFTS_API", "https://www.ebi.ac.uk/gifts/api/mappings/") +UNIPROT_API = os.getenv("UNIPROT_API", "https://www.ebi.ac.uk/proteins/api/proteins/") +DISABLED_BEACONS = os.environ.get("DISABLED_BEACONS", "").split(",") + +logger.debug(f"Environment is {ENV}") + + +@lru_cache(maxsize=None) +def read_data_file(filename): + data_filepath = os.path.join(os.path.dirname(__file__), filename) + with open(data_filepath) as fp: + data = json.load(fp) + + # check for REGISTRY_DATA_JSON in env and loads the JSON if exists + data_json_env = os.getenv("REGISTRY_DATA_JSON") + + if data_json_env: + logger.info( + f"REGISTRY_DATA_JSON env var exists, trying to load JSON @ {data_json_env}" + ) + data = read_registry_data(data_json_env) + + logger.info(f"Loaded data JSON: {DATA_FILE}") + return data + + +def read_registry_data(data_json_env): + import requests + + try: + request_data = requests.get(data_json_env) + if request_data.status_code == 200: + data = request_data.json() + else: + raise Exception + except Exception: + logger.info("Registry JSON cannot be retrieved, fallback to default data.json") + return data + + +def get_services( + service_type: str = None, provider: Query = None, exclude_provider: Query = None +): + """Returns a list of services available. + + Args: + service_type (str, optional): A type of service. + provider (Query, optional): A provider. + exclude_provider (Query, optional): Provider to exclude. + Returns: + list: A list of services based on the parameters passed. + """ + data_file = DATA_FILE + data = read_data_file(data_file) + results = [] + + # assuming all services to be returned when no service_type and provider is passed + if not service_type and not provider and not exclude_provider: + return data["services"] + + # filter services for a service type + if service_type: + results = list( + filter( + lambda x: x["serviceType"] == service_type, + [x for x in data["services"]], + ) + ) + + # filter services for a provider + if provider: + results = list( + filter(lambda x: x["provider"] == provider, [x for x in results]) + ) + + if DISABLED_BEACONS: + results = list( + filter( + lambda x: x["provider"] not in DISABLED_BEACONS, [x for x in results] + ) + ) + + if exclude_provider: + results = list( + filter(lambda x: x["provider"] != exclude_provider, [x for x in results]) + ) + + return results + + +@lru_cache(maxsize=None) +def get_providers(): + data_file = DATA_FILE + data = read_data_file(data_file) + + return data["providers"] + + +def get_base_service_url(provider: str) -> str: + url_key = "baseServiceUrl" + + if ENV == "DEV": + url_key = "devBaseServiceUrl" + + providers = get_providers() + return list(filter(lambda x: x["providerId"] == provider, providers))[0][url_key] + + +@lru_cache(maxsize=None) +def load_data_file(): + data_file = DATA_FILE + read_data_file(data_file) + return diff --git a/app/constants.py b/app/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..8216365a3f3ab2488bd7817751bd964d3b9b21d7 --- /dev/null +++ b/app/constants.py @@ -0,0 +1,28 @@ +# UNIPROT related description +UNIPROT_AC_DESC = "UniProt accession, e.g. P00520" +UNIPROT_ID_DESC = "UniProt identifier, e.g. ABL1_MOUSE" +UNIPROT_RANGE_DESC = "Specify a UniProt sequence residue range; separated by hyphen(-)." +UNIPROT_QUAL_DESC = "UniProtKB accession number (AC) or entry name (ID)" +QUERY_DESC = ( + "UniProtKB accession number (AC), entry name (ID) or CRC64 checksum " + "of the UniProt sequence" +) +TEMPLATE_DESC = ( + "Template is 4 letter PDB code, or 4 letter code with " + "assembly ID and chain for SMTL entries" +) +UNP_CHECKSUM_DESC = "CRC64 checksum of the UniProt sequence" +ENSEMBL_QUAL_DESC = "Ensembl identifier." + +# RESPONSE MESSAGES +NO_JOB_FOUND_MESSAGE = ( + "No search job found for the given sequence, please submit the job again!" +) +SEARCH_IN_PROGRESS_MESSAGE = "Search in progress, please try after sometime!" +JOB_SUBMISSION_ERROR_MESSAGE = "Error in submitting the job, please retry!" +JOB_FAILED_ERROR_MESSAGE = ( + "Failed to process the search request, please submit the sequence again!" +) + +# EXAMPLE params +UNIPROT_ID_PARAM = "Q14676" diff --git a/app/ensembl/__init__.py b/app/ensembl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/ensembl/ensembl.py b/app/ensembl/ensembl.py new file mode 100644 index 0000000000000000000000000000000000000000..468e01851106229d474b9b78870662c49438dd73 --- /dev/null +++ b/app/ensembl/ensembl.py @@ -0,0 +1,150 @@ +from typing import Any, Dict, List, Optional, Set + +from fastapi.params import Path, Query +from fastapi.routing import APIRouter +from starlette import status +from starlette.responses import JSONResponse + +from app.config import GIFTS_API, MAX_POST_LIMIT, get_services +from app.constants import ENSEMBL_QUAL_DESC +from app.ensembl.schema import EnsemblSummary +from app.uniprot.helper import ( + get_list_of_uniprot_summary_helper, + get_uniprot_api_results, + get_uniprot_name, +) +from app.uniprot.schema import AccessionListRequest +from app.utils import clean_args, request_get + +ensembl_route = APIRouter() + + +@ensembl_route.get( + "/summary/{qualifier}.json", + status_code=status.HTTP_200_OK, + response_model=EnsemblSummary, + response_model_exclude_unset=True, + tags=["Ensembl"], +) +async def get_ensembl_summary( + qualifier: Any = Path( + ..., + description=ENSEMBL_QUAL_DESC, + openapi_examples={ + "default": { + "summary": "Example Ensembl gene ID", + "value": "ENSG00000288864", + } + }, + ), + provider: Optional[Any] = Query( + None, enum=[x["provider"] for x in get_services("summary")] + ), +): + f"""Returns summary of experimental and theoretical models for an Ensembl gene ID. + + Args: + qualifier (str): {ENSEMBL_QUAL_DESC} + provider (str, optional): Data provider + + Returns: + Result: A Result summary object with experimental and theoretical models. + """ + ensembl_summary = await get_ensembl_summary_helper(qualifier, provider) + + if not ensembl_summary: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + + return ensembl_summary + + +@clean_args() +async def get_ensembl_summary_helper( + qualifier: str, + provider=None, +): + f"""Returns summary of experimental and theoretical models for a UniProt + accession or entry name + + Args: + qualifier (str): {ENSEMBL_QUAL_DESC} + provider (str, optional): Data provider + + Returns: + Result: A Result summary object with experimental and theoretical models. + """ + qualifier = qualifier.upper() + + ensembl_mappings = await get_ensembl_mappings(qualifier) + + if not ensembl_mappings: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + + transcript_dict: Dict[str, List] = {} + uniprot_request_list = AccessionListRequest(accessions=[], provider=provider) + uniprot_set: Set = set() + + for mapping in ensembl_mappings["entryMappings"]: + if len(uniprot_set) >= MAX_POST_LIMIT: + break + + uniprot_accession = mapping["uniprotEntry"]["uniprotAccession"] + uniprot_set.add(uniprot_accession) + mapping["ensemblTranscript"].update( + { + "alignment_difference": mapping["alignment_difference"], + "transcript_id": str(mapping["ensemblTranscript"]["transcript_id"]), + } + ) + + if not transcript_dict.get(uniprot_accession): + transcript_dict[uniprot_accession] = [] + + transcript_dict[uniprot_accession].append(mapping["ensemblTranscript"]) + + uniprot_request_list.accessions = list(uniprot_set) + uniprot_summary = await get_list_of_uniprot_summary_helper(uniprot_request_list) + uniprot_api_response = await get_uniprot_api_results( + uniprot_request_list.accessions + ) + + if not uniprot_summary: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + + results = { + "ensembl_id": qualifier, + "species": ensembl_mappings["taxonomy"]["species"], + "taxid": str(ensembl_mappings["taxonomy"]["ensemblTaxId"]), + "uniprot_mappings": [], + } + + for uniprot in uniprot_summary: + uniprot_response = uniprot_api_response.get(uniprot.uniprot_entry.ac) + uniprot.uniprot_entry.description = get_uniprot_name(uniprot_response) + + for ensembl_transcript in transcript_dict[uniprot.uniprot_entry.ac]: + results["uniprot_mappings"].append( + { + "ensembl_transcript": ensembl_transcript, + "uniprot_accession": uniprot, + } + ) + + return results + + +async def get_ensembl_mappings(qualifier: str): + f"""Get UniProt mappings for a gene ID. + + Args: + qualifier (str): {ENSEMBL_QUAL_DESC} + + Returns: + Dict: Mappings for a gene ID. + """ + result = await request_get(f"{GIFTS_API}?searchTerm={qualifier}&format=json") + + if result.status_code == status.HTTP_200_OK: + return dict(result.json()).get("results")[0] + + return None diff --git a/app/ensembl/schema.py b/app/ensembl/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..13743f86f5c8380dd07765adeafde13806214abc --- /dev/null +++ b/app/ensembl/schema.py @@ -0,0 +1,32 @@ +# generated by datamodel-codegen: +# filename: 3dbeacons.yaml +# timestamp: 2022-05-13T10:29:41+00:00 + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import BaseModel, Field + +from app.uniprot.schema import UniprotSummary + + +class EnsemblTranscript(BaseModel): + transcript_id: str = Field(..., description="Transcript identifier") + seqRegionStart: int = Field(..., description="Start position of the transcript") + seqRegionEnd: int = Field(..., description="End position of the transcript") + alignment_difference: Optional[float] = Field( + None, description="Fraction of alignment difference (0 to 1)", ge=0, le=1 + ) + + +class UniprotMapping(BaseModel): + ensembl_transcript: EnsemblTranscript + uniprot_accession: UniprotSummary + + +class EnsemblSummary(BaseModel): + ensembl_id: str = Field(..., description="An Ensembl identifier") + species: str = Field(..., description="Species name") + taxid: str = Field(..., description="Taxonomy identifier") + uniprot_mappings: List[UniprotMapping] diff --git a/app/exception.py b/app/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..d99769ba6738658b1befa6d56dc2fb719ea72183 --- /dev/null +++ b/app/exception.py @@ -0,0 +1,22 @@ +class JobNotFoundException(Exception): + pass + + +class JobResultsNotFoundException(Exception): + pass + + +class JobStatusNotFoundException(Exception): + pass + + +class NotInCacheException(Exception): + pass + + +class RequestSubmissionException(Exception): + pass + + +class RequestTimeoutException(Exception): + pass diff --git a/app/gunicorn_conf.py b/app/gunicorn_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..9279c6066ee47149b6b1a34843d6843b90423943 --- /dev/null +++ b/app/gunicorn_conf.py @@ -0,0 +1,11 @@ +# Gunicorn config variables +loglevel = "info" +errorlog = "-" # stderr +accesslog = "-" # stdout +worker_tmp_dir = "/dev/shm" +graceful_timeout = 120 +timeout = 120 +keepalive = 5 +threads = 10 +workers = 3 +worker_class = "app.app.CustomUvicornWorker" diff --git a/app/health/__init__.py b/app/health/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/health/health.py b/app/health/health.py new file mode 100644 index 0000000000000000000000000000000000000000..ecbe9f3e48b3b11ad326223f4d1b6765029dbdc0 --- /dev/null +++ b/app/health/health.py @@ -0,0 +1,86 @@ +from fastapi.encoders import jsonable_encoder +from fastapi.routing import APIRouter +from starlette import status +from starlette.responses import JSONResponse + +from app.config import get_base_service_url, get_services +from app.health.schema import HealthResponse, HealthStatus +from app.utils import get_final_service_url, send_async_requests + +health_route = APIRouter() + + +@health_route.get( + "/", + summary="Health Check", + description="Returns the health status of all the beacons.", + response_model=HealthResponse, + responses={ + status.HTTP_200_OK: { + "description": "Service is healthy.", + "content": { + "application/health+json": { + "example": [ + { + "status": "pass", + "service_id": "pdbe", + "beacons_api_version": "2.7.0", + "output": "", + } + ] + } + }, + }, + status.HTTP_500_INTERNAL_SERVER_ERROR: { + "description": "Service is down or unhealthy.", + "content": { + "application/health+json": { + "example": [ + { + "status": "fail", + "service_id": "pdbe", + "beacons_api_version": "2.7.0", + "output": "Service is unhealthy, not able to " + "reach the backend!", + } + ] + } + }, + }, + }, +) +async def health_check(): + """ + Returns the health status of all the beacons. + """ + services = get_services(service_type="health") + calls = [] + for service in services: + base_url = get_base_service_url(service["provider"]) + final_url = get_final_service_url(base_url, service["accessPoint"]) + + calls.append(final_url) + + result = await send_async_requests(calls) + final_result = [] + + failed = False + for beacons_response in result: + if beacons_response.status_code != status.HTTP_200_OK: + # If any service returns a non-200 status, we consider the + # overall health check as failed + failed = True + for beacons_status in beacons_response.json(): + final_result.append(HealthStatus(**beacons_status)) + + if failed: + return JSONResponse( + media_type="application/health+json", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + content=jsonable_encoder(final_result), + ) + return JSONResponse( + media_type="application/health+json", + status_code=status.HTTP_200_OK, + content=jsonable_encoder(final_result), + ) diff --git a/app/health/schema.py b/app/health/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3f7310bc8a4fa0e863d9384d57154e41e3c621 --- /dev/null +++ b/app/health/schema.py @@ -0,0 +1,36 @@ +from enum import Enum +from typing import List, Optional + +from pydantic import BaseModel, Field, RootModel + + +# Health Endpoint Models +class HealthStatusEnum(str, Enum): + """Health status enumeration based on the OpenAPI spec""" + + PASS = "pass" + WARN = "warn" + FAIL = "fail" + + +class HealthStatus(BaseModel): + """Individual service health status model for /health endpoint""" + + status: HealthStatusEnum = Field(..., description="The status of the service") + service_id: str = Field( + ..., + description="The identifier of the service, corresponds to the provider ID " + "in the registry", + ) + beacons_api_version: str = Field( + ..., description="The version of the 3DBeacons API" + ) + output: Optional[str] = Field( + None, description="Raw error output, in case of 'fail' or 'warn' states" + ) + + +class HealthResponse(RootModel[List[HealthStatus]]): + """Response model for /health endpoint - returns array of status objects""" + + model_config = {"title": "HealthResponse"} diff --git a/app/sequence/helper.py b/app/sequence/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee3e359fcc8890cdc403d9266e1b9d4f0a911c6 --- /dev/null +++ b/app/sequence/helper.py @@ -0,0 +1,52 @@ +import hashlib + +from starlette.responses import JSONResponse +from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST + +from app.constants import NO_JOB_FOUND_MESSAGE +from app.exception import RequestSubmissionException +from app.utils import request_post +from worker.cache.utils import clear_jobdispatcher_id + + +def generate_hash(sequence: str): + """Generate an MD5 hash from a sequence. + + Args: + sequence (str): A protein sequence string + """ + return hashlib.md5(sequence.encode()).hexdigest() + + +async def submit_sequence_search_job(sequence: str) -> str: + """Submit a sequence to the search engine. + + Args: + sequence (str): A protein sequence string + Returns: + str: A job id + """ + url = "https://www.ebi.ac.uk/Tools/services/rest/ncbiblast/run" + data = { + "email": "pdbekb_help@ebi.ac.uk", + "program": "blastp", + "stype": "protein", + "sequence": sequence, + "database": "uniprotkb", + } + try: + response = await request_post(url, data) + if response and response.status_code == HTTP_200_OK: + return response.content.decode() + except Exception: + pass + raise RequestSubmissionException("Request submission failed!") + + +async def handle_no_job_error(job_id: str): + clear_jobdispatcher_id(hashed_sequence=job_id) + + return JSONResponse( + status_code=HTTP_400_BAD_REQUEST, + content={"message": NO_JOB_FOUND_MESSAGE}, + ) diff --git a/app/sequence/schema.py b/app/sequence/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..397a19f57ddd00c993d0103c4667c4707533a953 --- /dev/null +++ b/app/sequence/schema.py @@ -0,0 +1,302 @@ +from enum import Enum +from typing import List, Optional + +from pydantic import BaseModel, Field + +from app.constants import ( + JOB_FAILED_ERROR_MESSAGE, + JOB_SUBMISSION_ERROR_MESSAGE, + NO_JOB_FOUND_MESSAGE, + SEARCH_IN_PROGRESS_MESSAGE, +) +from app.uniprot.schema import UniprotSummary + + +class Sequence(BaseModel): + sequence: str + + +class JobSubmissionErrorMessage(BaseModel): + message: str = JOB_SUBMISSION_ERROR_MESSAGE + + +class SearchSuccessMessage(BaseModel): + job_id: str + + +class SearchInProgressMessage(BaseModel): + message: str = SEARCH_IN_PROGRESS_MESSAGE + + +class NoJobFoundMessage(BaseModel): + message: str = NO_JOB_FOUND_MESSAGE + + +class JobFailedErrorMessage(BaseModel): + message: str = JOB_FAILED_ERROR_MESSAGE + + +class HSPS(BaseModel): + hsp_score: float + hsp_bit_score: float + hsp_align_len: int + hsp_identity: float + hsp_positive: float + hsp_qseq: str + hsp_hseq: str + hsp_mseq: str + hsp_expect: float + + +class SearchAccession(BaseModel): + accession: str + id: str + description: str + hit_length: int + hit_hsps: List[HSPS] + summary: UniprotSummary = None + hit_uni_ox: int + hit_uni_os: str + hit_com_os: str + title: str + + +class SearchResults(BaseModel): + hits: List[SearchAccession] + total_hits: int + current_page: int + total_pages: int + max_results_per_page: int + + +class ChecksumType(str, Enum): + """Type of checksum enumeration""" + + CRC64 = "CRC64" + MD5 = "MD5" + + +class ModelCategory(str, Enum): + """Model category enumeration""" + + EXPERIMENTALLY_DETERMINED = "EXPERIMENTALLY DETERMINED" + TEMPLATE_BASED = "TEMPLATE-BASED" + AB_INITIO = "AB-INITIO" + CONFORMATIONAL_ENSEMBLE = "CONFORMATIONAL ENSEMBLE" + + +class ModelFormat(str, Enum): + """Model format enumeration""" + + PDB = "PDB" + MMCIF = "MMCIF" + BCIF = "BCIF" + + +class ModelType(str, Enum): + """Model type enumeration""" + + ATOMIC = "ATOMIC" + DUMMY = "DUMMY" + MIX = "MIX" + + +class ExperimentalMethod(str, Enum): + """Experimental method enumeration""" + + ELECTRON_CRYSTALLOGRAPHY = "ELECTRON CRYSTALLOGRAPHY" + ELECTRON_MICROSCOPY = "ELECTRON MICROSCOPY" + EPR = "EPR" + FIBER_DIFFRACTION = "FIBER DIFFRACTION" + FLUORESCENCE_TRANSFER = "FLUORESCENCE TRANSFER" + INFRARED_SPECTROSCOPY = "INFRARED SPECTROSCOPY" + NEUTRON_DIFFRACTION = "NEUTRON DIFFRACTION" + X_RAY_POWDER_DIFFRACTION = "X-RAY POWDER DIFFRACTION" + SOLID_STATE_NMR = "SOLID-STATE NMR" + SOLUTION_NMR = "SOLUTION NMR" + X_RAY_SOLUTION_SCATTERING = "X-RAY SOLUTION SCATTERING" + THEORETICAL_MODEL = "THEORETICAL MODEL" + X_RAY_DIFFRACTION = "X-RAY DIFFRACTION" + HYBRID = "HYBRID" + + +class ConfidenceType(str, Enum): + """Confidence type enumeration""" + + PLDDT = "pLDDT" + QMEANDISCO = "QMEANDisCo" + IPTM_PTM = "ipTM+pTM" + + +class OligomericState(str, Enum): + """Oligomeric state enumeration""" + + MONOMER = "MONOMER" + HOMODIMER = "HOMODIMER" + HETERODIMER = "HETERODIMER" + HOMO_OLIGOMER = "HOMO-OLIGOMER" + HETERO_OLIGOMER = "HETERO-OLIGOMER" + + +class EntityType(str, Enum): + """Entity type enumeration""" + + BRANCHED = "BRANCHED" + MACROLIDE = "MACROLIDE" + NON_POLYMER = "NON-POLYMER" + POLYMER = "POLYMER" + WATER = "WATER" + + +class EntityPolyType(str, Enum): + """Entity poly type enumeration""" + + CYCLIC_PSEUDO_PEPTIDE = "CYCLIC-PSEUDO-PEPTIDE" + PEPTIDE_NUCLEIC_ACID = "PEPTIDE NUCLEIC ACID" + POLYDEOXYRIBONUCLEOTIDE = "POLYDEOXYRIBONUCLEOTIDE" + POLYDEOXYRIBONUCLEOTIDE_POLYRIBONUCLEOTIDE_HYBRID = ( + "POLYDEOXYRIBONUCLEOTIDE/POLYRIBONUCLEOTIDE HYBRID" + ) + POLYPEPTIDE_D = "POLYPEPTIDE(D)" + POLYPEPTIDE_L = "POLYPEPTIDE(L)" + POLYRIBONUCLEOTIDE = "POLYRIBONUCLEOTIDE" + OTHER = "OTHER" + + +class IdentifierCategory(str, Enum): + """Identifier category enumeration""" + + UNIPROT = "UNIPROT" + RFAM = "RFAM" + CCD = "CCD" + SMILES = "SMILES" + INCHI = "INCHI" + INCHIKEY = "INCHIKEY" + + +class SequenceIdType(str, Enum): + SEQUENCE = "sequence" + CRC64 = "crc64" + MD5 = "md5" + + +class Entity(BaseModel): + """Molecular entity in the model""" + + entity_type: EntityType = Field(..., description="Type of the molecular entity") + entity_poly_type: Optional[EntityPolyType] = Field( + None, description="Type of the molecular entity polymer" + ) + identifier: Optional[str] = Field(None, description="Identifier of the molecule") + identifier_category: Optional[IdentifierCategory] = Field( + None, description="Category of the identifier" + ) + description: str = Field(..., description="Textual label of the molecule") + chain_ids: List[str] = Field( + ..., description="List of chain identifiers of the molecule" + ) + + +class SummaryItems(BaseModel): + """Summary items for a structure""" + + model_identifier: str = Field( + ..., description="Identifier of the model, such as PDB id" + ) + model_category: ModelCategory = Field(..., description="Category of the model") + model_url: str = Field(..., description="URL of the model coordinates") + model_format: ModelFormat = Field(..., description="File format of the coordinates") + model_type: Optional[ModelType] = Field( + None, + description="Defines if coordinates are atomic-level or contain dummy atoms", + ) + model_page_url: Optional[str] = Field( + None, description="URL of a web page showing the model" + ) + provider: str = Field(..., description="Name of the model provider") + number_of_conformers: Optional[float] = Field( + None, description="Number of conformers in a conformational ensemble" + ) + ensemble_sample_url: Optional[str] = Field( + None, description="URL of a sample of conformations from ensemble" + ) + ensemble_sample_format: Optional[ModelFormat] = Field( + None, description="File format of the sample coordinates" + ) + created: str = Field( + ..., + description="Date of release of model generation in the format of YYYY-MM-DD", + json_schema_extra={"example": "2021-12-21"}, + ) + sequence_identity: float = Field( + ..., ge=0, le=1, description="Sequence identity of model to UniProt sequence" + ) + coverage: float = Field( + ..., ge=0, le=1, description="Fraction of UniProt sequence covered by the model" + ) + experimental_method: Optional[ExperimentalMethod] = Field( + None, description="Experimental method used to determine structure" + ) + resolution: Optional[float] = Field( + None, gt=0, description="Resolution of the model in Angstrom" + ) + confidence_type: Optional[ConfidenceType] = Field( + None, description="Type of confidence measure" + ) + confidence_version: Optional[str] = Field( + None, description="Version of confidence measure software" + ) + confidence_avg_local_score: Optional[float] = Field( + None, description="Average of confidence measures" + ) + oligomeric_state: Optional[OligomericState] = Field( + None, description="Oligomeric state of the model" + ) + oligomeric_state_confidence: Optional[float] = Field( + None, description="Confidence in oligomeric state" + ) + preferred_assembly_id: Optional[str] = Field( + None, description="Identifier of preferred assembly" + ) + entities: List[Entity] = Field( + ..., description="List of molecular entities in the model" + ) + + +class SequenceOverview(BaseModel): + """Sequence overview containing summary items""" + + summary: SummaryItems = Field( + ..., description="Summary information for the structure" + ) + + +class Entry(BaseModel): + """Entry information for sequence summary""" + + sequence: str = Field(..., description="The protein sequence") + checksum: str = Field(..., description="CRC64 or MD5 checksum of the sequence") + checksum_type: ChecksumType = Field(..., description="Type of the checksum") + + +class SequenceSummary(BaseModel): + """Main response model for /sequence/summary endpoint""" + + entry: Entry = Field( + ..., description="Entry information including sequence and checksum" + ) + structures: List[SequenceOverview] = Field( + ..., description="List of available structures" + ) + + +# Request models for the endpoint +class SequenceSummaryRequest(BaseModel): + """Request parameters for /sequence/summary endpoint""" + + +# Response models +class SequenceSummaryResponse(BaseModel): + """Response wrapper for successful requests""" + + data: SequenceSummary diff --git a/app/sequence/sequence.py b/app/sequence/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..51965628772da23ab2ca97e5500173d0f8649625 --- /dev/null +++ b/app/sequence/sequence.py @@ -0,0 +1,245 @@ +from typing import List, Optional + +import pydantic +from celery.result import AsyncResult +from fastapi.params import Query +from fastapi.routing import APIRouter +from starlette.responses import JSONResponse +from starlette.status import ( + HTTP_200_OK, + HTTP_202_ACCEPTED, + HTTP_400_BAD_REQUEST, + HTTP_404_NOT_FOUND, +) + +from app import logger +from app.config import get_base_service_url, get_services +from app.constants import ( + JOB_FAILED_ERROR_MESSAGE, + JOB_SUBMISSION_ERROR_MESSAGE, + SEARCH_IN_PROGRESS_MESSAGE, +) +from app.exception import ( + JobNotFoundException, + JobResultsNotFoundException, + RequestSubmissionException, +) +from app.sequence.helper import ( + generate_hash, + handle_no_job_error, + submit_sequence_search_job, +) +from app.sequence.schema import ( + Entry, + JobSubmissionErrorMessage, + NoJobFoundMessage, + SearchAccession, + SearchInProgressMessage, + SearchSuccessMessage, + Sequence, + SequenceIdType, + SequenceOverview, + SequenceSummary, +) +from app.utils import get_final_service_url, send_async_requests +from worker.cache.utils import ( + clear_celery_task_id, + clear_jobdispatcher_id, + get_celery_task_id, + get_jobdispatcher_id, + set_celery_task_id, + set_jobdispatcher_id, +) +from worker.worker import retrieve_result + +sequence_route = APIRouter() + + +@sequence_route.post( + "/search", + status_code=HTTP_202_ACCEPTED, + response_model=str, + responses={ + HTTP_200_OK: {"model": SearchSuccessMessage}, + HTTP_202_ACCEPTED: {"model": SearchSuccessMessage}, + HTTP_400_BAD_REQUEST: {"model": JobSubmissionErrorMessage}, + }, + tags=["Sequence"], + include_in_schema=True, +) +async def search(sequence: Sequence): + hashed_sequence = generate_hash(sequence.sequence) + + try: + jdispatcher_id = get_jobdispatcher_id(hashed_sequence) + except JobNotFoundException: + jdispatcher_id = None + + if jdispatcher_id: + return JSONResponse( + content={"job_id": hashed_sequence}, status_code=HTTP_200_OK + ) + + try: + jdispatcher_id = await submit_sequence_search_job(sequence.sequence) + except RequestSubmissionException: + return JSONResponse( + content={"message": JOB_SUBMISSION_ERROR_MESSAGE}, + status_code=HTTP_400_BAD_REQUEST, + ) + + logger.debug(f"Sequence {sequence.sequence} submitted to search engine") + + set_jobdispatcher_id(hashed_sequence, jdispatcher_id) + + # submit the task to celery + result_task = retrieve_result.delay(jdispatcher_id, hashed_sequence) + + set_celery_task_id(hashed_sequence, result_task) + + return JSONResponse( + status_code=HTTP_202_ACCEPTED, + content={"job_id": hashed_sequence}, + ) + + +@sequence_route.get( + "/result", + status_code=HTTP_200_OK, + response_model=List[SearchAccession], + responses={ + HTTP_200_OK: {"model": List[SearchAccession]}, + HTTP_202_ACCEPTED: {"model": SearchInProgressMessage}, + HTTP_400_BAD_REQUEST: {"model": NoJobFoundMessage}, + }, + tags=["Sequence"], + include_in_schema=True, +) +async def result( + job_id: str, +): + celery_job_id = None + + try: + celery_job_id = get_celery_task_id(hashed_sequence=job_id) + if not celery_job_id: + return await handle_no_job_error(job_id) + + except JobNotFoundException: + return await handle_no_job_error(job_id) + + try: + celery_job = AsyncResult(celery_job_id) + + if celery_job.status == "SUCCESS": + result = celery_job.get() + + if not result: + return JSONResponse( + status_code=HTTP_404_NOT_FOUND, + content={}, + ) + else: + return [x for x in result.values()] + + elif celery_job.status in ["STARTED", "PENDING"]: + return JSONResponse( + status_code=HTTP_202_ACCEPTED, + content={"message": SEARCH_IN_PROGRESS_MESSAGE}, + ) + elif celery_job.status == "FAILURE": + clear_celery_task_id(hashed_sequence=job_id) + clear_jobdispatcher_id(hashed_sequence=job_id) + + return JSONResponse( + status_code=HTTP_400_BAD_REQUEST, + content={"message": JOB_FAILED_ERROR_MESSAGE}, + ) + + except JobResultsNotFoundException: + return await handle_no_job_error(job_id) + + +@sequence_route.get( + "/summary", + summary="Sequence Summary", + description="Retrieve a summary of experimentally determined and predicted" + "structure models available for a sequence.", + response_model=SequenceSummary, + tags=["Sequence"], +) +async def sequence_summary_api( + id: str = Query( + ..., description="Identifier for the type specified in the type parameter" + ), + type: Optional[SequenceIdType] = Query( + SequenceIdType.SEQUENCE, description="Type of the identifier" + ), +): + """ + Retrieve a summary of experimentally determined and predicted structure " + "models available for a sequence. + """ + result = await fetch_sequence_summary(id, type) + if result is None: + return JSONResponse( + status_code=HTTP_404_NOT_FOUND, + content={}, + ) + return result + + +async def fetch_sequence_summary( + id: str, + type: Optional[SequenceIdType] = SequenceIdType.SEQUENCE, +) -> Optional[SequenceSummary]: + services = get_services(service_type="sequence") + calls = [] + for service in services: + base_url = get_base_service_url(service["provider"]) + final_url = get_final_service_url( + base_url, service["accessPoint"], f"?id={id}&type={type.value}" + ) + calls.append(final_url) + print(calls) + + result = await send_async_requests(calls) + final_result = [] + + for x in result: + if x and x.status_code == HTTP_200_OK: + try: + final_result.append(dict(x.json())) + except Exception: + logger.error(f"Error parsing response from {x.url}") + + if not final_result: + return None + + final_structures: List[SequenceOverview] = [] + entry: Entry = None + + for item in final_result: + # Remove erroneous responses + try: + SequenceOverview(**item["structures"][0]) + entry = Entry(**item["entry"]) + final_structures.extend(item["structures"]) + except pydantic.ValidationError: + provider = item["structures"][0].get("provider") + if provider: + logger.warning( + f"{provider} returned an erroneous response for " + f"{id} with type {type.value}" + ) + except Exception: + pass + + if not final_structures: + return None + + api_result: SequenceSummary = SequenceSummary( + **{"entry": entry, "structures": final_structures} + ) + + return api_result diff --git a/app/uniprot/__init__.py b/app/uniprot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/uniprot/helper.py b/app/uniprot/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b7228bb0fe272156bd9868de78a5a2c598a896 --- /dev/null +++ b/app/uniprot/helper.py @@ -0,0 +1,196 @@ +import asyncio +from typing import Dict, List + +import pydantic +from starlette import status +from starlette.responses import JSONResponse + +from app import logger +from app.config import MAX_POST_LIMIT, UNIPROT_API, get_base_service_url, get_services +from app.constants import TEMPLATE_DESC, UNIPROT_QUAL_DESC, UNP_CHECKSUM_DESC +from app.uniprot.schema import ( + AccessionListRequest, + Overview, + UniprotEntry, + UniprotSummary, +) +from app.utils import clean_args, get_final_service_url, send_async_requests +from worker.helper import get_nested_value_from_json + + +async def get_list_of_uniprot_summary_helper(list_request: AccessionListRequest): + """Returns summary of experimental and theoretical models for a list of UniProt + accessions + + Args: + list_request (AccessionListRequest): List of UniProt accession objects + + Returns: + Result: A list of Result summary object with experimental and theoretical + models for UniProt accessions. + """ + if len(list_request.accessions) > int(MAX_POST_LIMIT): + return JSONResponse( + content={ + "message": f"We cannot accept more than {MAX_POST_LIMIT} accessions!" + }, + status_code=status.HTTP_400_BAD_REQUEST, + ) + + summary_jobs = [ + asyncio.create_task( + get_uniprot_summary_helper( + q, + list_request.provider, + template=None, + res_range=None, + exclude_provider=list_request.exclude_provider, + uniprot_checksum=None, + ) + ) + for q in list_request.accessions + ] + + results = await asyncio.gather(*summary_jobs) + + if not results or all([x is None for x in results]): + return None + + return [x for x in results if x] + + +@clean_args() +async def get_uniprot_summary_helper( + qualifier: str, + provider=None, + template=None, + res_range=None, + exclude_provider=None, + uniprot_checksum=None, +): + f"""Helper function to get uniprot summary. + + Args: + qualifier (str): {UNIPROT_QUAL_DESC} + provider (str, optional): Data provider + template (str, optional): {TEMPLATE_DESC} + res_range (str, optional): Residue range + exclude_provider (str, optional): Provider to exclude + uniprot_checksum (str, optional): {UNP_CHECKSUM_DESC} + + Returns: + Result: A Result summary object with experimental and theoretical models. + """ + qualifier = qualifier.upper() + services = get_services( + service_type="summary", provider=provider, exclude_provider=exclude_provider + ) + calls = [] + for service in services: + base_url = get_base_service_url(service["provider"]) + final_url = get_final_service_url( + base_url, service["accessPoint"], f"{qualifier}.json" + ) + + if res_range: + final_url = f"{final_url}&range={res_range}" + + calls.append(final_url) + + result = await send_async_requests(calls) + final_result = [] + + for x in result: + if x and x.status_code == status.HTTP_200_OK: + try: + final_result.append(dict(x.json())) + except Exception: + logger.error(f"Error parsing response from {x.url}") + + # filter out beacons results where there are no structures + final_result = list(filter(lambda x: x.get("structures"), final_result)) + + if uniprot_checksum: + final_result = filter_on_checksum(final_result, uniprot_checksum) + + if not final_result: + return None + + final_structures: List[Overview] = [] + uniprot_entry: UniprotEntry = UniprotEntry( + **get_first_entry_with_checksum(final_result) + ) + + for item in final_result: + # Remove erroneous responses + for structure in item["structures"]: + try: + Overview(**structure) + final_structures.append(structure) + except pydantic.ValidationError: + provider = structure.get("provider") + if provider: + logger.warning( + f"{provider} returned an erroneous response for {qualifier}" + ) + except Exception: + pass + + if not final_structures: + return None + + api_result: UniprotSummary = UniprotSummary( + **{"uniprot_entry": uniprot_entry, "structures": final_structures} + ) + return api_result + + +def filter_on_checksum(in_result, checksum: str): + checksum_filtered_list = [] + + for item in in_result: + uniprot_checksum = item["uniprot_entry"].get("uniprot_checksum") + if uniprot_checksum and uniprot_checksum == checksum: + checksum_filtered_list.append(item) + + return checksum_filtered_list + + +def get_first_entry_with_checksum(in_result: List): + for item in in_result: + uniprot_checksum = item["uniprot_entry"].get("uniprot_checksum") + if uniprot_checksum: + return item["uniprot_entry"] + + if in_result: + return in_result[0]["uniprot_entry"] + + return None + + +async def get_uniprot_api_results(accessions: List[str]): + result = await send_async_requests([f"{UNIPROT_API}{x}" for x in accessions]) + + final_result = {} + + for x in result: + if x and x.status_code == status.HTTP_200_OK: + try: + response = dict(x.json()) + final_result[response["accession"]] = response + except Exception: + logger.error(f"Error parsing response from {x.url}") + + return final_result + + +def get_uniprot_name(response: Dict) -> str: + protein_name = get_nested_value_from_json( + response, "protein.recommendedName.fullName.value" + ) + if not protein_name: + protein_name = get_nested_value_from_json( + response, "protein.submittedName[0].fullName.value" + ) + + return protein_name or "Uncharacterized" diff --git a/app/uniprot/schema.py b/app/uniprot/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..68e56caf01b04a44687d2b11900f973077f576a4 --- /dev/null +++ b/app/uniprot/schema.py @@ -0,0 +1,672 @@ +# generated by datamodel-codegen: +# filename: 3dbeacons.yaml +# timestamp: 2022-05-13T10:29:41+00:00 + +from __future__ import annotations + +from enum import Enum +from typing import List, Optional + +from pydantic import BaseModel, Field, RootModel + + +class StrictBaseModel(BaseModel): + model_config = {"extra": "ignore"} + + +class UniprotEntry(StrictBaseModel): + ac: str = Field( + ..., description="UniProt accession", json_schema_extra={"example": "P00520"} + ) + id: Optional[str] = Field( + None, + description="UniProt identifier", + json_schema_extra={"example": "ABL1_MOUSE"}, + ) + uniprot_checksum: Optional[str] = Field( + None, + description="CRC64 checksum of the UniProt sequence", + json_schema_extra={"example": "5F9BA1D4C7DE6925"}, + ) + sequence_length: Optional[int] = Field( + None, + description="Length of the UniProt sequence", + json_schema_extra={"example": 76}, + ) + segment_start: Optional[int] = Field( + None, + description="1-indexed first residue of the UniProt sequence segment", + json_schema_extra={"example": 1}, + ) + segment_end: Optional[int] = Field( + None, + description="1-indexed last residue of the UniProt sequence segment", + json_schema_extra={"example": 86}, + ) + description: Optional[str] = Field( + None, + description="Description of the UniProt entry", + json_schema_extra={"example": "Proto-oncogene tyrosine-protein kinase ABL1"}, + ) + + +class PdbEntry(StrictBaseModel): + entry_id: str = Field( + ..., description="PDB entry identifier", json_schema_extra={"example": "3bow"} + ) + chain_id: str = Field( + ..., description="PDB chain identifier", json_schema_extra={"example": "A"} + ) + mapped_uniprot: Optional[str] = Field( + None, + description="UniProt accession mapped to the PDB entry", + json_schema_extra={"example": "P12345"}, + ) + uniprot_start: int = Field( + ..., + description="1-indexed first residue in the mapped UniProt", + json_schema_extra={"example": 1}, + ) + uniprot_end: int = Field( + ..., + description="1-indexed last residue in the mapped UniProt", + json_schema_extra={"example": 100}, + ) + + +class ModelCategory(Enum): + EXPERIMENTALLY_DETERMINED = "EXPERIMENTALLY DETERMINED" + TEMPLATE_BASED = "TEMPLATE-BASED" + AB_INITIO = "AB-INITIO" + CONFORMATIONAL_ENSEMBLE = "CONFORMATIONAL ENSEMBLE" + + +class ModelFormat(Enum): + PDB = "PDB" + MMCIF = "MMCIF" + BCIF = "BCIF" + + +class ModelType(Enum): + ATOMIC = "ATOMIC" + DUMMY = "DUMMY" + MIX = "MIX" + + +class EnsembleSampleFormat(Enum): + PDB = "PDB" + MMCIF = "MMCIF" + BCIF = "BCIF" + + +class ExperimentalMethod(Enum): + ELECTRON_CRYSTALLOGRAPHY = "ELECTRON CRYSTALLOGRAPHY" + ELECTRON_MICROSCOPY = "ELECTRON MICROSCOPY" + EPR = "EPR" + FIBER_DIFFRACTION = "FIBER DIFFRACTION" + FLUORESCENCE_TRANSFER = "FLUORESCENCE TRANSFER" + INFRARED_SPECTROSCOPY = "INFRARED SPECTROSCOPY" + NEUTRON_DIFFRACTION = "NEUTRON DIFFRACTION" + X_RAY_POWDER_DIFFRACTION = "X-RAY POWDER DIFFRACTION" + SOLID_STATE_NMR = "SOLID-STATE NMR" + SOLUTION_NMR = "SOLUTION NMR" + X_RAY_SOLUTION_SCATTERING = "X-RAY SOLUTION SCATTERING" + THEORETICAL_MODEL = "THEORETICAL MODEL" + X_RAY_DIFFRACTION = "X-RAY DIFFRACTION" + HYBRID = "HYBRID" + + +class ConfidenceType(Enum): + pLDDT = "pLDDT" + QMEANDisCo = "QMEANDisCo" + ipTMPlusPTM = "ipTM+pTM" + + +class OligomericState(Enum): + MONOMER = "MONOMER" + HOMODIMER = "HOMODIMER" + HETERODIMER = "HETERODIMER" + HOMO_OLIGOMER = "HOMO-OLIGOMER" + HETERO_OLIGOMER = "HETERO-OLIGOMER" + + +class EntityType(Enum): + BRANCHED = "BRANCHED" + MACROLIDE = "MACROLIDE" + NON_POLYMER = "NON-POLYMER" + POLYMER = "POLYMER" + WATER = "WATER" + + +class EntityPolyType(Enum): + CYCLIC_PSEUDO_PEPTIDE = "CYCLIC-PSEUDO-PEPTIDE" + PEPTIDE_NUCLEIC_ACID = "PEPTIDE NUCLEIC ACID" + POLYDEOXYRIBONUCLEOTIDE = "POLYDEOXYRIBONUCLEOTIDE" + POLYDEOXYRIBONUCLEOTIDE_POLYRIBONUCLEOTIDE_HYBRID = ( + "POLYDEOXYRIBONUCLEOTIDE/POLYRIBONUCLEOTIDE HYBRID" + ) + POLYPEPTIDE_D_ = "POLYPEPTIDE(D)" + POLYPEPTIDE_L_ = "POLYPEPTIDE(L)" + POLYRIBONUCLEOTIDE = "POLYRIBONUCLEOTIDE" + OTHER = "OTHER" + + +class IdentifierCategory(Enum): + UNIPROT = "UNIPROT" + RFAM = "RFAM" + CCD = "CCD" + SMILES = "SMILES" + INCHI = "INCHI" + INCHIKEY = "INCHIKEY" + + +class Entity(StrictBaseModel): + entity_type: EntityType = Field( + ..., + description="The type of the molecular entity; similar to _entity.type in" + " mmCIF", + json_schema_extra={"example": "POLYMER"}, + ) + entity_poly_type: Optional[EntityPolyType] = Field( + None, + description="The type of the molecular entity; similar to _entity_poly.type" + " in mmCIF", + json_schema_extra={"example": "PEPTIDE NUCLEIC ACID"}, + ) + identifier: Optional[str] = Field( + None, + description="Identifier of the molecule", + json_schema_extra={"example": "Q13033"}, + ) + identifier_category: Optional[IdentifierCategory] = Field( + None, + description="Category of the identifier", + json_schema_extra={"example": "UNIPROT"}, + ) + description: str = Field( + ..., + description="A textual label of the molecule", + json_schema_extra={"example": "Striatin-3"}, + ) + chain_ids: List[str] = Field( + ..., + description="A list of label_asym identifiers " + "( chain_id in the case of PDB format) of the molecule", + json_schema_extra={"example": ["A", "B"]}, + ) + + +class SummaryItems(StrictBaseModel): + model_identifier: str = Field( + ..., + description="Identifier of the model, such as PDB id", + json_schema_extra={"example": "8kfa"}, + ) + model_category: ModelCategory = Field( + ..., + description="Category of the model", + json_schema_extra={"example": "TEMPLATE-BASED"}, + ) + model_url: str = Field( + ..., + description="URL of the model coordinates", + json_schema_extra={ + "example": "https://www.ebi.ac.uk/pdbe/static/entry/1t29_updated.cif" + }, + ) + model_format: ModelFormat = Field( + ..., + description="File format of the coordinates", + json_schema_extra={"example": "MMCIF"}, + ) + model_type: Optional[ModelType] = Field( + None, + description="Defines if the coordinates are atomic-level or contains " + "dummy atoms (e.g. SAXS models), or a mix of both (e.g. hybrid models)\n", + json_schema_extra={"example": "ATOMIC"}, + ) + model_page_url: Optional[str] = Field( + None, + description="URL of a web page of the data provider that show the model", + json_schema_extra={"example": "https://alphafold.ebi.ac.uk/entry/Q5VSL9"}, + ) + provider: str = Field( + ..., + description="Name of the model provider", + json_schema_extra={"example": "SWISS-MODEL"}, + ) + number_of_conformers: Optional[float] = Field( + None, + description="The number of conformers in a conformational ensemble", + json_schema_extra={"example": 42}, + ) + ensemble_sample_url: Optional[str] = Field( + None, + description="URL of a sample of conformations from a conformational " + "ensemble", + json_schema_extra={ + "example": "https://proteinensemble.org/api/ensemble_sample/PED00001e001" + }, + ) + ensemble_sample_format: Optional[EnsembleSampleFormat] = Field( + None, + description="File format of the sample coordinates, e.g. PDB", + json_schema_extra={"example": "PDB"}, + ) + created: str = Field( + ..., + description="Date of release of model generation in the format of YYYY-MM-DD", + json_schema_extra={"example": "2021-12-21"}, + ) + sequence_identity: float = Field( + ..., + description="Sequence identity in the range of [0,1] of the model to the " + "UniProt sequence\n", + json_schema_extra={"example": 0.97}, + ) + uniprot_start: int = Field( + ..., + description="1-indexed first residue of the model according to UniProt " + "sequence numbering\n", + json_schema_extra={"example": 1}, + ) + uniprot_end: int = Field( + ..., + description="1-indexed last residue of the model according to UniProt " + "sequence numbering\n", + json_schema_extra={"example": 142}, + ) + coverage: float = Field( + ..., + description="Fraction in range of [0, 1] of the UniProt sequence covered by " + "the model. This is calculated as (uniprot_end - uniprot_start + 1) / " + "uniprot_sequence_length\n", + json_schema_extra={"example": 0.4}, + ) + experimental_method: Optional[ExperimentalMethod] = Field( + None, + description="Experimental method used to determine the structure, if " + "applicable", + ) + resolution: Optional[float] = Field( + None, + description="The resolution of the model in Angstrom, if applicable", + json_schema_extra={"example": 1.4}, + ) + confidence_type: Optional[ConfidenceType] = Field( + None, + description="Type of the confidence measure. This is required for " + "theoretical models.\n", + json_schema_extra={"example": "QMEANDisCo"}, + ) + confidence_version: Optional[str] = Field( + None, + description="Version of confidence measure software used to calculate quality. " + "This is required for theoretical models.\n", + json_schema_extra={"example": "v1.0.2"}, + ) + confidence_avg_local_score: Optional[float] = Field( + None, + description="Average of the confidence measures in the range of [0,1] for " + "QMEANDisCo and [0,100] for pLDDT. Please contact 3D-Beacons developers " + "if other estimates are to be added. This is required for theoretical " + "models.\n", + json_schema_extra={"example": 0.95}, + ) + oligomeric_state: Optional[OligomericState] = Field( + None, + description="Oligomeric state of the model", + json_schema_extra={"example": "MONOMER"}, + ) + oligomeric_state_confidence: Optional[float] = Field( + None, + description="Numerical value that describes the confidence in the oligomeric " + "state of the predicted complex", + json_schema_extra={"example": 0.4603}, + ) + preferred_assembly_id: Optional[str] = Field( + None, + description="Identifier of the preferred assembly in the model", + json_schema_extra={"example": "1A"}, + ) + entities: List[Entity] = Field( + ..., description="A list of molecular entities in the model" + ) + + +class ExperimentalMethod1(Enum): + ELECTRON_CRYSTALLOGRAPHY = "ELECTRON CRYSTALLOGRAPHY" + ELECTRON_MICROSCOPY = "ELECTRON MICROSCOPY" + EPR = "EPR" + FIBER_DIFFRACTION = "FIBER DIFFRACTION" + FLUORESCENCE_TRANSFER = "FLUORESCENCE TRANSFER" + INFRARED_SPECTROSCOPY = "INFRARED SPECTROSCOPY" + NEUTRON_DIFFRACTION = "NEUTRON DIFFRACTION" + POWDER_DIFFRACTION = "POWDER DIFFRACTION" + SOLID_STATE_NMR = "SOLID-STATE NMR" + SOLUTION_NMR = "SOLUTION NMR" + SOLUTION_SCATTERING = "SOLUTION SCATTERING" + THEORETICAL_MODEL = "THEORETICAL MODEL" + X_RAY_DIFFRACTION = "X-RAY DIFFRACTION" + HYBRID = "HYBRID" + + +class Template(StrictBaseModel): + template_id: str = Field( + ..., + description="Identifier of the template", + json_schema_extra={"example": "2aqa"}, + ) + chain_id: str = Field( + ..., + description="Identifier of the chain of the template; this is label_asym_id in " + "mmCIF", + json_schema_extra={"example": "C"}, + ) + template_sequence_identity: float = Field( + ..., + description="Sequence identity of the template with the UniProt accession, " + "in the range of [0,1]\n", + json_schema_extra={"example": 0.97}, + ) + last_updated: str = Field( + ..., + description="Date of release of the last update in the format of YYYY-MM-DD\n", + json_schema_extra={"example": "2021-08-06"}, + ) + provider: str = Field( + ..., + description="Provider of the template", + json_schema_extra={"example": "PDB"}, + ) + experimental_method: ExperimentalMethod1 = Field( + ..., + description="Experimental method used to determine the template", + json_schema_extra={"example": "HYBRID"}, + ) + resolution: float = Field( + ..., + description="Resolution of the template, in Angstrom", + json_schema_extra={"example": 2.1}, + ) + preferred_assembly_id: Optional[str] = Field( + None, + description="Identifier of the preferred assembly of the template", + json_schema_extra={"example": "1"}, + ) + + +class Seqres(StrictBaseModel): + aligned_sequence: str = Field( + ..., + description="Sequence of the model", + json_schema_extra={"example": "AAGTGHLKKKYT..."}, + ) + from_: int = Field( + ..., + alias="from", + description="1-indexed first residue", + json_schema_extra={"example": 32}, + ) + to: int = Field( + ..., description="1-indexed last residue", json_schema_extra={"example": 976} + ) + + +class Uniprot(StrictBaseModel): + aligned_sequence: str = Field( + ..., + description="Sequence of the UniProt accession", + json_schema_extra={"example": "AAGTGHLKKKYTAAGTGHLKKKYT..."}, + ) + from_: int = Field( + ..., + alias="from", + description="1-indexed first residue", + json_schema_extra={"example": 23}, + ) + to: int = Field( + ..., description="1-indexed last residue", json_schema_extra={"example": 868} + ) + + +class Residue(StrictBaseModel): + confidence: Optional[float] = Field( + None, + description="Confidence score in the range of [0,1]", + json_schema_extra={"example": 0.99}, + ) + model_residue_label: int = Field( + ..., description="Model residue index", json_schema_extra={"example": 1} + ) + uniprot_residue_number: int = Field( + ..., description="UniProt residue index", json_schema_extra={"example": 1} + ) + + +class Segment(StrictBaseModel): + templates: Optional[List[Template]] = Field( + None, description="Information on the template(s) used for the model" + ) + seqres: Seqres = Field(..., description="Information on the sequence of the model") + uniprot: Uniprot + residues: List[Residue] + + +class Chain(StrictBaseModel): + chain_id: str + segments: Optional[List[Segment]] = None + + +class Chains(RootModel[List[Chain]]): + model_config = {"title": "Chains"} + + +class LigandItem(StrictBaseModel): + id: str = Field( + ..., + description="Three-letter code of the ligand", + json_schema_extra={"example": "IHP"}, + ) + name: str = Field( + ..., + description="Name of the small ligand", + json_schema_extra={"example": "INOSITOL HEXAKISPHOSPHATE"}, + ) + formula: str = Field( + ..., + description="Chemical composition formula of the ligand", + json_schema_extra={"example": "C6 H18 O24 P6"}, + ) + inchikey: str = Field( + ..., + description="InChIKey of the ligand", + json_schema_extra={"example": "IMQLKJBTEOYOSI-GPIVLXJGSA-N"}, + ) + + +class Type(Enum): + HELIX = "HELIX" + SHEET = "SHEET" + COIL = "COIL" + + +class RegionItem(StrictBaseModel): + start: int = Field( + ..., + description="The first position of the annotation", + json_schema_extra={"example": 23}, + ) + end: int = Field( + ..., + description="The last position of the annotation", + json_schema_extra={"example": 42}, + ) + + +class SecondaryStructureItem(StrictBaseModel): + type: Type = Field( + ..., + description="Type of the secondary structure element", + json_schema_extra={"example": "HELIX"}, + ) + region: Optional[List[RegionItem]] = None + + +class Type1(Enum): + CARBOHYD = "CARBOHYD" + DOMAIN = "DOMAIN" + CA_BIND = "CA_BIND" + DNA_BIND = "DNA_BIND" + NP_BIND = "NP_BIND" + ACT_SITE = "ACT_SITE" + METAL = "METAL" + BINDING = "BINDING" + NON_STD = "NON_STD" + MOD_RES = "MOD_RES" + DISULFID = "DISULFID" + MUTAGEN = "MUTAGEN" + + +class Region(StrictBaseModel): + start: int = Field( + ..., + description="The first position of the annotation", + json_schema_extra={"example": 23}, + ) + end: int = Field( + ..., + description="The last position of the annotation", + json_schema_extra={"example": 42}, + ) + + +class FeatureItem(StrictBaseModel): + type: Type1 = Field( + ..., + description="Type of the annotation", + json_schema_extra={"example": "ACT_SITE"}, + ) + description: str = Field( + ..., + description="Description/Label of the annotation", + json_schema_extra={"example": "Pfam N1221 (PF07923)"}, + ) + residues: Optional[List[int]] = Field( + None, description="An array of residue indices" + ) + regions: Optional[List[Region]] = None + + +class Annotations(StrictBaseModel): + accession: str = Field( + ..., description="A UniProt accession", json_schema_extra={"example": "P00734"} + ) + id: Optional[str] = Field( + None, + description="A UniProt identifier", + json_schema_extra={"example": "FGFR2_HUMAN"}, + ) + sequence: str = Field( + ..., + description="The sequence of the protein", + json_schema_extra={"example": "AFFGVAATRKL"}, + ) + ligand: Optional[List[LigandItem]] = Field( + None, description="Contains ligand annotations" + ) + secondary_structure: Optional[List[SecondaryStructureItem]] = None + feature: Optional[List[FeatureItem]] = None + + +class MappingAccessionType(Enum): + uniprot = "uniprot" + pfam = "pfam" + + +class ModelCategory1(Enum): + EXPERIMENTALLY_DETERMINED = "EXPERIMENTALLY DETERMINED" + TEMPLATE_BASED = "TEMPLATE-BASED" + AB_INITIO = "AB-INITIO" + CONFORMATIONAL_ENSEMBLE = "CONFORMATIONAL ENSEMBLE" + DEEP_LEARNING = "DEEP-LEARNING" + + +class ModelType1(Enum): + single = "single" + complex = "complex" + + +class Metadata(StrictBaseModel): + mappingAccession: str = Field( + ..., + description="Accession/identifier of the entity the model is mapped to", + json_schema_extra={"example": "P38398"}, + ) + mappingAccessionType: MappingAccessionType = Field( + ..., + description="The name of the data provider the model is mapped to", + json_schema_extra={"example": "uniprot"}, + ) + start: int = Field( + ..., + description="The index of the first residue of the model according to the " + "mapping", + json_schema_extra={"example": 1}, + ) + end: int = Field( + ..., + description="The index of the last residue of the model according to the " + "mapping", + json_schema_extra={"example": 103}, + ) + modelCategory: ModelCategory1 = Field( + ..., + description="Category of the model", + json_schema_extra={"example": "TEMPLATE-BASED"}, + ) + modelType: ModelType1 = Field( + ..., + description="Monomeric or complex strutures", + json_schema_extra={"example": "single"}, + ) + + +class Detailed(StrictBaseModel): + summary: SummaryItems + chains: Chains + + +class Overview(StrictBaseModel): + summary: SummaryItems + + +class UniprotSummary(StrictBaseModel): + uniprot_entry: Optional[UniprotEntry] = None + structures: Optional[List[Overview]] = None + + +class UniprotDetails(StrictBaseModel): + uniprot_entry: Optional[UniprotEntry] = None + structures: Optional[List[Detailed]] = None + + +class PdbSummary(StrictBaseModel): + uniprot_entry: Optional[PdbEntry] = None + structures: Optional[List[Overview]] = None + + +class AccessionListRequest(StrictBaseModel): + accessions: List[str] = Field( + ..., + description="A list of UniProt accessions", + json_schema_extra={"example": ["P00734", "P38398"]}, + ) + provider: Optional[str] = Field( + None, + description="Name of the model provider", + json_schema_extra={"example": "swissmodel"}, + ) + exclude_provider: Optional[str] = Field( + None, description="Provider to exclude.", json_schema_extra={"example": "pdbe"} + ) diff --git a/app/uniprot/uniprot.py b/app/uniprot/uniprot.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5c039b505ccd4af6e5fa49d4d534b0f332bac0 --- /dev/null +++ b/app/uniprot/uniprot.py @@ -0,0 +1,282 @@ +from typing import Any, List, Optional + +import pydantic +from fastapi.params import Path, Query +from fastapi.routing import APIRouter +from starlette import status +from starlette.responses import JSONResponse + +from app import logger +from app.config import get_base_service_url, get_services +from app.constants import ( + QUERY_DESC, + TEMPLATE_DESC, + UNIPROT_QUAL_DESC, + UNP_CHECKSUM_DESC, +) +from app.uniprot.helper import ( + filter_on_checksum, + get_first_entry_with_checksum, + get_list_of_uniprot_summary_helper, + get_uniprot_summary_helper, +) +from app.uniprot.schema import ( + AccessionListRequest, + Detailed, + UniprotDetails, + UniprotEntry, + UniprotSummary, +) +from app.utils import clean_args, get_final_service_url, send_async_requests + +uniprot_route = APIRouter() + + +@uniprot_route.get( + "/summary/{qualifier}.json", + status_code=status.HTTP_200_OK, + response_model=UniprotSummary, + response_model_exclude_unset=True, + tags=["UniProt"], + description=""" + Retrieve a summary of experimentally determined and predicted structure models + available for a UniProtKB accession, entry name, or CRC64 checksum associated + with a UniProt sequence. + + Note that some model providers may not support searches by entry name or + CRC64 checksum. + """, +) +async def get_uniprot_summary( + qualifier: Any = Path( + ..., + description=QUERY_DESC, + openapi_examples={ + "default": {"summary": "Example qualifier", "value": "P38398"} + }, + ), + provider: Optional[Any] = Query( + None, enum=[x["provider"] for x in get_services("summary")] + ), + template: Optional[Any] = Query( + None, + description=TEMPLATE_DESC, + ), + res_range: Optional[Any] = Query( + None, + description="Specify a UniProt sequence residue range", + pattern="^[0-9]+-[0-9]+$", + alias="range", + ), + exclude_provider: Optional[str] = Query( + None, + description="Provider to exclude.", + enum=[x["provider"] for x in get_services("summary")], + ), + uniprot_checksum: Optional[str] = Query(None, description=UNP_CHECKSUM_DESC), +): + f"""Returns summary of experimental and theoretical models for a UniProt + accession or entry name + + Args: + qualifier (str): {QUERY_DESC} + provider (str, optional): Data provider + template (str, optional): {TEMPLATE_DESC} + res_range (str, optional): Residue range + exclude_provider (str, optional): Provider to exclude + uniport_checksum (str, optional): {UNP_CHECKSUM_DESC} + + Returns: + Result: A Result summary object with experimental and theoretical models. + """ + results = await get_uniprot_summary_helper( + qualifier, + provider, + template, + res_range, + exclude_provider, + uniprot_checksum, + ) + + if not results: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + else: + return results + + +@uniprot_route.post( + "/summary", + status_code=status.HTTP_200_OK, + response_model=List[UniprotSummary], + response_model_exclude_unset=True, + description="Returns summary of experimental and theoretical models for a " + "list of UniProt accessions", + tags=["UniProt"], +) +async def get_list_of_uniprot_summary(list_request: AccessionListRequest): + """Returns summary of experimental and theoretical models for a list of UniProt + accessions + + Args: + list_request (AccessionListRequest): List of UniProt accession objects + + Returns: + Result: A list of Result summary object with experimental and theoretical + models for UniProt accessions. + """ + + results = await get_list_of_uniprot_summary_helper(list_request) + + if not results: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + + return list(results) + + +@clean_args() +async def get_uniprot_helper( + qualifier: str, + provider=None, + template=None, + res_range=None, + uniprot_checksum=None, +): + f"""Helper function to get uniprot details. + + Args: + qualifier (str): {UNIPROT_QUAL_DESC} + provider (str, optional): Data provider + template (str, optional): {TEMPLATE_DESC} + res_range (str, optional): Residue range + uniprot_checksum (str, optional): {UNP_CHECKSUM_DESC} + + Returns: + Result: A Result object with experimental and theoretical models. + """ + qualifier = qualifier.upper() + services = get_services(service_type="uniprot", provider=provider) + calls = [] + for service in services: + base_url = get_base_service_url(service["provider"]) + final_url = get_final_service_url( + base_url, service["accessPoint"], f"{qualifier}.json" + ) + + if res_range: + final_url = f"{final_url}&range={res_range}" + + calls.append(final_url) + + result = await send_async_requests(calls) + final_result = [] + + for x in result: + if x and x.status_code == status.HTTP_200_OK: + try: + final_result.append(dict(x.json())) + except Exception: + logger.error(f"Error parsing response from {x.url}") + + # filter out beacons results where there are no structures + final_result = list(filter(lambda x: x.get("structures"), final_result)) + + if uniprot_checksum: + final_result = filter_on_checksum(final_result, uniprot_checksum) + + if not final_result: + return None + + final_structures: List[Detailed] = [] + uniprot_entry: UniprotEntry = UniprotEntry( + **get_first_entry_with_checksum(final_result) + ) + + for item in final_result: + # Remove erroneous responses + try: + Detailed(**item["structures"][0]) + UniprotEntry(**item["uniprot_entry"]) + final_structures.extend(item["structures"]) + except pydantic.ValidationError: + provider = item["structures"][0].get("provider") + if provider: + logger.warning( + f"{provider} returned an erroneous response for {qualifier}" + ) + except Exception: + pass + + if not final_structures: + return None + + api_result: UniprotDetails = UniprotDetails( + **{"uniprot_entry": uniprot_entry, "structures": final_structures} + ) + + return api_result + + +@uniprot_route.get( + "/{qualifier}.json", + status_code=status.HTTP_200_OK, + response_model=UniprotDetails, + tags=["UniProt"], + description=""" + Retrieve residue-level mappings for experimentally determined and predicted + structure models available for a UniProtKB accession, entry name, or CRC64 + checksum associated with a UniProt sequence. + + Note that some model providers may not support searches by entry name or + CRC64 checksum. + """, +) +async def get_uniprot( + qualifier: Any = Path( + ..., + description=QUERY_DESC, + openapi_examples={ + "default": {"summary": "Example qualifier", "value": "P38398"} + }, + ), + provider: Optional[Any] = Query( + None, enum=[x["provider"] for x in get_services("uniprot")] + ), + template: Optional[Any] = Query( + None, + description="Template is 4 letter PDB code, or 4 letter code with " + "assembly ID and chain for SMTL entries", + ), + res_range: Optional[Any] = Query( + None, + description="Specify a UniProt sequence residue range", + pattern="^[0-9]+-[0-9]+$", + alias="range", + ), + uniprot_checksum: Optional[str] = Query(None, description=UNP_CHECKSUM_DESC), +): + f"""Returns experimental and theoretical models for a UniProt accession or entry name + + Args: + qualifier (str): {QUERY_DESC} + provider (str, optional): Data provider + template (str, optional): {TEMPLATE_DESC} + res_range (str, optional): Residue range + exclude_provider (str, optional): Provider to exclude + uniprot_checksum (str, optional): {UNP_CHECKSUM_DESC} + + Returns: + Result: A Result object with experimental and theoretical models. + """ + + results = await get_uniprot_helper( + qualifier, + provider, + template, + res_range, + uniprot_checksum, + ) + + if not results: + return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) + else: + return results diff --git a/app/utils.py b/app/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5312de7187c3ae2bf5f9899624e62525f4e00459 --- /dev/null +++ b/app/utils.py @@ -0,0 +1,117 @@ +import asyncio +import functools +import os +import re +import time + +import httpx + +from app import logger +from app.version import __major__version__ + +REQUEST_TIMEOUT = 5 + + +def timeit(fn): + def wrapper(*args, **kwargs): + start = time.time() + result = fn(*args, **kwargs) + end = time.time() + logger.info(f"{fn.__name__} took {end - start} seconds") + logger.info(args) + return result + + return wrapper + + +# @timeit +async def request_get(url: str): + """Makes an HTTP/HTTPS request and returns a response. + + Args: + url (str): A request URL. + + Returns: + Response: A Response object. + """ + response = None + async with httpx.AsyncClient() as client: + try: + response = await client.get(url, timeout=REQUEST_TIMEOUT) + except httpx.TimeoutException: + logger.error(f"Timeout for {url}") + except httpx.HTTPError: + logger.error(f"Error while making a request to {url}", exc_info=True) + except Exception: + logger.error( + f"Unknown error while making a request to {url}", exc_info=True + ) + finally: + await client.aclose() + return response + + +async def request_post(url: str, data): + response = None + async with httpx.AsyncClient() as client: + try: + response = await client.post(url, timeout=REQUEST_TIMEOUT, data=data) + except httpx.TimeoutException: + logger.error(f"Timeout for {url}") + except httpx.HTTPError: + logger.error(f"Error while making a request to {url}", exc_info=True) + except Exception: + logger.error( + f"Unknown error while making a request to {url}", exc_info=True + ) + finally: + await client.aclose() + return response + + +async def send_async_requests(endpoints): + tasks = [asyncio.create_task(request_get(call)) for call in endpoints] + return await asyncio.gather(*tasks) + + +def get_final_service_url(*parts): + """Returns a final service URL, handling existing query parameters.""" + url = "/".join(parts) + url = re.sub(r"([^:])//", r"\1/", url) + + # remove / before query params + url = url.replace("/?", "?") + + # Check if there is already a query string + if "?" in url: + return url + f"&version={__major__version__}" + else: + return url + f"?version={__major__version__}" + + +def clean_args(): + def wrapper(func): + @functools.wraps(func) + def inner(*args, **kwargs): + cleaned_args = [] + for x in args: + if x and not isinstance(x, str): + x = str(x) + cleaned_args.append(x.strip(" ") if x else x) + return func(*cleaned_args, **kwargs) + + return inner + + return wrapper + + +def include_in_schema() -> bool: + """Returns if the endpoint should be included in the OpenAPI schema. + Returns: + bool: True if ENVIRONMENT envvar is not PROD or not set, otherwise False. + """ + env = os.environ.get("ENVIRONMENT", None) + + if env == "DEV" or env == "dev": + return True + return False diff --git a/app/version.py b/app/version.py new file mode 100644 index 0000000000000000000000000000000000000000..f01ea798c984c8e543819b319650528b9664401f --- /dev/null +++ b/app/version.py @@ -0,0 +1,2 @@ +__version__ = "2.7.1" +__major__version__ = f"{__version__.split('.')[0]}.0.0" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..29228165e8e298eb6ee9604a29841783efd1cbb0 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,120 @@ +import hashlib +import json +from typing import List + +import pytest + +from app.uniprot.schema import UniprotSummary +from tests.utils import StubResponse + + +class AsyncResult: + def __init__(self, status, result): + self.result = result + self.status = status + + def get(self): + return self.result + + +@pytest.fixture(scope="session") +def invalid_uniprot(): + return "X0" + + +@pytest.fixture(scope="session") +def valid_uniprot(): + return "P0DTD1" + + +@pytest.fixture(scope="session") +def valid_uniprot_structures(): + valid_structures = [] + valid_structures.append(StubResponse(status_code=200, stub_for="uniprot")) + return valid_structures + + +@pytest.fixture(scope="session") +def valid_uniprot_structures_summary(): + valid_structures = [] + valid_structures.append(StubResponse(status_code=200, stub_for="uniprot_summary")) + return valid_structures + + +@pytest.fixture(scope="session") +def registry(): + with open("tests/stubs/registry.json") as fp: + data = json.load(fp) + return data + + +@pytest.fixture(scope="session") +def valid_gifts_response(): + with open("tests/stubs/gifts_response.json") as fp: + data = json.load(fp) + return data + + +@pytest.fixture(scope="session") +def valid_annotation_response(): + with open("tests/stubs/annotations_response.json") as fp: + data = json.load(fp) + return data + + +@pytest.fixture(scope="session") +def valid_uniprot_list_summary(): + return StubResponse(status_code=200, stub_for="uniprot_list_summary") + + +@pytest.fixture(scope="session") +def seq_search_response(): + return StubResponse(status_code=200, stub_for="seq_search_response") + + +@pytest.fixture(scope="session") +def sample_sequence(): + return "MVLSEGEWQLVLHVWAKVEADVAGHGQDILIRLFKSH" + + +@pytest.fixture(scope="session") +def sample_sequence_hash(): + return hashlib.md5("MVLSEGEWQLVLHVWAKVEADVAGHGQDILIRLFKSH".encode()).hexdigest() + + +@pytest.fixture(scope="session") +def uniprot_summary_obj_list(): + summary_results: List[UniprotSummary] = [] + + with open("tests/stubs/uniprot_list_summary.json") as f: + for item in json.load(f): + summary_results.append(UniprotSummary(**item)) + + return summary_results + + +@pytest.fixture(scope="session") +def uniprot_details(): + with open("tests/stubs/uniprot.json") as f: + return json.load(f) + + +@pytest.fixture(scope="session") +def uniprot_summary(): + with open("tests/stubs/uniprot_summary.json") as f: + return json.load(f) + + +@pytest.fixture(scope="session") +def pending_async_result(): + return AsyncResult("PENDING", None) + + +@pytest.fixture(scope="session") +def failed_async_result(): + return AsyncResult("FAILURE", None) + + +@pytest.fixture(scope="session") +def finished_none_async_result(): + return AsyncResult("SUCCESS", None) diff --git a/tests/stubs/annotations_response.json b/tests/stubs/annotations_response.json new file mode 100644 index 0000000000000000000000000000000000000000..0c57e747c9f501a0606ba11f9dfac8cd01822598 --- /dev/null +++ b/tests/stubs/annotations_response.json @@ -0,0 +1,49 @@ +{ + "accession": "Q14676", + "id": "MDC1_HUMAN", + "sequence": "MEDTQAIDWDVEEEEETEQSSESLRCNVEPVGRLHIFSGAHGPEKDFPLHLGKNVVGRMPDCSVALPFPSISKQHAEIEILAWDKAPILRDCGSLNGTQILRPPKVLSPGVSHRLRDQELILFADLLCQYHRLDVSLPFVSRGPLTVEETPRVQGETQPQRLLLAEDSEEEVDFLSERRMVKKSRTTSSSVIVPESDEEGHSPVLGGLGPPFAFNLNSDTDVEEGQQPATEEASSAARRGATVEAKQSEAEVVTEIQLEKDQPLVKERDNDTKVKRGAGNGVVPAGVILERSQPPGEDSDTDVDDDSRPPGRPAEVHLERAQPFGFIDSDTDAEEERIPATPVVIPMKKRKIFHGVGTRGPGAPGLAHLQESQAGSDTDVEEGKAPQAVPLEKSQASMVINSDTDDEEEVSAALTLAHLKESQPAIWNRDAEEDMPQRVVLLQRSQTTTERDSDTDVEEEELPVENREAVLKDHTKIRALVRAHSEKDQPPFGDSDDSVEADKSSPGIHLERSQASTTVDINTQVEKEVPPGSAIIHIKKHQVSVEGTNQTDVKAVGGPAKLLVVSLEEAWPLHGDCETDAEEGTSLTASVVADVRKSQLPAEGDAGAEWAAAVLKQERAHEVGAQGGPPVAQVEQDLPISRENLTDLVVDTDTLGESTQPQREGAQVPTGREREQHVGGTKDSEDNYGDSEDLDLQATQCFLENQGLEAVQSMEDEPTQAFMLTPPQELGPSHCSFQTTGTLDEPWEVLATQPFCLRESEDSETQPFDTHLEAYGPCLSPPRAIPGDQHPESPVHTEPMGIQGRGRQTVDKVMGIPKETAERVGPERGPLERETEKLLPERQTDVTGEEELTKGKQDREQKQLLARDTQRQESDKNGESASPERDRESLKVEIETSEEIQEKQVQKQTLPSKAFEREVERPVANRECDPAELEEKVPKVILERDTQRGEPEGGSQDQKGQASSPTPEPGVGAGDLPGPTSAPVPSGSQSGGRGSPVSPRRHQKGLLNCKMPPAEKASRIRAAEKVSRGDQESPDACLPPTVPEAPAPPQKPLNSQSQKHLAPPPLLSPLLPSIKPTVRKTRQDGSQEAPEAPLSSELEPFHPKPKIRTRKSSRMTPFPATSAAPEPHPSTSTAQPVTPKPTSQATRSRTNRSSVKTPEPVVPTAPELQPSTSTDQPVTSEPTSQVTRGRKSRSSVKTPETVVPTALELQPSTSTDRPVTSEPTSQATRGRKNRSSVKTPEPVVPTAPELQPSTSTDQPVTSEPTYQATRGRKNRSSVKTPEPVVPTAPELRPSTSTDRPVTPKPTSRTTRSRTNMSSVKTPETVVPTAPELQISTSTDQPVTPKPTSRTTRSRTNMSSVKNPESTVPIAPELPPSTSTEQPVTPEPTSRATRGRKNRSSGKTPETLVPTAPKLEPSTSTDQPVTPEPTSQATRGRTNRSSVKTPETVVPTAPELQPSTSTDQPVTPEPTSQATRGRTDRSSVKTPETVVPTAPELQASASTDQPVTSEPTSRTTRGRKNRSSVKTPETVVPAAPELQPSTSTDQPVTPEPTSRATRGRTNRSSVKTPESIVPIAPELQPSTSRNQLVTPEPTSRATRCRTNRSSVKTPEPVVPTAPEPHPTTSTDQPVTPKLTSRATRRKTNRSSVKTPKPVEPAASDLEPFTPTDQSVTPEAIAQGGQSKTLRSSTVRAMPVPTTPEFQSPVTTDQPISPEPITQPSCIKRQRAAGNPGSLAAPIDHKPCSAPLEPKSQASRNQRWGAVRAAESLTAIPEPASPQLLETPIHASQIQKVEPAGRSRFTPELQPKASQSRKRSLATMDSPPHQKQPQRGEVSQKTVIIKEEEEDTAEKPGKEEDVVTPKPGKRKRDQAEEEPNRIPSRSLRRTKLNQESTAPKVLFTGVVDARGERAVLALGGSLAGSAAEASHLVTDRIRRTVKFLCALGRGIPILSLDWLHQSRKAGFFLPPDEYVVTDPEQEKNFGFSLQDALSRARERRLLEGYEIYVTPGVQPPPPQMGEIISCCGGTYLPSMPRSYKPQRVVITCPQDFPHCSIPLRVGLPLLSPEFLLTGVLKQEAKPEAFVLSPLEMSST", + "annotation": [ + { + "type": "DOMAIN", + "description": "Tumour Suppressor Smad4 (3uotA00)", + "source_name": "CATH", + "evidence": "COMPUTATIONAL/PREDICTED", + "residues": [ + 19, + 20, + 21, + 22, + 23 + ], + "regions": [ + { + "start": 19, + "end": 23 + } + ] + }, + { + "type": "DOMAIN", + "description": "BRCT domain (IPR001357)", + "source_name": "InterPro", + "evidence": "COMPUTATIONAL/PREDICTED", + "residues": [ + 1889, + 1890, + 1891, + 1892, + 1893, + 1894, + 1895, + 1896, + 1897 + ], + "regions": [ + { + "start": 1889, + "end": 1897 + } + ] + } + ] + } diff --git a/tests/stubs/gifts_response.json b/tests/stubs/gifts_response.json new file mode 100644 index 0000000000000000000000000000000000000000..2ba14165bdcab5b65e0c16d1ea201892a56a9a81 --- /dev/null +++ b/tests/stubs/gifts_response.json @@ -0,0 +1 @@ +{"taxonomy":{"species":"Homo sapiens","ensemblTaxId":9606,"uniprotTaxId":9606},"entryMappings":[{"id":3946552,"mappingId":5357997,"groupingId":2010220,"timeMapped":"2022-05-31T12:31:15.321882Z","uniprotRelease":"2022_02","ensemblRelease":"105","uniprotEntry":{"uniprot_id":1263210,"uniprotAccession":"A0A8I5KS94","entryType":"TrEMBL","sequenceVersion":1,"upi":"UPI001E246DBC","md5":"2664563FCA54B44536D4380662BE87E3","isCanonical":true,"alias":null,"ensemblDerived":true,"gene_symbol":"ARHGAP11A-SCG5","gene_accession":"","length":623,"protein_existence_id":4},"ensemblTranscript":{"transcript_id":5507799,"enstId":"ENST00000689909","enstVersion":1,"upi":null,"biotype":"protein_coding","deleted":false,"chromosome":"15","regionAccession":"CM000677.2","seqRegionStart":32613860,"seqRegionEnd":32697077,"seqRegionStrand":1,"ensgId":"ENSG00000288864","ensgName":"ARHGAP11A-SCG5 readthrough","sequence":null,"ensgSymbol":"ARHGAP11A-SCG5","ensgAccession":"114118903","ensgRegionAccession":"CM000677.2","enspId":"ENSP00000510704","enspLen":623,"source":"havana","select":null},"alignment_difference":0,"status":"NOT_REVIEWED","status_history":[]},{"id":3946310,"mappingId":5357480,"groupingId":2010220,"timeMapped":"2022-05-31T12:31:15.321882Z","uniprotRelease":"2022_02","ensemblRelease":"105","uniprotEntry":{"uniprot_id":1263749,"uniprotAccession":"A0A8I5KWH8","entryType":"TrEMBL","sequenceVersion":1,"upi":"UPI00100D9C18","md5":"2AD04D04A00DD95D1864432478D7E2F7","isCanonical":true,"alias":null,"ensemblDerived":true,"gene_symbol":"ARHGAP11A-SCG5","gene_accession":"","length":625,"protein_existence_id":4},"ensemblTranscript":{"transcript_id":5507800,"enstId":"ENST00000692248","enstVersion":1,"upi":"UPI00100D9C18","biotype":"protein_coding","deleted":false,"chromosome":"15","regionAccession":"CM000677.2","seqRegionStart":32615448,"seqRegionEnd":32697095,"seqRegionStrand":1,"ensgId":"ENSG00000288864","ensgName":"ARHGAP11A-SCG5 readthrough","sequence":null,"ensgSymbol":"ARHGAP11A-SCG5","ensgAccession":"114118903","ensgRegionAccession":"CM000677.2","enspId":"ENSP00000510771","enspLen":625,"source":"havana","select":null},"alignment_difference":null,"status":"NOT_REVIEWED","status_history":[]}]} diff --git a/tests/stubs/hit_dictionary.json b/tests/stubs/hit_dictionary.json new file mode 100644 index 0000000000000000000000000000000000000000..52cb8a8b40338c09450891c60cad7d1e370dc363 --- /dev/null +++ b/tests/stubs/hit_dictionary.json @@ -0,0 +1,86 @@ +{ + "B4DKT3": { + "accession": "B4DKT3", + "description": "cDNA FLJ58390, highly similar to Aldo-keto reductase family 1 member C3homolog OS=Homo sapiens OX=9606 PE=2 SV=1", + "hit_length": 138, + "id": "B4DKT3_HUMAN", + "hit_uni_os":"Homo sapiens", + "hit_uni_ox": 9606, + "hit_hsps": [ + { + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 1.8e-83, + "hsp_align_len": 122, + "hsp_identity": 100, + "hsp_positive": 100, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + "A0A2I3HVB7": { + "accession": "A0A2I3HVB7", + "description": "Aldo-keto reductase family 1 member C3 OS=Nomascus leucogenys OX=61853 GN=AKR1C3 PE=3 SV=1", + "hit_length": 323, + "id": "A0A2I3HVB7_NOMLE", + "hit_uni_os": "Nomascus leucogenys", + "hit_uni_ox": 61853, + "hit_hsps": [ + { + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_align_len": 122, + "hsp_expect": 7.7e-81, + "hsp_identity": 100, + "hsp_positive": 100, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + "A0A2R9A0L9": { + "accession": "A0A2R9A0L9", + "description": "Aldo-keto reductase family 1 member C3 OS=Pan paniscus OX=9597 GN=AKR1C3 PE=3 SV=1", + "hit_length": 323, + "id": "A0A2R9A0L9_PANPA", + "hit_uni_os": "Pan paniscus", + "hit_uni_ox": 9597, + "hit_hsps": [ + { + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_align_len": 122, + "hsp_expect": 7.7e-81, + "hsp_identity": 100, + "hsp_positive": 100, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + "K7D0S3": { + "accession": "K7D0S3", + "description": "Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II) OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_length": 323, + "id": "K7D0S3_PANTR", + "hit_uni_os": "Pan troglodytes", + "hit_uni_ox": 9598, + "hit_hsps": [ + { + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_align_len": 122, + "hsp_expect": 7.7e-81, + "hsp_identity": 95, + "hsp_positive": 100, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + } +} diff --git a/tests/stubs/registry.json b/tests/stubs/registry.json new file mode 100644 index 0000000000000000000000000000000000000000..eedf30f7ce97eea2cf49b3b823709a977c0eca51 --- /dev/null +++ b/tests/stubs/registry.json @@ -0,0 +1,37 @@ +{ + "providers": [ + { + "providerId": "providerOneId", + "providerName": "providerOneName", + "providerDescription": "providerOneDesc", + "providerUrl": "https://providerOneUrl", + "baseServiceUrl": "https://providerOneBaseServiceUrl", + "devBaseServiceUrl": "https://providerOneDevBaseServiceUrl" + }, + { + "providerId": "providerTwoId", + "providerName": "providerTwoName", + "providerDescription": "providerTwoDesc", + "providerUrl": "https://providerTwoUrl", + "baseServiceUrl": "https://providerTwoBaseServiceUrl", + "devBaseServiceUrl": "https://providerTwoDevBaseServiceUrl" + } + ], + "services": [ + { + "serviceType": "serviceOne", + "provider": "providerOne", + "accessPoint": "service/" + }, + { + "serviceType": "serviceOne", + "provider": "providerTwo", + "accessPoint": "service/v/" + }, + { + "serviceType": "serviceTwo", + "provider": "providerOne", + "accessPoint": "service/2/" + } + ] +} diff --git a/tests/stubs/seq_search_response.json b/tests/stubs/seq_search_response.json new file mode 100644 index 0000000000000000000000000000000000000000..e0628d1492adc3d10e5abf0c65fd81d23cfd98d9 --- /dev/null +++ b/tests/stubs/seq_search_response.json @@ -0,0 +1,427 @@ +{ + "program": "blastp", + "version": "BLASTP 2.12.0+", + "command": "$APPBIN/ncbi-blast-2.9.0+/bin/blastp -db "uniprotkb" -query ncbiblast-R20230109-174035-0934-49668747-p2m.sequence -num_threads 32 -outfmt 11 -out ncbiblast-R20230109-174035-0934-49668747-p2m.archive -seg no -comp_based_stats F", + "query_def": "EMBOSS_001", + "query_stype": "protein", + "query_len": 129, + "db_count": 1, + "db_num": 230190369, + "db_len": 81010115241, + "dbs": [ + { + "name": "uniprotkb", + "stype": "protein", + "created": "2022-12-14T02:19:00+00:00" + } + ], + "expect_upper": 10, + "filter": "F", + "gap_extend": 1, + "gap_open": 11, + "matrix": "BLOSUM62", + "start": "2023-01-09T17:40:35+00:00", + "end": "2023-01-09T17:43:29+00:00", + "search": "P0Y0M0DT0H0M174.000S", + "hits": [ + { + "hit_num": 1, + "hit_def": "TR:B4DKT3 B4DKT3_HUMAN cDNA FLJ58390, highly similar to Aldo-keto reductase family 1 member C3homolog OS=Homo sapiens OX=9606 PE=2 SV=1", + "hit_db": "TR", + "hit_id": "B4DKT3_HUMAN", + "hit_acc": "B4DKT3", + "hit_desc": "cDNA FLJ58390, highly similar to Aldo-keto reductase family 1 member C3homolog OS=Homo sapiens OX=9606 PE=2 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/B4DKT3", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=B4DKT3", + "hit_os": "Homo sapiens", + "hit_uni_de": "cDNA FLJ58390, highly similar to Aldo-keto reductase family 1 member C3homolog", + "hit_uni_os": "Homo sapiens", + "hit_uni_ox": "9606", + "hit_uni_pe": "2", + "hit_uni_sv": "1", + "hit_len": 138, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 1.8e-83, + "hsp_align_len": 122, + "hsp_identity": 100, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 2, + "hit_def": "TR:A0A2I3HVB7 A0A2I3HVB7_NOMLE Aldo-keto reductase family 1 member C3 OS=Nomascus leucogenys OX=61853 GN=AKR1C3 PE=3 SV=1", + "hit_db": "TR", + "hit_id": "A0A2I3HVB7_NOMLE", + "hit_acc": "A0A2I3HVB7", + "hit_desc": "Aldo-keto reductase family 1 member C3 OS=Nomascus leucogenys OX=61853 GN=AKR1C3 PE=3 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/A0A2I3HVB7", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=A0A2I3HVB7", + "hit_os": "Nomascus leucogenys", + "hit_uni_de": "Aldo-keto reductase family 1 member C3", + "hit_uni_os": "Nomascus leucogenys", + "hit_uni_ox": "61853", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "3", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 100, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 3, + "hit_def": "TR:A0A2R9A0L9 A0A2R9A0L9_PANPA Aldo-keto reductase family 1 member C3 OS=Pan paniscus OX=9597 GN=AKR1C3 PE=3 SV=1", + "hit_db": "TR", + "hit_id": "A0A2R9A0L9_PANPA", + "hit_acc": "A0A2R9A0L9", + "hit_desc": "Aldo-keto reductase family 1 member C3 OS=Pan paniscus OX=9597 GN=AKR1C3 PE=3 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/A0A2R9A0L9", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=A0A2R9A0L9", + "hit_os": "Pan paniscus", + "hit_uni_de": "Aldo-keto reductase family 1 member C3", + "hit_uni_os": "Pan paniscus", + "hit_uni_ox": "9597", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "3", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 100, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 4, + "hit_def": "TR:K7D0S3 K7D0S3_PANTR Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II) OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_db": "TR", + "hit_id": "K7D0S3_PANTR", + "hit_acc": "K7D0S3", + "hit_desc": "Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II) OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/K7D0S3", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=K7D0S3", + "hit_os": "Pan troglodytes", + "hit_uni_de": "Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II)", + "hit_uni_os": "Pan troglodytes", + "hit_uni_ox": "9598", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "2", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 95, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 5, + "hit_def": "TR:A0A6D2VZ66 A0A6D2VZ66_PANTR AKR1C3 isoform 2 OS=Pan troglodytes OX=9598 GN=CK820_G0036122 PE=3 SV=1", + "hit_db": "TR", + "hit_id": "A0A6D2VZ66_PANTR", + "hit_acc": "A0A6D2VZ66", + "hit_desc": "AKR1C3 isoform 2 OS=Pan troglodytes OX=9598 GN=CK820_G0036122 PE=3 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/A0A6D2VZ66", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=A0A6D2VZ66", + "hit_os": "Pan troglodytes", + "hit_uni_de": "AKR1C3 isoform 2", + "hit_uni_os": "Pan troglodytes", + "hit_uni_ox": "9598", + "hit_uni_gn": "CK820_G0036122", + "hit_uni_pe": "3", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 94, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 6, + "hit_def": "TR:K7CEU8 K7CEU8_PANTR Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II) OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_db": "TR", + "hit_id": "K7CEU8_PANTR", + "hit_acc": "K7CEU8", + "hit_desc": "Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II) OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/K7CEU8", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=K7CEU8", + "hit_os": "Pan troglodytes", + "hit_uni_de": "Aldo-keto reductase family 1, member C3 (3-alpha hydroxysteroid dehydrogenase, type II)", + "hit_uni_os": "Pan troglodytes", + "hit_uni_ox": "9598", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "2", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 91, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 7, + "hit_def": "TR:A0A2I3SPE1 A0A2I3SPE1_PANTR Aldo-keto reductase family 1 member C3 OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_db": "TR", + "hit_id": "A0A2I3SPE1_PANTR", + "hit_acc": "A0A2I3SPE1", + "hit_desc": "Aldo-keto reductase family 1 member C3 OS=Pan troglodytes OX=9598 GN=AKR1C3 PE=2 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/A0A2I3SPE1", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=A0A2I3SPE1", + "hit_os": "Pan troglodytes", + "hit_uni_de": "Aldo-keto reductase family 1 member C3", + "hit_uni_os": "Pan troglodytes", + "hit_uni_ox": "9598", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "2", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 89, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 8, + "hit_def": "SP:Q5R7C9 AK1C3_PONAB Aldo-keto reductase family 1 member C3 OS=Pongo abelii OX=9601 GN=AKR1C3 PE=2 SV=1", + "hit_db": "SP", + "hit_id": "AK1C3_PONAB", + "hit_acc": "Q5R7C9", + "hit_desc": "Aldo-keto reductase family 1 member C3 OS=Pongo abelii OX=9601 GN=AKR1C3 PE=2 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/Q5R7C9", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=Q5R7C9", + "hit_os": "Pongo abelii", + "hit_uni_de": "Aldo-keto reductase family 1 member C3", + "hit_uni_os": "Pongo abelii", + "hit_uni_ox": "9601", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "2", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 70, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 9, + "hit_def": "SP:P42330 AK1C3_HUMAN Aldo-keto reductase family 1 member C3 OS=Homo sapiens OX=9606 GN=AKR1C3 PE=1 SV=4", + "hit_db": "SP", + "hit_id": "AK1C3_HUMAN", + "hit_acc": "P42330", + "hit_desc": "Aldo-keto reductase family 1 member C3 OS=Homo sapiens OX=9606 GN=AKR1C3 PE=1 SV=4", + "hit_url": "https://www.uniprot.org/uniprot/P42330", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=P42330", + "hit_os": "Homo sapiens", + "hit_uni_de": "Aldo-keto reductase family 1 member C3", + "hit_uni_os": "Homo sapiens", + "hit_uni_ox": "9606", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "1", + "hit_uni_sv": "4", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 637, + "hsp_bit_score": 249.98, + "hsp_expect": 7.7e-81, + "hsp_align_len": 122, + "hsp_identity": 87, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + }, + { + "hit_num": 10, + "hit_def": "TR:A0A2R9A1P7 A0A2R9A1P7_PANPA Aldo-keto reductase family 1 member C3 OS=Pan paniscus OX=9597 GN=AKR1C3 PE=3 SV=1", + "hit_db": "TR", + "hit_id": "A0A2R9A1P7_PANPA", + "hit_acc": "A0A2R9A1P7", + "hit_desc": "Aldo-keto reductase family 1 member C3 OS=Pan paniscus OX=9597 GN=AKR1C3 PE=3 SV=1", + "hit_url": "https://www.uniprot.org/uniprot/A0A2R9A1P7", + "hit_xref_url": "https://www.ebi.ac.uk/ebisearch/search.ebi?db=uniprot&query=A0A2R9A1P7", + "hit_os": "Pan paniscus", + "hit_uni_de": "Aldo-keto reductase family 1 member C3", + "hit_uni_os": "Pan paniscus", + "hit_uni_ox": "9597", + "hit_uni_gn": "AKR1C3", + "hit_uni_pe": "3", + "hit_uni_sv": "1", + "hit_len": 323, + "hit_hsps": [ + { + "hsp_num": 1, + "hsp_score": 634, + "hsp_bit_score": 248.825, + "hsp_expect": 2.2e-80, + "hsp_align_len": 122, + "hsp_identity": 82, + "hsp_positive": 100, + "hsp_gaps": 0, + "hsp_query_frame": "0", + "hsp_hit_frame": "0", + "hsp_strand": "none/none", + "hsp_query_from": 8, + "hsp_query_to": 129, + "hsp_hit_from": 2, + "hsp_hit_to": 123, + "hsp_qseq": "DSKHQCVKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_mseq": "DSKHQC+KLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK", + "hsp_hseq": "DSKHQCLKLNDGHFMPVLGFGTYAPPEVPRSKALEVTKLAIEAGFRHIDSAHLYNNEEQVGLAIRSKIADGSVKREDIFYTSKLWSTFHRPELVRPALENSLKKAQLDYVDLYLIHSPMSLK" + } + ] + } + ] +} diff --git a/tests/stubs/uniprot.json b/tests/stubs/uniprot.json new file mode 100644 index 0000000000000000000000000000000000000000..e2bde3d125e148b268efc64fedeb2fb458688d66 --- /dev/null +++ b/tests/stubs/uniprot.json @@ -0,0 +1 @@ +{"uniprot_entry":{"ac":"P07550","id":"ADRB2_HUMAN","uniprot_checksum":"408C22731C6EDFBE","sequence_length":413,"segment_start":null,"segment_end":null},"structures":[{"summary":{"model_identifier":"4lde","model_category":"EXPERIMENTALLY DETERMINED","model_url":"https://www.ebi.ac.uk/pdbe/static/entry/4lde_updated.cif","model_format":"MMCIF","model_type":null,"model_page_url":"https://www.ebi.ac.uk/pdbe/entry/pdb/4lde","provider":"PDBe","number_of_conformers":null,"ensemble_sample_url":null,"ensemble_sample_format":null,"created":"2013-06-24","sequence_identity":90,"uniprot_start":29,"uniprot_end":348,"coverage":70.7,"experimental_method":"X-RAY DIFFRACTION","resolution":2.79,"confidence_type":null,"confidence_version":null,"confidence_avg_local_score":null,"oligomeric_state":null,"preferred_assembly_id":null,"entities":[{"entity_type":"POLYMER","entity_poly_type":"POLYPEPTIDE(L)","identifier":"P00720","identifier_category":"UNIPROT","description":"Lysozyme, Beta-2 adrenergic receptor","chain_ids":["A"]},{"entity_type":"NON-POLYMER","entity_poly_type":null,"identifier":"NA","identifier_category":"CCD","description":"SODIUM ION","chain_ids":["A"]}]},"chains":[{"chain_id":"A","segments":[{"templates":null,"seqres":{"aligned_sequence":"DEVWVVGMGIVMSLIVLAIVFGNVLVITAIAKFERLQTVTNYFITSLACADLVMGLAVVPFGAAHILTKTWTFGNFWCEFWTSIDVLCVTASIETLCVIAVDRYFAITSPFKYQSLLTKNKARVIILMVWIVSGLTSFLPIQMHWYRATHQEAINCYAEETCCDFFTNQAYAIASSIVSFYVPLVIMVFVYSRVFQEAKRQLQKIDKFALKEHKALKTLGIIMGTFTLCWLPFFIVNIVHVIQDNLIRKEVYILLNWIGYVNSGFNPLIYCRSPDFRIAFQELLCLRRSSLK","from":178,"to":384},"uniprot":{"aligned_sequence":"DEVWVVGMGIVMSLIVLAIVFGNVLVITAIAKFERLQTVTNYFITSLACADLVMGLAVVPFGAAHILMKMWTFGNFWCEFWTSIDVLCVTASIETLCVIAVDRYFAITSPFKYQSLLTKNKARVIILMVWIVSGLTSFLPIQMHWYRATHQEAINCYANETCCDFFTNQAYAIASSIVSFYVPLVIMVFVYSRVFQEAKRQLQKIDKFCLKEHKALKTLGIIMGTFTLCWLPFFIVNIVHVIQDNLIRKEVYILLNWIGYVNSGFNPLIYCRSPDFRIAFQELLCLRRSSLK","from":29,"to":235},"residues":[{"confidence":null,"model_residue_label":178,"uniprot_residue_number":29},{"confidence":null,"model_residue_label":179,"uniprot_residue_number":30}]},{"templates":null,"seqres":{"aligned_sequence":"DEVWVVGMGIVMSLIVLAIVFGNVLVITAIAKFERLQTVTNYFITSLACADLVMGLAVVPFGAAHILTKTWTFGNFWCEFWTSIDVLCVTASIETLCVIAVDRYFAITSPFKYQSLLTKNKARVIILMVWIVSGLTSFLPIQMHWYRATHQEAINCYAEETCCDFFTNQAYAIASSIVSFYVPLVIMVFVYSRVFQEAKRQLQKIDKFALKEHKALKTLGIIMGTFTLCWLPFFIVNIVHVIQDNLIRKEVYILLNWIGYVNSGFNPLIYCRSPDFRIAFQELLCLRRSSLK","from":385,"to":469},"uniprot":{"aligned_sequence":"DEVWVVGMGIVMSLIVLAIVFGNVLVITAIAKFERLQTVTNYFITSLACADLVMGLAVVPFGAAHILMKMWTFGNFWCEFWTSIDVLCVTASIETLCVIAVDRYFAITSPFKYQSLLTKNKARVIILMVWIVSGLTSFLPIQMHWYRATHQEAINCYANETCCDFFTNQAYAIASSIVSFYVPLVIMVFVYSRVFQEAKRQLQKIDKFCLKEHKALKTLGIIMGTFTLCWLPFFIVNIVHVIQDNLIRKEVYILLNWIGYVNSGFNPLIYCRSPDFRIAFQELLCLRRSSLK","from":264,"to":348},"residues":[{"confidence":null,"model_residue_label":385,"uniprot_residue_number":264},{"confidence":null,"model_residue_label":386,"uniprot_residue_number":265}]}]}]}]} diff --git a/tests/stubs/uniprot_list_summary.json b/tests/stubs/uniprot_list_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..85416a82f88525a89465c50296ec55646c7307e1 --- /dev/null +++ b/tests/stubs/uniprot_list_summary.json @@ -0,0 +1 @@ +[{"uniprot_entry":{"ac":"A0A8I5KS94","id":"A0A8I5KS94_HUMAN","uniprot_checksum":"EA44F0E7563755ED","sequence_length":623,"segment_start":41,"segment_end":250},"structures":[{"summary":{"model_identifier":"A0A8I5KS94_41-250:3eap.1.A","model_category":"TEMPLATE-BASED","model_url":"https://swissmodel.expasy.org/3d-beacons/uniprot/A0A8I5KS94.pdb?range=41-250&template=3eap.1.A&provider=swissmodel","model_format":"PDB","model_type":"ATOMIC","model_page_url":"https://swissmodel.expasy.org/repository/uniprot/A0A8I5KS94?range=41-250&template=3eap.1.A","provider":"SWISS-MODEL","created":"2022-11-13","sequence_identity":1,"uniprot_start":41,"uniprot_end":250,"coverage":0.337,"confidence_type":"QMEANDisCo","confidence_version":"4.3.0","confidence_avg_local_score":0.76,"oligomeric_state":"MONOMER","entities":[{"entity_type":"POLYMER","entity_poly_type":"POLYPEPTIDE(L)","identifier":"A0A8I5KS94","identifier_category":"UNIPROT","description":"model based on template 3eap.1.A:Rho GTPase-activating protein 11A","chain_ids":["A"]}]}}]},{"uniprot_entry":{"ac":"A0A8I5KWH8","id":"A0A8I5KWH8_HUMAN","uniprot_checksum":"7AA3847ABA0CC68B","sequence_length":625,"segment_start":1,"segment_end":252},"structures":[{"summary":{"model_identifier":"A0A8I5KWH8_1-252:3eap.1.A","model_category":"TEMPLATE-BASED","model_url":"https://swissmodel.expasy.org/3d-beacons/uniprot/A0A8I5KWH8.pdb?range=1-252&template=3eap.1.A&provider=swissmodel","model_format":"PDB","model_type":"ATOMIC","model_page_url":"https://swissmodel.expasy.org/repository/uniprot/A0A8I5KWH8?range=1-252&template=3eap.1.A","provider":"SWISS-MODEL","created":"2022-11-13","sequence_identity":1,"uniprot_start":1,"uniprot_end":252,"coverage":0.403,"confidence_type":"QMEANDisCo","confidence_version":"4.3.0","confidence_avg_local_score":0.791,"oligomeric_state":"MONOMER","entities":[{"entity_type":"POLYMER","entity_poly_type":"POLYPEPTIDE(L)","identifier":"A0A8I5KWH8","identifier_category":"UNIPROT","description":"model based on template 3eap.1.A:Rho GTPase-activating protein 11A","chain_ids":["A"]}]}}]}] diff --git a/tests/stubs/uniprot_summary.json b/tests/stubs/uniprot_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..7e619415396a4e8050b12eb7a2ee4efb26e67b61 --- /dev/null +++ b/tests/stubs/uniprot_summary.json @@ -0,0 +1 @@ +{"uniprot_entry":{"ac":"P07550","id":"ADRB2_HUMAN","sequence_length":413},"structures":[{"summary":{"model_identifier":"4lde","model_category":"EXPERIMENTALLY DETERMINED","model_url":"https://www.ebi.ac.uk/pdbe/static/entry/4lde_updated.cif","model_format":"MMCIF","model_page_url":"https://www.ebi.ac.uk/pdbe/entry/pdb/4lde","provider":"PDBe","created":"2013-06-24","sequence_identity":90,"uniprot_start":29,"uniprot_end":348,"coverage":70.7,"experimental_method":"X-RAY DIFFRACTION","resolution":2.79,"entities":[{"entity_type":"POLYMER","entity_poly_type":"POLYPEPTIDE(L)","identifier":"P00720","identifier_category":"UNIPROT","description":"Lysozyme, Beta-2 adrenergic receptor","chain_ids":["A"]},{"entity_type":"NON-POLYMER","identifier":"NA","identifier_category":"CCD","description":"SODIUM ION","chain_ids":["A"]}]}},{"summary":{"model_identifier":"6mxt","model_category":"EXPERIMENTALLY DETERMINED","model_url":"https://www.ebi.ac.uk/pdbe/static/entry/6mxt_updated.cif","model_format":"MMCIF","model_page_url":"https://www.ebi.ac.uk/pdbe/entry/pdb/6mxt","provider":"PDBe","created":"2018-10-31","sequence_identity":91,"uniprot_start":29,"uniprot_end":365,"coverage":74.82,"experimental_method":"X-RAY DIFFRACTION","resolution":2.95934213525,"entities":[{"entity_type":"POLYMER","entity_poly_type":"POLYPEPTIDE(L)","identifier":"P00720","identifier_category":"UNIPROT","description":"Endolysin, Beta-2 adrenergic receptor chimera","chain_ids":["A"]},{"entity_type":"NON-POLYMER","identifier":"OLA","identifier_category":"CCD","description":"OLEIC ACID","chain_ids":["A"]}]}}]} diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..80842667dc52ce3a15485ae889d8b745631785f1 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,14 @@ +import pytest +from click.testing import CliRunner + +from app import cli + + +@pytest.fixture(scope="module") +def runner(): + return CliRunner() + + +def test_main(runner): + result = runner.invoke(cli.main, ["--help"]) + assert result.exit_code == 0 diff --git a/tests/test_health.py b/tests/test_health.py new file mode 100644 index 0000000000000000000000000000000000000000..908356359b81333e0a0e5e3ae561af8135e712de --- /dev/null +++ b/tests/test_health.py @@ -0,0 +1,109 @@ +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import FastAPI, status +from starlette.testclient import TestClient + +from app.health.health import health_route + +app = FastAPI() +app.include_router(health_route, prefix="/health") + + +@pytest.fixture +def client(): + return TestClient(app) + + +@pytest.mark.asyncio +@patch("app.health.health.get_services") +@patch("app.health.health.get_base_service_url") +@patch("app.health.health.get_final_service_url") +@patch("app.health.health.send_async_requests", new_callable=AsyncMock) +async def test_health_check_success( + mock_send_async_requests, + mock_get_final_service_url, + mock_get_base_service_url, + mock_get_services, + client, +): + # Mock service discovery + mock_get_services.return_value = [ + {"provider": "pdbe", "accessPoint": "/api/health"} + ] + mock_get_base_service_url.return_value = "http://mocked" + mock_get_final_service_url.return_value = "http://mocked/api/health" + + # Mock response from downstream service + class MockResponse: + status_code = status.HTTP_200_OK + + def json(self): + return [ + { + "status": "pass", + "service_id": "pdbe", + "beacons_api_version": "2.7.0", + "output": "", + } + ] + + mock_send_async_requests.return_value = [MockResponse()] + + response = client.get("/health/") + assert response.status_code == status.HTTP_200_OK + assert response.headers["content-type"].startswith("application/health+json") + assert response.json() == [ + { + "status": "pass", + "service_id": "pdbe", + "beacons_api_version": "2.7.0", + "output": "", + } + ] + + +@pytest.mark.asyncio +@patch("app.health.health.get_services") +@patch("app.health.health.get_base_service_url") +@patch("app.health.health.get_final_service_url") +@patch("app.health.health.send_async_requests", new_callable=AsyncMock) +async def test_health_check_failure( + mock_send_async_requests, + mock_get_final_service_url, + mock_get_base_service_url, + mock_get_services, + client, +): + mock_get_services.return_value = [ + {"provider": "pdbe", "accessPoint": "/api/health"} + ] + mock_get_base_service_url.return_value = "http://mocked" + mock_get_final_service_url.return_value = "http://mocked/api/health" + + class MockResponse: + status_code = status.HTTP_500_INTERNAL_SERVER_ERROR + + def json(self): + return [ + { + "status": "fail", + "service_id": "pdbe", + "beacons_api_version": "2.7.0", + "output": "Service is unhealthy, not able to reach the backend!", + } + ] + + mock_send_async_requests.return_value = [MockResponse()] + + response = client.get("/health/") + assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + assert response.headers["content-type"].startswith("application/health+json") + assert response.json() == [ + { + "status": "fail", + "service_id": "pdbe", + "beacons_api_version": "2.7.0", + "output": "Service is unhealthy, not able to reach the backend!", + } + ] diff --git a/tests/test_hub.py b/tests/test_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..99c6fa2fafcd03d1a6b078468e1dd78ff36eb0af --- /dev/null +++ b/tests/test_hub.py @@ -0,0 +1,110 @@ +import asyncio + +import pytest +from async_asgi_testclient import TestClient +from starlette import status + +from app.app import app + +client = TestClient(app) + + +# Using 'with TestClient' to test the startup and shutdown events +@pytest.mark.asyncio +async def test_get_uniprot_api(mocker, valid_uniprot, uniprot_details, registry): + async with TestClient(app) as client: + future = asyncio.Future() + future.set_result(uniprot_details) + mocker.patch( + "app.uniprot.helper.get_services", return_value=registry["services"] + ) + mocker.patch("app.uniprot.uniprot.get_uniprot_helper", return_value=future) + mocker.patch( + "app.uniprot.helper.get_base_service_url", return_value="http://test" + ) + response = await client.get(f"/uniprot/{valid_uniprot}.json") + assert response.status_code == status.HTTP_200_OK + + +@pytest.mark.asyncio +async def test_get_uniprot_summary_api( + mocker, valid_uniprot, uniprot_summary, registry +): + future = asyncio.Future() + future.set_result(uniprot_summary) + mocker.patch("app.uniprot.helper.get_services", return_value=registry["services"]) + mocker.patch("app.uniprot.uniprot.get_uniprot_summary_helper", return_value=future) + mocker.patch("app.uniprot.helper.get_base_service_url", return_value="http://test") + response = await client.get(f"/uniprot/summary/{valid_uniprot}.json") + assert response.status_code == status.HTTP_200_OK + + +@pytest.mark.asyncio +async def test_get_uniprot_summaries_api(mocker, uniprot_summary_obj_list, registry): + future = asyncio.Future() + future.set_result(uniprot_summary_obj_list) + mocker.patch("app.uniprot.helper.get_services", return_value=registry["services"]) + mocker.patch( + "app.uniprot.uniprot.get_list_of_uniprot_summary_helper", return_value=future + ) + mocker.patch("app.uniprot.helper.get_base_service_url", return_value="http://test") + response = await client.post( + "/uniprot/summary", json={"accessions": ["P12345", "P23456"]} + ) + + assert response.status_code == status.HTTP_200_OK + + +@pytest.mark.asyncio +async def test_get_ensembl_summaries_api( + mocker, + valid_gifts_response, + uniprot_summary_obj_list, +): + mocker.patch( + "app.ensembl.ensembl.get_ensembl_mappings", return_value=valid_gifts_response + ) + + mocker.patch( + "app.ensembl.ensembl.get_list_of_uniprot_summary_helper", + return_value=uniprot_summary_obj_list, + ) + mocker.patch( + "app.ensembl.ensembl.get_uniprot_api_results", + return_value={}, + ) + mocker.patch( + "app.ensembl.ensembl.get_uniprot_name", + return_value="Test protein", + ) + + response = await client.get( + "/ensembl/summary/ENSG00000288864.json", + ) + + assert response.status_code == status.HTTP_200_OK + response_json = response.json() + assert response_json["uniprot_mappings"] + assert all( + isinstance(mapping["ensembl_transcript"]["transcript_id"], str) + for mapping in response_json["uniprot_mappings"] + ) + + +@pytest.mark.asyncio +async def test_annotations_api( + mocker, valid_annotation_response, registry, valid_uniprot +): + future = asyncio.Future() + future.set_result(valid_annotation_response) + mocker.patch( + "app.annotations.annotations.get_services", return_value=registry["services"] + ) + mocker.patch( + "app.annotations.annotations.get_annotations_api_helper", return_value=future + ) + mocker.patch( + "app.annotations.annotations.get_base_service_url", return_value="http://test" + ) + response = await client.get(f"/annotations/{valid_uniprot}.json?type=DOMAIN") + assert response.status_code == status.HTTP_200_OK diff --git a/tests/test_sequence.py b/tests/test_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..8d32f9bfbda42f487ff8955f60074c22210ff3c1 --- /dev/null +++ b/tests/test_sequence.py @@ -0,0 +1,277 @@ +import asyncio + +import msgpack +import pytest +from async_asgi_testclient import TestClient +from pydantic import ValidationError +from starlette import status + +from app.app import app +from app.constants import ( + JOB_FAILED_ERROR_MESSAGE, + NO_JOB_FOUND_MESSAGE, + SEARCH_IN_PROGRESS_MESSAGE, +) +from app.exception import RequestSubmissionException +from app.sequence.helper import submit_sequence_search_job +from app.sequence.schema import SequenceIdType, SequenceOverview +from app.sequence.sequence import fetch_sequence_summary +from tests.utils import StubHttpResponse + +client = TestClient(app) + + +@pytest.mark.asyncio +async def test_search_job_id_from_cache( + mocker, + sample_sequence, + sample_sequence_hash, +): + mocker.patch( + "app.sequence.sequence.get_jobdispatcher_id", return_value="non-existing-job-id" + ) + + response = await client.post("/sequence/search", json={"sequence": sample_sequence}) + + assert response.json() == {"job_id": sample_sequence_hash} + assert response.status_code == status.HTTP_200_OK + + +@pytest.mark.asyncio +async def test_result_api_no_job_id( + mocker, +): + mocker.patch("app.sequence.sequence.get_celery_task_id", return_value=None) + clear_mock = mocker.patch("app.sequence.helper.clear_jobdispatcher_id") + + response = await client.get( + "/sequence/result?job_id=ncbiblast-2021-01-01-12-12-12", + ) + + clear_mock.assert_called_once() + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json() == {"message": NO_JOB_FOUND_MESSAGE} + + +@pytest.mark.asyncio +async def test_result_api_valid_job_id_and_issue_in_celery_job( + mocker, + failed_async_result, +): + mocker.patch( + "app.sequence.sequence.get_celery_task_id", return_value="valid-job-id" + ) + mocker.patch("app.sequence.sequence.AsyncResult", return_value=failed_async_result) + clear_mock_one = mocker.patch("app.sequence.sequence.clear_jobdispatcher_id") + clear_mock_two = mocker.patch("app.sequence.sequence.clear_celery_task_id") + + response = await client.get( + "/sequence/result?job_id=ncbiblast-2021-01-01-12-12-12", + ) + + clear_mock_one.assert_called_once() + clear_mock_two.assert_called_once() + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json() == {"message": JOB_FAILED_ERROR_MESSAGE} + + +@pytest.mark.asyncio +async def test_result_api_valid_job_id_and_job_pending(mocker, pending_async_result): + mocker.patch( + "app.sequence.sequence.get_celery_task_id", return_value="valid-job-id" + ) + + mocker.patch("app.sequence.sequence.AsyncResult", return_value=pending_async_result) + + response = await client.get( + "/sequence/result?job_id=ncbiblast-2021-01-01-12-12-12", + ) + + assert response.status_code == status.HTTP_202_ACCEPTED + assert response.json() == {"message": SEARCH_IN_PROGRESS_MESSAGE} + + +@pytest.mark.asyncio +async def test_result_api_valid_job_id_and_job_finished( + mocker, + finished_none_async_result, +): + future = asyncio.Future() + future.set_result(msgpack.dumps("ncbiblast-2021-01-01-12-12-12")) + mocker.patch( + "app.sequence.sequence.get_celery_task_id", return_value="valid-job-id" + ) + + mocker.patch( + "app.sequence.sequence.AsyncResult", return_value=finished_none_async_result + ) + + response = await client.get( + "/sequence/result?job_id=ncbiblast-2021-01-01-12-12-12", + ) + + assert response.status_code == status.HTTP_404_NOT_FOUND + assert response.json() == {} + + +@pytest.mark.asyncio +async def test_submit_sequence_search_job_valid(mocker, sample_sequence): + future = asyncio.Future() + future.set_result( + StubHttpResponse(status_code=200, data="ncbiblast-2021-01-01-12-12-12") + ) + mocker.patch("app.sequence.helper.request_post", return_value=future) + + with pytest.raises(RequestSubmissionException): + assert ( + await submit_sequence_search_job(sample_sequence) + == "ncbiblast-2021-01-01-12-12-12" + ) + + +@pytest.mark.asyncio +async def test_submit_sequence_search_job_invalid(mocker, sample_sequence): + future = asyncio.Future() + future.set_result(None) + mocker.patch("app.sequence.helper.request_post", return_value=future) + + with pytest.raises(RequestSubmissionException): + assert await submit_sequence_search_job(sample_sequence) + + @pytest.mark.asyncio + async def test_fetch_sequence_summary_success(mocker): + # Mock get_services to return a single service + mocker.patch( + "app.sequence.sequence.get_services", + return_value=[ + {"provider": "test_provider", "accessPoint": "test_access"} + ], + ) + # Mock get_base_service_url to return a base url + mocker.patch( + "app.sequence.sequence.get_base_service_url", + return_value="http://test-service", + ) + # Mock get_final_service_url to return a final url + mocker.patch( + "app.sequence.sequence.get_final_service_url", + return_value="http://test-service/test_access?id=abc&type=sequence", + ) + # Prepare a valid response + valid_json = { + "entry": {"id": "abc", "name": "test_entry"}, + "structures": [ + {"id": "str1", "provider": "test_provider", "other_field": "value"} + ], + } + + # Patch send_async_requests to return a list with a mock response + class MockResponse: + status_code = 200 + + def json(self): + return valid_json + + mocker.patch( + "app.sequence.sequence.send_async_requests", + return_value=[MockResponse()], + ) + # Patch SequenceOverview and Entry to accept the test dicts + mocker.patch( + "app.sequence.sequence.SequenceOverview", + side_effect=lambda **kwargs: type("S", (), kwargs)(), + ) + mocker.patch( + "app.sequence.sequence.Entry", + side_effect=lambda **kwargs: type("E", (), kwargs)(), + ) + # Patch SequenceSummary to accept the test dicts + mocker.patch( + "app.sequence.sequence.SequenceSummary", + side_effect=lambda **kwargs: type("SS", (), kwargs)(), + ) + + result = await fetch_sequence_summary("abc", SequenceIdType.SEQUENCE) + assert result is not None + + @pytest.mark.asyncio + async def test_fetch_sequence_summary_no_services(mocker): + mocker.patch("app.sequence.sequence.get_services", return_value=[]) + result = await fetch_sequence_summary("abc", SequenceIdType.SEQUENCE) + assert result is None + + @pytest.mark.asyncio + async def test_fetch_sequence_summary_no_valid_responses(mocker): + mocker.patch( + "app.sequence.sequence.get_services", + return_value=[ + {"provider": "test_provider", "accessPoint": "test_access"} + ], + ) + mocker.patch( + "app.sequence.sequence.get_base_service_url", + return_value="http://test-service", + ) + mocker.patch( + "app.sequence.sequence.get_final_service_url", + return_value="http://test-service/test_access?id=abc&type=sequence", + ) + + # Mock send_async_requests to return a response with non-200 status + class MockResponse: + status_code = 404 + + def json(self): + return {} + + mocker.patch( + "app.sequence.sequence.send_async_requests", + return_value=[MockResponse()], + ) + result = await fetch_sequence_summary("abc", SequenceIdType.SEQUENCE) + assert result is None + + @pytest.mark.asyncio + async def test_fetch_sequence_summary_invalid_structure_response(mocker): + mocker.patch( + "app.sequence.sequence.get_services", + return_value=[ + {"provider": "test_provider", "accessPoint": "test_access"} + ], + ) + mocker.patch( + "app.sequence.sequence.get_base_service_url", + return_value="http://test-service", + ) + mocker.patch( + "app.sequence.sequence.get_final_service_url", + return_value="http://test-service/test_access?id=abc&type=sequence", + ) + # Prepare a response with an invalid structure (will raise ValidationError) + invalid_json = { + "entry": {"id": "abc", "name": "test_entry"}, + "structures": [ + { + "provider": "test_provider" + # missing required fields for SequenceOverview + } + ], + } + + class MockResponse: + status_code = 200 + + def json(self): + return invalid_json + + mocker.patch( + "app.sequence.sequence.send_async_requests", + return_value=[MockResponse()], + ) + # Patch SequenceOverview to raise ValidationError + mocker.patch( + "app.sequence.sequence.SequenceOverview", + side_effect=ValidationError([], model=SequenceOverview), + ) + result = await fetch_sequence_summary("abc", SequenceIdType.SEQUENCE) + assert result is None diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9f16ee96b1a436da8e73059df75ace206b645838 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,97 @@ +from app.config import get_base_service_url, get_services +from app.uniprot.uniprot import filter_on_checksum, get_first_entry_with_checksum +from app.utils import get_final_service_url +from app.version import __major__version__ + + +def test_get_final_service_url(): + assert ( + get_final_service_url("http://example.com", "api", "v1") + == f"http://example.com/api/v1?version={__major__version__}" + ) + + +def test_filter_on_checksum(): + in_list = [ + {"uniprot_entry": {"uniprot_checksum": "123"}}, + {"uniprot_entry": {"uniprot_checksum": "1234"}}, + {"uniprot_entry": {}}, + ] + + assert filter_on_checksum(in_list, "123") == [ + {"uniprot_entry": {"uniprot_checksum": "123"}} + ] + + +def test_get_first_entry_with_checksum_valid(): + in_list = [ + {"uniprot_entry": {"ac": "P12345"}}, + {"uniprot_entry": {"ac": "P23456", "uniprot_checksum": "123"}}, + {"uniprot_entry": {"ac": "P34567", "uniprot_checksum": "123"}}, + ] + + assert get_first_entry_with_checksum(in_list) == { + "ac": "P23456", + "uniprot_checksum": "123", + } + + +def test_get_first_entry_with_checksum_none(): + in_list = [] + + assert not get_first_entry_with_checksum(in_list) + + +def test_get_first_entry_with_checksum_valid_no_checksum(): + in_list = [ + {"uniprot_entry": {"ac": "P12345"}}, + {"uniprot_entry": {"ac": "P23456"}}, + {"uniprot_entry": {"ac": "P34567"}}, + ] + + assert get_first_entry_with_checksum(in_list) == {"ac": "P12345"} + + +def test_get_services(mocker, registry): + mocker.patch("app.config.read_data_file", return_value=registry) + assert get_services(service_type="serviceOne") == [ + { + "serviceType": "serviceOne", + "provider": "providerOne", + "accessPoint": "service/", + }, + { + "serviceType": "serviceOne", + "provider": "providerTwo", + "accessPoint": "service/v/", + }, + ] + + +def test_get_services_exclude_provider(mocker, registry): + mocker.patch("app.config.read_data_file", return_value=registry) + assert get_services(service_type="serviceOne", exclude_provider="providerTwo") == [ + { + "serviceType": "serviceOne", + "provider": "providerOne", + "accessPoint": "service/", + }, + ] + + +def test_get_services_provider(mocker, registry): + mocker.patch("app.config.read_data_file", return_value=registry) + assert get_services(service_type="serviceOne", provider="providerOne") == [ + { + "serviceType": "serviceOne", + "provider": "providerOne", + "accessPoint": "service/", + }, + ] + + +def test_get_base_service_url(mocker, registry): + mocker.patch("app.config.get_providers", return_value=registry["providers"]) + assert ( + get_base_service_url("providerOneId") == "https://providerOneDevBaseServiceUrl" + ) diff --git a/tests/test_worker.py b/tests/test_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..047eeb1021d12636b21ac0b33db8e463a622dd61 --- /dev/null +++ b/tests/test_worker.py @@ -0,0 +1,58 @@ +import json + +import pytest + +from tests.utils import StubHttpResponse +from worker.helper import ( + JobResultsNotFoundException, + filter_json_results, + get_job_dispatcher_json_results, + prepare_accession_list, + prepare_hit_dictionary, +) +from worker.schema import AccessionListRequest + + +def test_prepare_accession_list(): + accessions = ["P12345", "P23456", "P34567"] + assert prepare_accession_list(accessions) == AccessionListRequest( + accessions=accessions + ) + + +def test_filter_json_results_90(seq_search_response): + assert len(filter_json_results(seq_search_response.data, 90)) == 6 + + +def test_filter_json_results_95(seq_search_response): + assert len(filter_json_results(seq_search_response.data, 95)) == 4 + + +def test_prepare_hit_dictionary(seq_search_response): + filtered_hits = filter_json_results(seq_search_response.data, 95) + expected_hit_dictionary = {} + + with open("tests/stubs/hit_dictionary.json", "r") as f: + expected_hit_dictionary = json.loads(f.read()) + + assert prepare_hit_dictionary(filtered_hits) == expected_hit_dictionary + + +@pytest.mark.asyncio +async def test_get_job_dispatcher_json_results_valid(mocker, sample_sequence_hash): + mocker.patch( + "worker.helper.requests.get", + return_value=StubHttpResponse(status_code=200, data={"results": "results"}), + ) + + assert get_job_dispatcher_json_results(sample_sequence_hash) == { + "results": "results" + } + + +@pytest.mark.asyncio +async def test_get_job_dispatcher_json_results_invalid(mocker, sample_sequence_hash): + mocker.patch("worker.helper.requests.get", return_value=None) + + with pytest.raises(JobResultsNotFoundException): + assert get_job_dispatcher_json_results(sample_sequence_hash) diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9de09202ccd5a9ca468f4633d5685bf1602e7a7c --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,47 @@ +import json + + +async def request_get_stub(url: str, stub_for: str, status_code: int = 200): + """Returns an object with stub response. + + Args: + url (str): A request URL. + stub_for (str): Type of stub required. + + Returns: + StubResponse: A StubResponse object. + """ + return StubResponse(stub_for=stub_for, status_code=status_code) + + +class StubResponse: + """A Stub response class to return a response from JSON.""" + + def __init__(self, status_code: int, stub_for: str) -> None: + self.status_code = status_code + self.prefix = "tests/stubs/" + self.data = {} + + with open(f"{self.prefix}/{stub_for}.json") as f: + self.data = json.load(f) + + def json(self): + return self.data + + +class Content: + def __init__(self, data) -> None: + self.data = data + + def decode(self): + return self.data + + +class StubHttpResponse: + def __init__(self, status_code: int, data): + self.status_code = status_code + self.content = Content(data) + self.data = data + + def json(self): + return self.data diff --git a/worker/__init__.py b/worker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/worker/cache/redis_cache.py b/worker/cache/redis_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..57a4f1a22c46f1f5aeaae97ae511c8e89ef56713 --- /dev/null +++ b/worker/cache/redis_cache.py @@ -0,0 +1,48 @@ +from typing import Optional + +from redis import Redis + + +class RedisCache: + """RedisCache class gives access to aioredis functionality""" + + redis_client: Optional[Redis] = None + + @classmethod + def init_redis(cls, url: str, encoding: str) -> None: + if cls.redis_client is None: + cls.redis_client = Redis.from_url( + url, + encoding=encoding, + decode_responses=False, + ) + + @classmethod + def get(cls, key: str) -> Optional[bytes]: + return cls.redis_client.get(key) + + @classmethod + def set(cls, key: str, value: str) -> bool: + return bool(cls.redis_client.set(key, value)) + + @classmethod + def hget(cls, prefix: str, key: str, decode: bool = True) -> Optional[bytes | str]: + value = cls.redis_client.hget(prefix, key) + if not value: + return None + if decode: + return value.decode() + return value + + @classmethod + def hset(cls, prefix: str, key: str, value: str) -> int: + return int(cls.redis_client.hset(prefix, key, value)) + + @classmethod + def hdel(cls, prefix: str, key: str) -> int: + return int(cls.redis_client.hdel(prefix, key)) + + @classmethod + def flush(cls) -> None: + if cls.redis_client: + cls.redis_client.flushall() diff --git a/worker/cache/utils.py b/worker/cache/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9ab610df8efb47792a6ecc0a2b7b95bb0d2dbed1 --- /dev/null +++ b/worker/cache/utils.py @@ -0,0 +1,47 @@ +from typing import Any, Dict, List, Optional + +import msgpack + +from worker.cache.redis_cache import RedisCache + + +def get_job_results(hashed_sequence: str) -> Optional[List[Any]]: + packed = RedisCache.hget("job-results", hashed_sequence, decode=False) + + if packed is None: + return None + + data: Dict[str, Any] = msgpack.loads(packed) + return list(data.values()) + + +def set_job_results(hashed_sequence: str, result): + RedisCache.hset("job-results", hashed_sequence, msgpack.dumps(result)) + + +def get_celery_task_id(hashed_sequence: str): + return RedisCache.hget("sequence-task-mapping", hashed_sequence) + + +def get_jobdispatcher_id(hashed_sequence: str): + return RedisCache.hget("sequence-jdid-mapping", hashed_sequence) + + +def set_jobdispatcher_id(hashed_sequence: str, jdispatcher_id: str): + RedisCache.hset("sequence-jdid-mapping", hashed_sequence, jdispatcher_id) + + +def set_celery_task_id(hashed_sequence: str, result_task): + RedisCache.hset("sequence-task-mapping", hashed_sequence, result_task.id) + + +def clear_job_results(hashed_sequence: str): + RedisCache.hdel("job-results", hashed_sequence) + + +def clear_celery_task_id(hashed_sequence: str): + RedisCache.hdel("sequence-task-mapping", hashed_sequence) + + +def clear_jobdispatcher_id(hashed_sequence: str): + RedisCache.hdel("sequence-jdid-mapping", hashed_sequence) diff --git a/worker/helper.py b/worker/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..86ecbadc2eeebb33f8d37418f8ac918b8e9e55d5 --- /dev/null +++ b/worker/helper.py @@ -0,0 +1,192 @@ +import os +import re +from time import sleep +from typing import Dict, List + +import requests + +from app import logger +from worker.schema import AccessionListRequest + +MAX_POST_LIMIT = int(os.environ.get("MAX_POST_LIMIT", 10)) +BEACONS_API_URL = os.environ.get("BEACONS_API_URL") +ARRAY_REGEX = r"(\w+)(\[(\d+)\])?" + + +class JobStatusNotFoundException(Exception): + pass + + +class JobResultsNotFoundException(Exception): + pass + + +def prepare_hit_dictionary(hit_list: List) -> Dict: + """Creates a dictionary of hits. + + Args: + hit_list (List): List of hits + + Returns: + Dict: A dictionary of hits + """ + hit_dictionary = {} + + for hit in hit_list: + hit_dictionary.update( + { + hit["hit_acc"]: { + "accession": hit["hit_acc"], + "description": hit["hit_desc"], + "hit_length": hit["hit_len"], + "id": hit["hit_id"], + "hit_uni_os": hit["hit_uni_os"], + "hit_uni_ox": int(hit["hit_uni_ox"]) if hit["hit_uni_ox"] else None, + "hit_hsps": [ + { + "hsp_score": x["hsp_score"], + "hsp_bit_score": x["hsp_bit_score"], + "hsp_expect": x["hsp_expect"], + "hsp_align_len": x["hsp_align_len"], + "hsp_identity": x["hsp_identity"], + "hsp_positive": x["hsp_positive"], + "hsp_qseq": x["hsp_qseq"], + "hsp_mseq": x["hsp_mseq"], + "hsp_hseq": x["hsp_hseq"], + } + for x in hit["hit_hsps"] + ], + } + } + ) + + return hit_dictionary + + +def filter_json_results(results: Dict, hsp_identity: int = 90) -> List: + """Filter the results from the search engine. Only returns MAX_POST_LIMIT results. + + Args: + results (Dict): Results from the search engine + hsp_identity (int, optional): Minimum identity percentage. Defaults to 90. + + Returns: + List: A list of filtered results + """ + return [ + x for x in results["hits"] if x["hit_hsps"][0]["hsp_identity"] >= hsp_identity + ] + + +def divide_chunks(list: List[str], batch_size: int): + for i in range(0, len(list), batch_size): + yield list[i : i + batch_size] + + +def prepare_accession_list(accession_list: List) -> AccessionListRequest: + """Creates an AccessionListRequest object. + + Args: + accession_list (List): A list of accessions + + Returns: + AccessionListRequest: An AccessionListRequest object + """ + return AccessionListRequest(accessions=accession_list) + + +def prepare_hit_dictionary_with_summary_results(hit_dictionary: Dict): + final_hit_dictionary = {} + with requests.Session() as session: + for accessions_batch in divide_chunks( + list(hit_dictionary.keys()), MAX_POST_LIMIT + ): + summary_response = session.post( + f"{BEACONS_API_URL}/uniprot/summary", + json={"accessions": accessions_batch}, + ) + + if ( + summary_response + and summary_response.status_code == 200 + and summary_response.json() + ): + for result in summary_response.json(): + accession = result["uniprot_entry"]["ac"] + accession_record = hit_dictionary[accession] + accession_record.update({"summary": result}) + final_hit_dictionary.update({accession: accession_record}) + + return final_hit_dictionary + + +def get_job_dispatcher_job_status(job_id: str): + """Check the status of a job. + + Args: + job_id (str): A job id + """ + url = f"https://www.ebi.ac.uk/Tools/services/rest/ncbiblast/status/{job_id}" + + response = requests.get(url) + + if response and response.status_code == 200: + return response.content.decode() + raise JobStatusNotFoundException("Job status not found!") + + +def get_job_dispatcher_json_results(job_id: str): + """Get the results of a job. + + Args: + job_id (str): A job id + """ + url = f"https://www.ebi.ac.uk/Tools/services/rest/ncbiblast/result/{job_id}/json" + response = requests.get(url) + + if response and response.status_code == 200: + return response.json() + raise JobResultsNotFoundException("Job results not found!") + + +def get_uniprot_summaries(accession_list): + response_dict = {} + with requests.Session() as session: + for accessions_batch in divide_chunks( + accession_list, + 100, # UniProt accepts max 100 accessions per request + ): + accessions = ",".join(accessions_batch) + try_count = 1 + url = f"https://www.ebi.ac.uk/proteins/api/proteins?accession={accessions}" + + while try_count <= 3: + try: + response = session.get(url, headers={"Accept": "application/json"}) + break + except Exception: + sleep(0.2) + try_count += 1 + logger.warning(f"Error fetching {url}! Retry count: {try_count}") + continue + + if response and response.status_code == 200: + for result in response.json(): + accession = result["accession"] + response_dict[accession] = result + + return response_dict + + +def get_nested_value_from_json(json_obj, key): + obj = json_obj.copy() + try: + for token in key.split("."): + match = re.match(ARRAY_REGEX, token) + if match.group(3): + obj = obj.get(match.group(1))[int(match.group(3))] + else: + obj = obj.get(token) + return obj + except Exception: + return None diff --git a/worker/schema.py b/worker/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..46903380ddad4b9a3ee1ec5c9c734502f514f164 --- /dev/null +++ b/worker/schema.py @@ -0,0 +1,19 @@ +from typing import List, Optional + +from pydantic import BaseModel, Field + + +class AccessionListRequest(BaseModel): + accessions: List[str] = Field( + ..., + description="A list of UniProt accessions", + json_schema_extra={"example": ["P00734", "P38398"]}, + ) + provider: Optional[str] = Field( + None, + description="Name of the model provider", + json_schema_extra={"example": "swissmodel"}, + ) + exclude_provider: Optional[str] = Field( + None, description="Provider to exclude.", json_schema_extra={"example": "pdbe"} + ) diff --git a/worker/worker.py b/worker/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..f12af04592255e2aaab081c013c4690c3445ecdc --- /dev/null +++ b/worker/worker.py @@ -0,0 +1,118 @@ +import os +import time + +from celery import Celery, current_task +from celery.app import trace + +from worker.cache.redis_cache import RedisCache +from worker.cache.utils import clear_jobdispatcher_id, get_celery_task_id +from worker.helper import ( + JobStatusNotFoundException, + filter_json_results, + get_job_dispatcher_job_status, + get_job_dispatcher_json_results, + get_nested_value_from_json, + get_uniprot_summaries, + prepare_hit_dictionary, + prepare_hit_dictionary_with_summary_results, +) + +CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", "redis://redis:6379/0") +CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", "redis://redis:6379/1") +REDIS_URL = os.environ.get("REDIS_URL", "redis://redis:6379/1") +celery = Celery("worker", backend=CELERY_RESULT_BACKEND, broker=CELERY_BROKER_URL) +RedisCache.init_redis(REDIS_URL, "utf-8") +MAX_WAIT_TIME = int(os.environ.get("MAX_WAIT_TIME", 600)) +SLEEP_TIME = int(os.environ.get("SLEEP_TIME", 20)) + +trace.LOG_SUCCESS = """\ +Task %(name)s[%(id)s] succeeded in %(runtime)ss\ +""" + +celery.conf.update( + result_serializer="msgpack", + accept_content=["msgpack", "json"], + result_expires=0, +) + + +@celery.task( + time_limit=MAX_WAIT_TIME, + soft_time_limit=MAX_WAIT_TIME - SLEEP_TIME, +) +def retrieve_result(job_id: str, hashed_sequence: str): + waited_time = 0 + + while True: + existing_job = get_celery_task_id(hashed_sequence) + + if existing_job and current_task.request.id != existing_job: + return + + if waited_time > MAX_WAIT_TIME: + clear_jobdispatcher_id(hashed_sequence) + break + try: + job_status = get_job_dispatcher_job_status(job_id) + except JobStatusNotFoundException: + clear_jobdispatcher_id(hashed_sequence) + break + + if job_status == "RUNNING": + time.sleep(SLEEP_TIME) + waited_time += SLEEP_TIME + continue + + elif job_status == "FINISHED": + search_job_results = get_job_dispatcher_json_results(job_id) + filtered_results = filter_json_results(search_job_results) + hit_dictionary = prepare_hit_dictionary(filtered_results) + final_hit_dictionary = prepare_hit_dictionary_with_summary_results( + hit_dictionary + ) + + if all(not x.get("summary") for x in final_hit_dictionary.values()): + clear_jobdispatcher_id(hashed_sequence) + return + + # get uniprot api results + uniprot_api_results = get_uniprot_summaries( + list(final_hit_dictionary.keys()) + ) + + for key in final_hit_dictionary: + accession_result = uniprot_api_results.get(key) + + if accession_result: + protein_name = get_nested_value_from_json( + accession_result, "protein.recommendedName.fullName.value" + ) + + if not protein_name: + protein_name = get_nested_value_from_json( + accession_result, "protein.submittedName[0].fullName.value" + ) + + organism_names = { + name["type"]: name["value"] + for name in get_nested_value_from_json( + accession_result, "organism.names" + ) + } + + final_hit_dictionary[key].update( + { + "title": protein_name, + "hit_com_os": organism_names.get("common") + if organism_names.get("common") + else organism_names.get("scientific"), + } + ) + + return final_hit_dictionary + + elif job_status == "NOT_FOUND": + clear_jobdispatcher_id(hashed_sequence) + break + + return