File size: 23,682 Bytes
af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf ecb1d75 af567cf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | import httpx
import re
import logging
import os
import asyncio
import time
from urllib.parse import quote
from typing import Optional
from app.models.variant import VariantResponse, VariantInfo, ClinVarInfo, GnomADInfo, ACMGInfo
GENEBE_API = "https://api.genebe.net/cloud/api-public/v1/variant"
MYVARIANT_API = "http://myvariant.info/v1/variant"
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
ENSEMBL_RECODER_API = "https://rest.ensembl.org/variant_recoder/homo_sapiens"
ENSEMBL_VEP_HGVS_API = "https://rest.ensembl.org/vep/human/hgvs"
HTTPX_TRUST_ENV = os.getenv("HTTPX_TRUST_ENV", "false").lower() in {"1", "true", "yes", "on"}
CACHE_TTL_SEARCH = 600
CACHE_TTL_ANNOTATE = 900
CACHE_TTL_HGVS = 86400
_SEARCH_CACHE: dict[tuple[str, str], tuple[float, list[VariantResponse]]] = {}
_ANNOTATE_CACHE: dict[str, tuple[float, Optional[VariantResponse]]] = {}
_HGVS_CACHE: dict[str, tuple[float, Optional[dict]]] = {}
ACCESSION_REGEX = re.compile(r"NC_0*([0-9]+)")
GENOMIC_HGVS_REGEX = re.compile(
r"^(?:chr)?([0-9]+|X|Y|MT|M):g\.(\d+)(?:(?:([ACGTN]+)>([ACGTN]+))|(dup|del|ins)([ACGTN]*))$",
re.IGNORECASE,
)
SV_QUERY_REGEX = re.compile(
r"^(DEL|DUP|INS|INV|CNV|TRANS|BND):(?:chr)?([0-9]+|X|Y|MT|M):(\d+)-(\d+)$",
re.IGNORECASE,
)
SV_FRANKLIN_ID_REGEX = re.compile(
r"^(?:sv:)?(?:chr)?([0-9]+|X|Y|MT|M)-(\d+)-(\d+)-(DEL|DUP|INS|INV|CNV|TRANS|BND)(?:-(hg19|hg38|grch37|grch38))?$",
re.IGNORECASE,
)
DNA_COMPLEMENT = str.maketrans({"A": "T", "T": "A", "C": "G", "G": "C", "N": "N"})
def _cache_get(cache: dict, key):
entry = cache.get(key)
if not entry:
return None
expires_at, value = entry
if expires_at < time.time():
cache.pop(key, None)
return None
return value
def _cache_set(cache: dict, key, value, ttl: int):
cache[key] = (time.time() + ttl, value)
def _normalize_chromosome(raw: str) -> str:
value = raw.upper()
if value == "M":
return "MT"
return value
def _chromosome_from_accession(accession: str) -> Optional[str]:
match = ACCESSION_REGEX.match(accession)
if not match:
return None
chrom_num = int(match.group(1))
if chrom_num == 23:
return "X"
if chrom_num == 24:
return "Y"
if chrom_num == 12920:
return "MT"
return str(chrom_num)
def _parse_spdi(spdi: str) -> Optional[dict]:
parts = spdi.split(":")
if len(parts) != 4:
return None
chrom = _chromosome_from_accession(parts[0])
if not chrom:
return None
# SPDI uses 0-based interbase coordinates; GENEBE expects 1-based position.
return {
"chromosome": chrom,
"position": int(parts[1]) + 1,
"ref": parts[2],
"alt": parts[3],
}
def _parse_genomic_hgvs(value: str) -> Optional[dict]:
match = GENOMIC_HGVS_REGEX.match(value)
if not match:
return None
chrom = _normalize_chromosome(match.group(1))
pos = int(match.group(2))
# SNV case: A>G
if match.group(3) and match.group(4):
return {
"chromosome": chrom,
"position": pos,
"ref": match.group(3).upper(),
"alt": match.group(4).upper(),
}
# Handle dup, del, ins cases from variant_recoder
variant_type = (match.group(5) or "").lower()
alleles = (match.group(6) or "").upper()
if variant_type == "dup":
# For duplication, we often don't know the ref base easily without a lookup,
# but in genomic HGVS "posdup" means the base at pos is duplicated.
# We can return ref="N" or empty and let downstream handle it,
# but better to at least have the type.
return {
"chromosome": chrom,
"position": pos,
"ref": "N",
"alt": f"DUP",
}
elif variant_type == "del":
return {
"chromosome": chrom,
"position": pos,
"ref": alleles if alleles else "N",
"alt": "",
}
elif variant_type == "ins":
return {
"chromosome": chrom,
"position": pos,
"ref": "",
"alt": alleles if alleles else "INS",
}
return None
def _collect_strings(payload) -> list[str]:
values = []
if isinstance(payload, str):
values.append(payload)
elif isinstance(payload, list):
for item in payload:
values.extend(_collect_strings(item))
elif isinstance(payload, dict):
for item in payload.values():
values.extend(_collect_strings(item))
return values
def _complement_dna(seq: str) -> str:
return seq.upper().translate(DNA_COMPLEMENT)
def _parse_vep_to_coordinates(data: list, hgvs: str) -> Optional[dict]:
if not data or not isinstance(data, list):
return None
for item in data:
if not isinstance(item, dict):
continue
chrom = item.get("seq_region_name")
pos_raw = item.get("start")
allele_string = item.get("allele_string", "")
strand = item.get("strand")
if not chrom or pos_raw is None or "/" not in allele_string:
continue
pos = int(pos_raw)
raw_alleles = allele_string.split("/")
if len(raw_alleles) < 2:
continue
ref = raw_alleles[0].upper()
alt = raw_alleles[1].upper()
# Handle insertion/deletion/duplication represented by '-'
# and convert to VCF-style (preceding base included)
if ref == "-" or alt == "-" or len(ref) != len(alt):
# Try to find the reference base in codons if available
# Codons format: 'cCt/cAt' or '-/C'
codons = item.get("codons", "")
if codons and "/" in codons:
ref_codon, alt_codon = codons.split("/")
if ref_codon and ref_codon != "-":
# Simple case: single base codon or start of codon
ref_base = ref_codon[0].upper()
if strand == -1:
ref_base = _complement_dna(ref_base)
else:
ref_base = "N"
else:
ref_base = "N"
if ref == "-": # Insertion
pos = pos - 1
ref = ref_base
alt = ref_base + alt
elif alt == "-": # Deletion
pos = pos - 1
alt = ref_base
ref = ref_base + ref
if not ref or ref == "-": ref = ref_base
if not alt or alt == "-": alt = ref_base
# VEP HGVS can return alleles in transcript orientation for negative-strand transcripts.
# Convert to genomic forward strand before querying downstream services.
if strand == -1:
ref = _complement_dna(ref)
alt = _complement_dna(alt)
return {
"chromosome": _normalize_chromosome(str(chrom)),
"position": int(pos),
"ref": ref,
"alt": alt,
"source": "ensembl_vep",
"hgvs": hgvs,
}
return None
async def get_reference_base(chromosome: str, position: int, client: httpx.AsyncClient) -> str:
"""Fetch the reference base at a specific genomic position using Ensembl API"""
try:
chrom = _normalize_chromosome(chromosome)
url = f"https://rest.ensembl.org/sequence/region/human/{chrom}:{position}-{position}:1?content-type=application/json"
response = await client.get(url, timeout=5.0)
if response.status_code == 200:
data = response.json()
if isinstance(data, dict):
return data.get("seq", "N").upper()
except Exception as e:
logger.warning("Failed to fetch reference base", extra={"chrom": chromosome, "pos": position, "error": str(e)})
return "N"
def parse_variant_query(query: str) -> dict:
"""Parse variant query string into components"""
query = query.strip()
if not query:
return {"type": "unknown", "value": query}
sv_match = SV_QUERY_REGEX.match(query)
if sv_match:
return {
"type": "sv",
"sv_type": sv_match.group(1).upper(),
"chromosome": _normalize_chromosome(sv_match.group(2)),
"start": int(sv_match.group(3)),
"end": int(sv_match.group(4)),
}
sv_franklin_match = SV_FRANKLIN_ID_REGEX.match(query)
if sv_franklin_match:
reference_version = sv_franklin_match.group(5)
return {
"type": "sv",
"sv_type": sv_franklin_match.group(4).upper(),
"chromosome": _normalize_chromosome(sv_franklin_match.group(1)),
"start": int(sv_franklin_match.group(2)),
"end": int(sv_franklin_match.group(3)),
"reference_version": reference_version.lower() if reference_version else None,
}
if query.startswith("rs"):
return {"type": "rsid", "value": query}
if ":" in query and ("c." in query or "g." in query or "p." in query):
return {"type": "hgvs", "value": query}
if "-" in query:
parts = query.replace("chr", "").split("-")
if len(parts) >= 4:
return {
"type": "coordinates",
"chromosome": parts[0],
"position": int(parts[1]),
"ref": parts[2],
"alt": parts[3]
}
return {"type": "unknown", "value": query}
async def hgvs_to_coordinates(hgvs: str, client: httpx.AsyncClient) -> Optional[dict]:
"""Convert HGVS notation to genomic coordinates using external APIs"""
# 1. Memory Cache
cached = _cache_get(_HGVS_CACHE, hgvs)
if cached is not None:
return cached
# 2. Persistent SQLite Cache
from app.services.franklin_service import load_hgvs_mapping, save_hgvs_mapping
persistent_cached = load_hgvs_mapping(hgvs)
if persistent_cached:
logger.info("HGVS mapping persistent cache hit", extra={"hgvs": hgvs, "coords": persistent_cached})
_cache_set(_HGVS_CACHE, hgvs, persistent_cached, CACHE_TTL_HGVS)
return persistent_cached
encoded_hgvs = quote(hgvs, safe="")
async def _try_vep() -> Optional[dict]:
try:
response = await client.get(
f"{ENSEMBL_VEP_HGVS_API}/{encoded_hgvs}",
headers={"Content-Type": "application/json", "Accept": "application/json"},
timeout=8.0,
)
if response.status_code == 200:
coords = _parse_vep_to_coordinates(response.json(), hgvs)
if coords:
logger.info("Parsed HGVS via Ensembl VEP", extra={"hgvs": hgvs, "coords": coords})
return coords
except Exception:
pass
return None
async def _try_recoder_get(active_client: httpx.AsyncClient) -> Optional[dict]:
try:
response = await active_client.get(
f"{ENSEMBL_RECODER_API}/{encoded_hgvs}",
headers={"Content-Type": "application/json"},
timeout=8.0,
)
return await _parse_ensembl_response(response, hgvs)
except Exception:
return None
async def _try_recoder_post(active_client: httpx.AsyncClient) -> Optional[dict]:
try:
response = await active_client.post(
ENSEMBL_RECODER_API,
headers={"Content-Type": "application/json", "Accept": "application/json"},
json={"ids": [hgvs]},
timeout=10.0,
)
return await _parse_ensembl_response(response, hgvs)
except Exception:
return None
# Step 1: Parallel VEP and Recoder GET
logger.info("Starting parallel HGVS lookup for %s", hgvs)
vep_task = asyncio.create_task(_try_vep())
recoder_task = asyncio.create_task(_try_recoder_get(client))
# Wait for the first success or both to finish
done, pending = await asyncio.wait(
[vep_task, recoder_task],
return_when=asyncio.FIRST_COMPLETED
)
for task in done:
res = task.result()
if res:
# Resolve 'N' if present
if res.get("ref") == "N" or res.get("alt") == "N":
base = await get_reference_base(res["chromosome"], res["position"], client)
if base != "N":
if res["ref"] == "N":
res["alt"] = base + res["alt"].replace("N", "")
res["ref"] = base
elif res["alt"] == "N":
res["ref"] = base + res["ref"].replace("N", "")
res["alt"] = base
for p in pending: p.cancel()
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
save_hgvs_mapping(hgvs, res)
return res
# Wait for the remaining one in Step 1
if pending:
done2, pending2 = await asyncio.wait(pending, timeout=2.0)
for task in done2:
res = task.result()
if res:
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
save_hgvs_mapping(hgvs, res)
return res
# Step 2: Fallback to POST if Step 1 failed
logger.info("HGVS Step 1 failed, trying POST fallback for %s", hgvs)
res = await _try_recoder_post(client)
if res:
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
save_hgvs_mapping(hgvs, res)
return res
# Step 3: Direct fallback without env proxy
logger.info("Trying Ensembl direct fallback without env proxy for HGVS: %s", hgvs)
async with httpx.AsyncClient(timeout=15.0, trust_env=False) as direct_client:
# Try both GET and POST in parallel for direct client
tasks = [
asyncio.create_task(_try_recoder_get(direct_client)),
asyncio.create_task(_try_recoder_post(direct_client))
]
done3, pending3 = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done3:
res = task.result()
if res:
for p in pending3: p.cancel()
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
save_hgvs_mapping(hgvs, res)
return res
if pending3:
done4, _ = await asyncio.wait(pending3, timeout=5.0)
for task in done4:
res = task.result()
if res:
_cache_set(_HGVS_CACHE, hgvs, res, CACHE_TTL_HGVS)
save_hgvs_mapping(hgvs, res)
return res
logger.warning("Failed to convert HGVS to coordinates after all attempts", extra={"hgvs": hgvs})
_cache_set(_HGVS_CACHE, hgvs, None, 300)
return None
async def _parse_ensembl_response(response: httpx.Response, hgvs: str) -> Optional[dict]:
if response.status_code != 200:
return None
data = response.json()
if not data or not isinstance(data, list):
return None
for variant_data in data:
if not isinstance(variant_data, dict):
continue
string_values = _collect_strings(variant_data)
for value in string_values:
if value.startswith("NC_"):
parsed_spdi = _parse_spdi(value)
if parsed_spdi:
return parsed_spdi
for value in string_values:
parsed_hgvs = _parse_genomic_hgvs(value)
if parsed_hgvs:
return parsed_hgvs
return None
async def annotate_variant(variant_id: str, client: Optional[httpx.AsyncClient] = None) -> Optional[VariantResponse]:
"""Annotate a single variant using external API"""
cached = _cache_get(_ANNOTATE_CACHE, variant_id)
if cached is not None:
return cached
if client:
result = await _annotate_variant_with_client(variant_id, client)
else:
async with httpx.AsyncClient(timeout=12.0, trust_env=HTTPX_TRUST_ENV) as new_client:
result = await _annotate_variant_with_client(variant_id, new_client)
_cache_set(_ANNOTATE_CACHE, variant_id, result, CACHE_TTL_ANNOTATE if result else 120)
return result
async def _annotate_variant_with_client(variant_id: str, client: httpx.AsyncClient) -> Optional[VariantResponse]:
parsed = parse_variant_query(variant_id)
try:
if parsed["type"] == "coordinates":
params = {
"chr": parsed["chromosome"],
"pos": parsed["position"],
"ref": parsed["ref"],
"alt": parsed["alt"],
"genome": "hg38"
}
response = await client.get(GENEBE_API, params=params)
logger.info("GENEBE annotate response", extra={"query": variant_id, "status_code": response.status_code, "params": params})
if response.status_code == 200:
data = response.json()
variants = data.get("variants", [])
if variants:
return build_variant_response(variants[0], parsed)
logger.warning("GENEBE annotate no variants", extra={"query": variant_id, "params": params})
except Exception as e:
logger.exception("Error annotating variant", extra={"query": variant_id, "error": str(e)})
return None
async def search_variants(query: str, genome_build: str = "hg38") -> list[VariantResponse]:
"""Search for variants matching a query"""
start_time = time.time()
cache_key = (query, genome_build)
cached_results = _cache_get(_SEARCH_CACHE, cache_key)
if cached_results is not None:
logger.info(
"Search variants cache hit",
extra={
"query": query,
"genome_build": genome_build,
"elapsed_ms": int((time.time() - start_time) * 1000),
},
)
return cached_results
parsed = parse_variant_query(query)
if parsed["type"] == "unknown":
from app.services.franklin_service import parse_search_query_via_franklin
try:
franklin_parsed = await asyncio.wait_for(
parse_search_query_via_franklin(query, genome_build),
timeout=4.0,
)
except asyncio.TimeoutError:
franklin_parsed = None
if franklin_parsed and franklin_parsed.get("response_type") == "SNP_VARIANT":
best = franklin_parsed.get("best_variant_option", {})
if best.get("chrom"):
parsed = {
"type": "coordinates",
"chromosome": str(best["chrom"]).replace("chr", ""),
"position": int(best["pos"]),
"ref": best.get("ref", ""),
"alt": best.get("alt", "")
}
logger.info("Search variants", extra={"query": query, "parsed_type": parsed.get("type"), "genome_build": genome_build})
results = []
logger.info("Using HTTPX trust_env setting", extra={"trust_env": HTTPX_TRUST_ENV})
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
if parsed["type"] == "coordinates":
variant = await annotate_variant(
f"{parsed['chromosome']}-{parsed['position']}-{parsed['ref']}-{parsed['alt']}",
client=client
)
if variant:
results.append(variant)
elif parsed["type"] == "hgvs":
coords = await hgvs_to_coordinates(parsed["value"], client)
if coords and coords.get("chromosome"):
variant = await annotate_variant(
f"{coords['chromosome']}-{coords['position']}-{coords['ref']}-{coords['alt']}",
client=client
)
if variant:
results.append(variant)
else:
logger.warning("HGVS conversion returned no coordinates", extra={"query": query})
raise RuntimeError(f"Failed to resolve HGVS query: {query}")
elif parsed["type"] == "rsid":
pass
elif parsed["type"] == "sv":
chrom = parsed["chromosome"]
start = int(parsed["start"])
end = int(parsed["end"])
sv_type = parsed["sv_type"].upper()
sv_id = f"chr{chrom}-{start}-{end}-{sv_type}-{genome_build.lower()}"
results.append(
VariantResponse(
variant=VariantInfo(
id=sv_id,
chromosome=chrom,
position=start,
ref="N",
alt=sv_type,
),
consequences={
"variant_type": "SV",
"sv_type": sv_type,
"start": start,
"end": end,
"genome_build": genome_build,
},
)
)
_cache_set(_SEARCH_CACHE, cache_key, results, CACHE_TTL_SEARCH)
logger.info(
"Search variants completed",
extra={
"query": query,
"genome_build": genome_build,
"parsed_type": parsed.get("type"),
"elapsed_ms": int((time.time() - start_time) * 1000),
"result_count": len(results),
},
)
return results
def build_variant_response(data: dict, parsed: dict) -> VariantResponse:
"""Build VariantResponse from API data"""
consequences = data.get("consequences", [])
first_consequence = consequences[0] if isinstance(consequences, list) and consequences else {}
variant_info = VariantInfo(
id=f"{parsed.get('chromosome', '')}-{parsed.get('position', '')}-{parsed.get('ref', '')}-{parsed.get('alt', '')}",
chromosome=parsed.get("chromosome", ""),
position=parsed.get("position", 0),
ref=parsed.get("ref", ""),
alt=parsed.get("alt", ""),
gene=data.get("gene_symbol"),
transcript=first_consequence.get("mane_select") if first_consequence else None,
protein_change=first_consequence.get("protein_change") if first_consequence else None,
hgvs_c=first_consequence.get("hgvs_c") if first_consequence else None,
hgvs_p=first_consequence.get("hgvs_p") if first_consequence else None
)
clinvar = None
if data.get("clinvar_classification"):
clinvar = ClinVarInfo(
classification=data.get("clinvar_classification"),
disease=data.get("clinvar_disease"),
accession=data.get("clinvar_accession")
)
gnomad = None
if data.get("gnomad_exomes_af") or data.get("gnomad_genomes_af"):
gnomad = GnomADInfo(
exomes_af=data.get("gnomad_exomes_af"),
genomes_af=data.get("gnomad_genomes_af"),
exomes_ac=data.get("gnomad_exomes_ac"),
genomes_ac=data.get("gnomad_genomes_ac")
)
acmg = None
if data.get("acmg_classification"):
acmg_class = data.get("acmg_classification", "").replace("_", " ")
acmg = ACMGInfo(
classification=acmg_class,
criteria=data.get("acmg_criteria")
)
return VariantResponse(
variant=variant_info,
clinvar=clinvar,
gnomad=gnomad,
acmg=acmg,
consequences=first_consequence
)
|