David (Xiang) Xia commited on
Commit ·
ecb1d75
1
Parent(s): af567cf
Optimize search latency with caching and logging
Browse files- app/services/franklin_service.py +230 -106
- app/services/variant_service.py +341 -178
app/services/franklin_service.py
CHANGED
|
@@ -294,6 +294,7 @@ def _get_cache_connection() -> sqlite3.Connection:
|
|
| 294 |
path = _cache_db_path()
|
| 295 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 296 |
connection = sqlite3.connect(path, timeout=30, check_same_thread=False)
|
|
|
|
| 297 |
connection.execute(
|
| 298 |
"""
|
| 299 |
CREATE TABLE IF NOT EXISTS franklin_sv_cache (
|
|
@@ -306,6 +307,17 @@ def _get_cache_connection() -> sqlite3.Connection:
|
|
| 306 |
)
|
| 307 |
"""
|
| 308 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
connection.commit()
|
| 310 |
return connection
|
| 311 |
|
|
@@ -371,6 +383,44 @@ def _save_cached_sv_assessment(
|
|
| 371 |
connection.commit()
|
| 372 |
|
| 373 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
def _is_cache_stale(cached: dict[str, Any]) -> bool:
|
| 375 |
fetched_at_raw = cached.get("fetched_at")
|
| 376 |
if not isinstance(fetched_at_raw, str):
|
|
@@ -629,109 +679,68 @@ async def _franklin_request(
|
|
| 629 |
url = f"{FRANKLIN_BASE_URL}{endpoint}"
|
| 630 |
|
| 631 |
async def _do_request(active_client: httpx.AsyncClient) -> dict[str, Any]:
|
| 632 |
-
response = await active_client.request(
|
| 633 |
-
method=method.upper(),
|
| 634 |
-
url=url,
|
| 635 |
-
json=payload if method.upper() in {"POST", "PUT", "PATCH"} else None,
|
| 636 |
-
params=params,
|
| 637 |
-
timeout=20.0,
|
| 638 |
-
headers={"Accept": "application/json"},
|
| 639 |
-
)
|
| 640 |
try:
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 650 |
async def _do_curl_request() -> dict[str, Any]:
|
| 651 |
request_url = url
|
| 652 |
if params:
|
| 653 |
request_url = f"{url}?{urlencode(params, doseq=True)}"
|
| 654 |
|
| 655 |
-
command = [
|
| 656 |
-
"curl",
|
| 657 |
-
"-sS",
|
| 658 |
-
"-L",
|
| 659 |
-
"--max-time",
|
| 660 |
-
"20",
|
| 661 |
-
"-H",
|
| 662 |
-
"Accept: application/json",
|
| 663 |
-
"-w",
|
| 664 |
-
"\\n%{http_code}",
|
| 665 |
-
]
|
| 666 |
if method.upper() in {"POST", "PUT", "PATCH"}:
|
| 667 |
-
command.extend(
|
| 668 |
-
[
|
| 669 |
-
"-X",
|
| 670 |
-
method.upper(),
|
| 671 |
-
"-H",
|
| 672 |
-
"Content-Type: application/json",
|
| 673 |
-
"--data",
|
| 674 |
-
json.dumps(payload if payload is not None else {}),
|
| 675 |
-
]
|
| 676 |
-
)
|
| 677 |
command.append(request_url)
|
| 678 |
|
| 679 |
-
process = await asyncio.create_subprocess_exec(
|
| 680 |
-
*command,
|
| 681 |
-
stdout=asyncio.subprocess.PIPE,
|
| 682 |
-
stderr=asyncio.subprocess.PIPE,
|
| 683 |
-
)
|
| 684 |
-
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=25.0)
|
| 685 |
-
if process.returncode != 0:
|
| 686 |
-
message = stderr.decode("utf-8", errors="ignore").strip() or stdout.decode("utf-8", errors="ignore").strip()
|
| 687 |
-
return {"ok": False, "status": 500, "error": message or "curl request failed"}
|
| 688 |
-
|
| 689 |
-
body, _, status_line = stdout.decode("utf-8", errors="ignore").rpartition("\n")
|
| 690 |
-
try:
|
| 691 |
-
status_code = int(status_line.strip())
|
| 692 |
-
except ValueError:
|
| 693 |
-
status_code = 200
|
| 694 |
-
body = stdout.decode("utf-8", errors="ignore")
|
| 695 |
-
|
| 696 |
try:
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
"data": data,
|
| 704 |
-
}
|
| 705 |
-
|
| 706 |
-
try:
|
| 707 |
-
curl_result = await _do_curl_request()
|
| 708 |
-
if curl_result.get("ok") or curl_result.get("status") in {400, 401, 403, 404}:
|
| 709 |
-
return curl_result
|
| 710 |
-
logger.warning(
|
| 711 |
-
"Franklin curl path returned retryable error, falling back to httpx",
|
| 712 |
-
extra={"endpoint": endpoint, "status": curl_result.get("status"), "error": curl_result.get("error")},
|
| 713 |
-
)
|
| 714 |
-
except Exception as curl_exc:
|
| 715 |
-
logger.warning("Franklin curl path failed, falling back to httpx", extra={"endpoint": endpoint, "error": str(curl_exc)})
|
| 716 |
-
|
| 717 |
-
try:
|
| 718 |
-
return await _do_request(client)
|
| 719 |
-
except httpx.TimeoutException:
|
| 720 |
-
if HTTPX_TRUST_ENV:
|
| 721 |
try:
|
| 722 |
-
|
| 723 |
-
return await _do_request(direct_client)
|
| 724 |
except Exception:
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
return await _do_request(direct_client)
|
| 732 |
-
except Exception:
|
| 733 |
-
return {"ok": False, "status": 500, "error": str(exc)}
|
| 734 |
-
return {"ok": False, "status": 500, "error": str(exc)}
|
| 735 |
|
| 736 |
|
| 737 |
async def _fetch_structural_variant_assessment(
|
|
@@ -1129,7 +1138,6 @@ async def get_franklin_variant_assessment(
|
|
| 1129 |
community_frequency,
|
| 1130 |
variant_matcher,
|
| 1131 |
alt_reference,
|
| 1132 |
-
publications,
|
| 1133 |
org_assessments,
|
| 1134 |
uploaded_files,
|
| 1135 |
) = await asyncio.gather(
|
|
@@ -1150,12 +1158,6 @@ async def get_franklin_variant_assessment(
|
|
| 1150 |
payload={"snp_variant": payload},
|
| 1151 |
),
|
| 1152 |
_franklin_request(client, "POST", "/api/fetch_alt_reference_variant", payload=payload),
|
| 1153 |
-
_franklin_request(
|
| 1154 |
-
client,
|
| 1155 |
-
"POST",
|
| 1156 |
-
"/api/feed/get_posts",
|
| 1157 |
-
payload={"variant_id": active_context.hash_id, "from_index": 0, "to_index": 10},
|
| 1158 |
-
),
|
| 1159 |
_franklin_request(client, "POST", "/api/org/fetch_interpretation", payload=payload),
|
| 1160 |
_franklin_request(client, "POST", "/api/organization/variant/attachment/list", payload=payload),
|
| 1161 |
)
|
|
@@ -1171,6 +1173,108 @@ async def get_franklin_variant_assessment(
|
|
| 1171 |
}
|
| 1172 |
region_data = await _franklin_request(client, "GET", "/api/fetch_region_data", params=region_params)
|
| 1173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1174 |
return {
|
| 1175 |
"variant": {
|
| 1176 |
"query": query,
|
|
@@ -1194,16 +1298,36 @@ async def get_franklin_variant_assessment(
|
|
| 1194 |
"clinical_evidence": evidences,
|
| 1195 |
"predictions": predictions,
|
| 1196 |
"population_frequencies": frequencies,
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
|
| 1200 |
-
|
| 1201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1202 |
},
|
| 1203 |
-
"publications": publications,
|
| 1204 |
-
"gene_assessment": impacts,
|
| 1205 |
"curated_gene_data": impacts,
|
| 1206 |
-
"associated_conditions": summary,
|
| 1207 |
"somatic_clinical_evidence": evidences,
|
| 1208 |
"organization_assessments": org_assessments,
|
| 1209 |
"my_organization_assessments": org_assessments,
|
|
|
|
| 294 |
path = _cache_db_path()
|
| 295 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 296 |
connection = sqlite3.connect(path, timeout=30, check_same_thread=False)
|
| 297 |
+
# Original SV cache table
|
| 298 |
connection.execute(
|
| 299 |
"""
|
| 300 |
CREATE TABLE IF NOT EXISTS franklin_sv_cache (
|
|
|
|
| 307 |
)
|
| 308 |
"""
|
| 309 |
)
|
| 310 |
+
# Generic key-value cache (e.g. for HGVS mappings)
|
| 311 |
+
connection.execute(
|
| 312 |
+
"""
|
| 313 |
+
CREATE TABLE IF NOT EXISTS openvar_generic_cache (
|
| 314 |
+
cache_key TEXT PRIMARY KEY,
|
| 315 |
+
value_json TEXT NOT NULL,
|
| 316 |
+
expires_at TEXT NOT NULL,
|
| 317 |
+
updated_at TEXT NOT NULL
|
| 318 |
+
)
|
| 319 |
+
"""
|
| 320 |
+
)
|
| 321 |
connection.commit()
|
| 322 |
return connection
|
| 323 |
|
|
|
|
| 383 |
connection.commit()
|
| 384 |
|
| 385 |
|
| 386 |
+
def save_hgvs_mapping(hgvs: str, coords: dict) -> None:
|
| 387 |
+
"""Save HGVS-to-coordinates mapping to persistent cache."""
|
| 388 |
+
cache_key = f"hgvs_map:{hgvs}"
|
| 389 |
+
now = datetime.now(timezone.utc)
|
| 390 |
+
expires_at = (now + timedelta(days=30)).isoformat()
|
| 391 |
+
updated_at = now.isoformat()
|
| 392 |
+
with _get_cache_connection() as connection:
|
| 393 |
+
connection.execute(
|
| 394 |
+
"""
|
| 395 |
+
INSERT INTO openvar_generic_cache (cache_key, value_json, expires_at, updated_at)
|
| 396 |
+
VALUES (?, ?, ?, ?)
|
| 397 |
+
ON CONFLICT(cache_key) DO UPDATE SET
|
| 398 |
+
value_json = excluded.value_json,
|
| 399 |
+
expires_at = excluded.expires_at,
|
| 400 |
+
updated_at = excluded.updated_at
|
| 401 |
+
""",
|
| 402 |
+
(cache_key, json.dumps(coords), expires_at, updated_at),
|
| 403 |
+
)
|
| 404 |
+
connection.commit()
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def load_hgvs_mapping(hgvs: str) -> Optional[dict]:
|
| 408 |
+
"""Load HGVS-to-coordinates mapping from persistent cache."""
|
| 409 |
+
cache_key = f"hgvs_map:{hgvs}"
|
| 410 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 411 |
+
with _get_cache_connection() as connection:
|
| 412 |
+
row = connection.execute(
|
| 413 |
+
"""
|
| 414 |
+
SELECT value_json FROM openvar_generic_cache
|
| 415 |
+
WHERE cache_key = ? AND expires_at > ?
|
| 416 |
+
""",
|
| 417 |
+
(cache_key, now),
|
| 418 |
+
).fetchone()
|
| 419 |
+
if row:
|
| 420 |
+
return json.loads(row[0])
|
| 421 |
+
return None
|
| 422 |
+
|
| 423 |
+
|
| 424 |
def _is_cache_stale(cached: dict[str, Any]) -> bool:
|
| 425 |
fetched_at_raw = cached.get("fetched_at")
|
| 426 |
if not isinstance(fetched_at_raw, str):
|
|
|
|
| 679 |
url = f"{FRANKLIN_BASE_URL}{endpoint}"
|
| 680 |
|
| 681 |
async def _do_request(active_client: httpx.AsyncClient) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 682 |
try:
|
| 683 |
+
response = await active_client.request(
|
| 684 |
+
method=method.upper(),
|
| 685 |
+
url=url,
|
| 686 |
+
json=payload if method.upper() in {"POST", "PUT", "PATCH"} else None,
|
| 687 |
+
params=params,
|
| 688 |
+
timeout=20.0,
|
| 689 |
+
headers={"Accept": "application/json"},
|
| 690 |
+
)
|
| 691 |
+
try:
|
| 692 |
+
data = response.json()
|
| 693 |
+
except Exception:
|
| 694 |
+
data = {"raw": response.text[:2000]}
|
| 695 |
+
return {
|
| 696 |
+
"ok": response.status_code < 400,
|
| 697 |
+
"status": response.status_code,
|
| 698 |
+
"data": data,
|
| 699 |
+
}
|
| 700 |
+
except Exception as e:
|
| 701 |
+
logger.warning("Franklin httpx request failed", extra={"url": url, "error": str(e)})
|
| 702 |
+
return {"ok": False, "status": 500, "error": str(e)}
|
| 703 |
+
|
| 704 |
+
# Step 1: Try primary client (trust_env respects os.environ)
|
| 705 |
+
result = await _do_request(client)
|
| 706 |
+
if result.get("ok") or result.get("status") in {400, 401, 403, 404}:
|
| 707 |
+
return result
|
| 708 |
+
|
| 709 |
+
# Step 2: If primary fails (e.g. proxy issues), try direct fallback
|
| 710 |
+
if HTTPX_TRUST_ENV:
|
| 711 |
+
logger.info("Retrying Franklin request without trust_env", extra={"endpoint": endpoint})
|
| 712 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as direct_client:
|
| 713 |
+
result = await _do_request(direct_client)
|
| 714 |
+
if result.get("ok") or result.get("status") in {400, 401, 403, 404}:
|
| 715 |
+
return result
|
| 716 |
+
|
| 717 |
+
# Step 3: Ultimate fallback to curl (spawning a process is expensive but robust)
|
| 718 |
async def _do_curl_request() -> dict[str, Any]:
|
| 719 |
request_url = url
|
| 720 |
if params:
|
| 721 |
request_url = f"{url}?{urlencode(params, doseq=True)}"
|
| 722 |
|
| 723 |
+
command = ["curl", "-sS", "-L", "--max-time", "20", "-H", "Accept: application/json", "-w", "\\n%{http_code}"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
if method.upper() in {"POST", "PUT", "PATCH"}:
|
| 725 |
+
command.extend(["-X", method.upper(), "-H", "Content-Type: application/json", "--data", json.dumps(payload or {})])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 726 |
command.append(request_url)
|
| 727 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 728 |
try:
|
| 729 |
+
process = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
| 730 |
+
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=25.0)
|
| 731 |
+
if process.returncode != 0:
|
| 732 |
+
return {"ok": False, "status": 500, "error": stderr.decode().strip()}
|
| 733 |
+
body, _, status_line = stdout.decode().rpartition("\n")
|
| 734 |
+
status_code = int(status_line.strip()) if status_line.strip().isdigit() else 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 735 |
try:
|
| 736 |
+
data = json.loads(body) if body.strip() else {}
|
|
|
|
| 737 |
except Exception:
|
| 738 |
+
data = {"raw": body[:2000]}
|
| 739 |
+
return {"ok": status_code < 400, "status": status_code, "data": data}
|
| 740 |
+
except Exception as e:
|
| 741 |
+
return {"ok": False, "status": 500, "error": str(e)}
|
| 742 |
+
|
| 743 |
+
return await _do_curl_request()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 744 |
|
| 745 |
|
| 746 |
async def _fetch_structural_variant_assessment(
|
|
|
|
| 1138 |
community_frequency,
|
| 1139 |
variant_matcher,
|
| 1140 |
alt_reference,
|
|
|
|
| 1141 |
org_assessments,
|
| 1142 |
uploaded_files,
|
| 1143 |
) = await asyncio.gather(
|
|
|
|
| 1158 |
payload={"snp_variant": payload},
|
| 1159 |
),
|
| 1160 |
_franklin_request(client, "POST", "/api/fetch_alt_reference_variant", payload=payload),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1161 |
_franklin_request(client, "POST", "/api/org/fetch_interpretation", payload=payload),
|
| 1162 |
_franklin_request(client, "POST", "/api/organization/variant/attachment/list", payload=payload),
|
| 1163 |
)
|
|
|
|
| 1173 |
}
|
| 1174 |
region_data = await _franklin_request(client, "GET", "/api/fetch_region_data", params=region_params)
|
| 1175 |
|
| 1176 |
+
gene_symbol = gene_symbol or _extract_gene_symbol(query, variant_details, impacts) or ""
|
| 1177 |
+
pub_variants = [
|
| 1178 |
+
{
|
| 1179 |
+
"chrom": active_context.chrom_with_prefix,
|
| 1180 |
+
"pos": active_context.position,
|
| 1181 |
+
"reference": active_context.ref,
|
| 1182 |
+
"alternative": active_context.alt,
|
| 1183 |
+
"referenceVersion": reference_version,
|
| 1184 |
+
}
|
| 1185 |
+
]
|
| 1186 |
+
pub_genes = [gene_symbol] if gene_symbol else []
|
| 1187 |
+
pub_count_payload = {
|
| 1188 |
+
"gene": gene_symbol,
|
| 1189 |
+
"variants": pub_variants,
|
| 1190 |
+
"genes": pub_genes,
|
| 1191 |
+
}
|
| 1192 |
+
(
|
| 1193 |
+
pub_variant_count,
|
| 1194 |
+
pub_amino_count,
|
| 1195 |
+
pub_domain_count,
|
| 1196 |
+
pub_gene_count,
|
| 1197 |
+
publications_feed,
|
| 1198 |
+
) = await asyncio.gather(
|
| 1199 |
+
_franklin_request(
|
| 1200 |
+
client,
|
| 1201 |
+
"POST",
|
| 1202 |
+
"/api/v2/publications/count",
|
| 1203 |
+
payload={**pub_count_payload, "scope": "VARIANT"},
|
| 1204 |
+
),
|
| 1205 |
+
_franklin_request(
|
| 1206 |
+
client,
|
| 1207 |
+
"POST",
|
| 1208 |
+
"/api/v2/publications/count",
|
| 1209 |
+
payload={**pub_count_payload, "scope": "AMINO_ACID"},
|
| 1210 |
+
),
|
| 1211 |
+
_franklin_request(
|
| 1212 |
+
client,
|
| 1213 |
+
"POST",
|
| 1214 |
+
"/api/v2/publications/count",
|
| 1215 |
+
payload={**pub_count_payload, "scope": "DOMAIN"},
|
| 1216 |
+
),
|
| 1217 |
+
_franklin_request(
|
| 1218 |
+
client,
|
| 1219 |
+
"POST",
|
| 1220 |
+
"/api/v2/publications/count",
|
| 1221 |
+
payload={**pub_count_payload, "scope": "GENE"},
|
| 1222 |
+
),
|
| 1223 |
+
_franklin_request(
|
| 1224 |
+
client,
|
| 1225 |
+
"POST",
|
| 1226 |
+
"/api/v2/publications/search_with_feed",
|
| 1227 |
+
payload={
|
| 1228 |
+
"geneSymbol": gene_symbol,
|
| 1229 |
+
"phenotypes": [],
|
| 1230 |
+
"sorting": {"sortBy": "relevance", "direction": "DESCENDING"},
|
| 1231 |
+
"fromIndex": 0,
|
| 1232 |
+
"toIndex": 15,
|
| 1233 |
+
"gene": gene_symbol,
|
| 1234 |
+
"variants": pub_variants,
|
| 1235 |
+
"scope": "GENE",
|
| 1236 |
+
"genes": pub_genes,
|
| 1237 |
+
},
|
| 1238 |
+
),
|
| 1239 |
+
)
|
| 1240 |
+
|
| 1241 |
+
gene_details = await _franklin_request(
|
| 1242 |
+
client,
|
| 1243 |
+
"GET",
|
| 1244 |
+
"/api/gene/details",
|
| 1245 |
+
params={"gene_symbol": gene_symbol, "reference_version": reference_version},
|
| 1246 |
+
)
|
| 1247 |
+
curated_variants_distribution = await _franklin_request(
|
| 1248 |
+
client,
|
| 1249 |
+
"GET",
|
| 1250 |
+
"/api/curated_variants/distribution",
|
| 1251 |
+
params={"gene": gene_symbol, "reference_version": reference_version},
|
| 1252 |
+
)
|
| 1253 |
+
gene_sensitivity = await _franklin_request(
|
| 1254 |
+
client,
|
| 1255 |
+
"GET",
|
| 1256 |
+
"/api/gene/sensitivity",
|
| 1257 |
+
params={"gene": gene_symbol, "reference_version": reference_version},
|
| 1258 |
+
)
|
| 1259 |
+
gene_expression = await _franklin_request(
|
| 1260 |
+
client,
|
| 1261 |
+
"GET",
|
| 1262 |
+
"/api/gene/expression",
|
| 1263 |
+
params={"gene_symbol": gene_symbol, "reference_version": reference_version},
|
| 1264 |
+
)
|
| 1265 |
+
gene_gwas = await _franklin_request(
|
| 1266 |
+
client,
|
| 1267 |
+
"GET",
|
| 1268 |
+
"/api/gene/gwas_data",
|
| 1269 |
+
params={"gene_symbol": gene_symbol},
|
| 1270 |
+
)
|
| 1271 |
+
gene_clinvar_diseases = await _franklin_request(
|
| 1272 |
+
client,
|
| 1273 |
+
"GET",
|
| 1274 |
+
"/api/gene/clinvar/diseases_data",
|
| 1275 |
+
params={"gene_symbol": gene_symbol},
|
| 1276 |
+
)
|
| 1277 |
+
|
| 1278 |
return {
|
| 1279 |
"variant": {
|
| 1280 |
"query": query,
|
|
|
|
| 1298 |
"clinical_evidence": evidences,
|
| 1299 |
"predictions": predictions,
|
| 1300 |
"population_frequencies": frequencies,
|
| 1301 |
+
"transcripts_and_references": impacts,
|
| 1302 |
+
"uploaded_files": uploaded_files,
|
| 1303 |
+
"variant_details": variant_details,
|
| 1304 |
+
"search_data": search_data,
|
| 1305 |
+
"warmup": warmup,
|
| 1306 |
+
},
|
| 1307 |
+
"publications": {
|
| 1308 |
+
"ok": publications_feed.get("ok"),
|
| 1309 |
+
"status": publications_feed.get("status"),
|
| 1310 |
+
"data": {
|
| 1311 |
+
"counts": {
|
| 1312 |
+
"variant_scope": pub_variant_count.get("data", {}).get("searchCount"),
|
| 1313 |
+
"amino_acid_scope": pub_amino_count.get("data", {}).get("searchCount"),
|
| 1314 |
+
"domain_scope": pub_domain_count.get("data", {}).get("searchCount"),
|
| 1315 |
+
"gene_scope": pub_gene_count.get("data", {}).get("searchCount"),
|
| 1316 |
+
},
|
| 1317 |
+
"feed": publications_feed.get("data"),
|
| 1318 |
+
},
|
| 1319 |
+
"error": publications_feed.get("error"),
|
| 1320 |
+
},
|
| 1321 |
+
"gene_assessment": {
|
| 1322 |
+
"gene_details": gene_details,
|
| 1323 |
+
"curated_variants_distribution": curated_variants_distribution,
|
| 1324 |
+
"gene_sensitivity": gene_sensitivity,
|
| 1325 |
+
"gene_expression": gene_expression,
|
| 1326 |
+
"gene_gwas": gene_gwas,
|
| 1327 |
+
"gene_clinvar_diseases": gene_clinvar_diseases,
|
| 1328 |
},
|
|
|
|
|
|
|
| 1329 |
"curated_gene_data": impacts,
|
| 1330 |
+
"associated_conditions": summary.get("data", {}).get("associated_conditions", []),
|
| 1331 |
"somatic_clinical_evidence": evidences,
|
| 1332 |
"organization_assessments": org_assessments,
|
| 1333 |
"my_organization_assessments": org_assessments,
|
app/services/variant_service.py
CHANGED
|
@@ -2,6 +2,8 @@ import httpx
|
|
| 2 |
import re
|
| 3 |
import logging
|
| 4 |
import os
|
|
|
|
|
|
|
| 5 |
from urllib.parse import quote
|
| 6 |
from typing import Optional
|
| 7 |
from app.models.variant import VariantResponse, VariantInfo, ClinVarInfo, GnomADInfo, ACMGInfo
|
|
@@ -15,9 +17,16 @@ ENSEMBL_RECODER_API = "https://rest.ensembl.org/variant_recoder/homo_sapiens"
|
|
| 15 |
ENSEMBL_VEP_HGVS_API = "https://rest.ensembl.org/vep/human/hgvs"
|
| 16 |
HTTPX_TRUST_ENV = os.getenv("HTTPX_TRUST_ENV", "false").lower() in {"1", "true", "yes", "on"}
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
ACCESSION_REGEX = re.compile(r"NC_0*([0-9]+)")
|
| 19 |
GENOMIC_HGVS_REGEX = re.compile(
|
| 20 |
-
r"^(?:chr)?([0-9]+|X|Y|MT|M):g\.(\d+)([ACGTN]+)>([ACGTN]+)$",
|
| 21 |
re.IGNORECASE,
|
| 22 |
)
|
| 23 |
SV_QUERY_REGEX = re.compile(
|
|
@@ -31,6 +40,21 @@ SV_FRANKLIN_ID_REGEX = re.compile(
|
|
| 31 |
DNA_COMPLEMENT = str.maketrans({"A": "T", "T": "A", "C": "G", "G": "C", "N": "N"})
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def _normalize_chromosome(raw: str) -> str:
|
| 35 |
value = raw.upper()
|
| 36 |
if value == "M":
|
|
@@ -74,12 +98,50 @@ def _parse_genomic_hgvs(value: str) -> Optional[dict]:
|
|
| 74 |
match = GENOMIC_HGVS_REGEX.match(value)
|
| 75 |
if not match:
|
| 76 |
return None
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
|
| 85 |
def _collect_strings(payload) -> list[str]:
|
|
@@ -107,17 +169,49 @@ def _parse_vep_to_coordinates(data: list, hgvs: str) -> Optional[dict]:
|
|
| 107 |
if not isinstance(item, dict):
|
| 108 |
continue
|
| 109 |
chrom = item.get("seq_region_name")
|
| 110 |
-
|
| 111 |
allele_string = item.get("allele_string", "")
|
| 112 |
strand = item.get("strand")
|
| 113 |
-
if not chrom or
|
| 114 |
continue
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
| 118 |
continue
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
# VEP HGVS can return alleles in transcript orientation for negative-strand transcripts.
|
| 123 |
# Convert to genomic forward strand before querying downstream services.
|
|
@@ -136,6 +230,21 @@ def _parse_vep_to_coordinates(data: list, hgvs: str) -> Optional[dict]:
|
|
| 136 |
return None
|
| 137 |
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def parse_variant_query(query: str) -> dict:
|
| 140 |
"""Parse variant query string into components"""
|
| 141 |
query = query.strip()
|
|
@@ -186,170 +295,232 @@ def parse_variant_query(query: str) -> dict:
|
|
| 186 |
|
| 187 |
async def hgvs_to_coordinates(hgvs: str, client: httpx.AsyncClient) -> Optional[dict]:
|
| 188 |
"""Convert HGVS notation to genomic coordinates using external APIs"""
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
|
| 192 |
-
# variant_recoder may timeout.
|
| 193 |
-
try:
|
| 194 |
-
vep_response = await client.get(
|
| 195 |
-
f"{ENSEMBL_VEP_HGVS_API}/{encoded_hgvs}",
|
| 196 |
-
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
| 197 |
-
timeout=15.0,
|
| 198 |
-
)
|
| 199 |
-
logger.info(
|
| 200 |
-
"Ensembl VEP response",
|
| 201 |
-
extra={"hgvs": hgvs, "status_code": vep_response.status_code},
|
| 202 |
-
)
|
| 203 |
-
if vep_response.status_code == 200:
|
| 204 |
-
coords = _parse_vep_to_coordinates(vep_response.json(), hgvs)
|
| 205 |
-
if coords:
|
| 206 |
-
logger.info("Parsed HGVS via Ensembl VEP", extra={"hgvs": hgvs, "coords": coords})
|
| 207 |
-
return coords
|
| 208 |
-
except httpx.ReadTimeout:
|
| 209 |
-
logger.warning("Ensembl VEP timeout (hgvs=%s)", hgvs)
|
| 210 |
-
except Exception as e:
|
| 211 |
-
logger.exception("Error converting HGVS via Ensembl VEP", extra={"hgvs": hgvs, "error": str(e)})
|
| 212 |
|
| 213 |
-
async def
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
|
|
|
|
|
|
| 221 |
)
|
|
|
|
|
|
|
| 222 |
return None
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
return None
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
-
async def _try_recoder_with_client(active_client: httpx.AsyncClient, mode_label: str) -> Optional[dict]:
|
| 248 |
-
# First try GET endpoint.
|
| 249 |
-
for attempt in range(1, 4):
|
| 250 |
-
try:
|
| 251 |
-
response = await active_client.get(
|
| 252 |
-
f"{ENSEMBL_RECODER_API}/{encoded_hgvs}",
|
| 253 |
-
headers={"Content-Type": "application/json"},
|
| 254 |
-
timeout=20.0,
|
| 255 |
-
)
|
| 256 |
-
parsed = await _parse_ensembl_response(response)
|
| 257 |
-
if parsed:
|
| 258 |
-
return parsed
|
| 259 |
-
break
|
| 260 |
-
except httpx.ReadTimeout:
|
| 261 |
-
logger.warning(
|
| 262 |
-
"Ensembl GET timeout (mode=%s attempt=%s hgvs=%s)",
|
| 263 |
-
mode_label,
|
| 264 |
-
attempt,
|
| 265 |
-
hgvs,
|
| 266 |
-
)
|
| 267 |
-
except Exception as e:
|
| 268 |
-
logger.exception(
|
| 269 |
-
"Error converting HGVS via Ensembl GET",
|
| 270 |
-
extra={"hgvs": hgvs, "error": str(e), "attempt": attempt, "mode": mode_label},
|
| 271 |
-
)
|
| 272 |
-
break
|
| 273 |
-
|
| 274 |
-
# Fallback to POST endpoint supported by Ensembl variant_recoder.
|
| 275 |
-
for attempt in range(1, 3):
|
| 276 |
-
try:
|
| 277 |
-
response = await active_client.post(
|
| 278 |
-
ENSEMBL_RECODER_API,
|
| 279 |
-
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
| 280 |
-
json={"ids": [hgvs]},
|
| 281 |
-
timeout=25.0,
|
| 282 |
-
)
|
| 283 |
-
parsed = await _parse_ensembl_response(response)
|
| 284 |
-
if parsed:
|
| 285 |
-
return parsed
|
| 286 |
-
break
|
| 287 |
-
except httpx.ReadTimeout:
|
| 288 |
-
logger.warning(
|
| 289 |
-
"Ensembl POST timeout (mode=%s attempt=%s hgvs=%s)",
|
| 290 |
-
mode_label,
|
| 291 |
-
attempt,
|
| 292 |
-
hgvs,
|
| 293 |
-
)
|
| 294 |
-
except Exception as e:
|
| 295 |
-
logger.exception(
|
| 296 |
-
"Error converting HGVS via Ensembl POST",
|
| 297 |
-
extra={"hgvs": hgvs, "error": str(e), "attempt": attempt, "mode": mode_label},
|
| 298 |
-
)
|
| 299 |
-
break
|
| 300 |
-
return None
|
| 301 |
|
| 302 |
-
|
| 303 |
-
if
|
| 304 |
-
return
|
| 305 |
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
parsed = await _try_recoder_with_client(direct_client, mode_label="fallback_direct_no_env_proxy")
|
| 310 |
-
if parsed:
|
| 311 |
-
return parsed
|
| 312 |
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
return None
|
| 315 |
|
| 316 |
|
| 317 |
-
async def annotate_variant(variant_id: str) -> Optional[VariantResponse]:
|
| 318 |
"""Annotate a single variant using external API"""
|
| 319 |
-
|
|
|
|
|
|
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
"pos": parsed["position"],
|
| 327 |
-
"ref": parsed["ref"],
|
| 328 |
-
"alt": parsed["alt"],
|
| 329 |
-
"genome": "hg38"
|
| 330 |
-
}
|
| 331 |
-
response = await client.get(GENEBE_API, params=params)
|
| 332 |
-
logger.info("GENEBE annotate response", extra={"query": variant_id, "status_code": response.status_code, "params": params})
|
| 333 |
-
|
| 334 |
-
if response.status_code == 200:
|
| 335 |
-
data = response.json()
|
| 336 |
-
variants = data.get("variants", [])
|
| 337 |
-
if variants:
|
| 338 |
-
return build_variant_response(variants[0], parsed)
|
| 339 |
-
logger.warning("GENEBE annotate no variants", extra={"query": variant_id, "params": params})
|
| 340 |
-
except Exception as e:
|
| 341 |
-
logger.exception("Error annotating variant", extra={"query": variant_id, "error": str(e)})
|
| 342 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
return None
|
| 344 |
|
| 345 |
|
| 346 |
async def search_variants(query: str, genome_build: str = "hg38") -> list[VariantResponse]:
|
| 347 |
"""Search for variants matching a query"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
parsed = parse_variant_query(query)
|
| 349 |
|
| 350 |
if parsed["type"] == "unknown":
|
| 351 |
from app.services.franklin_service import parse_search_query_via_franklin
|
| 352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
if franklin_parsed and franklin_parsed.get("response_type") == "SNP_VARIANT":
|
| 354 |
best = franklin_parsed.get("best_variant_option", {})
|
| 355 |
if best.get("chrom"):
|
|
@@ -369,7 +540,8 @@ async def search_variants(query: str, genome_build: str = "hg38") -> list[Varian
|
|
| 369 |
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 370 |
if parsed["type"] == "coordinates":
|
| 371 |
variant = await annotate_variant(
|
| 372 |
-
f"{parsed['chromosome']}-{parsed['position']}-{parsed['ref']}-{parsed['alt']}"
|
|
|
|
| 373 |
)
|
| 374 |
if variant:
|
| 375 |
results.append(variant)
|
|
@@ -377,32 +549,12 @@ async def search_variants(query: str, genome_build: str = "hg38") -> list[Varian
|
|
| 377 |
elif parsed["type"] == "hgvs":
|
| 378 |
coords = await hgvs_to_coordinates(parsed["value"], client)
|
| 379 |
if coords and coords.get("chromosome"):
|
| 380 |
-
|
| 381 |
-
"
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
}
|
| 387 |
-
params = {
|
| 388 |
-
"chr": coords["chromosome"],
|
| 389 |
-
"pos": coords["position"],
|
| 390 |
-
"ref": coords["ref"],
|
| 391 |
-
"alt": coords["alt"],
|
| 392 |
-
"genome": "hg38"
|
| 393 |
-
}
|
| 394 |
-
try:
|
| 395 |
-
response = await client.get(GENEBE_API, params=params)
|
| 396 |
-
logger.info("GENEBE HGVS response", extra={"query": query, "status_code": response.status_code, "params": params})
|
| 397 |
-
if response.status_code == 200:
|
| 398 |
-
data = response.json()
|
| 399 |
-
variants = data.get("variants", [])
|
| 400 |
-
if variants:
|
| 401 |
-
results.append(build_variant_response(variants[0], parsed_coords))
|
| 402 |
-
else:
|
| 403 |
-
logger.warning("GENEBE HGVS no variants", extra={"query": query, "params": params})
|
| 404 |
-
except Exception as e:
|
| 405 |
-
logger.exception("Error annotating HGVS variant", extra={"query": query, "error": str(e)})
|
| 406 |
else:
|
| 407 |
logger.warning("HGVS conversion returned no coordinates", extra={"query": query})
|
| 408 |
raise RuntimeError(f"Failed to resolve HGVS query: {query}")
|
|
@@ -435,6 +587,17 @@ async def search_variants(query: str, genome_build: str = "hg38") -> list[Varian
|
|
| 435 |
)
|
| 436 |
)
|
| 437 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
return results
|
| 439 |
|
| 440 |
|
|
|
|
| 2 |
import re
|
| 3 |
import logging
|
| 4 |
import os
|
| 5 |
+
import asyncio
|
| 6 |
+
import time
|
| 7 |
from urllib.parse import quote
|
| 8 |
from typing import Optional
|
| 9 |
from app.models.variant import VariantResponse, VariantInfo, ClinVarInfo, GnomADInfo, ACMGInfo
|
|
|
|
| 17 |
ENSEMBL_VEP_HGVS_API = "https://rest.ensembl.org/vep/human/hgvs"
|
| 18 |
HTTPX_TRUST_ENV = os.getenv("HTTPX_TRUST_ENV", "false").lower() in {"1", "true", "yes", "on"}
|
| 19 |
|
| 20 |
+
CACHE_TTL_SEARCH = 600
|
| 21 |
+
CACHE_TTL_ANNOTATE = 900
|
| 22 |
+
CACHE_TTL_HGVS = 86400
|
| 23 |
+
_SEARCH_CACHE: dict[tuple[str, str], tuple[float, list[VariantResponse]]] = {}
|
| 24 |
+
_ANNOTATE_CACHE: dict[str, tuple[float, Optional[VariantResponse]]] = {}
|
| 25 |
+
_HGVS_CACHE: dict[str, tuple[float, Optional[dict]]] = {}
|
| 26 |
+
|
| 27 |
ACCESSION_REGEX = re.compile(r"NC_0*([0-9]+)")
|
| 28 |
GENOMIC_HGVS_REGEX = re.compile(
|
| 29 |
+
r"^(?:chr)?([0-9]+|X|Y|MT|M):g\.(\d+)(?:(?:([ACGTN]+)>([ACGTN]+))|(dup|del|ins)([ACGTN]*))$",
|
| 30 |
re.IGNORECASE,
|
| 31 |
)
|
| 32 |
SV_QUERY_REGEX = re.compile(
|
|
|
|
| 40 |
DNA_COMPLEMENT = str.maketrans({"A": "T", "T": "A", "C": "G", "G": "C", "N": "N"})
|
| 41 |
|
| 42 |
|
| 43 |
+
def _cache_get(cache: dict, key):
|
| 44 |
+
entry = cache.get(key)
|
| 45 |
+
if not entry:
|
| 46 |
+
return None
|
| 47 |
+
expires_at, value = entry
|
| 48 |
+
if expires_at < time.time():
|
| 49 |
+
cache.pop(key, None)
|
| 50 |
+
return None
|
| 51 |
+
return value
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _cache_set(cache: dict, key, value, ttl: int):
|
| 55 |
+
cache[key] = (time.time() + ttl, value)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
def _normalize_chromosome(raw: str) -> str:
|
| 59 |
value = raw.upper()
|
| 60 |
if value == "M":
|
|
|
|
| 98 |
match = GENOMIC_HGVS_REGEX.match(value)
|
| 99 |
if not match:
|
| 100 |
return None
|
| 101 |
+
|
| 102 |
+
chrom = _normalize_chromosome(match.group(1))
|
| 103 |
+
pos = int(match.group(2))
|
| 104 |
+
|
| 105 |
+
# SNV case: A>G
|
| 106 |
+
if match.group(3) and match.group(4):
|
| 107 |
+
return {
|
| 108 |
+
"chromosome": chrom,
|
| 109 |
+
"position": pos,
|
| 110 |
+
"ref": match.group(3).upper(),
|
| 111 |
+
"alt": match.group(4).upper(),
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
# Handle dup, del, ins cases from variant_recoder
|
| 115 |
+
variant_type = (match.group(5) or "").lower()
|
| 116 |
+
alleles = (match.group(6) or "").upper()
|
| 117 |
+
|
| 118 |
+
if variant_type == "dup":
|
| 119 |
+
# For duplication, we often don't know the ref base easily without a lookup,
|
| 120 |
+
# but in genomic HGVS "posdup" means the base at pos is duplicated.
|
| 121 |
+
# We can return ref="N" or empty and let downstream handle it,
|
| 122 |
+
# but better to at least have the type.
|
| 123 |
+
return {
|
| 124 |
+
"chromosome": chrom,
|
| 125 |
+
"position": pos,
|
| 126 |
+
"ref": "N",
|
| 127 |
+
"alt": f"DUP",
|
| 128 |
+
}
|
| 129 |
+
elif variant_type == "del":
|
| 130 |
+
return {
|
| 131 |
+
"chromosome": chrom,
|
| 132 |
+
"position": pos,
|
| 133 |
+
"ref": alleles if alleles else "N",
|
| 134 |
+
"alt": "",
|
| 135 |
+
}
|
| 136 |
+
elif variant_type == "ins":
|
| 137 |
+
return {
|
| 138 |
+
"chromosome": chrom,
|
| 139 |
+
"position": pos,
|
| 140 |
+
"ref": "",
|
| 141 |
+
"alt": alleles if alleles else "INS",
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
return None
|
| 145 |
|
| 146 |
|
| 147 |
def _collect_strings(payload) -> list[str]:
|
|
|
|
| 169 |
if not isinstance(item, dict):
|
| 170 |
continue
|
| 171 |
chrom = item.get("seq_region_name")
|
| 172 |
+
pos_raw = item.get("start")
|
| 173 |
allele_string = item.get("allele_string", "")
|
| 174 |
strand = item.get("strand")
|
| 175 |
+
if not chrom or pos_raw is None or "/" not in allele_string:
|
| 176 |
continue
|
| 177 |
+
|
| 178 |
+
pos = int(pos_raw)
|
| 179 |
+
raw_alleles = allele_string.split("/")
|
| 180 |
+
if len(raw_alleles) < 2:
|
| 181 |
continue
|
| 182 |
+
|
| 183 |
+
ref = raw_alleles[0].upper()
|
| 184 |
+
alt = raw_alleles[1].upper()
|
| 185 |
+
|
| 186 |
+
# Handle insertion/deletion/duplication represented by '-'
|
| 187 |
+
# and convert to VCF-style (preceding base included)
|
| 188 |
+
if ref == "-" or alt == "-" or len(ref) != len(alt):
|
| 189 |
+
# Try to find the reference base in codons if available
|
| 190 |
+
# Codons format: 'cCt/cAt' or '-/C'
|
| 191 |
+
codons = item.get("codons", "")
|
| 192 |
+
if codons and "/" in codons:
|
| 193 |
+
ref_codon, alt_codon = codons.split("/")
|
| 194 |
+
if ref_codon and ref_codon != "-":
|
| 195 |
+
# Simple case: single base codon or start of codon
|
| 196 |
+
ref_base = ref_codon[0].upper()
|
| 197 |
+
if strand == -1:
|
| 198 |
+
ref_base = _complement_dna(ref_base)
|
| 199 |
+
else:
|
| 200 |
+
ref_base = "N"
|
| 201 |
+
else:
|
| 202 |
+
ref_base = "N"
|
| 203 |
+
|
| 204 |
+
if ref == "-": # Insertion
|
| 205 |
+
pos = pos - 1
|
| 206 |
+
ref = ref_base
|
| 207 |
+
alt = ref_base + alt
|
| 208 |
+
elif alt == "-": # Deletion
|
| 209 |
+
pos = pos - 1
|
| 210 |
+
alt = ref_base
|
| 211 |
+
ref = ref_base + ref
|
| 212 |
+
|
| 213 |
+
if not ref or ref == "-": ref = ref_base
|
| 214 |
+
if not alt or alt == "-": alt = ref_base
|
| 215 |
|
| 216 |
# VEP HGVS can return alleles in transcript orientation for negative-strand transcripts.
|
| 217 |
# Convert to genomic forward strand before querying downstream services.
|
|
|
|
| 230 |
return None
|
| 231 |
|
| 232 |
|
| 233 |
+
async def get_reference_base(chromosome: str, position: int, client: httpx.AsyncClient) -> str:
|
| 234 |
+
"""Fetch the reference base at a specific genomic position using Ensembl API"""
|
| 235 |
+
try:
|
| 236 |
+
chrom = _normalize_chromosome(chromosome)
|
| 237 |
+
url = f"https://rest.ensembl.org/sequence/region/human/{chrom}:{position}-{position}:1?content-type=application/json"
|
| 238 |
+
response = await client.get(url, timeout=5.0)
|
| 239 |
+
if response.status_code == 200:
|
| 240 |
+
data = response.json()
|
| 241 |
+
if isinstance(data, dict):
|
| 242 |
+
return data.get("seq", "N").upper()
|
| 243 |
+
except Exception as e:
|
| 244 |
+
logger.warning("Failed to fetch reference base", extra={"chrom": chromosome, "pos": position, "error": str(e)})
|
| 245 |
+
return "N"
|
| 246 |
+
|
| 247 |
+
|
| 248 |
def parse_variant_query(query: str) -> dict:
|
| 249 |
"""Parse variant query string into components"""
|
| 250 |
query = query.strip()
|
|
|
|
| 295 |
|
| 296 |
async def hgvs_to_coordinates(hgvs: str, client: httpx.AsyncClient) -> Optional[dict]:
|
| 297 |
"""Convert HGVS notation to genomic coordinates using external APIs"""
|
| 298 |
+
# 1. Memory Cache
|
| 299 |
+
cached = _cache_get(_HGVS_CACHE, hgvs)
|
| 300 |
+
if cached is not None:
|
| 301 |
+
return cached
|
| 302 |
+
|
| 303 |
+
# 2. Persistent SQLite Cache
|
| 304 |
+
from app.services.franklin_service import load_hgvs_mapping, save_hgvs_mapping
|
| 305 |
+
persistent_cached = load_hgvs_mapping(hgvs)
|
| 306 |
+
if persistent_cached:
|
| 307 |
+
logger.info("HGVS mapping persistent cache hit", extra={"hgvs": hgvs, "coords": persistent_cached})
|
| 308 |
+
_cache_set(_HGVS_CACHE, hgvs, persistent_cached, CACHE_TTL_HGVS)
|
| 309 |
+
return persistent_cached
|
| 310 |
|
| 311 |
+
encoded_hgvs = quote(hgvs, safe="")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
+
async def _try_vep() -> Optional[dict]:
|
| 314 |
+
try:
|
| 315 |
+
response = await client.get(
|
| 316 |
+
f"{ENSEMBL_VEP_HGVS_API}/{encoded_hgvs}",
|
| 317 |
+
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
| 318 |
+
timeout=8.0,
|
| 319 |
+
)
|
| 320 |
+
if response.status_code == 200:
|
| 321 |
+
coords = _parse_vep_to_coordinates(response.json(), hgvs)
|
| 322 |
+
if coords:
|
| 323 |
+
logger.info("Parsed HGVS via Ensembl VEP", extra={"hgvs": hgvs, "coords": coords})
|
| 324 |
+
return coords
|
| 325 |
+
except Exception:
|
| 326 |
+
pass
|
| 327 |
+
return None
|
| 328 |
|
| 329 |
+
async def _try_recoder_get(active_client: httpx.AsyncClient) -> Optional[dict]:
|
| 330 |
+
try:
|
| 331 |
+
response = await active_client.get(
|
| 332 |
+
f"{ENSEMBL_RECODER_API}/{encoded_hgvs}",
|
| 333 |
+
headers={"Content-Type": "application/json"},
|
| 334 |
+
timeout=8.0,
|
| 335 |
)
|
| 336 |
+
return await _parse_ensembl_response(response, hgvs)
|
| 337 |
+
except Exception:
|
| 338 |
return None
|
| 339 |
|
| 340 |
+
async def _try_recoder_post(active_client: httpx.AsyncClient) -> Optional[dict]:
|
| 341 |
+
try:
|
| 342 |
+
response = await active_client.post(
|
| 343 |
+
ENSEMBL_RECODER_API,
|
| 344 |
+
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
| 345 |
+
json={"ids": [hgvs]},
|
| 346 |
+
timeout=10.0,
|
| 347 |
+
)
|
| 348 |
+
return await _parse_ensembl_response(response, hgvs)
|
| 349 |
+
except Exception:
|
| 350 |
return None
|
| 351 |
|
| 352 |
+
# Step 1: Parallel VEP and Recoder GET
|
| 353 |
+
logger.info("Starting parallel HGVS lookup for %s", hgvs)
|
| 354 |
+
vep_task = asyncio.create_task(_try_vep())
|
| 355 |
+
recoder_task = asyncio.create_task(_try_recoder_get(client))
|
| 356 |
+
|
| 357 |
+
# Wait for the first success or both to finish
|
| 358 |
+
done, pending = await asyncio.wait(
|
| 359 |
+
[vep_task, recoder_task],
|
| 360 |
+
return_when=asyncio.FIRST_COMPLETED
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
for task in done:
|
| 364 |
+
res = task.result()
|
| 365 |
+
if res:
|
| 366 |
+
# Resolve 'N' if present
|
| 367 |
+
if res.get("ref") == "N" or res.get("alt") == "N":
|
| 368 |
+
base = await get_reference_base(res["chromosome"], res["position"], client)
|
| 369 |
+
if base != "N":
|
| 370 |
+
if res["ref"] == "N":
|
| 371 |
+
res["alt"] = base + res["alt"].replace("N", "")
|
| 372 |
+
res["ref"] = base
|
| 373 |
+
elif res["alt"] == "N":
|
| 374 |
+
res["ref"] = base + res["ref"].replace("N", "")
|
| 375 |
+
res["alt"] = base
|
| 376 |
+
|
| 377 |
+
for p in pending: p.cancel()
|
| 378 |
+
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
|
| 379 |
+
save_hgvs_mapping(hgvs, res)
|
| 380 |
+
return res
|
| 381 |
+
|
| 382 |
+
# Wait for the remaining one in Step 1
|
| 383 |
+
if pending:
|
| 384 |
+
done2, pending2 = await asyncio.wait(pending, timeout=2.0)
|
| 385 |
+
for task in done2:
|
| 386 |
+
res = task.result()
|
| 387 |
+
if res:
|
| 388 |
+
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
|
| 389 |
+
save_hgvs_mapping(hgvs, res)
|
| 390 |
+
return res
|
| 391 |
+
|
| 392 |
+
# Step 2: Fallback to POST if Step 1 failed
|
| 393 |
+
logger.info("HGVS Step 1 failed, trying POST fallback for %s", hgvs)
|
| 394 |
+
res = await _try_recoder_post(client)
|
| 395 |
+
if res:
|
| 396 |
+
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
|
| 397 |
+
save_hgvs_mapping(hgvs, res)
|
| 398 |
+
return res
|
| 399 |
+
|
| 400 |
+
# Step 3: Direct fallback without env proxy
|
| 401 |
+
logger.info("Trying Ensembl direct fallback without env proxy for HGVS: %s", hgvs)
|
| 402 |
+
async with httpx.AsyncClient(timeout=15.0, trust_env=False) as direct_client:
|
| 403 |
+
# Try both GET and POST in parallel for direct client
|
| 404 |
+
tasks = [
|
| 405 |
+
asyncio.create_task(_try_recoder_get(direct_client)),
|
| 406 |
+
asyncio.create_task(_try_recoder_post(direct_client))
|
| 407 |
+
]
|
| 408 |
+
done3, pending3 = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
| 409 |
+
for task in done3:
|
| 410 |
+
res = task.result()
|
| 411 |
+
if res:
|
| 412 |
+
for p in pending3: p.cancel()
|
| 413 |
+
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
|
| 414 |
+
save_hgvs_mapping(hgvs, res)
|
| 415 |
+
return res
|
| 416 |
+
|
| 417 |
+
if pending3:
|
| 418 |
+
done4, _ = await asyncio.wait(pending3, timeout=5.0)
|
| 419 |
+
for task in done4:
|
| 420 |
+
res = task.result()
|
| 421 |
+
if res:
|
| 422 |
+
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
|
| 423 |
+
save_hgvs_mapping(hgvs, res)
|
| 424 |
+
return res
|
| 425 |
+
|
| 426 |
+
logger.warning("Failed to convert HGVS to coordinates after all attempts", extra={"hgvs": hgvs})
|
| 427 |
+
_cache_set(_HGVS_CACHE, hgvs, None, 300)
|
| 428 |
+
return None
|
| 429 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
|
| 431 |
+
async def _parse_ensembl_response(response: httpx.Response, hgvs: str) -> Optional[dict]:
|
| 432 |
+
if response.status_code != 200:
|
| 433 |
+
return None
|
| 434 |
|
| 435 |
+
data = response.json()
|
| 436 |
+
if not data or not isinstance(data, list):
|
| 437 |
+
return None
|
|
|
|
|
|
|
|
|
|
| 438 |
|
| 439 |
+
for variant_data in data:
|
| 440 |
+
if not isinstance(variant_data, dict):
|
| 441 |
+
continue
|
| 442 |
+
string_values = _collect_strings(variant_data)
|
| 443 |
+
|
| 444 |
+
for value in string_values:
|
| 445 |
+
if value.startswith("NC_"):
|
| 446 |
+
parsed_spdi = _parse_spdi(value)
|
| 447 |
+
if parsed_spdi:
|
| 448 |
+
return parsed_spdi
|
| 449 |
+
|
| 450 |
+
for value in string_values:
|
| 451 |
+
parsed_hgvs = _parse_genomic_hgvs(value)
|
| 452 |
+
if parsed_hgvs:
|
| 453 |
+
return parsed_hgvs
|
| 454 |
return None
|
| 455 |
|
| 456 |
|
| 457 |
+
async def annotate_variant(variant_id: str, client: Optional[httpx.AsyncClient] = None) -> Optional[VariantResponse]:
|
| 458 |
"""Annotate a single variant using external API"""
|
| 459 |
+
cached = _cache_get(_ANNOTATE_CACHE, variant_id)
|
| 460 |
+
if cached is not None:
|
| 461 |
+
return cached
|
| 462 |
|
| 463 |
+
if client:
|
| 464 |
+
result = await _annotate_variant_with_client(variant_id, client)
|
| 465 |
+
else:
|
| 466 |
+
async with httpx.AsyncClient(timeout=12.0, trust_env=HTTPX_TRUST_ENV) as new_client:
|
| 467 |
+
result = await _annotate_variant_with_client(variant_id, new_client)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
| 469 |
+
_cache_set(_ANNOTATE_CACHE, variant_id, result, CACHE_TTL_ANNOTATE if result else 120)
|
| 470 |
+
return result
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
async def _annotate_variant_with_client(variant_id: str, client: httpx.AsyncClient) -> Optional[VariantResponse]:
|
| 474 |
+
parsed = parse_variant_query(variant_id)
|
| 475 |
+
try:
|
| 476 |
+
if parsed["type"] == "coordinates":
|
| 477 |
+
params = {
|
| 478 |
+
"chr": parsed["chromosome"],
|
| 479 |
+
"pos": parsed["position"],
|
| 480 |
+
"ref": parsed["ref"],
|
| 481 |
+
"alt": parsed["alt"],
|
| 482 |
+
"genome": "hg38"
|
| 483 |
+
}
|
| 484 |
+
response = await client.get(GENEBE_API, params=params)
|
| 485 |
+
logger.info("GENEBE annotate response", extra={"query": variant_id, "status_code": response.status_code, "params": params})
|
| 486 |
+
|
| 487 |
+
if response.status_code == 200:
|
| 488 |
+
data = response.json()
|
| 489 |
+
variants = data.get("variants", [])
|
| 490 |
+
if variants:
|
| 491 |
+
return build_variant_response(variants[0], parsed)
|
| 492 |
+
logger.warning("GENEBE annotate no variants", extra={"query": variant_id, "params": params})
|
| 493 |
+
except Exception as e:
|
| 494 |
+
logger.exception("Error annotating variant", extra={"query": variant_id, "error": str(e)})
|
| 495 |
return None
|
| 496 |
|
| 497 |
|
| 498 |
async def search_variants(query: str, genome_build: str = "hg38") -> list[VariantResponse]:
|
| 499 |
"""Search for variants matching a query"""
|
| 500 |
+
start_time = time.time()
|
| 501 |
+
cache_key = (query, genome_build)
|
| 502 |
+
cached_results = _cache_get(_SEARCH_CACHE, cache_key)
|
| 503 |
+
if cached_results is not None:
|
| 504 |
+
logger.info(
|
| 505 |
+
"Search variants cache hit",
|
| 506 |
+
extra={
|
| 507 |
+
"query": query,
|
| 508 |
+
"genome_build": genome_build,
|
| 509 |
+
"elapsed_ms": int((time.time() - start_time) * 1000),
|
| 510 |
+
},
|
| 511 |
+
)
|
| 512 |
+
return cached_results
|
| 513 |
parsed = parse_variant_query(query)
|
| 514 |
|
| 515 |
if parsed["type"] == "unknown":
|
| 516 |
from app.services.franklin_service import parse_search_query_via_franklin
|
| 517 |
+
try:
|
| 518 |
+
franklin_parsed = await asyncio.wait_for(
|
| 519 |
+
parse_search_query_via_franklin(query, genome_build),
|
| 520 |
+
timeout=4.0,
|
| 521 |
+
)
|
| 522 |
+
except asyncio.TimeoutError:
|
| 523 |
+
franklin_parsed = None
|
| 524 |
if franklin_parsed and franklin_parsed.get("response_type") == "SNP_VARIANT":
|
| 525 |
best = franklin_parsed.get("best_variant_option", {})
|
| 526 |
if best.get("chrom"):
|
|
|
|
| 540 |
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 541 |
if parsed["type"] == "coordinates":
|
| 542 |
variant = await annotate_variant(
|
| 543 |
+
f"{parsed['chromosome']}-{parsed['position']}-{parsed['ref']}-{parsed['alt']}",
|
| 544 |
+
client=client
|
| 545 |
)
|
| 546 |
if variant:
|
| 547 |
results.append(variant)
|
|
|
|
| 549 |
elif parsed["type"] == "hgvs":
|
| 550 |
coords = await hgvs_to_coordinates(parsed["value"], client)
|
| 551 |
if coords and coords.get("chromosome"):
|
| 552 |
+
variant = await annotate_variant(
|
| 553 |
+
f"{coords['chromosome']}-{coords['position']}-{coords['ref']}-{coords['alt']}",
|
| 554 |
+
client=client
|
| 555 |
+
)
|
| 556 |
+
if variant:
|
| 557 |
+
results.append(variant)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
else:
|
| 559 |
logger.warning("HGVS conversion returned no coordinates", extra={"query": query})
|
| 560 |
raise RuntimeError(f"Failed to resolve HGVS query: {query}")
|
|
|
|
| 587 |
)
|
| 588 |
)
|
| 589 |
|
| 590 |
+
_cache_set(_SEARCH_CACHE, cache_key, results, CACHE_TTL_SEARCH)
|
| 591 |
+
logger.info(
|
| 592 |
+
"Search variants completed",
|
| 593 |
+
extra={
|
| 594 |
+
"query": query,
|
| 595 |
+
"genome_build": genome_build,
|
| 596 |
+
"parsed_type": parsed.get("type"),
|
| 597 |
+
"elapsed_ms": int((time.time() - start_time) * 1000),
|
| 598 |
+
"result_count": len(results),
|
| 599 |
+
},
|
| 600 |
+
)
|
| 601 |
return results
|
| 602 |
|
| 603 |
|