Spaces:
Sleeping
Sleeping
avoigt1121
Claude Opus 5.5
feat: the five knowledge endpoints, gradio_ui and frozen descriptor (s2)
3ed6b66 Download src/endpoints/targets.py from anne-voigt/pdac-knowledge-agent-dev: direct link, hf CLI and curl.
- Browser
- Download file 5.2 kB
-
https://huggingface.co/spaces/anne-voigt/pdac-knowledge-agent-dev/resolve/main/src/endpoints/targets.py
- Command line
-
hf download hf://spaces/anne-voigt/pdac-knowledge-agent-dev/src/endpoints/targets.py
-
curl -L -o targets.py https://huggingface.co/spaces/anne-voigt/pdac-knowledge-agent-dev/resolve/main/src/endpoints/targets.py
5.2 kB
| """targets_for_disease — the targets Open Targets most associates with a disease. | |
| A disease name is resolved by Open Targets' own search: an exact (case-insensitive) name match | |
| wins, else the first hit, and the payload names the id chosen and the alternatives it passed | |
| over. The ranking and the score are Open Targets' association score, relayed as its score; this | |
| endpoint ranks nothing itself. Open Targets moved most disease ids from EFO to MONDO | |
| (pancreatic ductal adenocarcinoma is ``MONDO_0005184``; the legacy ``EFO_0002618`` no longer | |
| resolves), so an unknown id is reported as unresolved with Open Targets' own message. | |
| """ | |
| from __future__ import annotations | |
| from typing import Any | |
| from src import payloads | |
| from src.endpoints._common import ( | |
| Budget, | |
| Collector, | |
| according_to, | |
| get_client, | |
| humanise_list, | |
| stamped, | |
| ) | |
| from src.identifiers import parse_disease | |
| ENDPOINT = "targets_for_disease" | |
| OT_SEARCH = "OpenTargets_get_disease_id_description_by_name" | |
| OT_TARGETS = "OpenTargets_get_associated_targets_by_disease_efoId" | |
| DEFAULT_SIZE = 25 | |
| MAX_SIZE = 50 | |
| MAX_ALTERNATIVES = 4 | |
| def targets_for_disease(disease: str = "", size: str = "") -> dict[str, Any]: | |
| parsed = parse_disease(disease) | |
| if not parsed.ok: | |
| return payloads.refused(ENDPOINT, parsed.reason, parsed.message) | |
| try: | |
| n = int((size or str(DEFAULT_SIZE)).strip()) | |
| except ValueError: | |
| n = 0 | |
| if not 1 <= n <= MAX_SIZE: | |
| return payloads.refused( | |
| ENDPOINT, "invalid_argument", f"size must be a whole number from 1 to {MAX_SIZE}." | |
| ) | |
| client, budget, out = get_client(), Budget(), Collector() | |
| given = parsed.identifiers[0] | |
| resolution: dict[str, Any] = {"input": given.value} | |
| if given.kind == "disease_id": | |
| disease_id, disease_name = given.value, None | |
| else: | |
| result = out.call(client, budget, OT_SEARCH, {"diseaseName": given.value}) | |
| if result is None: | |
| return payloads.error( | |
| ENDPOINT, | |
| "all_sources_failed", | |
| "Open Targets did not answer.", | |
| source_errors=out.source_errors, | |
| ) | |
| hits = ((result.data.get("search") or {}).get("hits")) or [] | |
| if not hits: | |
| return payloads.refused( | |
| ENDPOINT, "unknown_disease", f"Open Targets finds no disease named {given.value!r}." | |
| ) | |
| exact = [h for h in hits if (h.get("name") or "").casefold() == given.value.casefold()] | |
| chosen = (exact or hits)[0] | |
| disease_id, disease_name = chosen["id"], chosen.get("name") | |
| resolution = stamped( | |
| { | |
| "input": given.value, | |
| "id": disease_id, | |
| "name": disease_name, | |
| "matched": "exact name" if exact else "first search hit", | |
| "alternatives": [ | |
| {"id": h["id"], "name": h.get("name")} for h in hits if h["id"] != disease_id | |
| ][:MAX_ALTERNATIVES], | |
| }, | |
| result, | |
| ref=disease_id, | |
| url=f"https://platform.opentargets.org/disease/{disease_id}", | |
| ) | |
| result = out.call( | |
| client, | |
| budget, | |
| OT_TARGETS, | |
| {"efoId": disease_id, "size": n}, | |
| unknown=("no disease for ID", disease_id), | |
| ) | |
| if result is None: | |
| if out.unresolved: | |
| return payloads.refused(ENDPOINT, "unknown_disease", out.unresolved[0]["reason"]) | |
| return payloads.error( | |
| ENDPOINT, | |
| "all_sources_failed", | |
| "Open Targets did not answer.", | |
| source_errors=out.source_errors, | |
| ) | |
| data = result.data.get("disease") or {} | |
| disease_name = disease_name or data.get("name") | |
| assoc = data.get("associatedTargets") or {} | |
| for rank, row in enumerate(assoc.get("rows") or [], start=1): | |
| target = row["target"] | |
| out.rows.append( | |
| stamped( | |
| { | |
| "rank": rank, | |
| "target": target["approvedSymbol"], | |
| "target_ensembl_id": target["id"], | |
| "association_score": round(float(row["score"]), 4), | |
| }, | |
| result, | |
| ref=target["id"], | |
| url=f"https://platform.opentargets.org/evidence/{target['id']}/{disease_id}", | |
| ) | |
| ) | |
| lead = according_to(["opentargets"], out.retrieved) | |
| symbols = [r["target"] for r in out.rows] | |
| narrative = ( | |
| f"{lead}, the top {len(symbols)} of {assoc.get('count', len(symbols))} targets associated " | |
| f"with {disease_name or disease_id} ({disease_id}), ranked by Open Targets' own " | |
| f"association score: {humanise_list(symbols, limit=10)}." | |
| ) | |
| if resolution.get("matched") == "first search hit": | |
| narrative += f" No exact name match for {given.value!r}; Open Targets' first hit was used." | |
| return payloads.ok( | |
| ENDPOINT, | |
| query={"disease": given.value, "size": n}, | |
| rows=out.rows, | |
| sources_used=out.sources_used, | |
| narrative=narrative, | |
| unresolved=out.unresolved, | |
| source_errors=out.source_errors, | |
| disease=resolution, | |
| ) | |