David (Xiang) Xia commited on
Commit ·
af567cf
1
Parent(s): a368394
Deploy OpenVar backend to HF Space
Browse files- .gitignore +11 -0
- Dockerfile +21 -0
- README.md +13 -1
- app/__init__.py +0 -0
- app/api/__init__.py +0 -0
- app/api/auth.py +188 -0
- app/api/genes.py +48 -0
- app/api/organization.py +453 -0
- app/api/variant.py +84 -0
- app/config.py +16 -0
- app/database.py +30 -0
- app/main.py +43 -0
- app/models/__init__.py +0 -0
- app/models/db.py +141 -0
- app/models/variant.py +46 -0
- app/services/__init__.py +0 -0
- app/services/auth_service.py +98 -0
- app/services/franklin_service.py +1332 -0
- app/services/variant_service.py +490 -0
- assessment_test.json +0 -0
- create_superadmin.py +23 -0
- database_schema.sql +89 -0
- database_schema_neon.sql +77 -0
- pytest.ini +5 -0
- requirements-test.txt +2 -0
- requirements.txt +12 -0
- scripts/prime_franklin_sv_cache.sh +466 -0
- test_franklin_parse.py +10 -0
- tests/README.md +12 -0
- tests/test_api.py +112 -0
- tests/test_e2e.py +74 -0
- tests/test_franklin_service.py +301 -0
- tests/test_models.py +98 -0
- tests/test_variant_service.py +119 -0
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/.env
|
| 2 |
+
/.env.*
|
| 3 |
+
/.pytest_cache/
|
| 4 |
+
/__pycache__/
|
| 5 |
+
**/__pycache__/
|
| 6 |
+
/venv/
|
| 7 |
+
*.db
|
| 8 |
+
*.sqlite
|
| 9 |
+
*.sqlite3
|
| 10 |
+
*.log
|
| 11 |
+
/.DS_Store
|
Dockerfile
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system dependencies
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
libpq-dev \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Copy requirements first for better caching
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
# Copy application code
|
| 15 |
+
COPY . .
|
| 16 |
+
|
| 17 |
+
# Expose port (Hugging Face Spaces uses PORT env var)
|
| 18 |
+
EXPOSE 7860
|
| 19 |
+
|
| 20 |
+
# Run the application
|
| 21 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -4,7 +4,19 @@ emoji: 👁
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: yellow
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: yellow
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# OpenVar Backend (FastAPI)
|
| 12 |
+
|
| 13 |
+
This Space runs the OpenVar FastAPI backend.
|
| 14 |
+
|
| 15 |
+
## Environment Variables
|
| 16 |
+
|
| 17 |
+
- `DATABASE_URL` - Supabase Postgres connection string
|
| 18 |
+
- `CORS_ALLOW_ORIGINS` - Comma-separated list of allowed origins (e.g. `https://your-app.vercel.app`)
|
| 19 |
+
|
| 20 |
+
## Health Check
|
| 21 |
+
|
| 22 |
+
- `GET /health`
|
app/__init__.py
ADDED
|
File without changes
|
app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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Authentication API: login, signup, user profile."""
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
from fastapi import APIRouter, Depends, HTTPException, status
|
| 5 |
+
from pydantic import BaseModel, EmailStr
|
| 6 |
+
from sqlalchemy.orm import Session
|
| 7 |
+
|
| 8 |
+
from app.database import get_db
|
| 9 |
+
from app.models.db import User, UserType
|
| 10 |
+
from app.services.auth_service import (
|
| 11 |
+
hash_password,
|
| 12 |
+
verify_password,
|
| 13 |
+
create_access_token,
|
| 14 |
+
get_current_user,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
router = APIRouter()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ---------------------------------------------------------------------------
|
| 21 |
+
# Request / Response schemas
|
| 22 |
+
# ---------------------------------------------------------------------------
|
| 23 |
+
|
| 24 |
+
class SignupRequest(BaseModel):
|
| 25 |
+
email: str
|
| 26 |
+
password: str
|
| 27 |
+
full_name: str
|
| 28 |
+
user_type: str = "personal" # "personal" or "enterprise"
|
| 29 |
+
phone: Optional[str] = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class LoginRequest(BaseModel):
|
| 33 |
+
email: str
|
| 34 |
+
password: str
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class UserResponse(BaseModel):
|
| 38 |
+
id: str
|
| 39 |
+
email: str
|
| 40 |
+
full_name: str
|
| 41 |
+
user_type: str
|
| 42 |
+
is_active: bool
|
| 43 |
+
is_superadmin: bool
|
| 44 |
+
avatar_url: Optional[str] = None
|
| 45 |
+
phone: Optional[str] = None
|
| 46 |
+
|
| 47 |
+
class Config:
|
| 48 |
+
from_attributes = True
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class AuthResponse(BaseModel):
|
| 52 |
+
access_token: str
|
| 53 |
+
token_type: str = "bearer"
|
| 54 |
+
user: UserResponse
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class UpdateProfileRequest(BaseModel):
|
| 58 |
+
full_name: Optional[str] = None
|
| 59 |
+
phone: Optional[str] = None
|
| 60 |
+
avatar_url: Optional[str] = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ChangePasswordRequest(BaseModel):
|
| 64 |
+
old_password: str
|
| 65 |
+
new_password: str
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# Endpoints
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
@router.post("/signup", response_model=AuthResponse, status_code=status.HTTP_201_CREATED)
|
| 73 |
+
async def signup(request: SignupRequest, db: Session = Depends(get_db)):
|
| 74 |
+
"""Register a new user (personal or enterprise)."""
|
| 75 |
+
existing = db.query(User).filter(User.email == request.email).first()
|
| 76 |
+
if existing:
|
| 77 |
+
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
|
| 78 |
+
|
| 79 |
+
if len(request.password) < 6:
|
| 80 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Password must be at least 6 characters")
|
| 81 |
+
|
| 82 |
+
user_type = UserType.enterprise if request.user_type == "enterprise" else UserType.personal
|
| 83 |
+
|
| 84 |
+
user = User(
|
| 85 |
+
email=request.email,
|
| 86 |
+
hashed_password=hash_password(request.password),
|
| 87 |
+
full_name=request.full_name,
|
| 88 |
+
user_type=user_type,
|
| 89 |
+
phone=request.phone,
|
| 90 |
+
)
|
| 91 |
+
db.add(user)
|
| 92 |
+
db.commit()
|
| 93 |
+
db.refresh(user)
|
| 94 |
+
|
| 95 |
+
token = create_access_token({"sub": user.id, "email": user.email})
|
| 96 |
+
return AuthResponse(
|
| 97 |
+
access_token=token,
|
| 98 |
+
user=UserResponse(
|
| 99 |
+
id=user.id,
|
| 100 |
+
email=user.email,
|
| 101 |
+
full_name=user.full_name,
|
| 102 |
+
user_type=user.user_type.value,
|
| 103 |
+
is_active=user.is_active,
|
| 104 |
+
is_superadmin=user.is_superadmin,
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@router.post("/login", response_model=AuthResponse)
|
| 110 |
+
async def login(request: LoginRequest, db: Session = Depends(get_db)):
|
| 111 |
+
"""Authenticate user and return JWT token."""
|
| 112 |
+
user = db.query(User).filter(User.email == request.email).first()
|
| 113 |
+
if not user or not verify_password(request.password, user.hashed_password):
|
| 114 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid email or password")
|
| 115 |
+
|
| 116 |
+
if not user.is_active:
|
| 117 |
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account is deactivated")
|
| 118 |
+
|
| 119 |
+
token = create_access_token({"sub": user.id, "email": user.email})
|
| 120 |
+
return AuthResponse(
|
| 121 |
+
access_token=token,
|
| 122 |
+
user=UserResponse(
|
| 123 |
+
id=user.id,
|
| 124 |
+
email=user.email,
|
| 125 |
+
full_name=user.full_name,
|
| 126 |
+
user_type=user.user_type.value,
|
| 127 |
+
is_active=user.is_active,
|
| 128 |
+
is_superadmin=user.is_superadmin,
|
| 129 |
+
),
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@router.get("/me", response_model=UserResponse)
|
| 134 |
+
async def get_me(current_user: User = Depends(get_current_user)):
|
| 135 |
+
"""Get current user profile."""
|
| 136 |
+
return UserResponse(
|
| 137 |
+
id=current_user.id,
|
| 138 |
+
email=current_user.email,
|
| 139 |
+
full_name=current_user.full_name,
|
| 140 |
+
user_type=current_user.user_type.value,
|
| 141 |
+
is_active=current_user.is_active,
|
| 142 |
+
is_superadmin=current_user.is_superadmin,
|
| 143 |
+
avatar_url=current_user.avatar_url,
|
| 144 |
+
phone=current_user.phone,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@router.put("/me", response_model=UserResponse)
|
| 149 |
+
async def update_profile(
|
| 150 |
+
request: UpdateProfileRequest,
|
| 151 |
+
current_user: User = Depends(get_current_user),
|
| 152 |
+
db: Session = Depends(get_db),
|
| 153 |
+
):
|
| 154 |
+
"""Update current user profile."""
|
| 155 |
+
if request.full_name is not None:
|
| 156 |
+
current_user.full_name = request.full_name
|
| 157 |
+
if request.phone is not None:
|
| 158 |
+
current_user.phone = request.phone
|
| 159 |
+
if request.avatar_url is not None:
|
| 160 |
+
current_user.avatar_url = request.avatar_url
|
| 161 |
+
db.commit()
|
| 162 |
+
db.refresh(current_user)
|
| 163 |
+
return UserResponse(
|
| 164 |
+
id=current_user.id,
|
| 165 |
+
email=current_user.email,
|
| 166 |
+
full_name=current_user.full_name,
|
| 167 |
+
user_type=current_user.user_type.value,
|
| 168 |
+
is_active=current_user.is_active,
|
| 169 |
+
is_superadmin=current_user.is_superadmin,
|
| 170 |
+
avatar_url=current_user.avatar_url,
|
| 171 |
+
phone=current_user.phone,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@router.post("/change-password")
|
| 176 |
+
async def change_password(
|
| 177 |
+
request: ChangePasswordRequest,
|
| 178 |
+
current_user: User = Depends(get_current_user),
|
| 179 |
+
db: Session = Depends(get_db),
|
| 180 |
+
):
|
| 181 |
+
"""Change password for the current user."""
|
| 182 |
+
if not verify_password(request.old_password, current_user.hashed_password):
|
| 183 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Current password is incorrect")
|
| 184 |
+
if len(request.new_password) < 6:
|
| 185 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="New password must be at least 6 characters")
|
| 186 |
+
current_user.hashed_password = hash_password(request.new_password)
|
| 187 |
+
db.commit()
|
| 188 |
+
return {"message": "Password changed successfully"}
|
app/api/genes.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
|
| 5 |
+
router = APIRouter()
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class GeneInfo(BaseModel):
|
| 9 |
+
symbol: str
|
| 10 |
+
name: Optional[str] = None
|
| 11 |
+
chromosome: Optional[str] = None
|
| 12 |
+
variant_count: int = 0
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@router.get("", response_model=list[GeneInfo])
|
| 16 |
+
async def list_genes(
|
| 17 |
+
query: Optional[str] = None,
|
| 18 |
+
limit: int = Query(default=50, ge=1, le=200),
|
| 19 |
+
):
|
| 20 |
+
"""List genes, optionally filtered by query"""
|
| 21 |
+
genes = [
|
| 22 |
+
{"symbol": "BRCA1", "name": "BRCA1 DNA repair associated", "chromosome": "17", "variant_count": 1250},
|
| 23 |
+
{"symbol": "BRCA2", "name": "BRCA2 DNA repair associated", "chromosome": "13", "variant_count": 980},
|
| 24 |
+
{"symbol": "TP53", "name": "Tumor protein p53", "chromosome": "17", "variant_count": 2100},
|
| 25 |
+
{"symbol": "EGFR", "name": "Epidermal growth factor receptor", "chromosome": "7", "variant_count": 1850},
|
| 26 |
+
{"symbol": "KRAS", "name": "KRAS proto-oncogene GTPase", "chromosome": "12", "variant_count": 720},
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
if query:
|
| 30 |
+
genes = [g for g in genes if query.upper() in g["symbol"].upper()]
|
| 31 |
+
|
| 32 |
+
return genes[:limit]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@router.get("/{gene_symbol}", response_model=GeneInfo)
|
| 36 |
+
async def get_gene(gene_symbol: str):
|
| 37 |
+
"""Get information about a specific gene"""
|
| 38 |
+
genes_db = {
|
| 39 |
+
"BRCA1": {"symbol": "BRCA1", "name": "BRCA1 DNA repair associated", "chromosome": "17", "variant_count": 1250},
|
| 40 |
+
"BRCA2": {"symbol": "BRCA2", "name": "BRCA2 DNA repair associated", "chromosome": "13", "variant_count": 980},
|
| 41 |
+
"TP53": {"symbol": "TP53", "name": "Tumor protein p53", "chromosome": "17", "variant_count": 2100},
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
gene = genes_db.get(gene_symbol.upper())
|
| 45 |
+
if not gene:
|
| 46 |
+
raise HTTPException(status_code=404, detail="Gene not found")
|
| 47 |
+
|
| 48 |
+
return gene
|
app/api/organization.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Organization, Department, and Membership management API."""
|
| 2 |
+
|
| 3 |
+
from datetime import datetime, timezone
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
from fastapi import APIRouter, Depends, HTTPException, status
|
| 6 |
+
from pydantic import BaseModel
|
| 7 |
+
from sqlalchemy.orm import Session
|
| 8 |
+
|
| 9 |
+
from app.database import get_db
|
| 10 |
+
from app.models.db import (
|
| 11 |
+
User, Organization, Department, Membership,
|
| 12 |
+
UserType, OrgStatus, MemberRole,
|
| 13 |
+
)
|
| 14 |
+
from app.services.auth_service import get_current_user, require_superadmin
|
| 15 |
+
|
| 16 |
+
router = APIRouter()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
# Schemas
|
| 21 |
+
# ---------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
class CreateOrgRequest(BaseModel):
|
| 24 |
+
name: str
|
| 25 |
+
display_name: Optional[str] = None
|
| 26 |
+
description: Optional[str] = None
|
| 27 |
+
website: Optional[str] = None
|
| 28 |
+
industry: Optional[str] = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class OrgResponse(BaseModel):
|
| 32 |
+
id: str
|
| 33 |
+
name: str
|
| 34 |
+
display_name: Optional[str]
|
| 35 |
+
description: Optional[str]
|
| 36 |
+
status: str
|
| 37 |
+
creator_id: str
|
| 38 |
+
website: Optional[str]
|
| 39 |
+
industry: Optional[str]
|
| 40 |
+
max_members: int
|
| 41 |
+
rejection_reason: Optional[str]
|
| 42 |
+
created_at: str
|
| 43 |
+
approved_at: Optional[str]
|
| 44 |
+
|
| 45 |
+
class Config:
|
| 46 |
+
from_attributes = True
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class CreateDeptRequest(BaseModel):
|
| 50 |
+
name: str
|
| 51 |
+
description: Optional[str] = None
|
| 52 |
+
parent_id: Optional[str] = None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class DeptResponse(BaseModel):
|
| 56 |
+
id: str
|
| 57 |
+
organization_id: str
|
| 58 |
+
name: str
|
| 59 |
+
description: Optional[str]
|
| 60 |
+
parent_id: Optional[str]
|
| 61 |
+
member_count: int = 0
|
| 62 |
+
|
| 63 |
+
class Config:
|
| 64 |
+
from_attributes = True
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class AddMemberRequest(BaseModel):
|
| 68 |
+
email: str
|
| 69 |
+
department_id: Optional[str] = None
|
| 70 |
+
role: str = "member"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class MemberResponse(BaseModel):
|
| 74 |
+
id: str
|
| 75 |
+
user_id: str
|
| 76 |
+
user_email: str
|
| 77 |
+
user_name: str
|
| 78 |
+
organization_id: str
|
| 79 |
+
department_id: Optional[str]
|
| 80 |
+
department_name: Optional[str]
|
| 81 |
+
role: str
|
| 82 |
+
is_active: bool
|
| 83 |
+
joined_at: str
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ApproveOrgRequest(BaseModel):
|
| 87 |
+
approved: bool
|
| 88 |
+
rejection_reason: Optional[str] = None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
# Helpers
|
| 93 |
+
# ---------------------------------------------------------------------------
|
| 94 |
+
|
| 95 |
+
def _org_response(org: Organization) -> OrgResponse:
|
| 96 |
+
return OrgResponse(
|
| 97 |
+
id=org.id,
|
| 98 |
+
name=org.name,
|
| 99 |
+
display_name=org.display_name,
|
| 100 |
+
description=org.description,
|
| 101 |
+
status=org.status.value,
|
| 102 |
+
creator_id=org.creator_id,
|
| 103 |
+
website=org.website,
|
| 104 |
+
industry=org.industry,
|
| 105 |
+
max_members=org.max_members,
|
| 106 |
+
rejection_reason=org.rejection_reason,
|
| 107 |
+
created_at=org.created_at.isoformat() if org.created_at else "",
|
| 108 |
+
approved_at=org.approved_at.isoformat() if org.approved_at else None,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _require_org_admin(user: User, org: Organization, db: Session):
|
| 113 |
+
"""Ensure user is org creator or org_admin member."""
|
| 114 |
+
if user.is_superadmin:
|
| 115 |
+
return
|
| 116 |
+
if org.creator_id == user.id:
|
| 117 |
+
return
|
| 118 |
+
membership = db.query(Membership).filter(
|
| 119 |
+
Membership.user_id == user.id,
|
| 120 |
+
Membership.organization_id == org.id,
|
| 121 |
+
Membership.role == MemberRole.org_admin,
|
| 122 |
+
Membership.is_active == True,
|
| 123 |
+
).first()
|
| 124 |
+
if not membership:
|
| 125 |
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Organization admin access required")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ---------------------------------------------------------------------------
|
| 129 |
+
# Organization CRUD
|
| 130 |
+
# ---------------------------------------------------------------------------
|
| 131 |
+
|
| 132 |
+
@router.post("/", response_model=OrgResponse, status_code=status.HTTP_201_CREATED)
|
| 133 |
+
async def create_organization(
|
| 134 |
+
request: CreateOrgRequest,
|
| 135 |
+
current_user: User = Depends(get_current_user),
|
| 136 |
+
db: Session = Depends(get_db),
|
| 137 |
+
):
|
| 138 |
+
"""Enterprise user applies to create an organization. Status starts as 'pending'."""
|
| 139 |
+
if current_user.user_type != UserType.enterprise:
|
| 140 |
+
raise HTTPException(
|
| 141 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 142 |
+
detail="Only enterprise users can create organizations",
|
| 143 |
+
)
|
| 144 |
+
existing = db.query(Organization).filter(Organization.name == request.name).first()
|
| 145 |
+
if existing:
|
| 146 |
+
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Organization name already taken")
|
| 147 |
+
|
| 148 |
+
org = Organization(
|
| 149 |
+
name=request.name,
|
| 150 |
+
display_name=request.display_name or request.name,
|
| 151 |
+
description=request.description,
|
| 152 |
+
website=request.website,
|
| 153 |
+
industry=request.industry,
|
| 154 |
+
creator_id=current_user.id,
|
| 155 |
+
status=OrgStatus.pending,
|
| 156 |
+
)
|
| 157 |
+
db.add(org)
|
| 158 |
+
db.commit()
|
| 159 |
+
db.refresh(org)
|
| 160 |
+
return _org_response(org)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@router.get("/", response_model=List[OrgResponse])
|
| 164 |
+
async def list_my_organizations(
|
| 165 |
+
current_user: User = Depends(get_current_user),
|
| 166 |
+
db: Session = Depends(get_db),
|
| 167 |
+
):
|
| 168 |
+
"""List organizations the current user belongs to or created."""
|
| 169 |
+
created = db.query(Organization).filter(Organization.creator_id == current_user.id).all()
|
| 170 |
+
member_orgs = (
|
| 171 |
+
db.query(Organization)
|
| 172 |
+
.join(Membership, Membership.organization_id == Organization.id)
|
| 173 |
+
.filter(Membership.user_id == current_user.id, Membership.is_active == True)
|
| 174 |
+
.all()
|
| 175 |
+
)
|
| 176 |
+
all_orgs = {org.id: org for org in created + member_orgs}
|
| 177 |
+
return [_org_response(org) for org in all_orgs.values()]
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@router.get("/{org_id}", response_model=OrgResponse)
|
| 181 |
+
async def get_organization(
|
| 182 |
+
org_id: str,
|
| 183 |
+
current_user: User = Depends(get_current_user),
|
| 184 |
+
db: Session = Depends(get_db),
|
| 185 |
+
):
|
| 186 |
+
"""Get organization details."""
|
| 187 |
+
org = db.query(Organization).filter(Organization.id == org_id).first()
|
| 188 |
+
if not org:
|
| 189 |
+
raise HTTPException(status_code=404, detail="Organization not found")
|
| 190 |
+
return _org_response(org)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ---------------------------------------------------------------------------
|
| 194 |
+
# Department management
|
| 195 |
+
# ---------------------------------------------------------------------------
|
| 196 |
+
|
| 197 |
+
@router.post("/{org_id}/departments", response_model=DeptResponse, status_code=status.HTTP_201_CREATED)
|
| 198 |
+
async def create_department(
|
| 199 |
+
org_id: str,
|
| 200 |
+
request: CreateDeptRequest,
|
| 201 |
+
current_user: User = Depends(get_current_user),
|
| 202 |
+
db: Session = Depends(get_db),
|
| 203 |
+
):
|
| 204 |
+
"""Add a department to an organization."""
|
| 205 |
+
org = db.query(Organization).filter(Organization.id == org_id).first()
|
| 206 |
+
if not org:
|
| 207 |
+
raise HTTPException(status_code=404, detail="Organization not found")
|
| 208 |
+
_require_org_admin(current_user, org, db)
|
| 209 |
+
|
| 210 |
+
existing = db.query(Department).filter(
|
| 211 |
+
Department.organization_id == org_id, Department.name == request.name
|
| 212 |
+
).first()
|
| 213 |
+
if existing:
|
| 214 |
+
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Department name already exists")
|
| 215 |
+
|
| 216 |
+
dept = Department(
|
| 217 |
+
organization_id=org_id,
|
| 218 |
+
name=request.name,
|
| 219 |
+
description=request.description,
|
| 220 |
+
parent_id=request.parent_id,
|
| 221 |
+
)
|
| 222 |
+
db.add(dept)
|
| 223 |
+
db.commit()
|
| 224 |
+
db.refresh(dept)
|
| 225 |
+
return DeptResponse(
|
| 226 |
+
id=dept.id,
|
| 227 |
+
organization_id=dept.organization_id,
|
| 228 |
+
name=dept.name,
|
| 229 |
+
description=dept.description,
|
| 230 |
+
parent_id=dept.parent_id,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@router.get("/{org_id}/departments", response_model=List[DeptResponse])
|
| 235 |
+
async def list_departments(
|
| 236 |
+
org_id: str,
|
| 237 |
+
current_user: User = Depends(get_current_user),
|
| 238 |
+
db: Session = Depends(get_db),
|
| 239 |
+
):
|
| 240 |
+
"""List all departments in an organization."""
|
| 241 |
+
departments = db.query(Department).filter(Department.organization_id == org_id).all()
|
| 242 |
+
result = []
|
| 243 |
+
for dept in departments:
|
| 244 |
+
count = db.query(Membership).filter(
|
| 245 |
+
Membership.department_id == dept.id, Membership.is_active == True
|
| 246 |
+
).count()
|
| 247 |
+
result.append(DeptResponse(
|
| 248 |
+
id=dept.id,
|
| 249 |
+
organization_id=dept.organization_id,
|
| 250 |
+
name=dept.name,
|
| 251 |
+
description=dept.description,
|
| 252 |
+
parent_id=dept.parent_id,
|
| 253 |
+
member_count=count,
|
| 254 |
+
))
|
| 255 |
+
return result
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@router.delete("/{org_id}/departments/{dept_id}")
|
| 259 |
+
async def delete_department(
|
| 260 |
+
org_id: str,
|
| 261 |
+
dept_id: str,
|
| 262 |
+
current_user: User = Depends(get_current_user),
|
| 263 |
+
db: Session = Depends(get_db),
|
| 264 |
+
):
|
| 265 |
+
"""Delete a department."""
|
| 266 |
+
org = db.query(Organization).filter(Organization.id == org_id).first()
|
| 267 |
+
if not org:
|
| 268 |
+
raise HTTPException(status_code=404, detail="Organization not found")
|
| 269 |
+
_require_org_admin(current_user, org, db)
|
| 270 |
+
|
| 271 |
+
dept = db.query(Department).filter(Department.id == dept_id, Department.organization_id == org_id).first()
|
| 272 |
+
if not dept:
|
| 273 |
+
raise HTTPException(status_code=404, detail="Department not found")
|
| 274 |
+
db.delete(dept)
|
| 275 |
+
db.commit()
|
| 276 |
+
return {"message": "Department deleted"}
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# ---------------------------------------------------------------------------
|
| 280 |
+
# Member management
|
| 281 |
+
# ---------------------------------------------------------------------------
|
| 282 |
+
|
| 283 |
+
@router.post("/{org_id}/members", response_model=MemberResponse, status_code=status.HTTP_201_CREATED)
|
| 284 |
+
async def add_member(
|
| 285 |
+
org_id: str,
|
| 286 |
+
request: AddMemberRequest,
|
| 287 |
+
current_user: User = Depends(get_current_user),
|
| 288 |
+
db: Session = Depends(get_db),
|
| 289 |
+
):
|
| 290 |
+
"""Add a user to an organization by email. Creates an account if the user doesn't exist."""
|
| 291 |
+
org = db.query(Organization).filter(Organization.id == org_id).first()
|
| 292 |
+
if not org:
|
| 293 |
+
raise HTTPException(status_code=404, detail="Organization not found")
|
| 294 |
+
if org.status != OrgStatus.approved:
|
| 295 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Organization is not approved yet")
|
| 296 |
+
_require_org_admin(current_user, org, db)
|
| 297 |
+
|
| 298 |
+
user = db.query(User).filter(User.email == request.email).first()
|
| 299 |
+
if not user:
|
| 300 |
+
raise HTTPException(status_code=404, detail=f"User with email {request.email} not found. They must register first.")
|
| 301 |
+
|
| 302 |
+
existing = db.query(Membership).filter(
|
| 303 |
+
Membership.user_id == user.id,
|
| 304 |
+
Membership.organization_id == org_id,
|
| 305 |
+
Membership.department_id == request.department_id,
|
| 306 |
+
).first()
|
| 307 |
+
if existing:
|
| 308 |
+
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="User is already a member")
|
| 309 |
+
|
| 310 |
+
role = MemberRole(request.role) if request.role in [r.value for r in MemberRole] else MemberRole.member
|
| 311 |
+
|
| 312 |
+
membership = Membership(
|
| 313 |
+
user_id=user.id,
|
| 314 |
+
organization_id=org_id,
|
| 315 |
+
department_id=request.department_id,
|
| 316 |
+
role=role,
|
| 317 |
+
)
|
| 318 |
+
db.add(membership)
|
| 319 |
+
db.commit()
|
| 320 |
+
db.refresh(membership)
|
| 321 |
+
|
| 322 |
+
dept_name = None
|
| 323 |
+
if membership.department_id:
|
| 324 |
+
dept = db.query(Department).filter(Department.id == membership.department_id).first()
|
| 325 |
+
dept_name = dept.name if dept else None
|
| 326 |
+
|
| 327 |
+
return MemberResponse(
|
| 328 |
+
id=membership.id,
|
| 329 |
+
user_id=user.id,
|
| 330 |
+
user_email=user.email,
|
| 331 |
+
user_name=user.full_name,
|
| 332 |
+
organization_id=org_id,
|
| 333 |
+
department_id=membership.department_id,
|
| 334 |
+
department_name=dept_name,
|
| 335 |
+
role=membership.role.value,
|
| 336 |
+
is_active=membership.is_active,
|
| 337 |
+
joined_at=membership.joined_at.isoformat() if membership.joined_at else "",
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
@router.get("/{org_id}/members", response_model=List[MemberResponse])
|
| 342 |
+
async def list_members(
|
| 343 |
+
org_id: str,
|
| 344 |
+
current_user: User = Depends(get_current_user),
|
| 345 |
+
db: Session = Depends(get_db),
|
| 346 |
+
):
|
| 347 |
+
"""List all members in an organization."""
|
| 348 |
+
memberships = db.query(Membership).filter(
|
| 349 |
+
Membership.organization_id == org_id,
|
| 350 |
+
Membership.is_active == True,
|
| 351 |
+
).all()
|
| 352 |
+
result = []
|
| 353 |
+
for m in memberships:
|
| 354 |
+
user = db.query(User).filter(User.id == m.user_id).first()
|
| 355 |
+
dept_name = None
|
| 356 |
+
if m.department_id:
|
| 357 |
+
dept = db.query(Department).filter(Department.id == m.department_id).first()
|
| 358 |
+
dept_name = dept.name if dept else None
|
| 359 |
+
result.append(MemberResponse(
|
| 360 |
+
id=m.id,
|
| 361 |
+
user_id=m.user_id,
|
| 362 |
+
user_email=user.email if user else "",
|
| 363 |
+
user_name=user.full_name if user else "",
|
| 364 |
+
organization_id=org_id,
|
| 365 |
+
department_id=m.department_id,
|
| 366 |
+
department_name=dept_name,
|
| 367 |
+
role=m.role.value,
|
| 368 |
+
is_active=m.is_active,
|
| 369 |
+
joined_at=m.joined_at.isoformat() if m.joined_at else "",
|
| 370 |
+
))
|
| 371 |
+
return result
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@router.delete("/{org_id}/members/{member_id}")
|
| 375 |
+
async def remove_member(
|
| 376 |
+
org_id: str,
|
| 377 |
+
member_id: str,
|
| 378 |
+
current_user: User = Depends(get_current_user),
|
| 379 |
+
db: Session = Depends(get_db),
|
| 380 |
+
):
|
| 381 |
+
"""Remove a member from an organization."""
|
| 382 |
+
org = db.query(Organization).filter(Organization.id == org_id).first()
|
| 383 |
+
if not org:
|
| 384 |
+
raise HTTPException(status_code=404, detail="Organization not found")
|
| 385 |
+
_require_org_admin(current_user, org, db)
|
| 386 |
+
|
| 387 |
+
membership = db.query(Membership).filter(Membership.id == member_id, Membership.organization_id == org_id).first()
|
| 388 |
+
if not membership:
|
| 389 |
+
raise HTTPException(status_code=404, detail="Membership not found")
|
| 390 |
+
membership.is_active = False
|
| 391 |
+
db.commit()
|
| 392 |
+
return {"message": "Member removed"}
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ---------------------------------------------------------------------------
|
| 396 |
+
# Admin endpoints (superadmin)
|
| 397 |
+
# ---------------------------------------------------------------------------
|
| 398 |
+
|
| 399 |
+
@router.get("/admin/pending", response_model=List[OrgResponse])
|
| 400 |
+
async def list_pending_organizations(
|
| 401 |
+
_admin: User = Depends(require_superadmin),
|
| 402 |
+
db: Session = Depends(get_db),
|
| 403 |
+
):
|
| 404 |
+
"""List all organizations pending approval (superadmin only)."""
|
| 405 |
+
pending = db.query(Organization).filter(Organization.status == OrgStatus.pending).all()
|
| 406 |
+
return [_org_response(org) for org in pending]
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@router.get("/admin/all", response_model=List[OrgResponse])
|
| 410 |
+
async def list_all_organizations(
|
| 411 |
+
_admin: User = Depends(require_superadmin),
|
| 412 |
+
db: Session = Depends(get_db),
|
| 413 |
+
):
|
| 414 |
+
"""List all organizations (superadmin only)."""
|
| 415 |
+
orgs = db.query(Organization).order_by(Organization.created_at.desc()).all()
|
| 416 |
+
return [_org_response(org) for org in orgs]
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@router.post("/admin/{org_id}/review", response_model=OrgResponse)
|
| 420 |
+
async def review_organization(
|
| 421 |
+
org_id: str,
|
| 422 |
+
request: ApproveOrgRequest,
|
| 423 |
+
_admin: User = Depends(require_superadmin),
|
| 424 |
+
db: Session = Depends(get_db),
|
| 425 |
+
):
|
| 426 |
+
"""Approve or reject a pending organization (superadmin only)."""
|
| 427 |
+
org = db.query(Organization).filter(Organization.id == org_id).first()
|
| 428 |
+
if not org:
|
| 429 |
+
raise HTTPException(status_code=404, detail="Organization not found")
|
| 430 |
+
|
| 431 |
+
if request.approved:
|
| 432 |
+
org.status = OrgStatus.approved
|
| 433 |
+
org.approved_at = datetime.now(timezone.utc)
|
| 434 |
+
org.rejection_reason = None
|
| 435 |
+
# Automatically add creator as org_admin
|
| 436 |
+
existing = db.query(Membership).filter(
|
| 437 |
+
Membership.user_id == org.creator_id,
|
| 438 |
+
Membership.organization_id == org.id,
|
| 439 |
+
).first()
|
| 440 |
+
if not existing:
|
| 441 |
+
membership = Membership(
|
| 442 |
+
user_id=org.creator_id,
|
| 443 |
+
organization_id=org.id,
|
| 444 |
+
role=MemberRole.org_admin,
|
| 445 |
+
)
|
| 446 |
+
db.add(membership)
|
| 447 |
+
else:
|
| 448 |
+
org.status = OrgStatus.rejected
|
| 449 |
+
org.rejection_reason = request.rejection_reason or "Application not approved"
|
| 450 |
+
|
| 451 |
+
db.commit()
|
| 452 |
+
db.refresh(org)
|
| 453 |
+
return _org_response(org)
|
app/api/variant.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
|
| 3 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from app.models.variant import VariantSearchRequest, VariantResponse
|
| 6 |
+
from app.services.variant_service import annotate_variant, search_variants
|
| 7 |
+
from app.services.franklin_service import (
|
| 8 |
+
get_franklin_variant_assessment,
|
| 9 |
+
proxy_franklin_api,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
router = APIRouter()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FranklinProxyRequest(BaseModel):
|
| 16 |
+
endpoint: str
|
| 17 |
+
method: str = "GET"
|
| 18 |
+
payload: Optional[Any] = None
|
| 19 |
+
params: Optional[dict[str, Any]] = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@router.api_route("/search", methods=["POST", "GET"], response_model=list[VariantResponse])
|
| 23 |
+
async def search_variants_endpoint(
|
| 24 |
+
request: Optional[VariantSearchRequest] = None,
|
| 25 |
+
query: Optional[str] = Query(default=None),
|
| 26 |
+
genome_build: Optional[str] = Query(default=None),
|
| 27 |
+
):
|
| 28 |
+
"""Search for variants by query string (POST body or GET query params)."""
|
| 29 |
+
try:
|
| 30 |
+
if request is not None:
|
| 31 |
+
q = request.query
|
| 32 |
+
build = request.genome_build or "hg38"
|
| 33 |
+
else:
|
| 34 |
+
q = query
|
| 35 |
+
build = genome_build or "hg38"
|
| 36 |
+
if not q:
|
| 37 |
+
raise HTTPException(status_code=400, detail="Missing query parameter")
|
| 38 |
+
results = await search_variants(q, build)
|
| 39 |
+
return results
|
| 40 |
+
except HTTPException:
|
| 41 |
+
raise
|
| 42 |
+
except Exception as e:
|
| 43 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@router.get("/franklin/{variant_query:path}")
|
| 47 |
+
async def get_franklin_assessment(variant_query: str, reference_version: str = "hg19"):
|
| 48 |
+
"""Fetch Franklin-like tab data for a given variant query."""
|
| 49 |
+
try:
|
| 50 |
+
return await get_franklin_variant_assessment(variant_query, reference_version=reference_version)
|
| 51 |
+
except ValueError as e:
|
| 52 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 53 |
+
except Exception as e:
|
| 54 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@router.post("/franklin/proxy")
|
| 58 |
+
async def franklin_proxy_endpoint(request: FranklinProxyRequest):
|
| 59 |
+
"""Generic Franklin API proxy for /api/* endpoints."""
|
| 60 |
+
try:
|
| 61 |
+
return await proxy_franklin_api(
|
| 62 |
+
endpoint=request.endpoint,
|
| 63 |
+
method=request.method,
|
| 64 |
+
payload=request.payload,
|
| 65 |
+
params=request.params,
|
| 66 |
+
)
|
| 67 |
+
except ValueError as e:
|
| 68 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 69 |
+
except Exception as e:
|
| 70 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@router.get("/{variant_id}", response_model=VariantResponse)
|
| 74 |
+
async def get_variant(variant_id: str):
|
| 75 |
+
"""Get detailed information about a specific variant"""
|
| 76 |
+
try:
|
| 77 |
+
result = await annotate_variant(variant_id)
|
| 78 |
+
if not result:
|
| 79 |
+
raise HTTPException(status_code=404, detail="Variant not found")
|
| 80 |
+
return result
|
| 81 |
+
except HTTPException:
|
| 82 |
+
raise
|
| 83 |
+
except Exception as e:
|
| 84 |
+
raise HTTPException(status_code=500, detail=str(e))
|
app/config.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Settings(BaseSettings):
|
| 6 |
+
DATABASE_URL: str = ""
|
| 7 |
+
SUPABASE_URL: str = ""
|
| 8 |
+
SUPABASE_KEY: str = ""
|
| 9 |
+
JWT_SECRET: str = "dev-secret-key-change-in-production"
|
| 10 |
+
GENEBE_API_KEY: str = ""
|
| 11 |
+
|
| 12 |
+
class Config:
|
| 13 |
+
env_file = ".env"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
settings = Settings()
|
app/database.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Database configuration for PostgreSQL via SQLAlchemy."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
from sqlalchemy import create_engine
|
| 9 |
+
from sqlalchemy.orm import sessionmaker, declarative_base
|
| 10 |
+
|
| 11 |
+
DATABASE_URL = os.getenv("DATABASE_URL", "")
|
| 12 |
+
|
| 13 |
+
# If DATABASE_URL is not set, use a dummy engine (for development without DB)
|
| 14 |
+
if not DATABASE_URL:
|
| 15 |
+
# Create a dummy in-memory database for when no DB is configured
|
| 16 |
+
engine = create_engine("sqlite:///:memory:", echo=False)
|
| 17 |
+
else:
|
| 18 |
+
engine = create_engine(DATABASE_URL, pool_pre_ping=True, pool_size=10, max_overflow=20)
|
| 19 |
+
|
| 20 |
+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 21 |
+
Base = declarative_base()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_db():
|
| 25 |
+
"""Dependency that yields a database session."""
|
| 26 |
+
db = SessionLocal()
|
| 27 |
+
try:
|
| 28 |
+
yield db
|
| 29 |
+
finally:
|
| 30 |
+
db.close()
|
app/main.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from app.api import variant, genes, auth, organization
|
| 5 |
+
from app.database import engine, Base
|
| 6 |
+
|
| 7 |
+
# Try to create tables, but don't fail if database is not available
|
| 8 |
+
try:
|
| 9 |
+
Base.metadata.create_all(bind=engine)
|
| 10 |
+
except Exception as e:
|
| 11 |
+
print(f"Database connection warning: {e}")
|
| 12 |
+
|
| 13 |
+
app = FastAPI(
|
| 14 |
+
title="OpenVar API",
|
| 15 |
+
description="Clinical Variant Interpretation Platform",
|
| 16 |
+
version="1.0.0"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
cors_origins_raw = os.getenv("CORS_ALLOW_ORIGINS", "*")
|
| 20 |
+
cors_origins = ["*"] if cors_origins_raw.strip() == "*" else [
|
| 21 |
+
origin.strip() for origin in cors_origins_raw.split(",") if origin.strip()
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
app.add_middleware(
|
| 25 |
+
CORSMiddleware,
|
| 26 |
+
allow_origins=cors_origins,
|
| 27 |
+
allow_credentials=True,
|
| 28 |
+
allow_methods=["*"],
|
| 29 |
+
allow_headers=["*"],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
app.include_router(variant.router, prefix="/api/variant", tags=["variant"])
|
| 33 |
+
app.include_router(genes.router, prefix="/api/genes", tags=["genes"])
|
| 34 |
+
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
|
| 35 |
+
app.include_router(organization.router, prefix="/api/organizations", tags=["organizations"])
|
| 36 |
+
|
| 37 |
+
@app.get("/")
|
| 38 |
+
async def root():
|
| 39 |
+
return {"message": "OpenVar API", "version": "1.0.0"}
|
| 40 |
+
|
| 41 |
+
@app.get("/health")
|
| 42 |
+
async def health():
|
| 43 |
+
return {"status": "healthy"}
|
app/models/__init__.py
ADDED
|
File without changes
|
app/models/db.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SQLAlchemy ORM models for users, organizations, departments, and memberships."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from sqlalchemy import (
|
| 6 |
+
Column, String, Boolean, DateTime, Text, ForeignKey, Enum as SAEnum, Integer, UniqueConstraint
|
| 7 |
+
)
|
| 8 |
+
from sqlalchemy.orm import relationship
|
| 9 |
+
from app.database import Base
|
| 10 |
+
import enum
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _uuid() -> str:
|
| 14 |
+
return str(uuid.uuid4())
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _utcnow() -> datetime:
|
| 18 |
+
return datetime.now(timezone.utc)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ---------------------------------------------------------------------------
|
| 22 |
+
# Enums
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
class UserType(str, enum.Enum):
|
| 26 |
+
personal = "personal"
|
| 27 |
+
enterprise = "enterprise"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class OrgStatus(str, enum.Enum):
|
| 31 |
+
pending = "pending"
|
| 32 |
+
approved = "approved"
|
| 33 |
+
rejected = "rejected"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MemberRole(str, enum.Enum):
|
| 37 |
+
member = "member"
|
| 38 |
+
dept_admin = "dept_admin"
|
| 39 |
+
org_admin = "org_admin"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ---------------------------------------------------------------------------
|
| 43 |
+
# Users
|
| 44 |
+
# ---------------------------------------------------------------------------
|
| 45 |
+
|
| 46 |
+
class User(Base):
|
| 47 |
+
__tablename__ = "users"
|
| 48 |
+
|
| 49 |
+
id = Column(String(36), primary_key=True, default=_uuid)
|
| 50 |
+
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 51 |
+
hashed_password = Column(String(255), nullable=False)
|
| 52 |
+
full_name = Column(String(255), nullable=False)
|
| 53 |
+
user_type = Column(SAEnum(UserType), nullable=False, default=UserType.personal)
|
| 54 |
+
is_active = Column(Boolean, default=True)
|
| 55 |
+
is_superadmin = Column(Boolean, default=False)
|
| 56 |
+
avatar_url = Column(String(512), nullable=True)
|
| 57 |
+
phone = Column(String(32), nullable=True)
|
| 58 |
+
created_at = Column(DateTime(timezone=True), default=_utcnow)
|
| 59 |
+
updated_at = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
|
| 60 |
+
|
| 61 |
+
# Relationships
|
| 62 |
+
memberships = relationship("Membership", back_populates="user", cascade="all, delete-orphan")
|
| 63 |
+
created_organizations = relationship("Organization", back_populates="creator")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ---------------------------------------------------------------------------
|
| 67 |
+
# Organizations
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
class Organization(Base):
|
| 71 |
+
__tablename__ = "organizations"
|
| 72 |
+
|
| 73 |
+
id = Column(String(36), primary_key=True, default=_uuid)
|
| 74 |
+
name = Column(String(255), unique=True, nullable=False)
|
| 75 |
+
display_name = Column(String(255), nullable=True)
|
| 76 |
+
description = Column(Text, nullable=True)
|
| 77 |
+
status = Column(SAEnum(OrgStatus), nullable=False, default=OrgStatus.pending)
|
| 78 |
+
creator_id = Column(String(36), ForeignKey("users.id"), nullable=False)
|
| 79 |
+
logo_url = Column(String(512), nullable=True)
|
| 80 |
+
website = Column(String(512), nullable=True)
|
| 81 |
+
industry = Column(String(128), nullable=True)
|
| 82 |
+
max_members = Column(Integer, default=50)
|
| 83 |
+
rejection_reason = Column(Text, nullable=True)
|
| 84 |
+
approved_at = Column(DateTime(timezone=True), nullable=True)
|
| 85 |
+
created_at = Column(DateTime(timezone=True), default=_utcnow)
|
| 86 |
+
updated_at = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
|
| 87 |
+
|
| 88 |
+
# Relationships
|
| 89 |
+
creator = relationship("User", back_populates="created_organizations")
|
| 90 |
+
departments = relationship("Department", back_populates="organization", cascade="all, delete-orphan")
|
| 91 |
+
memberships = relationship("Membership", back_populates="organization", cascade="all, delete-orphan")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------
|
| 95 |
+
# Departments
|
| 96 |
+
# ---------------------------------------------------------------------------
|
| 97 |
+
|
| 98 |
+
class Department(Base):
|
| 99 |
+
__tablename__ = "departments"
|
| 100 |
+
|
| 101 |
+
id = Column(String(36), primary_key=True, default=_uuid)
|
| 102 |
+
organization_id = Column(String(36), ForeignKey("organizations.id"), nullable=False)
|
| 103 |
+
name = Column(String(255), nullable=False)
|
| 104 |
+
description = Column(Text, nullable=True)
|
| 105 |
+
parent_id = Column(String(36), ForeignKey("departments.id"), nullable=True)
|
| 106 |
+
created_at = Column(DateTime(timezone=True), default=_utcnow)
|
| 107 |
+
updated_at = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
|
| 108 |
+
|
| 109 |
+
__table_args__ = (
|
| 110 |
+
UniqueConstraint("organization_id", "name", name="uq_dept_org_name"),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Relationships
|
| 114 |
+
organization = relationship("Organization", back_populates="departments")
|
| 115 |
+
parent = relationship("Department", remote_side=[id], backref="children")
|
| 116 |
+
memberships = relationship("Membership", back_populates="department", cascade="all, delete-orphan")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# ---------------------------------------------------------------------------
|
| 120 |
+
# Memberships (user <-> organization <-> department)
|
| 121 |
+
# ---------------------------------------------------------------------------
|
| 122 |
+
|
| 123 |
+
class Membership(Base):
|
| 124 |
+
__tablename__ = "memberships"
|
| 125 |
+
|
| 126 |
+
id = Column(String(36), primary_key=True, default=_uuid)
|
| 127 |
+
user_id = Column(String(36), ForeignKey("users.id"), nullable=False)
|
| 128 |
+
organization_id = Column(String(36), ForeignKey("organizations.id"), nullable=False)
|
| 129 |
+
department_id = Column(String(36), ForeignKey("departments.id"), nullable=True)
|
| 130 |
+
role = Column(SAEnum(MemberRole), nullable=False, default=MemberRole.member)
|
| 131 |
+
is_active = Column(Boolean, default=True)
|
| 132 |
+
joined_at = Column(DateTime(timezone=True), default=_utcnow)
|
| 133 |
+
|
| 134 |
+
__table_args__ = (
|
| 135 |
+
UniqueConstraint("user_id", "organization_id", "department_id", name="uq_membership"),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Relationships
|
| 139 |
+
user = relationship("User", back_populates="memberships")
|
| 140 |
+
organization = relationship("Organization", back_populates="memberships")
|
| 141 |
+
department = relationship("Department", back_populates="memberships")
|
app/models/variant.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class VariantSearchRequest(BaseModel):
|
| 6 |
+
query: str
|
| 7 |
+
genome_build: Optional[str] = "hg38"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class VariantInfo(BaseModel):
|
| 11 |
+
id: str
|
| 12 |
+
chromosome: str
|
| 13 |
+
position: int
|
| 14 |
+
ref: str
|
| 15 |
+
alt: str
|
| 16 |
+
gene: Optional[str] = None
|
| 17 |
+
transcript: Optional[str] = None
|
| 18 |
+
protein_change: Optional[str] = None
|
| 19 |
+
hgvs_c: Optional[str] = None
|
| 20 |
+
hgvs_p: Optional[str] = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ClinVarInfo(BaseModel):
|
| 24 |
+
classification: Optional[str] = None
|
| 25 |
+
disease: Optional[str] = None
|
| 26 |
+
accession: Optional[str] = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class GnomADInfo(BaseModel):
|
| 30 |
+
exomes_af: Optional[float] = None
|
| 31 |
+
genomes_af: Optional[float] = None
|
| 32 |
+
exomes_ac: Optional[int] = None
|
| 33 |
+
genomes_ac: Optional[int] = None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ACMGInfo(BaseModel):
|
| 37 |
+
classification: Optional[str] = None
|
| 38 |
+
criteria: Optional[str] = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class VariantResponse(BaseModel):
|
| 42 |
+
variant: VariantInfo
|
| 43 |
+
clinvar: Optional[ClinVarInfo] = None
|
| 44 |
+
gnomad: Optional[GnomADInfo] = None
|
| 45 |
+
acmg: Optional[ACMGInfo] = None
|
| 46 |
+
consequences: Optional[dict] = None
|
app/services/__init__.py
ADDED
|
File without changes
|
app/services/auth_service.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Authentication utilities: password hashing and JWT token management."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from datetime import datetime, timedelta, timezone
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
from jose import JWTError, jwt
|
| 8 |
+
from passlib.context import CryptContext
|
| 9 |
+
from fastapi import Depends, HTTPException, status
|
| 10 |
+
from fastapi.security import OAuth2PasswordBearer
|
| 11 |
+
from sqlalchemy.orm import Session
|
| 12 |
+
|
| 13 |
+
from app.database import get_db
|
| 14 |
+
from app.models.db import User
|
| 15 |
+
|
| 16 |
+
JWT_SECRET = os.getenv("JWT_SECRET", "openvar-dev-secret-change-in-production")
|
| 17 |
+
JWT_ALGORITHM = "HS256"
|
| 18 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours
|
| 19 |
+
|
| 20 |
+
import bcrypt
|
| 21 |
+
|
| 22 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
| 23 |
+
|
| 24 |
+
def hash_password(password: str) -> str:
|
| 25 |
+
salt = bcrypt.gensalt()
|
| 26 |
+
return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8")
|
| 27 |
+
|
| 28 |
+
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
| 29 |
+
try:
|
| 30 |
+
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
|
| 31 |
+
except ValueError:
|
| 32 |
+
return False
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
| 36 |
+
to_encode = data.copy()
|
| 37 |
+
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
| 38 |
+
to_encode.update({"exp": expire})
|
| 39 |
+
return jwt.encode(to_encode, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def decode_token(token: str) -> dict:
|
| 43 |
+
try:
|
| 44 |
+
return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
| 45 |
+
except JWTError:
|
| 46 |
+
raise HTTPException(
|
| 47 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 48 |
+
detail="Invalid or expired token",
|
| 49 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
async def get_current_user(
|
| 54 |
+
token: Optional[str] = Depends(oauth2_scheme),
|
| 55 |
+
db: Session = Depends(get_db),
|
| 56 |
+
) -> User:
|
| 57 |
+
"""Extract and validate current user from JWT token."""
|
| 58 |
+
if not token:
|
| 59 |
+
raise HTTPException(
|
| 60 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 61 |
+
detail="Not authenticated",
|
| 62 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 63 |
+
)
|
| 64 |
+
payload = decode_token(token)
|
| 65 |
+
user_id: str = payload.get("sub", "")
|
| 66 |
+
if not user_id:
|
| 67 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token payload")
|
| 68 |
+
user = db.query(User).filter(User.id == user_id).first()
|
| 69 |
+
if not user or not user.is_active:
|
| 70 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or inactive")
|
| 71 |
+
return user
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
async def get_current_user_optional(
|
| 75 |
+
token: Optional[str] = Depends(oauth2_scheme),
|
| 76 |
+
db: Session = Depends(get_db),
|
| 77 |
+
) -> Optional[User]:
|
| 78 |
+
"""Return current user if authenticated, None otherwise."""
|
| 79 |
+
if not token:
|
| 80 |
+
return None
|
| 81 |
+
try:
|
| 82 |
+
payload = decode_token(token)
|
| 83 |
+
user_id = payload.get("sub", "")
|
| 84 |
+
if not user_id:
|
| 85 |
+
return None
|
| 86 |
+
user = db.query(User).filter(User.id == user_id).first()
|
| 87 |
+
return user if user and user.is_active else None
|
| 88 |
+
except HTTPException:
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
async def require_superadmin(
|
| 93 |
+
current_user: User = Depends(get_current_user),
|
| 94 |
+
) -> User:
|
| 95 |
+
"""Dependency that ensures the current user is a superadmin."""
|
| 96 |
+
if not current_user.is_superadmin:
|
| 97 |
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Superadmin access required")
|
| 98 |
+
return current_user
|
app/services/franklin_service.py
ADDED
|
@@ -0,0 +1,1332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import sqlite3
|
| 7 |
+
import subprocess
|
| 8 |
+
import threading
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from datetime import datetime, timedelta, timezone
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Optional
|
| 13 |
+
from urllib.parse import urlencode
|
| 14 |
+
|
| 15 |
+
import httpx
|
| 16 |
+
|
| 17 |
+
from app.services.variant_service import (
|
| 18 |
+
HTTPX_TRUST_ENV,
|
| 19 |
+
hgvs_to_coordinates,
|
| 20 |
+
parse_variant_query,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
FRANKLIN_BASE_URL = "https://franklin.genoox.com"
|
| 26 |
+
ENSEMBL_MAP_API = "https://rest.ensembl.org/map/human"
|
| 27 |
+
CACHE_TTL = timedelta(days=7)
|
| 28 |
+
_SV_CACHE_LOCK = threading.Lock()
|
| 29 |
+
_SV_REFRESH_INFLIGHT: set[str] = set()
|
| 30 |
+
SV_REGION_BUCKET_SIZE = 1_000_000
|
| 31 |
+
SV_REGION_TRACKS = [
|
| 32 |
+
"EXONS",
|
| 33 |
+
"GENES",
|
| 34 |
+
"GENE_DOSAGE_SENSITIVITY",
|
| 35 |
+
"SV_EVIDENCES",
|
| 36 |
+
"DGV",
|
| 37 |
+
"DGV_GOLD",
|
| 38 |
+
"GNOMAD",
|
| 39 |
+
]
|
| 40 |
+
SV_DEFAULT_VIEW_PADDING_RATIO = 0.338249
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class FranklinVariantContext:
|
| 45 |
+
chrom: str
|
| 46 |
+
position: int
|
| 47 |
+
ref: str
|
| 48 |
+
alt: str
|
| 49 |
+
reference_version: str
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def chrom_with_prefix(self) -> str:
|
| 53 |
+
return self.chrom if self.chrom.startswith("chr") else f"chr{self.chrom}"
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def hash_id(self) -> str:
|
| 57 |
+
start = self.position - 1
|
| 58 |
+
allele_hash = hashlib.md5(f"{self.ref}-{self.alt}".encode("utf-8")).hexdigest()
|
| 59 |
+
return f"{self.chrom_with_prefix}:{start}-{self.position}:{allele_hash}"
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def variant_key(self) -> str:
|
| 63 |
+
return f"{self.chrom_with_prefix}-{self.position}-{self.ref}-{self.alt}"
|
| 64 |
+
|
| 65 |
+
def to_snp_payload(self) -> dict[str, Any]:
|
| 66 |
+
return {
|
| 67 |
+
"chrom": self.chrom_with_prefix,
|
| 68 |
+
"chr": self.chrom_with_prefix,
|
| 69 |
+
"pos": self.position,
|
| 70 |
+
"ref": self.ref,
|
| 71 |
+
"alt": self.alt,
|
| 72 |
+
"hash_id": self.hash_id,
|
| 73 |
+
"hashId": self.hash_id,
|
| 74 |
+
"variantIdType": "SNP",
|
| 75 |
+
"reference_version": self.reference_version,
|
| 76 |
+
"referenceGenome": self.reference_version,
|
| 77 |
+
"reference_type": self.reference_version,
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@dataclass
|
| 82 |
+
class FranklinStructuralVariantContext:
|
| 83 |
+
chrom: str
|
| 84 |
+
start: int
|
| 85 |
+
end: int
|
| 86 |
+
sv_type: str
|
| 87 |
+
reference_version: str
|
| 88 |
+
ci_pos: str = "0,0"
|
| 89 |
+
ci_end: str = "0,0"
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def chrom_with_prefix(self) -> str:
|
| 93 |
+
return self.chrom if self.chrom.startswith("chr") else f"chr{self.chrom}"
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def reference_label(self) -> str:
|
| 97 |
+
value = self.reference_version.lower()
|
| 98 |
+
if value in {"hg19", "grch37"}:
|
| 99 |
+
return "hg19"
|
| 100 |
+
return "hg38"
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def hash_id(self) -> str:
|
| 104 |
+
return f"{self.chrom_with_prefix}-{self.start}-{self.end}-{self.sv_type}-{self.reference_label}"
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def variant_key(self) -> str:
|
| 108 |
+
return self.hash_id
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def sv_length(self) -> int:
|
| 112 |
+
return max(self.end - self.start, 0)
|
| 113 |
+
|
| 114 |
+
def to_sv_payload(self) -> dict[str, Any]:
|
| 115 |
+
return {
|
| 116 |
+
"chr": self.chrom_with_prefix,
|
| 117 |
+
"start_pos": self.start,
|
| 118 |
+
"end_pos": self.end,
|
| 119 |
+
"sv_type": self.sv_type,
|
| 120 |
+
"ci_pos": self.ci_pos,
|
| 121 |
+
"ci_end": self.ci_end,
|
| 122 |
+
"hashId": self.hash_id,
|
| 123 |
+
"referenceGenome": self.reference_label,
|
| 124 |
+
"reference_version": self.reference_label,
|
| 125 |
+
"variantIdType": "SV",
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
def to_sv_query_params(self) -> dict[str, Any]:
|
| 129 |
+
return {
|
| 130 |
+
"chr": self.chrom_with_prefix,
|
| 131 |
+
"start_pos": self.start,
|
| 132 |
+
"end_pos": self.end,
|
| 133 |
+
"sv_type": self.sv_type,
|
| 134 |
+
"ci_pos": "",
|
| 135 |
+
"ci_end": "",
|
| 136 |
+
"var_type": "sv",
|
| 137 |
+
"version": "",
|
| 138 |
+
"analysis_id": "",
|
| 139 |
+
"reference_version": self.reference_label,
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _infer_sv_region_tier(sv_type: str) -> str:
|
| 144 |
+
# Franklin's SV region viewer currently requests TIER_3 for public assessment pages.
|
| 145 |
+
return "TIER_3"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _build_sv_default_view(
|
| 149 |
+
start: int,
|
| 150 |
+
end: int,
|
| 151 |
+
chrom_end: Optional[int],
|
| 152 |
+
) -> dict[str, int]:
|
| 153 |
+
span = max(end - start, 1)
|
| 154 |
+
padding = max(1, int(round(span * SV_DEFAULT_VIEW_PADDING_RATIO)))
|
| 155 |
+
view_start = start - padding
|
| 156 |
+
view_end = end + padding
|
| 157 |
+
min_pos = 1
|
| 158 |
+
max_pos = max(chrom_end or view_end, view_end)
|
| 159 |
+
if view_start < min_pos:
|
| 160 |
+
view_start = min_pos
|
| 161 |
+
view_end = min(max_pos, end + padding)
|
| 162 |
+
if view_end > max_pos:
|
| 163 |
+
view_end = max_pos
|
| 164 |
+
view_start = max(min_pos, start - padding)
|
| 165 |
+
return {"start": view_start, "end": view_end}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _build_sv_region_buckets(view_start: int, view_end: int) -> list[int]:
|
| 169 |
+
start_bucket = max(1, view_start // SV_REGION_BUCKET_SIZE - 1)
|
| 170 |
+
end_bucket = max(start_bucket, view_end // SV_REGION_BUCKET_SIZE + 1)
|
| 171 |
+
return list(range(start_bucket, end_bucket + 1))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _collect_sv_public_occurrences(region_data: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
|
| 175 |
+
merged: dict[str, dict[str, dict[str, Any]]] = {
|
| 176 |
+
"dgv": {},
|
| 177 |
+
"dgv_gold": {},
|
| 178 |
+
"gnomad": {},
|
| 179 |
+
}
|
| 180 |
+
mapping = {
|
| 181 |
+
"dgv": "dgv_occurrences",
|
| 182 |
+
"dgv_gold": "dgv_gold_occurrences",
|
| 183 |
+
"gnomad": "gnomad_occurrences",
|
| 184 |
+
}
|
| 185 |
+
for bucket_data in region_data.values():
|
| 186 |
+
if not isinstance(bucket_data, dict):
|
| 187 |
+
continue
|
| 188 |
+
for target_key, source_key in mapping.items():
|
| 189 |
+
for item in bucket_data.get(source_key, []):
|
| 190 |
+
if not isinstance(item, dict):
|
| 191 |
+
continue
|
| 192 |
+
item_id = str(item.get("id") or json.dumps(item, sort_keys=True))
|
| 193 |
+
merged[target_key][item_id] = item
|
| 194 |
+
return {key: list(items.values()) for key, items in merged.items()}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
async def _resolve_variant_context(
|
| 198 |
+
query: str,
|
| 199 |
+
reference_version: str = "hg19",
|
| 200 |
+
) -> Optional[FranklinVariantContext]:
|
| 201 |
+
parsed = parse_variant_query(query)
|
| 202 |
+
|
| 203 |
+
if parsed.get("type") == "coordinates":
|
| 204 |
+
return FranklinVariantContext(
|
| 205 |
+
chrom=str(parsed["chromosome"]).replace("chr", ""),
|
| 206 |
+
position=int(parsed["position"]),
|
| 207 |
+
ref=str(parsed["ref"]).upper(),
|
| 208 |
+
alt=str(parsed["alt"]).upper(),
|
| 209 |
+
reference_version=reference_version,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if parsed.get("type") == "hgvs":
|
| 213 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 214 |
+
coords = await hgvs_to_coordinates(parsed["value"], client)
|
| 215 |
+
if not coords:
|
| 216 |
+
return None
|
| 217 |
+
chrom = str(coords["chromosome"]).replace("chr", "")
|
| 218 |
+
position = int(coords["position"])
|
| 219 |
+
|
| 220 |
+
# Ensembl HGVS commonly resolves on GRCh38; Franklin SNP page is GRCh37(hg19).
|
| 221 |
+
if reference_version.lower() in {"hg19", "grch37"}:
|
| 222 |
+
mapped_position = await _map_grch38_to_grch37(chrom, position)
|
| 223 |
+
if mapped_position:
|
| 224 |
+
position = mapped_position
|
| 225 |
+
|
| 226 |
+
return FranklinVariantContext(
|
| 227 |
+
chrom=chrom,
|
| 228 |
+
position=position,
|
| 229 |
+
ref=str(coords["ref"]).upper(),
|
| 230 |
+
alt=str(coords["alt"]).upper(),
|
| 231 |
+
reference_version=reference_version,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# Accept compact coordinate id directly: chr9-135800978-A-G
|
| 235 |
+
parts = query.replace("chr", "").split("-")
|
| 236 |
+
if len(parts) >= 4 and parts[1].isdigit():
|
| 237 |
+
return FranklinVariantContext(
|
| 238 |
+
chrom=parts[0],
|
| 239 |
+
position=int(parts[1]),
|
| 240 |
+
ref=parts[2].upper(),
|
| 241 |
+
alt=parts[3].upper(),
|
| 242 |
+
reference_version=reference_version,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Fallback to Franklin's /api/parse_search API
|
| 246 |
+
franklin_parsed = await parse_search_query_via_franklin(query, reference_version)
|
| 247 |
+
if not franklin_parsed or (franklin_parsed and franklin_parsed.get("response_type") != "SNP_VARIANT"):
|
| 248 |
+
other_version = "hg38" if reference_version.lower() in {"hg19", "grch37"} else "hg19"
|
| 249 |
+
franklin_fallback = await parse_search_query_via_franklin(query, other_version)
|
| 250 |
+
if franklin_fallback and franklin_fallback.get("response_type") == "SNP_VARIANT":
|
| 251 |
+
franklin_parsed = franklin_fallback
|
| 252 |
+
|
| 253 |
+
if franklin_parsed and franklin_parsed.get("response_type") == "SNP_VARIANT":
|
| 254 |
+
best = franklin_parsed.get("best_variant_option")
|
| 255 |
+
if best and best.get("chrom"):
|
| 256 |
+
return FranklinVariantContext(
|
| 257 |
+
chrom=str(best["chrom"]).replace("chr", ""),
|
| 258 |
+
position=int(best["pos"]),
|
| 259 |
+
ref=best.get("ref", "").upper(),
|
| 260 |
+
alt=best.get("alt", "").upper(),
|
| 261 |
+
reference_version=best.get("reference_version", reference_version).lower(),
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
return None
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _resolve_structural_variant_context(
|
| 268 |
+
query: str,
|
| 269 |
+
reference_version: str = "hg19",
|
| 270 |
+
) -> Optional[FranklinStructuralVariantContext]:
|
| 271 |
+
parsed = parse_variant_query(query)
|
| 272 |
+
if parsed.get("type") != "sv":
|
| 273 |
+
return None
|
| 274 |
+
|
| 275 |
+
parsed_reference = parsed.get("reference_version")
|
| 276 |
+
effective_reference = str(parsed_reference or reference_version or "hg38").lower()
|
| 277 |
+
return FranklinStructuralVariantContext(
|
| 278 |
+
chrom=str(parsed["chromosome"]).replace("chr", ""),
|
| 279 |
+
start=int(parsed["start"]),
|
| 280 |
+
end=int(parsed["end"]),
|
| 281 |
+
sv_type=str(parsed["sv_type"]).upper(),
|
| 282 |
+
reference_version=effective_reference,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _cache_db_path() -> Path:
|
| 287 |
+
configured = os.getenv("FRANKLIN_CACHE_DB_PATH")
|
| 288 |
+
if configured:
|
| 289 |
+
return Path(configured)
|
| 290 |
+
return Path(__file__).resolve().parents[2] / "data" / "franklin_cache.sqlite3"
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
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 (
|
| 300 |
+
cache_key TEXT PRIMARY KEY,
|
| 301 |
+
query TEXT NOT NULL,
|
| 302 |
+
reference_version TEXT NOT NULL,
|
| 303 |
+
payload_json TEXT NOT NULL,
|
| 304 |
+
fetched_at TEXT NOT NULL,
|
| 305 |
+
updated_at TEXT NOT NULL
|
| 306 |
+
)
|
| 307 |
+
"""
|
| 308 |
+
)
|
| 309 |
+
connection.commit()
|
| 310 |
+
return connection
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _load_cached_sv_assessment(cache_key: str) -> Optional[dict[str, Any]]:
|
| 314 |
+
with _get_cache_connection() as connection:
|
| 315 |
+
row = connection.execute(
|
| 316 |
+
"""
|
| 317 |
+
SELECT payload_json, fetched_at, updated_at
|
| 318 |
+
FROM franklin_sv_cache
|
| 319 |
+
WHERE cache_key = ?
|
| 320 |
+
""",
|
| 321 |
+
(cache_key,),
|
| 322 |
+
).fetchone()
|
| 323 |
+
if not row:
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
payload = json.loads(row[0])
|
| 327 |
+
fetched_at = row[1]
|
| 328 |
+
updated_at = row[2]
|
| 329 |
+
return {
|
| 330 |
+
"payload": payload,
|
| 331 |
+
"fetched_at": fetched_at,
|
| 332 |
+
"updated_at": updated_at,
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _delete_cached_sv_assessment(cache_key: str) -> None:
|
| 337 |
+
with _get_cache_connection() as connection:
|
| 338 |
+
connection.execute(
|
| 339 |
+
"""
|
| 340 |
+
DELETE FROM franklin_sv_cache
|
| 341 |
+
WHERE cache_key = ?
|
| 342 |
+
""",
|
| 343 |
+
(cache_key,),
|
| 344 |
+
)
|
| 345 |
+
connection.commit()
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def _save_cached_sv_assessment(
|
| 349 |
+
cache_key: str,
|
| 350 |
+
query: str,
|
| 351 |
+
reference_version: str,
|
| 352 |
+
payload: dict[str, Any],
|
| 353 |
+
) -> None:
|
| 354 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 355 |
+
with _get_cache_connection() as connection:
|
| 356 |
+
connection.execute(
|
| 357 |
+
"""
|
| 358 |
+
INSERT INTO franklin_sv_cache (
|
| 359 |
+
cache_key, query, reference_version, payload_json, fetched_at, updated_at
|
| 360 |
+
)
|
| 361 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 362 |
+
ON CONFLICT(cache_key) DO UPDATE SET
|
| 363 |
+
query = excluded.query,
|
| 364 |
+
reference_version = excluded.reference_version,
|
| 365 |
+
payload_json = excluded.payload_json,
|
| 366 |
+
fetched_at = excluded.fetched_at,
|
| 367 |
+
updated_at = excluded.updated_at
|
| 368 |
+
""",
|
| 369 |
+
(cache_key, query, reference_version, json.dumps(payload), now, now),
|
| 370 |
+
)
|
| 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):
|
| 377 |
+
return True
|
| 378 |
+
try:
|
| 379 |
+
fetched_at = datetime.fromisoformat(fetched_at_raw)
|
| 380 |
+
except ValueError:
|
| 381 |
+
return True
|
| 382 |
+
if fetched_at.tzinfo is None:
|
| 383 |
+
fetched_at = fetched_at.replace(tzinfo=timezone.utc)
|
| 384 |
+
return datetime.now(timezone.utc) - fetched_at > CACHE_TTL
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _attach_cache_metadata(
|
| 388 |
+
payload: dict[str, Any],
|
| 389 |
+
*,
|
| 390 |
+
source: str,
|
| 391 |
+
stale: bool,
|
| 392 |
+
fetched_at: Optional[str] = None,
|
| 393 |
+
) -> dict[str, Any]:
|
| 394 |
+
enriched = dict(payload)
|
| 395 |
+
enriched["cache"] = {
|
| 396 |
+
"source": source,
|
| 397 |
+
"stale": stale,
|
| 398 |
+
"fetched_at": fetched_at,
|
| 399 |
+
}
|
| 400 |
+
return enriched
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def _has_cacheable_sv_payload(payload: dict[str, Any]) -> bool:
|
| 404 |
+
tabs = payload.get("tabs")
|
| 405 |
+
if not isinstance(tabs, dict):
|
| 406 |
+
return False
|
| 407 |
+
|
| 408 |
+
variant_assessment = tabs.get("variant_assessment")
|
| 409 |
+
if not isinstance(variant_assessment, dict):
|
| 410 |
+
return False
|
| 411 |
+
|
| 412 |
+
summary = variant_assessment.get("summary")
|
| 413 |
+
summary_data = summary.get("data") if isinstance(summary, dict) else {}
|
| 414 |
+
if not isinstance(summary_data, dict):
|
| 415 |
+
summary_data = {}
|
| 416 |
+
if summary_data.get("genes") or summary_data.get("cytobands_description") or summary_data.get("severest_region"):
|
| 417 |
+
return True
|
| 418 |
+
|
| 419 |
+
details = variant_assessment.get("variant_details")
|
| 420 |
+
details_data = details.get("data") if isinstance(details, dict) else {}
|
| 421 |
+
if isinstance(details_data, dict) and (
|
| 422 |
+
details_data.get("genes") or details_data.get("cytobands_description") or details_data.get("linkouts")
|
| 423 |
+
):
|
| 424 |
+
return True
|
| 425 |
+
|
| 426 |
+
region_viewer = variant_assessment.get("region_viewer")
|
| 427 |
+
region_result = region_viewer.get("region_data") if isinstance(region_viewer, dict) else {}
|
| 428 |
+
region_data = region_result.get("data") if isinstance(region_result, dict) else {}
|
| 429 |
+
if isinstance(region_data, dict):
|
| 430 |
+
bucketed = region_data.get("region_data")
|
| 431 |
+
if isinstance(bucketed, dict) and any(bool(bucket) for bucket in bucketed.values()):
|
| 432 |
+
return True
|
| 433 |
+
|
| 434 |
+
population = variant_assessment.get("population_frequencies")
|
| 435 |
+
population_data = population.get("data") if isinstance(population, dict) else {}
|
| 436 |
+
if isinstance(population_data, dict):
|
| 437 |
+
for key in ("dgv", "dgv_gold", "gnomad"):
|
| 438 |
+
values = population_data.get(key)
|
| 439 |
+
if isinstance(values, list) and values:
|
| 440 |
+
return True
|
| 441 |
+
|
| 442 |
+
clinical = variant_assessment.get("clinical_evidence")
|
| 443 |
+
clinical_data = clinical.get("data") if isinstance(clinical, dict) else {}
|
| 444 |
+
if isinstance(clinical_data, dict):
|
| 445 |
+
for key in ("clinvar", "community", "decipher"):
|
| 446 |
+
evidence_group = clinical_data.get(key)
|
| 447 |
+
entries = evidence_group.get("entries") if isinstance(evidence_group, dict) else None
|
| 448 |
+
if isinstance(entries, list) and entries:
|
| 449 |
+
return True
|
| 450 |
+
|
| 451 |
+
alt_reference = tabs.get("alternate_reference")
|
| 452 |
+
alt_reference_data = alt_reference.get("data") if isinstance(alt_reference, dict) else {}
|
| 453 |
+
if isinstance(alt_reference_data, dict) and alt_reference_data.get("success"):
|
| 454 |
+
return True
|
| 455 |
+
|
| 456 |
+
return False
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _start_sv_cache_refresh(
|
| 460 |
+
cache_key: str,
|
| 461 |
+
query: str,
|
| 462 |
+
reference_version: str,
|
| 463 |
+
) -> None:
|
| 464 |
+
with _SV_CACHE_LOCK:
|
| 465 |
+
if cache_key in _SV_REFRESH_INFLIGHT:
|
| 466 |
+
return
|
| 467 |
+
_SV_REFRESH_INFLIGHT.add(cache_key)
|
| 468 |
+
|
| 469 |
+
def _runner() -> None:
|
| 470 |
+
try:
|
| 471 |
+
asyncio.run(_refresh_sv_cache(query, reference_version))
|
| 472 |
+
except Exception:
|
| 473 |
+
logger.exception("Background SV cache refresh failed", extra={"query": query})
|
| 474 |
+
finally:
|
| 475 |
+
with _SV_CACHE_LOCK:
|
| 476 |
+
_SV_REFRESH_INFLIGHT.discard(cache_key)
|
| 477 |
+
|
| 478 |
+
threading.Thread(target=_runner, daemon=True).start()
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
async def _refresh_sv_cache(query: str, reference_version: str) -> dict[str, Any]:
|
| 482 |
+
context = _resolve_structural_variant_context(query, reference_version=reference_version)
|
| 483 |
+
if not context:
|
| 484 |
+
raise ValueError(f"Unable to resolve structural variant coordinates: {query}")
|
| 485 |
+
payload = await _fetch_structural_variant_assessment(context, query)
|
| 486 |
+
if _has_cacheable_sv_payload(payload):
|
| 487 |
+
_save_cached_sv_assessment(context.variant_key, query, context.reference_label, payload)
|
| 488 |
+
return payload
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
async def _map_grch38_to_grch37(chrom: str, position: int) -> Optional[int]:
|
| 492 |
+
location = f"{chrom}:{position}..{position}:1"
|
| 493 |
+
url = f"{ENSEMBL_MAP_API}/GRCh38/{location}/GRCh37"
|
| 494 |
+
try:
|
| 495 |
+
async with httpx.AsyncClient(timeout=20.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 496 |
+
response = await client.get(url, headers={"Accept": "application/json"})
|
| 497 |
+
if response.status_code != 200:
|
| 498 |
+
return None
|
| 499 |
+
data = response.json()
|
| 500 |
+
mappings = data.get("mappings", [])
|
| 501 |
+
if not mappings:
|
| 502 |
+
return None
|
| 503 |
+
mapped = mappings[0].get("mapped", {})
|
| 504 |
+
mapped_start = mapped.get("start")
|
| 505 |
+
return int(mapped_start) if mapped_start else None
|
| 506 |
+
except Exception:
|
| 507 |
+
return None
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
async def _map_assembly_range(
|
| 511 |
+
chrom: str,
|
| 512 |
+
start: int,
|
| 513 |
+
end: int,
|
| 514 |
+
source_assembly: str,
|
| 515 |
+
target_assembly: str,
|
| 516 |
+
) -> Optional[dict[str, int | str]]:
|
| 517 |
+
location = f"{chrom}:{start}..{end}:1"
|
| 518 |
+
url = f"{ENSEMBL_MAP_API}/{source_assembly}/{location}/{target_assembly}"
|
| 519 |
+
|
| 520 |
+
def _parse_mapping_payload(data: dict[str, Any]) -> Optional[dict[str, int | str]]:
|
| 521 |
+
mappings = data.get("mappings", [])
|
| 522 |
+
if not isinstance(mappings, list) or not mappings:
|
| 523 |
+
return None
|
| 524 |
+
mapped_ranges: list[tuple[int, int, str]] = []
|
| 525 |
+
for item in mappings:
|
| 526 |
+
if not isinstance(item, dict):
|
| 527 |
+
continue
|
| 528 |
+
mapped = item.get("mapped", {})
|
| 529 |
+
if not isinstance(mapped, dict):
|
| 530 |
+
continue
|
| 531 |
+
mapped_start = mapped.get("start")
|
| 532 |
+
mapped_end = mapped.get("end")
|
| 533 |
+
mapped_chrom = mapped.get("seq_region_name")
|
| 534 |
+
if not mapped_start or not mapped_end or not mapped_chrom:
|
| 535 |
+
continue
|
| 536 |
+
mapped_ranges.append((int(mapped_start), int(mapped_end), str(mapped_chrom)))
|
| 537 |
+
if not mapped_ranges:
|
| 538 |
+
return None
|
| 539 |
+
mapped_ranges.sort(key=lambda item: item[0])
|
| 540 |
+
return {
|
| 541 |
+
"chrom": mapped_ranges[0][2],
|
| 542 |
+
"start_pos": min(item[0] for item in mapped_ranges),
|
| 543 |
+
"end_pos": max(item[1] for item in mapped_ranges),
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
try:
|
| 547 |
+
async with httpx.AsyncClient(timeout=20.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 548 |
+
response = await client.get(url, headers={"Accept": "application/json"})
|
| 549 |
+
if response.status_code == 200:
|
| 550 |
+
parsed = _parse_mapping_payload(response.json())
|
| 551 |
+
if parsed:
|
| 552 |
+
return parsed
|
| 553 |
+
except Exception:
|
| 554 |
+
logger.warning("Ensembl range map failed via httpx for %s", location)
|
| 555 |
+
|
| 556 |
+
try:
|
| 557 |
+
proc = await asyncio.create_subprocess_exec(
|
| 558 |
+
"curl",
|
| 559 |
+
"-fsSL",
|
| 560 |
+
url,
|
| 561 |
+
"-H",
|
| 562 |
+
"Accept: application/json",
|
| 563 |
+
stdout=asyncio.subprocess.PIPE,
|
| 564 |
+
stderr=asyncio.subprocess.PIPE,
|
| 565 |
+
)
|
| 566 |
+
stdout, _stderr = await asyncio.wait_for(proc.communicate(), timeout=20.0)
|
| 567 |
+
if proc.returncode == 0 and stdout:
|
| 568 |
+
parsed = _parse_mapping_payload(json.loads(stdout.decode("utf-8")))
|
| 569 |
+
if parsed:
|
| 570 |
+
return parsed
|
| 571 |
+
except (subprocess.SubprocessError, asyncio.TimeoutError, json.JSONDecodeError):
|
| 572 |
+
logger.warning("Ensembl range map failed via curl for %s", location)
|
| 573 |
+
|
| 574 |
+
return None
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
async def _build_sv_alt_reference_fallback(
|
| 578 |
+
context: FranklinStructuralVariantContext,
|
| 579 |
+
details_data: dict[str, Any],
|
| 580 |
+
) -> Optional[dict[str, Any]]:
|
| 581 |
+
source_assembly = "GRCh38" if context.reference_label == "hg38" else "GRCh37"
|
| 582 |
+
target_assembly = "GRCh37" if context.reference_label == "hg38" else "GRCh38"
|
| 583 |
+
target_label = "HG19" if target_assembly == "GRCh37" else "HG38"
|
| 584 |
+
mapped = await _map_assembly_range(
|
| 585 |
+
context.chrom.replace("chr", ""),
|
| 586 |
+
context.start,
|
| 587 |
+
context.end,
|
| 588 |
+
source_assembly,
|
| 589 |
+
target_assembly,
|
| 590 |
+
)
|
| 591 |
+
if not mapped:
|
| 592 |
+
return None
|
| 593 |
+
|
| 594 |
+
mapped_chrom = str(mapped["chrom"])
|
| 595 |
+
mapped_start = int(mapped["start_pos"])
|
| 596 |
+
mapped_end = int(mapped["end_pos"])
|
| 597 |
+
link_suffix = "" if target_label == "HG19" else "-hg38"
|
| 598 |
+
return {
|
| 599 |
+
"ok": True,
|
| 600 |
+
"status": 200,
|
| 601 |
+
"data": {
|
| 602 |
+
"success": True,
|
| 603 |
+
"reference_version": target_label,
|
| 604 |
+
"sv_variant": {
|
| 605 |
+
"chrom": f"chr{mapped_chrom}" if not mapped_chrom.startswith("chr") else mapped_chrom,
|
| 606 |
+
"start_pos": mapped_start,
|
| 607 |
+
"end_pos": mapped_end,
|
| 608 |
+
"sv_type": context.sv_type,
|
| 609 |
+
"reference_genome_type": target_label.lower(),
|
| 610 |
+
"reference_version": target_label,
|
| 611 |
+
"length": context.sv_length,
|
| 612 |
+
},
|
| 613 |
+
"cytobands": details_data.get("cytobands_description"),
|
| 614 |
+
"link": f"{FRANKLIN_BASE_URL}/clinical-db/variant/sv/"
|
| 615 |
+
f"{'chr' if not mapped_chrom.startswith('chr') else ''}{mapped_chrom}-{mapped_start}-{mapped_end}-{context.sv_type}{link_suffix}",
|
| 616 |
+
"source": "ensembl-map-fallback",
|
| 617 |
+
},
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
async def _franklin_request(
|
| 622 |
+
client: httpx.AsyncClient,
|
| 623 |
+
method: str,
|
| 624 |
+
endpoint: str,
|
| 625 |
+
*,
|
| 626 |
+
payload: Any = None,
|
| 627 |
+
params: Optional[dict[str, Any]] = None,
|
| 628 |
+
) -> dict[str, Any]:
|
| 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 |
+
data = response.json()
|
| 642 |
+
except Exception:
|
| 643 |
+
data = {"raw": response.text[:2000]}
|
| 644 |
+
return {
|
| 645 |
+
"ok": response.status_code < 400,
|
| 646 |
+
"status": response.status_code,
|
| 647 |
+
"data": data,
|
| 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 |
+
data = json.loads(body) if body else {}
|
| 698 |
+
except Exception:
|
| 699 |
+
data = {"raw": body[:2000]}
|
| 700 |
+
return {
|
| 701 |
+
"ok": status_code < 400,
|
| 702 |
+
"status": status_code,
|
| 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 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as direct_client:
|
| 723 |
+
return await _do_request(direct_client)
|
| 724 |
+
except Exception:
|
| 725 |
+
return {"ok": False, "status": 504, "error": "upstream timeout"}
|
| 726 |
+
return {"ok": False, "status": 504, "error": "upstream timeout"}
|
| 727 |
+
except Exception as exc:
|
| 728 |
+
if HTTPX_TRUST_ENV:
|
| 729 |
+
try:
|
| 730 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as direct_client:
|
| 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(
|
| 738 |
+
context: FranklinStructuralVariantContext,
|
| 739 |
+
query: str,
|
| 740 |
+
) -> dict[str, Any]:
|
| 741 |
+
payload = context.to_sv_payload()
|
| 742 |
+
query_params = context.to_sv_query_params()
|
| 743 |
+
provisional_default_view = _build_sv_default_view(context.start, context.end, None)
|
| 744 |
+
region_viewer_payload = {
|
| 745 |
+
"chr": context.chrom_with_prefix,
|
| 746 |
+
"sv_variant_start": context.start,
|
| 747 |
+
"sv_variant_end": context.end,
|
| 748 |
+
"sv_type": context.sv_type,
|
| 749 |
+
"tier": _infer_sv_region_tier(context.sv_type),
|
| 750 |
+
"reference_type": context.reference_label,
|
| 751 |
+
"reference_version": context.reference_label,
|
| 752 |
+
"buckets": _build_sv_region_buckets(
|
| 753 |
+
provisional_default_view["start"],
|
| 754 |
+
provisional_default_view["end"],
|
| 755 |
+
),
|
| 756 |
+
"tracks": SV_REGION_TRACKS,
|
| 757 |
+
}
|
| 758 |
+
|
| 759 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 760 |
+
(
|
| 761 |
+
variant_details,
|
| 762 |
+
region_presets,
|
| 763 |
+
cytobands,
|
| 764 |
+
carrier_status,
|
| 765 |
+
clinical_evidence,
|
| 766 |
+
region_viewer_data,
|
| 767 |
+
alt_reference,
|
| 768 |
+
org_assessments,
|
| 769 |
+
uploaded_files,
|
| 770 |
+
clingen_classification,
|
| 771 |
+
) = await asyncio.gather(
|
| 772 |
+
_franklin_request(client, "GET", "/api/fetch_sv_details", params=query_params),
|
| 773 |
+
_franklin_request(client, "GET", "/api/region_viewer/presets"),
|
| 774 |
+
_franklin_request(
|
| 775 |
+
client,
|
| 776 |
+
"GET",
|
| 777 |
+
"/api/cytobands/by_chromosome",
|
| 778 |
+
params={"chr": context.chrom_with_prefix, "reference_version": context.reference_label},
|
| 779 |
+
),
|
| 780 |
+
_franklin_request(
|
| 781 |
+
client,
|
| 782 |
+
"GET",
|
| 783 |
+
"/api/sv/summary/carrier_status",
|
| 784 |
+
params={
|
| 785 |
+
"chr": context.chrom_with_prefix,
|
| 786 |
+
"start_pos": context.start,
|
| 787 |
+
"end_pos": context.end,
|
| 788 |
+
"sv_type": context.sv_type,
|
| 789 |
+
"zygosity": "undefined",
|
| 790 |
+
"phenotypes": "undefined",
|
| 791 |
+
"reference_version": context.reference_label,
|
| 792 |
+
},
|
| 793 |
+
),
|
| 794 |
+
_franklin_request(client, "GET", "/api/sv/fetch_evidences", params=query_params),
|
| 795 |
+
_franklin_request(client, "POST", "/api/get_region_data", payload=region_viewer_payload),
|
| 796 |
+
_franklin_request(client, "GET", "/api/fetch_sv_alt_reference_variant", params=query_params),
|
| 797 |
+
_franklin_request(client, "GET", "/api/org/sv_interpretation", params=query_params),
|
| 798 |
+
_franklin_request(
|
| 799 |
+
client,
|
| 800 |
+
"POST",
|
| 801 |
+
"/api/organization/variant/attachment/list",
|
| 802 |
+
payload={"var_id": context.hash_id},
|
| 803 |
+
),
|
| 804 |
+
_franklin_request(
|
| 805 |
+
client,
|
| 806 |
+
"POST",
|
| 807 |
+
"/api/sv/clingen_classify",
|
| 808 |
+
payload={
|
| 809 |
+
"variant": {
|
| 810 |
+
"chrom": context.chrom_with_prefix,
|
| 811 |
+
"start": context.start,
|
| 812 |
+
"end": context.end,
|
| 813 |
+
"sv_type": context.sv_type,
|
| 814 |
+
"ci_pos": {"start": 0, "end": 0},
|
| 815 |
+
"ci_end": {"start": 0, "end": 0},
|
| 816 |
+
"reference_version": context.reference_label,
|
| 817 |
+
}
|
| 818 |
+
},
|
| 819 |
+
),
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
details_data = variant_details.get("data") if isinstance(variant_details.get("data"), dict) else {}
|
| 823 |
+
if not isinstance(details_data, dict):
|
| 824 |
+
details_data = {}
|
| 825 |
+
alt_reference_data = alt_reference.get("data") if isinstance(alt_reference.get("data"), dict) else {}
|
| 826 |
+
if not isinstance(alt_reference_data, dict):
|
| 827 |
+
alt_reference_data = {}
|
| 828 |
+
if (
|
| 829 |
+
not alt_reference.get("ok")
|
| 830 |
+
or alt_reference_data.get("raw") == "no token"
|
| 831 |
+
or not alt_reference_data.get("success")
|
| 832 |
+
):
|
| 833 |
+
alt_reference_fallback = await _build_sv_alt_reference_fallback(context, details_data)
|
| 834 |
+
if alt_reference_fallback:
|
| 835 |
+
alt_reference = alt_reference_fallback
|
| 836 |
+
region_viewer_data_payload = (
|
| 837 |
+
region_viewer_data.get("data") if isinstance(region_viewer_data.get("data"), dict) else {}
|
| 838 |
+
)
|
| 839 |
+
if not isinstance(region_viewer_data_payload, dict):
|
| 840 |
+
region_viewer_data_payload = {}
|
| 841 |
+
clingen_results = clingen_classification.get("data", {}).get("results", [])
|
| 842 |
+
primary_clingen_result = clingen_results[0] if isinstance(clingen_results, list) and clingen_results else {}
|
| 843 |
+
default_view = _build_sv_default_view(
|
| 844 |
+
context.start,
|
| 845 |
+
context.end,
|
| 846 |
+
region_viewer_data_payload.get("chrom_end") if isinstance(region_viewer_data_payload.get("chrom_end"), int) else None,
|
| 847 |
+
)
|
| 848 |
+
region_data = region_viewer_data_payload.get("region_data")
|
| 849 |
+
if not isinstance(region_data, dict):
|
| 850 |
+
region_data = {}
|
| 851 |
+
public_occurrences = _collect_sv_public_occurrences(region_data)
|
| 852 |
+
summary = {
|
| 853 |
+
"ok": variant_details.get("ok", False),
|
| 854 |
+
"status": variant_details.get("status"),
|
| 855 |
+
"data": {
|
| 856 |
+
"variant_type": "SV",
|
| 857 |
+
"sv_type": context.sv_type,
|
| 858 |
+
"range_descriptor": details_data.get("range_descriptor") or f"{context.chrom_with_prefix}:{context.start}-{context.end}",
|
| 859 |
+
"genes": details_data.get("genes") or [],
|
| 860 |
+
"cytobands_description": details_data.get("cytobands_description"),
|
| 861 |
+
"severest_impact": details_data.get("severest_impact"),
|
| 862 |
+
"severest_region": details_data.get("severest_region"),
|
| 863 |
+
"carrier_status": carrier_status.get("data"),
|
| 864 |
+
"classification": primary_clingen_result.get("classification"),
|
| 865 |
+
"classification_score": primary_clingen_result.get("score"),
|
| 866 |
+
"evidence_sections": primary_clingen_result.get("evidence", []),
|
| 867 |
+
"upstream_error": variant_details.get("error"),
|
| 868 |
+
},
|
| 869 |
+
}
|
| 870 |
+
region_viewer = {
|
| 871 |
+
"presets": region_presets,
|
| 872 |
+
"region_data": {
|
| 873 |
+
"ok": region_viewer_data.get("ok", False),
|
| 874 |
+
"status": region_viewer_data.get("status"),
|
| 875 |
+
"data": {
|
| 876 |
+
"variant_type": "SV",
|
| 877 |
+
"sv_type": context.sv_type,
|
| 878 |
+
"range": {
|
| 879 |
+
"chromosome": context.chrom_with_prefix,
|
| 880 |
+
"start": context.start,
|
| 881 |
+
"end": context.end,
|
| 882 |
+
"length": context.sv_length,
|
| 883 |
+
},
|
| 884 |
+
"default_view": default_view,
|
| 885 |
+
"cytobands": cytobands.get("data"),
|
| 886 |
+
"carrier_status": carrier_status.get("data"),
|
| 887 |
+
"region_data": region_data,
|
| 888 |
+
"buckets": region_viewer_payload["buckets"],
|
| 889 |
+
"chrom_end": region_viewer_data_payload.get("chrom_end"),
|
| 890 |
+
"variant_details": details_data,
|
| 891 |
+
},
|
| 892 |
+
"upstream": {
|
| 893 |
+
"cytobands": cytobands,
|
| 894 |
+
"carrier_status": carrier_status,
|
| 895 |
+
"region_data": region_viewer_data,
|
| 896 |
+
},
|
| 897 |
+
},
|
| 898 |
+
}
|
| 899 |
+
|
| 900 |
+
return {
|
| 901 |
+
"variant": {
|
| 902 |
+
"query": query,
|
| 903 |
+
"key": context.variant_key,
|
| 904 |
+
"chromosome": context.chrom_with_prefix,
|
| 905 |
+
"position": context.start,
|
| 906 |
+
"start": context.start,
|
| 907 |
+
"end": context.end,
|
| 908 |
+
"ref": "SV",
|
| 909 |
+
"alt": context.sv_type,
|
| 910 |
+
"hash_id": context.hash_id,
|
| 911 |
+
"reference_version": context.reference_label,
|
| 912 |
+
"sv_type": context.sv_type,
|
| 913 |
+
"sv_length": context.sv_length,
|
| 914 |
+
},
|
| 915 |
+
"tabs": {
|
| 916 |
+
"franklin_acmg_classification": summary,
|
| 917 |
+
"variant_assessment": {
|
| 918 |
+
"summary": summary,
|
| 919 |
+
"region_viewer": region_viewer,
|
| 920 |
+
"franklin_community_frequency": {"ok": True, "status": 200, "data": public_occurrences},
|
| 921 |
+
"clinical_evidence": clinical_evidence,
|
| 922 |
+
"predictions": summary,
|
| 923 |
+
"population_frequencies": {"ok": True, "status": 200, "data": public_occurrences},
|
| 924 |
+
"transcripts_and_references": region_viewer_data,
|
| 925 |
+
"uploaded_files": uploaded_files,
|
| 926 |
+
"variant_details": variant_details,
|
| 927 |
+
"search_data": {
|
| 928 |
+
"ok": True,
|
| 929 |
+
"status": 200,
|
| 930 |
+
"data": {
|
| 931 |
+
"query": query,
|
| 932 |
+
"sv_variant": payload,
|
| 933 |
+
},
|
| 934 |
+
},
|
| 935 |
+
"warmup": {
|
| 936 |
+
"ok": True,
|
| 937 |
+
"status": 200,
|
| 938 |
+
"data": {"message": "sv assessment loaded from Franklin region-viewer endpoints"},
|
| 939 |
+
},
|
| 940 |
+
},
|
| 941 |
+
"publications": {
|
| 942 |
+
"ok": True,
|
| 943 |
+
"status": 200,
|
| 944 |
+
"data": {
|
| 945 |
+
"genes": details_data.get("genes") or [],
|
| 946 |
+
"linkouts": details_data.get("linkouts") or [],
|
| 947 |
+
},
|
| 948 |
+
},
|
| 949 |
+
"gene_assessment": region_viewer_data,
|
| 950 |
+
"curated_gene_data": clinical_evidence,
|
| 951 |
+
"associated_conditions": summary,
|
| 952 |
+
"somatic_clinical_evidence": clinical_evidence,
|
| 953 |
+
"organization_assessments": org_assessments,
|
| 954 |
+
"my_organization_assessments": org_assessments,
|
| 955 |
+
"alternate_reference": alt_reference,
|
| 956 |
+
},
|
| 957 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 958 |
+
}
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
async def _get_cached_structural_variant_assessment(
|
| 962 |
+
query: str,
|
| 963 |
+
reference_version: str,
|
| 964 |
+
) -> dict[str, Any]:
|
| 965 |
+
context = _resolve_structural_variant_context(query, reference_version=reference_version)
|
| 966 |
+
if not context:
|
| 967 |
+
raise ValueError(f"Unable to resolve structural variant coordinates: {query}")
|
| 968 |
+
|
| 969 |
+
cached = _load_cached_sv_assessment(context.variant_key)
|
| 970 |
+
if cached and not _has_cacheable_sv_payload(cached["payload"]):
|
| 971 |
+
_delete_cached_sv_assessment(context.variant_key)
|
| 972 |
+
cached = None
|
| 973 |
+
if cached:
|
| 974 |
+
stale = _is_cache_stale(cached)
|
| 975 |
+
payload = _attach_cache_metadata(
|
| 976 |
+
cached["payload"],
|
| 977 |
+
source="local-cache",
|
| 978 |
+
stale=stale,
|
| 979 |
+
fetched_at=cached.get("fetched_at"),
|
| 980 |
+
)
|
| 981 |
+
if stale:
|
| 982 |
+
_start_sv_cache_refresh(context.variant_key, query, context.reference_label)
|
| 983 |
+
return payload
|
| 984 |
+
|
| 985 |
+
try:
|
| 986 |
+
fresh = await _fetch_structural_variant_assessment(context, query)
|
| 987 |
+
except Exception as exc:
|
| 988 |
+
logger.exception("SV Franklin fetch failed", extra={"query": query, "error": str(exc)})
|
| 989 |
+
fresh = {
|
| 990 |
+
"variant": {
|
| 991 |
+
"query": query,
|
| 992 |
+
"key": context.variant_key,
|
| 993 |
+
"chromosome": context.chrom_with_prefix,
|
| 994 |
+
"position": context.start,
|
| 995 |
+
"start": context.start,
|
| 996 |
+
"end": context.end,
|
| 997 |
+
"ref": "SV",
|
| 998 |
+
"alt": context.sv_type,
|
| 999 |
+
"hash_id": context.hash_id,
|
| 1000 |
+
"reference_version": context.reference_label,
|
| 1001 |
+
"sv_type": context.sv_type,
|
| 1002 |
+
"sv_length": context.sv_length,
|
| 1003 |
+
},
|
| 1004 |
+
"tabs": {
|
| 1005 |
+
"franklin_acmg_classification": {
|
| 1006 |
+
"ok": False,
|
| 1007 |
+
"status": 502,
|
| 1008 |
+
"data": {
|
| 1009 |
+
"variant_type": "SV",
|
| 1010 |
+
"sv_type": context.sv_type,
|
| 1011 |
+
"range_descriptor": f"{context.chrom_with_prefix}:{context.start}-{context.end}",
|
| 1012 |
+
"genes": [],
|
| 1013 |
+
"upstream_error": str(exc),
|
| 1014 |
+
},
|
| 1015 |
+
},
|
| 1016 |
+
"variant_assessment": {
|
| 1017 |
+
"summary": {
|
| 1018 |
+
"ok": False,
|
| 1019 |
+
"status": 502,
|
| 1020 |
+
"data": {
|
| 1021 |
+
"variant_type": "SV",
|
| 1022 |
+
"sv_type": context.sv_type,
|
| 1023 |
+
"range_descriptor": f"{context.chrom_with_prefix}:{context.start}-{context.end}",
|
| 1024 |
+
"genes": [],
|
| 1025 |
+
"upstream_error": str(exc),
|
| 1026 |
+
},
|
| 1027 |
+
},
|
| 1028 |
+
"region_viewer": {
|
| 1029 |
+
"presets": {"ok": True, "status": 200, "data": {"presets": []}},
|
| 1030 |
+
"region_data": {
|
| 1031 |
+
"ok": True,
|
| 1032 |
+
"status": 200,
|
| 1033 |
+
"data": {
|
| 1034 |
+
"variant_type": "SV",
|
| 1035 |
+
"sv_type": context.sv_type,
|
| 1036 |
+
"range": {
|
| 1037 |
+
"chromosome": context.chrom_with_prefix,
|
| 1038 |
+
"start": context.start,
|
| 1039 |
+
"end": context.end,
|
| 1040 |
+
"length": context.sv_length,
|
| 1041 |
+
},
|
| 1042 |
+
"genes_regions": None,
|
| 1043 |
+
"variant_details": {},
|
| 1044 |
+
},
|
| 1045 |
+
},
|
| 1046 |
+
},
|
| 1047 |
+
"franklin_community_frequency": {"occurrences": {"ok": False, "status": 502, "error": str(exc)}},
|
| 1048 |
+
"clinical_evidence": {"ok": False, "status": 502, "error": str(exc)},
|
| 1049 |
+
"predictions": {"ok": False, "status": 502, "error": str(exc)},
|
| 1050 |
+
"population_frequencies": {"ok": False, "status": 502, "error": str(exc)},
|
| 1051 |
+
"transcripts_and_references": {"ok": False, "status": 502, "error": str(exc)},
|
| 1052 |
+
"uploaded_files": {"ok": False, "status": 502, "error": str(exc)},
|
| 1053 |
+
"variant_details": {"ok": False, "status": 502, "error": str(exc)},
|
| 1054 |
+
"search_data": {"ok": False, "status": 502, "error": str(exc)},
|
| 1055 |
+
"warmup": {"ok": False, "status": 502, "error": str(exc)},
|
| 1056 |
+
},
|
| 1057 |
+
"publications": {"ok": False, "status": 502, "error": str(exc)},
|
| 1058 |
+
"gene_assessment": {"ok": False, "status": 502, "error": str(exc)},
|
| 1059 |
+
"curated_gene_data": {"ok": False, "status": 502, "error": str(exc)},
|
| 1060 |
+
"associated_conditions": {"ok": False, "status": 502, "error": str(exc)},
|
| 1061 |
+
"somatic_clinical_evidence": {"ok": False, "status": 502, "error": str(exc)},
|
| 1062 |
+
"organization_assessments": {"ok": False, "status": 502, "error": str(exc)},
|
| 1063 |
+
"my_organization_assessments": {"ok": False, "status": 502, "error": str(exc)},
|
| 1064 |
+
"alternate_reference": {"ok": False, "status": 502, "error": str(exc)},
|
| 1065 |
+
},
|
| 1066 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 1067 |
+
}
|
| 1068 |
+
if _has_cacheable_sv_payload(fresh):
|
| 1069 |
+
_save_cached_sv_assessment(context.variant_key, query, context.reference_label, fresh)
|
| 1070 |
+
return _attach_cache_metadata(
|
| 1071 |
+
fresh,
|
| 1072 |
+
source="franklin-live",
|
| 1073 |
+
stale=False,
|
| 1074 |
+
fetched_at=datetime.now(timezone.utc).isoformat(),
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
async def get_franklin_variant_assessment(
|
| 1079 |
+
query: str,
|
| 1080 |
+
reference_version: str = "hg19",
|
| 1081 |
+
) -> dict[str, Any]:
|
| 1082 |
+
parsed_query = parse_variant_query(query)
|
| 1083 |
+
if parsed_query.get("type") == "sv":
|
| 1084 |
+
sv_reference = parsed_query.get("reference_version") or reference_version or "hg38"
|
| 1085 |
+
return await _get_cached_structural_variant_assessment(query, str(sv_reference))
|
| 1086 |
+
|
| 1087 |
+
context = await _resolve_variant_context(query, reference_version=reference_version)
|
| 1088 |
+
if not context:
|
| 1089 |
+
raise ValueError(f"Unable to resolve variant coordinates: {query}")
|
| 1090 |
+
|
| 1091 |
+
async def _fetch_for_context(active_context: FranklinVariantContext) -> dict[str, Any]:
|
| 1092 |
+
payload = active_context.to_snp_payload()
|
| 1093 |
+
search_payload = {
|
| 1094 |
+
"search_data": {
|
| 1095 |
+
"search_session_id": "openvar",
|
| 1096 |
+
"search_input_text": query,
|
| 1097 |
+
"case_context": None,
|
| 1098 |
+
"snp_variant": {
|
| 1099 |
+
"chrom": active_context.chrom_with_prefix,
|
| 1100 |
+
"pos": active_context.position,
|
| 1101 |
+
"ref": active_context.ref,
|
| 1102 |
+
"alt": active_context.alt,
|
| 1103 |
+
"reference_version": reference_version,
|
| 1104 |
+
},
|
| 1105 |
+
}
|
| 1106 |
+
}
|
| 1107 |
+
community_params = {
|
| 1108 |
+
"ethnicities": "undefined",
|
| 1109 |
+
"phenotypes": "undefined",
|
| 1110 |
+
"sample_id": "null",
|
| 1111 |
+
"var_id": active_context.hash_id,
|
| 1112 |
+
"from_index": 0,
|
| 1113 |
+
"to_index": 2,
|
| 1114 |
+
"quick_filter": "undefined",
|
| 1115 |
+
"reference_version": reference_version,
|
| 1116 |
+
}
|
| 1117 |
+
|
| 1118 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 1119 |
+
(
|
| 1120 |
+
variant_details,
|
| 1121 |
+
search_data,
|
| 1122 |
+
warmup,
|
| 1123 |
+
summary,
|
| 1124 |
+
evidences,
|
| 1125 |
+
predictions,
|
| 1126 |
+
impacts,
|
| 1127 |
+
frequencies,
|
| 1128 |
+
region_presets,
|
| 1129 |
+
community_frequency,
|
| 1130 |
+
variant_matcher,
|
| 1131 |
+
alt_reference,
|
| 1132 |
+
publications,
|
| 1133 |
+
org_assessments,
|
| 1134 |
+
uploaded_files,
|
| 1135 |
+
) = await asyncio.gather(
|
| 1136 |
+
_franklin_request(client, "POST", "/api/fetch_variant_details", payload=payload),
|
| 1137 |
+
_franklin_request(client, "PUT", "/api/search_data", payload=search_payload),
|
| 1138 |
+
_franklin_request(client, "POST", "/api/warm_snp_data_json", payload=payload),
|
| 1139 |
+
_franklin_request(client, "POST", "/api/snp/fetch_summary", payload=payload),
|
| 1140 |
+
_franklin_request(client, "POST", "/api/fetch_evidences", payload=payload),
|
| 1141 |
+
_franklin_request(client, "POST", "/api/fetch_predictions", payload=payload),
|
| 1142 |
+
_franklin_request(client, "POST", "/api/fetch_impacts", payload=payload),
|
| 1143 |
+
_franklin_request(client, "POST", "/api/fetch_frequencies", payload=payload),
|
| 1144 |
+
_franklin_request(client, "GET", "/api/region_viewer/presets"),
|
| 1145 |
+
_franklin_request(client, "GET", "/api/affected_samples_data/fetch", params=community_params),
|
| 1146 |
+
_franklin_request(
|
| 1147 |
+
client,
|
| 1148 |
+
"POST",
|
| 1149 |
+
"/api/variant_matcher/search",
|
| 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 |
+
)
|
| 1162 |
+
|
| 1163 |
+
gene_symbol = _extract_gene_symbol(query, variant_details, impacts)
|
| 1164 |
+
region_params = {
|
| 1165 |
+
"chr": active_context.chrom_with_prefix,
|
| 1166 |
+
"start": max(active_context.position - 2018, 1),
|
| 1167 |
+
"end": active_context.position + 2018,
|
| 1168 |
+
"variant_position": active_context.position,
|
| 1169 |
+
"gene_symbol": gene_symbol or "",
|
| 1170 |
+
"reference_type": reference_version,
|
| 1171 |
+
}
|
| 1172 |
+
region_data = await _franklin_request(client, "GET", "/api/fetch_region_data", params=region_params)
|
| 1173 |
+
|
| 1174 |
+
return {
|
| 1175 |
+
"variant": {
|
| 1176 |
+
"query": query,
|
| 1177 |
+
"key": active_context.variant_key,
|
| 1178 |
+
"chromosome": active_context.chrom_with_prefix,
|
| 1179 |
+
"position": active_context.position,
|
| 1180 |
+
"ref": active_context.ref,
|
| 1181 |
+
"alt": active_context.alt,
|
| 1182 |
+
"hash_id": active_context.hash_id,
|
| 1183 |
+
"reference_version": reference_version,
|
| 1184 |
+
},
|
| 1185 |
+
"tabs": {
|
| 1186 |
+
"franklin_acmg_classification": summary,
|
| 1187 |
+
"variant_assessment": {
|
| 1188 |
+
"summary": summary,
|
| 1189 |
+
"region_viewer": {"presets": region_presets, "region_data": region_data},
|
| 1190 |
+
"franklin_community_frequency": {
|
| 1191 |
+
"affected_samples": community_frequency,
|
| 1192 |
+
"variant_matcher": variant_matcher,
|
| 1193 |
+
},
|
| 1194 |
+
"clinical_evidence": evidences,
|
| 1195 |
+
"predictions": predictions,
|
| 1196 |
+
"population_frequencies": frequencies,
|
| 1197 |
+
"transcripts_and_references": impacts,
|
| 1198 |
+
"uploaded_files": uploaded_files,
|
| 1199 |
+
"variant_details": variant_details,
|
| 1200 |
+
"search_data": search_data,
|
| 1201 |
+
"warmup": warmup,
|
| 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,
|
| 1210 |
+
"alternate_reference": alt_reference,
|
| 1211 |
+
},
|
| 1212 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 1213 |
+
}
|
| 1214 |
+
primary = await _fetch_for_context(context)
|
| 1215 |
+
|
| 1216 |
+
# If coordinate input accidentally carries GRCh38 position while asking for hg19,
|
| 1217 |
+
# probe liftover candidate and prefer the one with richer region/evidence payload.
|
| 1218 |
+
if reference_version.lower() in {"hg19", "grch37"} and parsed_query.get("type") == "coordinates":
|
| 1219 |
+
mapped_pos = await _map_grch38_to_grch37(context.chrom.replace("chr", ""), context.position)
|
| 1220 |
+
if mapped_pos and mapped_pos != context.position:
|
| 1221 |
+
alt_context = FranklinVariantContext(
|
| 1222 |
+
chrom=context.chrom.replace("chr", ""),
|
| 1223 |
+
position=mapped_pos,
|
| 1224 |
+
ref=context.ref,
|
| 1225 |
+
alt=context.alt,
|
| 1226 |
+
reference_version=context.reference_version,
|
| 1227 |
+
)
|
| 1228 |
+
alternative = await _fetch_for_context(alt_context)
|
| 1229 |
+
|
| 1230 |
+
def _score(payload: dict[str, Any]) -> int:
|
| 1231 |
+
score = 0
|
| 1232 |
+
region = (
|
| 1233 |
+
payload.get("tabs", {})
|
| 1234 |
+
.get("variant_assessment", {})
|
| 1235 |
+
.get("region_viewer", {})
|
| 1236 |
+
.get("region_data", {})
|
| 1237 |
+
.get("data", {})
|
| 1238 |
+
)
|
| 1239 |
+
evidence_count = len(region.get("evidence_variant_classifications", []) or [])
|
| 1240 |
+
transcript_count = len(region.get("data_by_transcript", []) or [])
|
| 1241 |
+
score += evidence_count * 2
|
| 1242 |
+
score += transcript_count
|
| 1243 |
+
summary = (
|
| 1244 |
+
payload.get("tabs", {})
|
| 1245 |
+
.get("variant_assessment", {})
|
| 1246 |
+
.get("summary", {})
|
| 1247 |
+
.get("data", {})
|
| 1248 |
+
.get("organization_classification", {})
|
| 1249 |
+
.get("classification")
|
| 1250 |
+
)
|
| 1251 |
+
if isinstance(summary, str) and summary and summary != "NONE":
|
| 1252 |
+
score += 20
|
| 1253 |
+
return score
|
| 1254 |
+
|
| 1255 |
+
if _score(alternative) > _score(primary):
|
| 1256 |
+
return alternative
|
| 1257 |
+
|
| 1258 |
+
return primary
|
| 1259 |
+
|
| 1260 |
+
|
| 1261 |
+
async def proxy_franklin_api(
|
| 1262 |
+
endpoint: str,
|
| 1263 |
+
method: str = "GET",
|
| 1264 |
+
payload: Any = None,
|
| 1265 |
+
params: Optional[dict[str, Any]] = None,
|
| 1266 |
+
) -> dict[str, Any]:
|
| 1267 |
+
if not endpoint.startswith("/api/"):
|
| 1268 |
+
raise ValueError("Only /api/* endpoints are allowed")
|
| 1269 |
+
if ".." in endpoint:
|
| 1270 |
+
raise ValueError("Invalid endpoint path")
|
| 1271 |
+
|
| 1272 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 1273 |
+
result = await _franklin_request(
|
| 1274 |
+
client,
|
| 1275 |
+
method,
|
| 1276 |
+
endpoint,
|
| 1277 |
+
payload=payload,
|
| 1278 |
+
params=params,
|
| 1279 |
+
)
|
| 1280 |
+
result["endpoint"] = endpoint
|
| 1281 |
+
result["method"] = method.upper()
|
| 1282 |
+
return result
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
async def parse_search_query_via_franklin(query: str, reference_version: str = "hg38") -> Optional[dict[str, Any]]:
|
| 1286 |
+
"""Use Franklin's parse_search API to resolve complex string queries."""
|
| 1287 |
+
payload = {
|
| 1288 |
+
"reference_version": reference_version.upper(),
|
| 1289 |
+
"search_text_input": query
|
| 1290 |
+
}
|
| 1291 |
+
async with httpx.AsyncClient(timeout=15.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 1292 |
+
try:
|
| 1293 |
+
result = await _franklin_request(
|
| 1294 |
+
client,
|
| 1295 |
+
"POST",
|
| 1296 |
+
"/api/parse_search",
|
| 1297 |
+
payload=payload
|
| 1298 |
+
)
|
| 1299 |
+
if result.get("ok"):
|
| 1300 |
+
return result.get("data")
|
| 1301 |
+
except Exception as e:
|
| 1302 |
+
logger.warning("Franklin parse_search failed for query %s: %s", query, str(e))
|
| 1303 |
+
return None
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
def _extract_gene_symbol(
|
| 1307 |
+
query: str,
|
| 1308 |
+
variant_details: dict[str, Any],
|
| 1309 |
+
impacts: dict[str, Any],
|
| 1310 |
+
) -> Optional[str]:
|
| 1311 |
+
if ":" in query:
|
| 1312 |
+
candidate = query.split(":", 1)[0].strip()
|
| 1313 |
+
if candidate and not candidate.lower().startswith("chr"):
|
| 1314 |
+
return candidate
|
| 1315 |
+
|
| 1316 |
+
for source in (variant_details, impacts):
|
| 1317 |
+
data = source.get("data")
|
| 1318 |
+
if not isinstance(data, dict):
|
| 1319 |
+
continue
|
| 1320 |
+
for key in ("gene_symbol", "gene", "symbol"):
|
| 1321 |
+
value = data.get(key)
|
| 1322 |
+
if isinstance(value, str) and value:
|
| 1323 |
+
return value
|
| 1324 |
+
|
| 1325 |
+
impacts_list = data.get("impacts")
|
| 1326 |
+
if isinstance(impacts_list, list) and impacts_list:
|
| 1327 |
+
first = impacts_list[0]
|
| 1328 |
+
if isinstance(first, dict):
|
| 1329 |
+
gene = first.get("gene_symbol") or first.get("gene")
|
| 1330 |
+
if isinstance(gene, str) and gene:
|
| 1331 |
+
return gene
|
| 1332 |
+
return None
|
app/services/variant_service.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
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
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
GENEBE_API = "https://api.genebe.net/cloud/api-public/v1/variant"
|
| 11 |
+
MYVARIANT_API = "http://myvariant.info/v1/variant"
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
logger.setLevel(logging.INFO)
|
| 14 |
+
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(
|
| 24 |
+
r"^(DEL|DUP|INS|INV|CNV|TRANS|BND):(?:chr)?([0-9]+|X|Y|MT|M):(\d+)-(\d+)$",
|
| 25 |
+
re.IGNORECASE,
|
| 26 |
+
)
|
| 27 |
+
SV_FRANKLIN_ID_REGEX = re.compile(
|
| 28 |
+
r"^(?:sv:)?(?:chr)?([0-9]+|X|Y|MT|M)-(\d+)-(\d+)-(DEL|DUP|INS|INV|CNV|TRANS|BND)(?:-(hg19|hg38|grch37|grch38))?$",
|
| 29 |
+
re.IGNORECASE,
|
| 30 |
+
)
|
| 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":
|
| 37 |
+
return "MT"
|
| 38 |
+
return value
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _chromosome_from_accession(accession: str) -> Optional[str]:
|
| 42 |
+
match = ACCESSION_REGEX.match(accession)
|
| 43 |
+
if not match:
|
| 44 |
+
return None
|
| 45 |
+
chrom_num = int(match.group(1))
|
| 46 |
+
if chrom_num == 23:
|
| 47 |
+
return "X"
|
| 48 |
+
if chrom_num == 24:
|
| 49 |
+
return "Y"
|
| 50 |
+
if chrom_num == 12920:
|
| 51 |
+
return "MT"
|
| 52 |
+
return str(chrom_num)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _parse_spdi(spdi: str) -> Optional[dict]:
|
| 56 |
+
parts = spdi.split(":")
|
| 57 |
+
if len(parts) != 4:
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
chrom = _chromosome_from_accession(parts[0])
|
| 61 |
+
if not chrom:
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
# SPDI uses 0-based interbase coordinates; GENEBE expects 1-based position.
|
| 65 |
+
return {
|
| 66 |
+
"chromosome": chrom,
|
| 67 |
+
"position": int(parts[1]) + 1,
|
| 68 |
+
"ref": parts[2],
|
| 69 |
+
"alt": parts[3],
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _parse_genomic_hgvs(value: str) -> Optional[dict]:
|
| 74 |
+
match = GENOMIC_HGVS_REGEX.match(value)
|
| 75 |
+
if not match:
|
| 76 |
+
return None
|
| 77 |
+
return {
|
| 78 |
+
"chromosome": _normalize_chromosome(match.group(1)),
|
| 79 |
+
"position": int(match.group(2)),
|
| 80 |
+
"ref": match.group(3).upper(),
|
| 81 |
+
"alt": match.group(4).upper(),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _collect_strings(payload) -> list[str]:
|
| 86 |
+
values = []
|
| 87 |
+
if isinstance(payload, str):
|
| 88 |
+
values.append(payload)
|
| 89 |
+
elif isinstance(payload, list):
|
| 90 |
+
for item in payload:
|
| 91 |
+
values.extend(_collect_strings(item))
|
| 92 |
+
elif isinstance(payload, dict):
|
| 93 |
+
for item in payload.values():
|
| 94 |
+
values.extend(_collect_strings(item))
|
| 95 |
+
return values
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _complement_dna(seq: str) -> str:
|
| 99 |
+
return seq.upper().translate(DNA_COMPLEMENT)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _parse_vep_to_coordinates(data: list, hgvs: str) -> Optional[dict]:
|
| 103 |
+
if not data or not isinstance(data, list):
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
for item in data:
|
| 107 |
+
if not isinstance(item, dict):
|
| 108 |
+
continue
|
| 109 |
+
chrom = item.get("seq_region_name")
|
| 110 |
+
pos = item.get("start")
|
| 111 |
+
allele_string = item.get("allele_string", "")
|
| 112 |
+
strand = item.get("strand")
|
| 113 |
+
if not chrom or not pos or "/" not in allele_string:
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
alleles = [a.upper() for a in allele_string.split("/") if a]
|
| 117 |
+
if len(alleles) < 2:
|
| 118 |
+
continue
|
| 119 |
+
ref = alleles[0]
|
| 120 |
+
alt = alleles[1]
|
| 121 |
+
|
| 122 |
+
# VEP HGVS can return alleles in transcript orientation for negative-strand transcripts.
|
| 123 |
+
# Convert to genomic forward strand before querying downstream services.
|
| 124 |
+
if strand == -1:
|
| 125 |
+
ref = _complement_dna(ref)
|
| 126 |
+
alt = _complement_dna(alt)
|
| 127 |
+
|
| 128 |
+
return {
|
| 129 |
+
"chromosome": _normalize_chromosome(str(chrom)),
|
| 130 |
+
"position": int(pos),
|
| 131 |
+
"ref": ref,
|
| 132 |
+
"alt": alt,
|
| 133 |
+
"source": "ensembl_vep",
|
| 134 |
+
"hgvs": hgvs,
|
| 135 |
+
}
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def parse_variant_query(query: str) -> dict:
|
| 140 |
+
"""Parse variant query string into components"""
|
| 141 |
+
query = query.strip()
|
| 142 |
+
if not query:
|
| 143 |
+
return {"type": "unknown", "value": query}
|
| 144 |
+
|
| 145 |
+
sv_match = SV_QUERY_REGEX.match(query)
|
| 146 |
+
if sv_match:
|
| 147 |
+
return {
|
| 148 |
+
"type": "sv",
|
| 149 |
+
"sv_type": sv_match.group(1).upper(),
|
| 150 |
+
"chromosome": _normalize_chromosome(sv_match.group(2)),
|
| 151 |
+
"start": int(sv_match.group(3)),
|
| 152 |
+
"end": int(sv_match.group(4)),
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
sv_franklin_match = SV_FRANKLIN_ID_REGEX.match(query)
|
| 156 |
+
if sv_franklin_match:
|
| 157 |
+
reference_version = sv_franklin_match.group(5)
|
| 158 |
+
return {
|
| 159 |
+
"type": "sv",
|
| 160 |
+
"sv_type": sv_franklin_match.group(4).upper(),
|
| 161 |
+
"chromosome": _normalize_chromosome(sv_franklin_match.group(1)),
|
| 162 |
+
"start": int(sv_franklin_match.group(2)),
|
| 163 |
+
"end": int(sv_franklin_match.group(3)),
|
| 164 |
+
"reference_version": reference_version.lower() if reference_version else None,
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
if query.startswith("rs"):
|
| 168 |
+
return {"type": "rsid", "value": query}
|
| 169 |
+
|
| 170 |
+
if ":" in query and ("c." in query or "g." in query or "p." in query):
|
| 171 |
+
return {"type": "hgvs", "value": query}
|
| 172 |
+
|
| 173 |
+
if "-" in query:
|
| 174 |
+
parts = query.replace("chr", "").split("-")
|
| 175 |
+
if len(parts) >= 4:
|
| 176 |
+
return {
|
| 177 |
+
"type": "coordinates",
|
| 178 |
+
"chromosome": parts[0],
|
| 179 |
+
"position": int(parts[1]),
|
| 180 |
+
"ref": parts[2],
|
| 181 |
+
"alt": parts[3]
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
return {"type": "unknown", "value": query}
|
| 185 |
+
|
| 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 |
+
encoded_hgvs = quote(hgvs, safe="")
|
| 190 |
+
|
| 191 |
+
# Prefer VEP HGVS endpoint: observed to be available in environments where
|
| 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 _parse_ensembl_response(response: httpx.Response) -> Optional[dict]:
|
| 214 |
+
logger.info("Ensembl recoder response", extra={"hgvs": hgvs, "status_code": response.status_code})
|
| 215 |
+
logger.debug("Ensembl recoder body: %s", response.text[:500])
|
| 216 |
+
|
| 217 |
+
if response.status_code != 200:
|
| 218 |
+
logger.warning(
|
| 219 |
+
"Ensembl recoder non-200",
|
| 220 |
+
extra={"hgvs": hgvs, "status_code": response.status_code, "body": response.text[:200]},
|
| 221 |
+
)
|
| 222 |
+
return None
|
| 223 |
+
|
| 224 |
+
data = response.json()
|
| 225 |
+
if not data or not isinstance(data, list):
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
for variant_data in data:
|
| 229 |
+
if not isinstance(variant_data, dict):
|
| 230 |
+
continue
|
| 231 |
+
string_values = _collect_strings(variant_data)
|
| 232 |
+
|
| 233 |
+
for value in string_values:
|
| 234 |
+
if value.startswith("NC_"):
|
| 235 |
+
parsed_spdi = _parse_spdi(value)
|
| 236 |
+
if parsed_spdi:
|
| 237 |
+
logger.info("Parsed HGVS via SPDI", extra={"hgvs": hgvs, "coords": parsed_spdi})
|
| 238 |
+
return parsed_spdi
|
| 239 |
+
|
| 240 |
+
for value in string_values:
|
| 241 |
+
parsed_hgvs = _parse_genomic_hgvs(value)
|
| 242 |
+
if parsed_hgvs:
|
| 243 |
+
logger.info("Parsed HGVS via genomic HGVS", extra={"hgvs": hgvs, "coords": parsed_hgvs})
|
| 244 |
+
return parsed_hgvs
|
| 245 |
+
return None
|
| 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 |
+
parsed = await _try_recoder_with_client(client, mode_label=f"primary_trust_env_{HTTPX_TRUST_ENV}")
|
| 303 |
+
if parsed:
|
| 304 |
+
return parsed
|
| 305 |
+
|
| 306 |
+
# If process environment proxy chain is unhealthy, retry without env proxy settings.
|
| 307 |
+
logger.info("Trying Ensembl direct fallback without env proxy for HGVS: %s", hgvs)
|
| 308 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as direct_client:
|
| 309 |
+
parsed = await _try_recoder_with_client(direct_client, mode_label="fallback_direct_no_env_proxy")
|
| 310 |
+
if parsed:
|
| 311 |
+
return parsed
|
| 312 |
+
|
| 313 |
+
logger.warning("Failed to convert HGVS to coordinates", extra={"hgvs": hgvs})
|
| 314 |
+
return None
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
async def annotate_variant(variant_id: str) -> Optional[VariantResponse]:
|
| 318 |
+
"""Annotate a single variant using external API"""
|
| 319 |
+
parsed = parse_variant_query(variant_id)
|
| 320 |
+
|
| 321 |
+
async with httpx.AsyncClient(timeout=30.0, trust_env=HTTPX_TRUST_ENV) as client:
|
| 322 |
+
try:
|
| 323 |
+
if parsed["type"] == "coordinates":
|
| 324 |
+
params = {
|
| 325 |
+
"chr": parsed["chromosome"],
|
| 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 |
+
franklin_parsed = await parse_search_query_via_franklin(query, genome_build)
|
| 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"):
|
| 356 |
+
parsed = {
|
| 357 |
+
"type": "coordinates",
|
| 358 |
+
"chromosome": str(best["chrom"]).replace("chr", ""),
|
| 359 |
+
"position": int(best["pos"]),
|
| 360 |
+
"ref": best.get("ref", ""),
|
| 361 |
+
"alt": best.get("alt", "")
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
logger.info("Search variants", extra={"query": query, "parsed_type": parsed.get("type"), "genome_build": genome_build})
|
| 365 |
+
|
| 366 |
+
results = []
|
| 367 |
+
|
| 368 |
+
logger.info("Using HTTPX trust_env setting", extra={"trust_env": HTTPX_TRUST_ENV})
|
| 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)
|
| 376 |
+
|
| 377 |
+
elif parsed["type"] == "hgvs":
|
| 378 |
+
coords = await hgvs_to_coordinates(parsed["value"], client)
|
| 379 |
+
if coords and coords.get("chromosome"):
|
| 380 |
+
parsed_coords = {
|
| 381 |
+
"type": "coordinates",
|
| 382 |
+
"chromosome": coords["chromosome"],
|
| 383 |
+
"position": coords["position"],
|
| 384 |
+
"ref": coords["ref"],
|
| 385 |
+
"alt": coords["alt"]
|
| 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}")
|
| 409 |
+
|
| 410 |
+
elif parsed["type"] == "rsid":
|
| 411 |
+
pass
|
| 412 |
+
|
| 413 |
+
elif parsed["type"] == "sv":
|
| 414 |
+
chrom = parsed["chromosome"]
|
| 415 |
+
start = int(parsed["start"])
|
| 416 |
+
end = int(parsed["end"])
|
| 417 |
+
sv_type = parsed["sv_type"].upper()
|
| 418 |
+
sv_id = f"chr{chrom}-{start}-{end}-{sv_type}-{genome_build.lower()}"
|
| 419 |
+
results.append(
|
| 420 |
+
VariantResponse(
|
| 421 |
+
variant=VariantInfo(
|
| 422 |
+
id=sv_id,
|
| 423 |
+
chromosome=chrom,
|
| 424 |
+
position=start,
|
| 425 |
+
ref="N",
|
| 426 |
+
alt=sv_type,
|
| 427 |
+
),
|
| 428 |
+
consequences={
|
| 429 |
+
"variant_type": "SV",
|
| 430 |
+
"sv_type": sv_type,
|
| 431 |
+
"start": start,
|
| 432 |
+
"end": end,
|
| 433 |
+
"genome_build": genome_build,
|
| 434 |
+
},
|
| 435 |
+
)
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
return results
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def build_variant_response(data: dict, parsed: dict) -> VariantResponse:
|
| 442 |
+
"""Build VariantResponse from API data"""
|
| 443 |
+
consequences = data.get("consequences", [])
|
| 444 |
+
first_consequence = consequences[0] if isinstance(consequences, list) and consequences else {}
|
| 445 |
+
|
| 446 |
+
variant_info = VariantInfo(
|
| 447 |
+
id=f"{parsed.get('chromosome', '')}-{parsed.get('position', '')}-{parsed.get('ref', '')}-{parsed.get('alt', '')}",
|
| 448 |
+
chromosome=parsed.get("chromosome", ""),
|
| 449 |
+
position=parsed.get("position", 0),
|
| 450 |
+
ref=parsed.get("ref", ""),
|
| 451 |
+
alt=parsed.get("alt", ""),
|
| 452 |
+
gene=data.get("gene_symbol"),
|
| 453 |
+
transcript=first_consequence.get("mane_select") if first_consequence else None,
|
| 454 |
+
protein_change=first_consequence.get("protein_change") if first_consequence else None,
|
| 455 |
+
hgvs_c=first_consequence.get("hgvs_c") if first_consequence else None,
|
| 456 |
+
hgvs_p=first_consequence.get("hgvs_p") if first_consequence else None
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
clinvar = None
|
| 460 |
+
if data.get("clinvar_classification"):
|
| 461 |
+
clinvar = ClinVarInfo(
|
| 462 |
+
classification=data.get("clinvar_classification"),
|
| 463 |
+
disease=data.get("clinvar_disease"),
|
| 464 |
+
accession=data.get("clinvar_accession")
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
gnomad = None
|
| 468 |
+
if data.get("gnomad_exomes_af") or data.get("gnomad_genomes_af"):
|
| 469 |
+
gnomad = GnomADInfo(
|
| 470 |
+
exomes_af=data.get("gnomad_exomes_af"),
|
| 471 |
+
genomes_af=data.get("gnomad_genomes_af"),
|
| 472 |
+
exomes_ac=data.get("gnomad_exomes_ac"),
|
| 473 |
+
genomes_ac=data.get("gnomad_genomes_ac")
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
acmg = None
|
| 477 |
+
if data.get("acmg_classification"):
|
| 478 |
+
acmg_class = data.get("acmg_classification", "").replace("_", " ")
|
| 479 |
+
acmg = ACMGInfo(
|
| 480 |
+
classification=acmg_class,
|
| 481 |
+
criteria=data.get("acmg_criteria")
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
return VariantResponse(
|
| 485 |
+
variant=variant_info,
|
| 486 |
+
clinvar=clinvar,
|
| 487 |
+
gnomad=gnomad,
|
| 488 |
+
acmg=acmg,
|
| 489 |
+
consequences=first_consequence
|
| 490 |
+
)
|
assessment_test.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
create_superadmin.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.database import SessionLocal
|
| 2 |
+
from app.models.db import User, UserType
|
| 3 |
+
from app.services.auth_service import hash_password
|
| 4 |
+
|
| 5 |
+
def setup():
|
| 6 |
+
db = SessionLocal()
|
| 7 |
+
existing = db.query(User).filter(User.email == "admin@openvar.io").first()
|
| 8 |
+
if not existing:
|
| 9 |
+
su = User(
|
| 10 |
+
email="admin@openvar.io",
|
| 11 |
+
hashed_password=hash_password("admin"),
|
| 12 |
+
full_name="OpenVar Admin",
|
| 13 |
+
user_type=UserType.enterprise,
|
| 14 |
+
is_superadmin=True,
|
| 15 |
+
)
|
| 16 |
+
db.add(su)
|
| 17 |
+
db.commit()
|
| 18 |
+
print("Admin created")
|
| 19 |
+
else:
|
| 20 |
+
print("Admin exists")
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
setup()
|
database_schema.sql
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- OpenVar Database Schema (Simplified - No Supabase Auth)
|
| 2 |
+
|
| 3 |
+
-- Genes table (public reference data)
|
| 4 |
+
CREATE TABLE IF NOT EXISTS public.genes (
|
| 5 |
+
id SERIAL PRIMARY KEY,
|
| 6 |
+
symbol VARCHAR(50) UNIQUE NOT NULL,
|
| 7 |
+
name VARCHAR(500),
|
| 8 |
+
chromosome VARCHAR(10),
|
| 9 |
+
start_position BIGINT,
|
| 10 |
+
end_position BIGINT,
|
| 11 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 12 |
+
);
|
| 13 |
+
|
| 14 |
+
-- Variants table (user-saved variants) - without user_id for now
|
| 15 |
+
CREATE TABLE IF NOT EXISTS public.variants (
|
| 16 |
+
id SERIAL PRIMARY KEY,
|
| 17 |
+
chromosome VARCHAR(10) NOT NULL,
|
| 18 |
+
position BIGINT NOT NULL,
|
| 19 |
+
ref VARCHAR(500) NOT NULL,
|
| 20 |
+
alt VARCHAR(500) NOT NULL,
|
| 21 |
+
gene_symbol VARCHAR(50),
|
| 22 |
+
classification VARCHAR(50),
|
| 23 |
+
notes TEXT,
|
| 24 |
+
is_followed BOOLEAN DEFAULT FALSE,
|
| 25 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
| 26 |
+
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 27 |
+
);
|
| 28 |
+
|
| 29 |
+
-- Variant classifications history
|
| 30 |
+
CREATE TABLE IF NOT EXISTS public.variant_classifications (
|
| 31 |
+
id SERIAL PRIMARY KEY,
|
| 32 |
+
variant_id INTEGER REFERENCES public.variants(id) ON DELETE CASCADE,
|
| 33 |
+
classification VARCHAR(50) NOT NULL,
|
| 34 |
+
criteria TEXT,
|
| 35 |
+
source VARCHAR(50),
|
| 36 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 37 |
+
);
|
| 38 |
+
|
| 39 |
+
-- Panels table
|
| 40 |
+
CREATE TABLE IF NOT EXISTS public.panels (
|
| 41 |
+
id SERIAL PRIMARY KEY,
|
| 42 |
+
name VARCHAR(255) NOT NULL,
|
| 43 |
+
description TEXT,
|
| 44 |
+
is_default BOOLEAN DEFAULT FALSE,
|
| 45 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 46 |
+
);
|
| 47 |
+
|
| 48 |
+
-- Panel genes (many-to-many)
|
| 49 |
+
CREATE TABLE IF NOT EXISTS public.panel_genes (
|
| 50 |
+
panel_id INTEGER REFERENCES public.panels(id) ON DELETE CASCADE,
|
| 51 |
+
gene_symbol VARCHAR(50) NOT NULL,
|
| 52 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
| 53 |
+
PRIMARY KEY (panel_id, gene_symbol)
|
| 54 |
+
);
|
| 55 |
+
|
| 56 |
+
-- Indexes
|
| 57 |
+
CREATE INDEX IF NOT EXISTS idx_variants_chromosome_position ON public.variants(chromosome, position);
|
| 58 |
+
CREATE INDEX IF NOT EXISTS idx_variants_gene ON public.variants(gene_symbol);
|
| 59 |
+
CREATE INDEX IF NOT EXISTS idx_genes_symbol ON public.genes(symbol);
|
| 60 |
+
|
| 61 |
+
-- Enable RLS
|
| 62 |
+
ALTER TABLE public.genes ENABLE ROW LEVEL SECURITY;
|
| 63 |
+
ALTER TABLE public.variants ENABLE ROW LEVEL SECURITY;
|
| 64 |
+
ALTER TABLE public.variant_classifications ENABLE ROW LEVEL SECURITY;
|
| 65 |
+
ALTER TABLE public.panels ENABLE ROW LEVEL SECURITY;
|
| 66 |
+
ALTER TABLE public.panel_genes ENABLE ROW LEVEL SECURITY;
|
| 67 |
+
|
| 68 |
+
-- RLS Policies
|
| 69 |
+
CREATE POLICY "Anyone can read genes" ON public.genes FOR SELECT USING (true);
|
| 70 |
+
CREATE POLICY "Anyone can read variants" ON public.variants FOR SELECT USING (true);
|
| 71 |
+
CREATE POLICY "Anyone can read panels" ON public.panels FOR SELECT USING (true);
|
| 72 |
+
|
| 73 |
+
-- Insert default genes
|
| 74 |
+
INSERT INTO public.genes (symbol, name, chromosome) VALUES
|
| 75 |
+
('TP53', 'Tumor protein p53', '17'),
|
| 76 |
+
('BRCA1', 'BRCA1 DNA repair associated', '17'),
|
| 77 |
+
('BRCA2', 'BRCA2 DNA repair associated', '13'),
|
| 78 |
+
('MLH1', 'MutL homolog 1', '3'),
|
| 79 |
+
('MSH2', 'MutS homolog 2', '2'),
|
| 80 |
+
('MSH6', 'MutS homolog 6', '2'),
|
| 81 |
+
('PMS2', 'PMS1 homolog 2', '7'),
|
| 82 |
+
('APC', 'Adenomatous polyposis coli', '5'),
|
| 83 |
+
('RYR1', 'Ryanodine receptor 1', '19'),
|
| 84 |
+
('RYR2', 'Ryanodine receptor 2', '1'),
|
| 85 |
+
('KCNQ1', 'Potassium voltage-gated channel subfamily Q member 1', '11'),
|
| 86 |
+
('MYBPC3', 'Myosin binding protein C3', '11'),
|
| 87 |
+
('MYH7', 'Myosin heavy chain 7', '14'),
|
| 88 |
+
('SCN5A', 'Sodium voltage-gated channel alpha subunit 5', '3')
|
| 89 |
+
ON CONFLICT (symbol) DO NOTHING;
|
database_schema_neon.sql
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- OpenVar Database Schema for Neon PostgreSQL
|
| 2 |
+
|
| 3 |
+
-- Genes table (public reference data)
|
| 4 |
+
CREATE TABLE IF NOT EXISTS genes (
|
| 5 |
+
id SERIAL PRIMARY KEY,
|
| 6 |
+
symbol VARCHAR(50) UNIQUE NOT NULL,
|
| 7 |
+
name VARCHAR(500),
|
| 8 |
+
chromosome VARCHAR(10),
|
| 9 |
+
start_position BIGINT,
|
| 10 |
+
end_position BIGINT,
|
| 11 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 12 |
+
);
|
| 13 |
+
|
| 14 |
+
-- Variants table (user-saved variants)
|
| 15 |
+
CREATE TABLE IF NOT EXISTS variants (
|
| 16 |
+
id SERIAL PRIMARY KEY,
|
| 17 |
+
chromosome VARCHAR(10) NOT NULL,
|
| 18 |
+
position BIGINT NOT NULL,
|
| 19 |
+
ref VARCHAR(500) NOT NULL,
|
| 20 |
+
alt VARCHAR(500) NOT NULL,
|
| 21 |
+
gene_symbol VARCHAR(50),
|
| 22 |
+
classification VARCHAR(50),
|
| 23 |
+
notes TEXT,
|
| 24 |
+
is_followed BOOLEAN DEFAULT FALSE,
|
| 25 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
| 26 |
+
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 27 |
+
);
|
| 28 |
+
|
| 29 |
+
-- Variant classifications history
|
| 30 |
+
CREATE TABLE IF NOT EXISTS variant_classifications (
|
| 31 |
+
id SERIAL PRIMARY KEY,
|
| 32 |
+
variant_id INTEGER REFERENCES variants(id) ON DELETE CASCADE,
|
| 33 |
+
classification VARCHAR(50) NOT NULL,
|
| 34 |
+
criteria TEXT,
|
| 35 |
+
source VARCHAR(50),
|
| 36 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 37 |
+
);
|
| 38 |
+
|
| 39 |
+
-- Panels table
|
| 40 |
+
CREATE TABLE IF NOT EXISTS panels (
|
| 41 |
+
id SERIAL PRIMARY KEY,
|
| 42 |
+
name VARCHAR(255) NOT NULL,
|
| 43 |
+
description TEXT,
|
| 44 |
+
is_default BOOLEAN DEFAULT FALSE,
|
| 45 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
| 46 |
+
);
|
| 47 |
+
|
| 48 |
+
-- Panel genes (many-to-many)
|
| 49 |
+
CREATE TABLE IF NOT EXISTS panel_genes (
|
| 50 |
+
panel_id INTEGER REFERENCES panels(id) ON DELETE CASCADE,
|
| 51 |
+
gene_symbol VARCHAR(50) NOT NULL,
|
| 52 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
| 53 |
+
PRIMARY KEY (panel_id, gene_symbol)
|
| 54 |
+
);
|
| 55 |
+
|
| 56 |
+
-- Indexes
|
| 57 |
+
CREATE INDEX idx_variants_chromosome_position ON variants(chromosome, position);
|
| 58 |
+
CREATE INDEX idx_variants_gene ON variants(gene_symbol);
|
| 59 |
+
CREATE INDEX idx_genes_symbol ON genes(symbol);
|
| 60 |
+
|
| 61 |
+
-- Insert default genes
|
| 62 |
+
INSERT INTO genes (symbol, name, chromosome) VALUES
|
| 63 |
+
('TP53', 'Tumor protein p53', '17'),
|
| 64 |
+
('BRCA1', 'BRCA1 DNA repair associated', '17'),
|
| 65 |
+
('BRCA2', 'BRCA2 DNA repair associated', '13'),
|
| 66 |
+
('MLH1', 'MutL homolog 1', '3'),
|
| 67 |
+
('MSH2', 'MutS homolog 2', '2'),
|
| 68 |
+
('MSH6', 'MutS homolog 6', '2'),
|
| 69 |
+
('PMS2', 'PMS1 homolog 2', '7'),
|
| 70 |
+
('APC', 'Adenomatous polyposis coli', '5'),
|
| 71 |
+
('RYR1', 'Ryanodine receptor 1', '19'),
|
| 72 |
+
('RYR2', 'Ryanodine receptor 2', '1'),
|
| 73 |
+
('KCNQ1', 'Potassium voltage-gated channel subfamily Q member 1', '11'),
|
| 74 |
+
('MYBPC3', 'Myosin binding protein C3', '11'),
|
| 75 |
+
('MYH7', 'Myosin heavy chain 7', '14'),
|
| 76 |
+
('SCN5A', 'Sodium voltage-gated channel alpha subunit 5', '3')
|
| 77 |
+
ON CONFLICT (symbol) DO NOTHING;
|
pytest.ini
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
testpaths = tests
|
| 3 |
+
python_files = test_*.py
|
| 4 |
+
python_classes = Test*
|
| 5 |
+
python_functions = test_*
|
requirements-test.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytest==7.4.4
|
| 2 |
+
httpx==0.26.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.109.0
|
| 2 |
+
uvicorn[standard]>=0.27.0
|
| 3 |
+
pydantic>=2.5.0
|
| 4 |
+
pydantic-settings>=2.1.0
|
| 5 |
+
sqlalchemy>=2.0.0
|
| 6 |
+
psycopg2-binary>=2.9.0
|
| 7 |
+
python-jose[cryptography]>=3.3.0
|
| 8 |
+
passlib[bcrypt]>=1.7.4
|
| 9 |
+
python-multipart>=0.0.6
|
| 10 |
+
httpx>=0.26.0
|
| 11 |
+
supabase>=2.0.0
|
| 12 |
+
python-dotenv>=1.0.0
|
scripts/prime_franklin_sv_cache.sh
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
usage() {
|
| 5 |
+
cat <<'EOF'
|
| 6 |
+
Usage:
|
| 7 |
+
prime_franklin_sv_cache.sh <query> [reference_version]
|
| 8 |
+
|
| 9 |
+
Examples:
|
| 10 |
+
prime_franklin_sv_cache.sh 'DUP:Chr5:125423848-128107072' hg38
|
| 11 |
+
prime_franklin_sv_cache.sh 'chr5-125423848-128107072-DUP-hg38'
|
| 12 |
+
|
| 13 |
+
This script fetches Franklin SV public payloads with shell curl and writes a
|
| 14 |
+
cache entry into backend/data/franklin_cache.sqlite3. It is a manual fallback
|
| 15 |
+
for environments where the Python runtime cannot resolve Franklin hosts.
|
| 16 |
+
EOF
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" || $# -lt 1 ]]; then
|
| 20 |
+
usage
|
| 21 |
+
exit 0
|
| 22 |
+
fi
|
| 23 |
+
|
| 24 |
+
query="$1"
|
| 25 |
+
requested_reference="${2:-}"
|
| 26 |
+
|
| 27 |
+
chrom=""
|
| 28 |
+
start=""
|
| 29 |
+
end=""
|
| 30 |
+
sv_type=""
|
| 31 |
+
reference_version=""
|
| 32 |
+
|
| 33 |
+
normalize_ref() {
|
| 34 |
+
local value="${1:-}"
|
| 35 |
+
value="$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')"
|
| 36 |
+
case "$value" in
|
| 37 |
+
hg19|grch37) echo "hg19" ;;
|
| 38 |
+
hg38|grch38|"") echo "hg38" ;;
|
| 39 |
+
*)
|
| 40 |
+
echo "Unsupported reference_version: $1" >&2
|
| 41 |
+
exit 1
|
| 42 |
+
;;
|
| 43 |
+
esac
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
if [[ "$query" =~ ^([Dd][Ee][Ll]|[Dd][Uu][Pp]|[Ii][Nn][Ss]|[Ii][Nn][Vv]|[Cc][Nn][Vv]|[Bb][Nn][Dd]|[Tt][Rr][Aa]|[Ll][Oo][Ss][Ss]|[Gg][Aa][Ii][Nn]):[Cc][Hh][Rr]?([0-9XYMxy]+):([0-9]+)-([0-9]+)$ ]]; then
|
| 47 |
+
sv_type="$(printf '%s' "${BASH_REMATCH[1]}" | tr '[:lower:]' '[:upper:]')"
|
| 48 |
+
chrom="$(printf '%s' "${BASH_REMATCH[2]}" | tr '[:lower:]' '[:upper:]')"
|
| 49 |
+
start="${BASH_REMATCH[3]}"
|
| 50 |
+
end="${BASH_REMATCH[4]}"
|
| 51 |
+
reference_version="$(normalize_ref "$requested_reference")"
|
| 52 |
+
elif [[ "$query" =~ ^[Cc][Hh][Rr]?([0-9XYMxy]+)-([0-9]+)-([0-9]+)-([A-Za-z]+)(-(hg19|hg38|grch37|grch38))?$ ]]; then
|
| 53 |
+
chrom="$(printf '%s' "${BASH_REMATCH[1]}" | tr '[:lower:]' '[:upper:]')"
|
| 54 |
+
start="${BASH_REMATCH[2]}"
|
| 55 |
+
end="${BASH_REMATCH[3]}"
|
| 56 |
+
sv_type="$(printf '%s' "${BASH_REMATCH[4]}" | tr '[:lower:]' '[:upper:]')"
|
| 57 |
+
embedded_ref="${BASH_REMATCH[6]:-}"
|
| 58 |
+
reference_version="$(normalize_ref "${requested_reference:-$embedded_ref}")"
|
| 59 |
+
else
|
| 60 |
+
echo "Unsupported SV query format: $query" >&2
|
| 61 |
+
exit 1
|
| 62 |
+
fi
|
| 63 |
+
|
| 64 |
+
chrom_prefixed="chr${chrom}"
|
| 65 |
+
cache_key="${chrom_prefixed}-${start}-${end}-${sv_type}-${reference_version}"
|
| 66 |
+
query="${query}"
|
| 67 |
+
|
| 68 |
+
span=$(( end - start ))
|
| 69 |
+
if (( span < 1 )); then
|
| 70 |
+
span=1
|
| 71 |
+
fi
|
| 72 |
+
padding="$(awk -v span="$span" 'BEGIN { printf "%d", (span * 0.338249) + 0.5 }')"
|
| 73 |
+
if (( padding < 1 )); then
|
| 74 |
+
padding=1
|
| 75 |
+
fi
|
| 76 |
+
view_start=$(( start - padding ))
|
| 77 |
+
view_end=$(( end + padding ))
|
| 78 |
+
if (( view_start < 1 )); then
|
| 79 |
+
view_start=1
|
| 80 |
+
fi
|
| 81 |
+
bucket_start=$(( view_start / 1000000 - 1 ))
|
| 82 |
+
bucket_end=$(( view_end / 1000000 + 1 ))
|
| 83 |
+
if (( bucket_start < 1 )); then
|
| 84 |
+
bucket_start=1
|
| 85 |
+
fi
|
| 86 |
+
if (( bucket_end < bucket_start )); then
|
| 87 |
+
bucket_end="$bucket_start"
|
| 88 |
+
fi
|
| 89 |
+
buckets_json="$(seq "$bucket_start" "$bucket_end" | jq -R . | jq -s 'map(select(length > 0) | tonumber)')"
|
| 90 |
+
|
| 91 |
+
workdir="$(mktemp -d)"
|
| 92 |
+
trap 'rm -rf "$workdir"' EXIT
|
| 93 |
+
|
| 94 |
+
fetch_response() {
|
| 95 |
+
local method="$1"
|
| 96 |
+
local url="$2"
|
| 97 |
+
local body_path="$3"
|
| 98 |
+
local status_path="$4"
|
| 99 |
+
local payload_path="${5:-}"
|
| 100 |
+
|
| 101 |
+
if [[ "$method" == "POST" ]]; then
|
| 102 |
+
curl -sS -L --max-time 30 \
|
| 103 |
+
-H 'Accept: application/json' \
|
| 104 |
+
-H 'Content-Type: application/json' \
|
| 105 |
+
-X POST \
|
| 106 |
+
--data "@${payload_path}" \
|
| 107 |
+
-o "$body_path" \
|
| 108 |
+
-w '%{http_code}' \
|
| 109 |
+
"$url" > "$status_path"
|
| 110 |
+
else
|
| 111 |
+
curl -sS -L --max-time 30 \
|
| 112 |
+
-H 'Accept: application/json' \
|
| 113 |
+
-o "$body_path" \
|
| 114 |
+
-w '%{http_code}' \
|
| 115 |
+
"$url" > "$status_path"
|
| 116 |
+
fi
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
cat > "${workdir}/region_payload.json" <<EOF
|
| 120 |
+
{
|
| 121 |
+
"chr": "${chrom_prefixed}",
|
| 122 |
+
"sv_variant_start": ${start},
|
| 123 |
+
"sv_variant_end": ${end},
|
| 124 |
+
"sv_type": "${sv_type}",
|
| 125 |
+
"tier": "TIER_3",
|
| 126 |
+
"reference_type": "${reference_version}",
|
| 127 |
+
"reference_version": "${reference_version}",
|
| 128 |
+
"buckets": ${buckets_json},
|
| 129 |
+
"tracks": ["EXONS", "GENES", "GENE_DOSAGE_SENSITIVITY", "SV_EVIDENCES", "DGV", "DGV_GOLD", "GNOMAD"]
|
| 130 |
+
}
|
| 131 |
+
EOF
|
| 132 |
+
|
| 133 |
+
cat > "${workdir}/uploaded_payload.json" <<EOF
|
| 134 |
+
{"var_id":"${cache_key}"}
|
| 135 |
+
EOF
|
| 136 |
+
|
| 137 |
+
cat > "${workdir}/clingen_payload.json" <<EOF
|
| 138 |
+
{
|
| 139 |
+
"variant": {
|
| 140 |
+
"chrom": "${chrom_prefixed}",
|
| 141 |
+
"start": ${start},
|
| 142 |
+
"end": ${end},
|
| 143 |
+
"sv_type": "${sv_type}",
|
| 144 |
+
"ci_pos": {"start": 0, "end": 0},
|
| 145 |
+
"ci_end": {"start": 0, "end": 0},
|
| 146 |
+
"reference_version": "${reference_version}"
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
EOF
|
| 150 |
+
|
| 151 |
+
fetch_response "GET" "https://franklin.genoox.com/api/fetch_sv_details?chr=${chrom_prefixed}&start_pos=${start}&end_pos=${end}&sv_type=${sv_type}&ci_pos=&ci_end=&var_type=sv&version=&analysis_id=&reference_version=${reference_version}" "${workdir}/details.body" "${workdir}/details.status"
|
| 152 |
+
fetch_response "GET" "https://franklin.genoox.com/api/region_viewer/presets" "${workdir}/presets.body" "${workdir}/presets.status"
|
| 153 |
+
fetch_response "GET" "https://franklin.genoox.com/api/cytobands/by_chromosome?chr=${chrom_prefixed}&reference_version=${reference_version}" "${workdir}/cytobands.body" "${workdir}/cytobands.status"
|
| 154 |
+
fetch_response "GET" "https://franklin.genoox.com/api/sv/summary/carrier_status?chr=${chrom_prefixed}&start_pos=${start}&end_pos=${end}&sv_type=${sv_type}&zygosity=undefined&phenotypes=undefined&reference_version=${reference_version}" "${workdir}/carrier.body" "${workdir}/carrier.status"
|
| 155 |
+
fetch_response "GET" "https://franklin.genoox.com/api/sv/fetch_evidences?chr=${chrom_prefixed}&start_pos=${start}&end_pos=${end}&sv_type=${sv_type}&ci_pos=&ci_end=&var_type=sv&version=&analysis_id=&reference_version=${reference_version}" "${workdir}/clinical.body" "${workdir}/clinical.status"
|
| 156 |
+
fetch_response "POST" "https://franklin.genoox.com/api/get_region_data" "${workdir}/region.body" "${workdir}/region.status" "${workdir}/region_payload.json"
|
| 157 |
+
fetch_response "GET" "https://franklin.genoox.com/api/fetch_sv_alt_reference_variant?chr=${chrom_prefixed}&start_pos=${start}&end_pos=${end}&sv_type=${sv_type}&ci_pos=&ci_end=&var_type=sv&version=&analysis_id=&reference_version=${reference_version}" "${workdir}/alt.body" "${workdir}/alt.status"
|
| 158 |
+
fetch_response "GET" "https://franklin.genoox.com/api/org/sv_interpretation?chr=${chrom_prefixed}&start_pos=${start}&end_pos=${end}&sv_type=${sv_type}&ci_pos=&ci_end=&var_type=sv&version=&analysis_id=&reference_version=${reference_version}" "${workdir}/org.body" "${workdir}/org.status"
|
| 159 |
+
fetch_response "POST" "https://franklin.genoox.com/api/organization/variant/attachment/list" "${workdir}/uploaded.body" "${workdir}/uploaded.status" "${workdir}/uploaded_payload.json"
|
| 160 |
+
fetch_response "POST" "https://franklin.genoox.com/api/sv/clingen_classify" "${workdir}/clingen.body" "${workdir}/clingen.status" "${workdir}/clingen_payload.json"
|
| 161 |
+
|
| 162 |
+
source_assembly="GRCh38"
|
| 163 |
+
target_assembly="GRCh37"
|
| 164 |
+
target_label="HG19"
|
| 165 |
+
link_suffix=""
|
| 166 |
+
if [[ "$reference_version" == "hg19" ]]; then
|
| 167 |
+
source_assembly="GRCh37"
|
| 168 |
+
target_assembly="GRCh38"
|
| 169 |
+
target_label="HG38"
|
| 170 |
+
link_suffix="-hg38"
|
| 171 |
+
fi
|
| 172 |
+
fetch_response "GET" "https://rest.ensembl.org/map/human/${source_assembly}/${chrom}:${start}..${end}:1/${target_assembly}?content-type=application/json" "${workdir}/map.body" "${workdir}/map.status"
|
| 173 |
+
|
| 174 |
+
db_path="${FRANKLIN_CACHE_DB_PATH:-$(cd "$(dirname "$0")/.." && pwd)/data/franklin_cache.sqlite3}"
|
| 175 |
+
|
| 176 |
+
python - <<'PY' "$workdir" "$db_path" "$cache_key" "$query" "$reference_version" "$chrom_prefixed" "$start" "$end" "$sv_type"
|
| 177 |
+
import json
|
| 178 |
+
import sqlite3
|
| 179 |
+
import sys
|
| 180 |
+
from datetime import datetime, timezone
|
| 181 |
+
from pathlib import Path
|
| 182 |
+
|
| 183 |
+
workdir = Path(sys.argv[1])
|
| 184 |
+
db_path = Path(sys.argv[2])
|
| 185 |
+
cache_key = sys.argv[3]
|
| 186 |
+
query = sys.argv[4]
|
| 187 |
+
reference_version = sys.argv[5]
|
| 188 |
+
chrom = sys.argv[6]
|
| 189 |
+
start = int(sys.argv[7])
|
| 190 |
+
end = int(sys.argv[8])
|
| 191 |
+
sv_type = sys.argv[9]
|
| 192 |
+
|
| 193 |
+
SV_DEFAULT_VIEW_PADDING_RATIO = 0.338249
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def parse_result(name: str) -> dict:
|
| 197 |
+
body = (workdir / f"{name}.body").read_text()
|
| 198 |
+
status = int((workdir / f"{name}.status").read_text().strip() or "200")
|
| 199 |
+
try:
|
| 200 |
+
data = json.loads(body) if body else {}
|
| 201 |
+
except Exception:
|
| 202 |
+
data = {"raw": body[:2000]}
|
| 203 |
+
return {
|
| 204 |
+
"ok": status < 400,
|
| 205 |
+
"status": status,
|
| 206 |
+
"data": data,
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def build_default_view(start_pos: int, end_pos: int, chrom_end: int | None) -> dict[str, int]:
|
| 211 |
+
span = max(end_pos - start_pos, 1)
|
| 212 |
+
padding = max(1, int(round(span * SV_DEFAULT_VIEW_PADDING_RATIO)))
|
| 213 |
+
view_start = start_pos - padding
|
| 214 |
+
view_end = end_pos + padding
|
| 215 |
+
min_pos = 1
|
| 216 |
+
max_pos = max(chrom_end or view_end, view_end)
|
| 217 |
+
if view_start < min_pos:
|
| 218 |
+
view_start = min_pos
|
| 219 |
+
view_end = min(max_pos, end_pos + padding)
|
| 220 |
+
if view_end > max_pos:
|
| 221 |
+
view_end = max_pos
|
| 222 |
+
view_start = max(min_pos, start_pos - padding)
|
| 223 |
+
return {"start": view_start, "end": view_end}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def collect_public_occurrences(region_data: dict) -> dict[str, list[dict]]:
|
| 227 |
+
merged = {"dgv": {}, "dgv_gold": {}, "gnomad": {}}
|
| 228 |
+
mapping = {
|
| 229 |
+
"dgv": "dgv_occurrences",
|
| 230 |
+
"dgv_gold": "dgv_gold_occurrences",
|
| 231 |
+
"gnomad": "gnomad_occurrences",
|
| 232 |
+
}
|
| 233 |
+
for bucket_data in region_data.values():
|
| 234 |
+
if not isinstance(bucket_data, dict):
|
| 235 |
+
continue
|
| 236 |
+
for target_key, source_key in mapping.items():
|
| 237 |
+
for item in bucket_data.get(source_key, []):
|
| 238 |
+
if not isinstance(item, dict):
|
| 239 |
+
continue
|
| 240 |
+
item_id = str(item.get("id") or json.dumps(item, sort_keys=True))
|
| 241 |
+
merged[target_key][item_id] = item
|
| 242 |
+
return {key: list(values.values()) for key, values in merged.items()}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
details = parse_result("details")
|
| 246 |
+
presets = parse_result("presets")
|
| 247 |
+
cytobands = parse_result("cytobands")
|
| 248 |
+
carrier_status = parse_result("carrier")
|
| 249 |
+
clinical_evidence = parse_result("clinical")
|
| 250 |
+
region_viewer_data = parse_result("region")
|
| 251 |
+
alt_reference = parse_result("alt")
|
| 252 |
+
org_assessments = parse_result("org")
|
| 253 |
+
uploaded_files = parse_result("uploaded")
|
| 254 |
+
clingen = parse_result("clingen")
|
| 255 |
+
map_result = parse_result("map")
|
| 256 |
+
|
| 257 |
+
details_data = details["data"] if isinstance(details.get("data"), dict) else {}
|
| 258 |
+
region_data_payload = region_viewer_data["data"] if isinstance(region_viewer_data.get("data"), dict) else {}
|
| 259 |
+
region_data = region_data_payload.get("region_data") if isinstance(region_data_payload.get("region_data"), dict) else {}
|
| 260 |
+
chrom_end = region_data_payload.get("chrom_end") if isinstance(region_data_payload.get("chrom_end"), int) else None
|
| 261 |
+
default_view = build_default_view(start, end, chrom_end)
|
| 262 |
+
|
| 263 |
+
public_occurrences = collect_public_occurrences(region_data)
|
| 264 |
+
clingen_results = clingen.get("data", {}).get("results", []) if isinstance(clingen.get("data"), dict) else []
|
| 265 |
+
primary_clingen = clingen_results[0] if isinstance(clingen_results, list) and clingen_results else {}
|
| 266 |
+
|
| 267 |
+
alt_data = alt_reference.get("data") if isinstance(alt_reference.get("data"), dict) else {}
|
| 268 |
+
if (
|
| 269 |
+
not alt_reference.get("ok")
|
| 270 |
+
or alt_data.get("raw") == "no token"
|
| 271 |
+
or not alt_data.get("success")
|
| 272 |
+
):
|
| 273 |
+
mappings = map_result.get("data", {}).get("mappings", []) if isinstance(map_result.get("data"), dict) else []
|
| 274 |
+
mapped = [item.get("mapped") for item in mappings if isinstance(item, dict) and isinstance(item.get("mapped"), dict)]
|
| 275 |
+
if mapped:
|
| 276 |
+
mapped_chrom = str(mapped[0].get("seq_region_name") or chrom.replace("chr", ""))
|
| 277 |
+
mapped_start = min(int(item["start"]) for item in mapped if item.get("start") is not None)
|
| 278 |
+
mapped_end = max(int(item["end"]) for item in mapped if item.get("end") is not None)
|
| 279 |
+
target_label = "HG19" if reference_version == "hg38" else "HG38"
|
| 280 |
+
link_suffix = "" if target_label == "HG19" else "-hg38"
|
| 281 |
+
alt_reference = {
|
| 282 |
+
"ok": True,
|
| 283 |
+
"status": 200,
|
| 284 |
+
"data": {
|
| 285 |
+
"success": True,
|
| 286 |
+
"reference_version": target_label,
|
| 287 |
+
"sv_variant": {
|
| 288 |
+
"chrom": mapped_chrom if mapped_chrom.startswith("chr") else f"chr{mapped_chrom}",
|
| 289 |
+
"start_pos": mapped_start,
|
| 290 |
+
"end_pos": mapped_end,
|
| 291 |
+
"sv_type": sv_type,
|
| 292 |
+
"reference_genome_type": target_label.lower(),
|
| 293 |
+
"reference_version": target_label,
|
| 294 |
+
"length": max(end - start, 0),
|
| 295 |
+
},
|
| 296 |
+
"cytobands": details_data.get("cytobands_description"),
|
| 297 |
+
"link": f"https://franklin.genoox.com/clinical-db/variant/sv/"
|
| 298 |
+
f"{'' if mapped_chrom.startswith('chr') else 'chr'}{mapped_chrom}-{mapped_start}-{mapped_end}-{sv_type}{link_suffix}",
|
| 299 |
+
"source": "ensembl-map-fallback",
|
| 300 |
+
},
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
summary = {
|
| 304 |
+
"ok": details.get("ok", False),
|
| 305 |
+
"status": details.get("status"),
|
| 306 |
+
"data": {
|
| 307 |
+
"variant_type": "SV",
|
| 308 |
+
"sv_type": sv_type,
|
| 309 |
+
"range_descriptor": details_data.get("range_descriptor") or f"{chrom}:{start}-{end}",
|
| 310 |
+
"genes": details_data.get("genes") or [],
|
| 311 |
+
"cytobands_description": details_data.get("cytobands_description"),
|
| 312 |
+
"severest_impact": details_data.get("severest_impact"),
|
| 313 |
+
"severest_region": details_data.get("severest_region"),
|
| 314 |
+
"carrier_status": carrier_status.get("data"),
|
| 315 |
+
"classification": primary_clingen.get("classification"),
|
| 316 |
+
"classification_score": primary_clingen.get("score"),
|
| 317 |
+
"evidence_sections": primary_clingen.get("evidence", []),
|
| 318 |
+
"upstream_error": details.get("error"),
|
| 319 |
+
"linkouts": details_data.get("linkouts") or [],
|
| 320 |
+
},
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
region_viewer = {
|
| 324 |
+
"presets": presets,
|
| 325 |
+
"region_data": {
|
| 326 |
+
"ok": region_viewer_data.get("ok", False),
|
| 327 |
+
"status": region_viewer_data.get("status"),
|
| 328 |
+
"data": {
|
| 329 |
+
"variant_type": "SV",
|
| 330 |
+
"sv_type": sv_type,
|
| 331 |
+
"range": {
|
| 332 |
+
"chromosome": chrom,
|
| 333 |
+
"start": start,
|
| 334 |
+
"end": end,
|
| 335 |
+
"length": max(end - start, 0),
|
| 336 |
+
},
|
| 337 |
+
"default_view": default_view,
|
| 338 |
+
"cytobands": cytobands.get("data"),
|
| 339 |
+
"carrier_status": carrier_status.get("data"),
|
| 340 |
+
"region_data": region_data,
|
| 341 |
+
"buckets": list(region_data.keys()),
|
| 342 |
+
"chrom_end": chrom_end,
|
| 343 |
+
"variant_details": details_data,
|
| 344 |
+
},
|
| 345 |
+
"upstream": {
|
| 346 |
+
"cytobands": cytobands,
|
| 347 |
+
"carrier_status": carrier_status,
|
| 348 |
+
"region_data": region_viewer_data,
|
| 349 |
+
},
|
| 350 |
+
},
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
payload = {
|
| 354 |
+
"variant": {
|
| 355 |
+
"query": query,
|
| 356 |
+
"key": cache_key,
|
| 357 |
+
"chromosome": chrom,
|
| 358 |
+
"position": start,
|
| 359 |
+
"start": start,
|
| 360 |
+
"end": end,
|
| 361 |
+
"ref": "SV",
|
| 362 |
+
"alt": sv_type,
|
| 363 |
+
"hash_id": cache_key,
|
| 364 |
+
"reference_version": reference_version,
|
| 365 |
+
"sv_type": sv_type,
|
| 366 |
+
"sv_length": max(end - start, 0),
|
| 367 |
+
},
|
| 368 |
+
"tabs": {
|
| 369 |
+
"franklin_acmg_classification": summary,
|
| 370 |
+
"variant_assessment": {
|
| 371 |
+
"summary": summary,
|
| 372 |
+
"region_viewer": region_viewer,
|
| 373 |
+
"franklin_community_frequency": {"ok": True, "status": 200, "data": public_occurrences},
|
| 374 |
+
"clinical_evidence": clinical_evidence,
|
| 375 |
+
"predictions": summary,
|
| 376 |
+
"population_frequencies": {"ok": True, "status": 200, "data": public_occurrences},
|
| 377 |
+
"transcripts_and_references": region_viewer_data,
|
| 378 |
+
"uploaded_files": uploaded_files,
|
| 379 |
+
"variant_details": details,
|
| 380 |
+
"search_data": {
|
| 381 |
+
"ok": True,
|
| 382 |
+
"status": 200,
|
| 383 |
+
"data": {
|
| 384 |
+
"query": query,
|
| 385 |
+
"sv_variant": {
|
| 386 |
+
"chr": chrom,
|
| 387 |
+
"start_pos": start,
|
| 388 |
+
"end_pos": end,
|
| 389 |
+
"sv_type": sv_type,
|
| 390 |
+
"ci_pos": "0,0",
|
| 391 |
+
"ci_end": "0,0",
|
| 392 |
+
"hashId": cache_key,
|
| 393 |
+
"referenceGenome": reference_version,
|
| 394 |
+
"reference_version": reference_version,
|
| 395 |
+
"variantIdType": "SV",
|
| 396 |
+
},
|
| 397 |
+
},
|
| 398 |
+
},
|
| 399 |
+
"warmup": {
|
| 400 |
+
"ok": True,
|
| 401 |
+
"status": 200,
|
| 402 |
+
"data": {"message": "sv assessment loaded from Franklin region-viewer endpoints"},
|
| 403 |
+
},
|
| 404 |
+
},
|
| 405 |
+
"publications": {
|
| 406 |
+
"ok": True,
|
| 407 |
+
"status": 200,
|
| 408 |
+
"data": {
|
| 409 |
+
"genes": details_data.get("genes") or [],
|
| 410 |
+
"linkouts": details_data.get("linkouts") or [],
|
| 411 |
+
},
|
| 412 |
+
},
|
| 413 |
+
"gene_assessment": region_viewer_data,
|
| 414 |
+
"curated_gene_data": clinical_evidence,
|
| 415 |
+
"associated_conditions": summary,
|
| 416 |
+
"somatic_clinical_evidence": clinical_evidence,
|
| 417 |
+
"organization_assessments": org_assessments,
|
| 418 |
+
"my_organization_assessments": org_assessments,
|
| 419 |
+
"alternate_reference": alt_reference,
|
| 420 |
+
},
|
| 421 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 425 |
+
with sqlite3.connect(db_path, timeout=30) as connection:
|
| 426 |
+
connection.execute(
|
| 427 |
+
"""
|
| 428 |
+
CREATE TABLE IF NOT EXISTS franklin_sv_cache (
|
| 429 |
+
cache_key TEXT PRIMARY KEY,
|
| 430 |
+
query TEXT NOT NULL,
|
| 431 |
+
reference_version TEXT NOT NULL,
|
| 432 |
+
payload_json TEXT NOT NULL,
|
| 433 |
+
fetched_at TEXT NOT NULL,
|
| 434 |
+
updated_at TEXT NOT NULL
|
| 435 |
+
)
|
| 436 |
+
"""
|
| 437 |
+
)
|
| 438 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 439 |
+
connection.execute(
|
| 440 |
+
"""
|
| 441 |
+
INSERT INTO franklin_sv_cache (
|
| 442 |
+
cache_key, query, reference_version, payload_json, fetched_at, updated_at
|
| 443 |
+
)
|
| 444 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 445 |
+
ON CONFLICT(cache_key) DO UPDATE SET
|
| 446 |
+
query = excluded.query,
|
| 447 |
+
reference_version = excluded.reference_version,
|
| 448 |
+
payload_json = excluded.payload_json,
|
| 449 |
+
fetched_at = excluded.fetched_at,
|
| 450 |
+
updated_at = excluded.updated_at
|
| 451 |
+
""",
|
| 452 |
+
(cache_key, query, reference_version, json.dumps(payload), now, now),
|
| 453 |
+
)
|
| 454 |
+
connection.commit()
|
| 455 |
+
|
| 456 |
+
print(json.dumps({
|
| 457 |
+
"cache_key": cache_key,
|
| 458 |
+
"db_path": str(db_path),
|
| 459 |
+
"genes": len(summary["data"]["genes"]),
|
| 460 |
+
"clinvar_entries": len(clinical_evidence.get("data", {}).get("clinvar", {}).get("entries", [])) if isinstance(clinical_evidence.get("data"), dict) else 0,
|
| 461 |
+
"dgv": len(public_occurrences["dgv"]),
|
| 462 |
+
"dgv_gold": len(public_occurrences["dgv_gold"]),
|
| 463 |
+
"gnomad": len(public_occurrences["gnomad"]),
|
| 464 |
+
"alternate_reference": alt_reference.get("data", {}).get("reference_version") if isinstance(alt_reference.get("data"), dict) else None,
|
| 465 |
+
}, ensure_ascii=True))
|
| 466 |
+
PY
|
test_franklin_parse.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from app.services.franklin_service import parse_search_query_via_franklin
|
| 3 |
+
|
| 4 |
+
async def main():
|
| 5 |
+
res1 = await parse_search_query_via_franklin("chr3:10142140 A-G", "hg19")
|
| 6 |
+
print("hg19:", res1)
|
| 7 |
+
res2 = await parse_search_query_via_franklin("chr3:10142140 A-G", "hg38")
|
| 8 |
+
print("hg38:", res2)
|
| 9 |
+
|
| 10 |
+
asyncio.run(main())
|
tests/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# E2E Tests
|
| 2 |
+
|
| 3 |
+
## Requirements
|
| 4 |
+
```bash
|
| 5 |
+
pip install playwright
|
| 6 |
+
playwright install chromium
|
| 7 |
+
```
|
| 8 |
+
|
| 9 |
+
## Run E2E Tests
|
| 10 |
+
```bash
|
| 11 |
+
playwright test
|
| 12 |
+
```
|
tests/test_api.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from fastapi.testclient import TestClient
|
| 3 |
+
from unittest.mock import patch, AsyncMock
|
| 4 |
+
from app.main import app
|
| 5 |
+
|
| 6 |
+
client = TestClient(app)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestHealthEndpoint:
|
| 10 |
+
def test_root(self):
|
| 11 |
+
response = client.get("/")
|
| 12 |
+
assert response.status_code == 200
|
| 13 |
+
assert response.json()["message"] == "OpenVar API"
|
| 14 |
+
|
| 15 |
+
def test_health(self):
|
| 16 |
+
response = client.get("/health")
|
| 17 |
+
assert response.status_code == 200
|
| 18 |
+
assert response.json()["status"] == "healthy"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestGenesAPI:
|
| 22 |
+
def test_list_genes(self):
|
| 23 |
+
response = client.get("/api/genes")
|
| 24 |
+
assert response.status_code == 200
|
| 25 |
+
data = response.json()
|
| 26 |
+
assert isinstance(data, list)
|
| 27 |
+
assert len(data) > 0
|
| 28 |
+
assert data[0]["symbol"] == "BRCA1"
|
| 29 |
+
|
| 30 |
+
def test_list_genes_with_query(self):
|
| 31 |
+
response = client.get("/api/genes?query=BRCA")
|
| 32 |
+
assert response.status_code == 200
|
| 33 |
+
data = response.json()
|
| 34 |
+
assert all("BRCA" in gene["symbol"] for gene in data)
|
| 35 |
+
|
| 36 |
+
def test_list_genes_limit_validation(self):
|
| 37 |
+
response = client.get("/api/genes?limit=1000")
|
| 38 |
+
assert response.status_code == 422
|
| 39 |
+
|
| 40 |
+
def test_get_gene(self):
|
| 41 |
+
response = client.get("/api/genes/BRCA1")
|
| 42 |
+
assert response.status_code == 200
|
| 43 |
+
data = response.json()
|
| 44 |
+
assert data["symbol"] == "BRCA1"
|
| 45 |
+
|
| 46 |
+
def test_get_gene_not_found(self):
|
| 47 |
+
response = client.get("/api/genes/UNKNOWN")
|
| 48 |
+
assert response.status_code == 404
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TestAuthAPI:
|
| 52 |
+
def test_login_success(self):
|
| 53 |
+
response = client.post(
|
| 54 |
+
"/api/auth/login",
|
| 55 |
+
json={"email": "demo@openvar.io", "password": "demo"}
|
| 56 |
+
)
|
| 57 |
+
assert response.status_code == 200
|
| 58 |
+
data = response.json()
|
| 59 |
+
assert "access_token" in data
|
| 60 |
+
assert data["user"]["email"] == "demo@openvar.io"
|
| 61 |
+
|
| 62 |
+
def test_login_invalid_credentials(self):
|
| 63 |
+
response = client.post(
|
| 64 |
+
"/api/auth/login",
|
| 65 |
+
json={"email": "wrong@example.com", "password": "wrong"}
|
| 66 |
+
)
|
| 67 |
+
assert response.status_code == 401
|
| 68 |
+
|
| 69 |
+
def test_get_current_user(self):
|
| 70 |
+
response = client.get("/api/auth/me")
|
| 71 |
+
assert response.status_code == 200
|
| 72 |
+
data = response.json()
|
| 73 |
+
assert "email" in data
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class TestVariantAPI:
|
| 77 |
+
@patch("app.services.variant_service.annotate_variant")
|
| 78 |
+
def test_search_variant_coordinates(self, mock_annotate):
|
| 79 |
+
mock_annotate.return_value = {
|
| 80 |
+
"variant": {
|
| 81 |
+
"id": "9-135800978-A-G",
|
| 82 |
+
"chromosome": "9",
|
| 83 |
+
"position": 135800978,
|
| 84 |
+
"ref": "A",
|
| 85 |
+
"alt": "G",
|
| 86 |
+
"gene": "PTPRD"
|
| 87 |
+
},
|
| 88 |
+
"acmg": {"classification": "Uncertain significance"}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
response = client.post(
|
| 92 |
+
"/api/variant/search",
|
| 93 |
+
json={"query": "chr9-135800978-A-G", "genome_build": "hg38"}
|
| 94 |
+
)
|
| 95 |
+
assert response.status_code == 200
|
| 96 |
+
data = response.json()
|
| 97 |
+
assert isinstance(data, list)
|
| 98 |
+
|
| 99 |
+
def test_search_structural_variant(self):
|
| 100 |
+
response = client.post(
|
| 101 |
+
"/api/variant/search",
|
| 102 |
+
json={"query": "DUP:Chr5:125423848-128107072", "genome_build": "hg38"}
|
| 103 |
+
)
|
| 104 |
+
assert response.status_code == 200
|
| 105 |
+
data = response.json()
|
| 106 |
+
assert len(data) == 1
|
| 107 |
+
assert data[0]["variant"]["id"] == "chr5-125423848-128107072-DUP-hg38"
|
| 108 |
+
assert data[0]["consequences"]["sv_type"] == "DUP"
|
| 109 |
+
|
| 110 |
+
def test_get_variant_not_found(self):
|
| 111 |
+
response = client.get("/api/variant/invalid-variant-id")
|
| 112 |
+
assert response.status_code == 404
|
tests/test_e2e.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from playwright.sync_api import sync_playwright, expect
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
BASE_URL = "http://localhost:3000"
|
| 6 |
+
API_URL = "http://localhost:8000"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestE2E:
|
| 10 |
+
@pytest.fixture(autouse=True)
|
| 11 |
+
def setup(self, browser):
|
| 12 |
+
self.context = browser.new_context()
|
| 13 |
+
self.page = self.context.new_page()
|
| 14 |
+
yield
|
| 15 |
+
self.context.close()
|
| 16 |
+
|
| 17 |
+
def test_homepage_loads(self):
|
| 18 |
+
"""Test that homepage loads successfully"""
|
| 19 |
+
self.page.goto(BASE_URL)
|
| 20 |
+
expect(self.page).to_have_title(/OpenVar/)
|
| 21 |
+
expect(self.page.get_by_text("Clinical Variant Interpretation")).to_be_visible()
|
| 22 |
+
|
| 23 |
+
def test_search_variants(self):
|
| 24 |
+
"""Test variant search functionality"""
|
| 25 |
+
self.page.goto(BASE_URL)
|
| 26 |
+
|
| 27 |
+
# Fill in search input
|
| 28 |
+
search_input = self.page.get_by_placeholder("Search variants")
|
| 29 |
+
search_input.fill("chr9-135800978-A-G")
|
| 30 |
+
|
| 31 |
+
# Click search button
|
| 32 |
+
self.page.get_by_role("button", name="Search").click()
|
| 33 |
+
|
| 34 |
+
# Wait for results (or no results message)
|
| 35 |
+
self.page.wait_for_timeout(1000)
|
| 36 |
+
|
| 37 |
+
def test_genes_page(self):
|
| 38 |
+
"""Test genes page loads"""
|
| 39 |
+
self.page.goto(f"{BASE_URL}/genes")
|
| 40 |
+
expect(self.page.get_by_text("Genes")).to_be_visible()
|
| 41 |
+
|
| 42 |
+
def test_knowledge_page(self):
|
| 43 |
+
"""Test knowledge base page loads"""
|
| 44 |
+
self.page.goto(f"{BASE_URL}/knowledge")
|
| 45 |
+
expect(self.page.get_by_text("Knowledge Base")).to_be_visible()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestAPIE2E:
|
| 49 |
+
def test_api_health(self, request):
|
| 50 |
+
"""Test API health endpoint"""
|
| 51 |
+
import httpx
|
| 52 |
+
response = httpx.get(f"{API_URL}/health")
|
| 53 |
+
assert response.status_code == 200
|
| 54 |
+
assert response.json()["status"] == "healthy"
|
| 55 |
+
|
| 56 |
+
def test_api_genes_list(self):
|
| 57 |
+
"""Test API genes list"""
|
| 58 |
+
import httpx
|
| 59 |
+
response = httpx.get(f"{API_URL}/api/genes")
|
| 60 |
+
assert response.status_code == 200
|
| 61 |
+
data = response.json()
|
| 62 |
+
assert isinstance(data, list)
|
| 63 |
+
assert len(data) > 0
|
| 64 |
+
|
| 65 |
+
def test_api_auth_login(self):
|
| 66 |
+
"""Test API login"""
|
| 67 |
+
import httpx
|
| 68 |
+
response = httpx.post(
|
| 69 |
+
f"{API_URL}/api/auth/login",
|
| 70 |
+
json={"email": "demo@openvar.io", "password": "demo"}
|
| 71 |
+
)
|
| 72 |
+
assert response.status_code == 200
|
| 73 |
+
data = response.json()
|
| 74 |
+
assert "access_token" in data
|
tests/test_franklin_service.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import sqlite3
|
| 3 |
+
from datetime import datetime, timedelta, timezone
|
| 4 |
+
|
| 5 |
+
from app.services import franklin_service
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestFranklinSvCache:
|
| 9 |
+
@staticmethod
|
| 10 |
+
def _cacheable_sv_payload():
|
| 11 |
+
return {
|
| 12 |
+
"variant": {"key": "chr5-125423848-128107072-DUP-hg38"},
|
| 13 |
+
"tabs": {
|
| 14 |
+
"variant_assessment": {
|
| 15 |
+
"summary": {
|
| 16 |
+
"ok": True,
|
| 17 |
+
"status": 200,
|
| 18 |
+
"data": {
|
| 19 |
+
"variant_type": "SV",
|
| 20 |
+
"genes": ["MARCH3"],
|
| 21 |
+
"cytobands_description": "5q23.2-q23.3",
|
| 22 |
+
},
|
| 23 |
+
},
|
| 24 |
+
"region_viewer": {
|
| 25 |
+
"region_data": {
|
| 26 |
+
"ok": True,
|
| 27 |
+
"status": 200,
|
| 28 |
+
"data": {
|
| 29 |
+
"region_data": {
|
| 30 |
+
"123": {
|
| 31 |
+
"genes": [{"gene": "MARCH3"}],
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
+
"population_frequencies": {
|
| 38 |
+
"ok": True,
|
| 39 |
+
"status": 200,
|
| 40 |
+
"data": {"dgv": [], "dgv_gold": [], "gnomad": []},
|
| 41 |
+
},
|
| 42 |
+
"clinical_evidence": {"ok": True, "status": 200, "data": {"clinvar": {"entries": []}}},
|
| 43 |
+
"variant_details": {"ok": True, "status": 200, "data": {"genes": ["MARCH3"]}},
|
| 44 |
+
},
|
| 45 |
+
"alternate_reference": {"ok": False, "status": 401, "data": {"raw": "no token"}},
|
| 46 |
+
},
|
| 47 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
def test_sv_region_defaults_follow_franklin_windowing(self):
|
| 51 |
+
default_view = franklin_service._build_sv_default_view(125423848, 128107072, None)
|
| 52 |
+
assert default_view == {"start": 124516250, "end": 129014670}
|
| 53 |
+
assert franklin_service._build_sv_region_buckets(default_view["start"], default_view["end"]) == [
|
| 54 |
+
123,
|
| 55 |
+
124,
|
| 56 |
+
125,
|
| 57 |
+
126,
|
| 58 |
+
127,
|
| 59 |
+
128,
|
| 60 |
+
129,
|
| 61 |
+
130,
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
def test_sv_occurrence_merge_deduplicates_across_buckets(self):
|
| 65 |
+
merged = franklin_service._collect_sv_public_occurrences(
|
| 66 |
+
{
|
| 67 |
+
"123": {
|
| 68 |
+
"dgv_occurrences": [{"id": "dgv-1"}, {"id": "dgv-2"}],
|
| 69 |
+
"dgv_gold_occurrences": [{"id": "gold-1"}],
|
| 70 |
+
"gnomad_occurrences": [{"id": "gn-1"}],
|
| 71 |
+
},
|
| 72 |
+
"124": {
|
| 73 |
+
"dgv_occurrences": [{"id": "dgv-2"}, {"id": "dgv-3"}],
|
| 74 |
+
"dgv_gold_occurrences": [{"id": "gold-1"}, {"id": "gold-2"}],
|
| 75 |
+
"gnomad_occurrences": [{"id": "gn-2"}],
|
| 76 |
+
},
|
| 77 |
+
}
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
assert [item["id"] for item in merged["dgv"]] == ["dgv-1", "dgv-2", "dgv-3"]
|
| 81 |
+
assert [item["id"] for item in merged["dgv_gold"]] == ["gold-1", "gold-2"]
|
| 82 |
+
assert [item["id"] for item in merged["gnomad"]] == ["gn-1", "gn-2"]
|
| 83 |
+
|
| 84 |
+
def test_sv_alt_reference_fallback_uses_ensembl_map(self, monkeypatch):
|
| 85 |
+
async def fake_map_range(chrom, start, end, source_assembly, target_assembly):
|
| 86 |
+
assert chrom == "5"
|
| 87 |
+
assert start == 125423848
|
| 88 |
+
assert end == 128107072
|
| 89 |
+
assert source_assembly == "GRCh38"
|
| 90 |
+
assert target_assembly == "GRCh37"
|
| 91 |
+
return {
|
| 92 |
+
"chrom": "5",
|
| 93 |
+
"start_pos": 124759541,
|
| 94 |
+
"end_pos": 127442764,
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
monkeypatch.setattr(franklin_service, "_map_assembly_range", fake_map_range)
|
| 98 |
+
|
| 99 |
+
context = franklin_service.FranklinStructuralVariantContext(
|
| 100 |
+
chrom="5",
|
| 101 |
+
start=125423848,
|
| 102 |
+
end=128107072,
|
| 103 |
+
sv_type="DUP",
|
| 104 |
+
reference_version="hg38",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
result = asyncio.run(
|
| 108 |
+
franklin_service._build_sv_alt_reference_fallback(
|
| 109 |
+
context,
|
| 110 |
+
{"cytobands_description": "5q23.2-q23.3"},
|
| 111 |
+
)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
assert result == {
|
| 115 |
+
"ok": True,
|
| 116 |
+
"status": 200,
|
| 117 |
+
"data": {
|
| 118 |
+
"success": True,
|
| 119 |
+
"reference_version": "HG19",
|
| 120 |
+
"sv_variant": {
|
| 121 |
+
"chrom": "chr5",
|
| 122 |
+
"start_pos": 124759541,
|
| 123 |
+
"end_pos": 127442764,
|
| 124 |
+
"sv_type": "DUP",
|
| 125 |
+
"reference_genome_type": "hg19",
|
| 126 |
+
"reference_version": "HG19",
|
| 127 |
+
"length": 2683224,
|
| 128 |
+
},
|
| 129 |
+
"cytobands": "5q23.2-q23.3",
|
| 130 |
+
"link": "https://franklin.genoox.com/clinical-db/variant/sv/chr5-124759541-127442764-DUP",
|
| 131 |
+
"source": "ensembl-map-fallback",
|
| 132 |
+
},
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
def test_sv_cache_miss_fetches_and_persists(self, monkeypatch, tmp_path):
|
| 136 |
+
cache_path = tmp_path / "franklin-cache.sqlite3"
|
| 137 |
+
monkeypatch.setenv("FRANKLIN_CACHE_DB_PATH", str(cache_path))
|
| 138 |
+
fetched_payload = self._cacheable_sv_payload()
|
| 139 |
+
|
| 140 |
+
async def fake_fetch(context, query):
|
| 141 |
+
assert context.chrom == "5"
|
| 142 |
+
assert context.start == 125423848
|
| 143 |
+
assert context.end == 128107072
|
| 144 |
+
assert context.sv_type == "DUP"
|
| 145 |
+
assert context.reference_label == "hg38"
|
| 146 |
+
assert query == "DUP:Chr5:125423848-128107072"
|
| 147 |
+
return fetched_payload
|
| 148 |
+
|
| 149 |
+
monkeypatch.setattr(franklin_service, "_fetch_structural_variant_assessment", fake_fetch)
|
| 150 |
+
|
| 151 |
+
result = asyncio.run(
|
| 152 |
+
franklin_service.get_franklin_variant_assessment(
|
| 153 |
+
"DUP:Chr5:125423848-128107072",
|
| 154 |
+
reference_version="hg38",
|
| 155 |
+
)
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
assert result["cache"]["source"] == "franklin-live"
|
| 159 |
+
assert result["cache"]["stale"] is False
|
| 160 |
+
|
| 161 |
+
with sqlite3.connect(cache_path) as connection:
|
| 162 |
+
row = connection.execute(
|
| 163 |
+
"SELECT cache_key, reference_version FROM franklin_sv_cache"
|
| 164 |
+
).fetchone()
|
| 165 |
+
|
| 166 |
+
assert row == ("chr5-125423848-128107072-DUP-hg38", "hg38")
|
| 167 |
+
|
| 168 |
+
def test_sv_cache_miss_does_not_persist_empty_failure_payload(self, monkeypatch, tmp_path):
|
| 169 |
+
cache_path = tmp_path / "franklin-cache.sqlite3"
|
| 170 |
+
monkeypatch.setenv("FRANKLIN_CACHE_DB_PATH", str(cache_path))
|
| 171 |
+
|
| 172 |
+
failed_payload = {
|
| 173 |
+
"variant": {"key": "chr5-125423848-128107072-DUP-hg38"},
|
| 174 |
+
"tabs": {
|
| 175 |
+
"variant_assessment": {
|
| 176 |
+
"summary": {
|
| 177 |
+
"ok": False,
|
| 178 |
+
"status": 502,
|
| 179 |
+
"data": {"variant_type": "SV", "genes": [], "upstream_error": "[Errno 8]"},
|
| 180 |
+
},
|
| 181 |
+
"region_viewer": {
|
| 182 |
+
"region_data": {
|
| 183 |
+
"ok": True,
|
| 184 |
+
"status": 200,
|
| 185 |
+
"data": {"region_data": {}},
|
| 186 |
+
}
|
| 187 |
+
},
|
| 188 |
+
"population_frequencies": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 189 |
+
"clinical_evidence": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 190 |
+
"variant_details": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 191 |
+
},
|
| 192 |
+
"alternate_reference": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 193 |
+
},
|
| 194 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
async def fake_fetch(context, query):
|
| 198 |
+
return failed_payload
|
| 199 |
+
|
| 200 |
+
monkeypatch.setattr(franklin_service, "_fetch_structural_variant_assessment", fake_fetch)
|
| 201 |
+
|
| 202 |
+
result = asyncio.run(
|
| 203 |
+
franklin_service.get_franklin_variant_assessment(
|
| 204 |
+
"DUP:Chr5:125423848-128107072",
|
| 205 |
+
reference_version="hg38",
|
| 206 |
+
)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
assert result["cache"]["source"] == "franklin-live"
|
| 210 |
+
|
| 211 |
+
with sqlite3.connect(cache_path) as connection:
|
| 212 |
+
row = connection.execute("SELECT COUNT(*) FROM franklin_sv_cache").fetchone()
|
| 213 |
+
|
| 214 |
+
assert row == (0,)
|
| 215 |
+
|
| 216 |
+
def test_sv_cache_hit_returns_cached_payload_and_triggers_background_refresh(self, monkeypatch, tmp_path):
|
| 217 |
+
cache_path = tmp_path / "franklin-cache.sqlite3"
|
| 218 |
+
monkeypatch.setenv("FRANKLIN_CACHE_DB_PATH", str(cache_path))
|
| 219 |
+
stale_payload = self._cacheable_sv_payload()
|
| 220 |
+
franklin_service._save_cached_sv_assessment(
|
| 221 |
+
"chr5-125423848-128107072-DUP-hg38",
|
| 222 |
+
"DUP:Chr5:125423848-128107072",
|
| 223 |
+
"hg38",
|
| 224 |
+
stale_payload,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
stale_time = (datetime.now(timezone.utc) - timedelta(days=8)).isoformat()
|
| 228 |
+
with sqlite3.connect(cache_path) as connection:
|
| 229 |
+
connection.execute(
|
| 230 |
+
"UPDATE franklin_sv_cache SET fetched_at = ?, updated_at = ? WHERE cache_key = ?",
|
| 231 |
+
(stale_time, stale_time, "chr5-125423848-128107072-DUP-hg38"),
|
| 232 |
+
)
|
| 233 |
+
connection.commit()
|
| 234 |
+
|
| 235 |
+
refresh_calls = []
|
| 236 |
+
|
| 237 |
+
def fake_refresh(cache_key, query, reference_version):
|
| 238 |
+
refresh_calls.append((cache_key, query, reference_version))
|
| 239 |
+
|
| 240 |
+
monkeypatch.setattr(franklin_service, "_start_sv_cache_refresh", fake_refresh)
|
| 241 |
+
|
| 242 |
+
result = asyncio.run(
|
| 243 |
+
franklin_service.get_franklin_variant_assessment(
|
| 244 |
+
"chr5-125423848-128107072-DUP-hg38",
|
| 245 |
+
reference_version="hg19",
|
| 246 |
+
)
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
assert result["cache"]["source"] == "local-cache"
|
| 250 |
+
assert result["cache"]["stale"] is True
|
| 251 |
+
assert refresh_calls == [
|
| 252 |
+
(
|
| 253 |
+
"chr5-125423848-128107072-DUP-hg38",
|
| 254 |
+
"chr5-125423848-128107072-DUP-hg38",
|
| 255 |
+
"hg38",
|
| 256 |
+
)
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
def test_bad_cached_payload_is_discarded_before_re_fetch(self, monkeypatch, tmp_path):
|
| 260 |
+
cache_path = tmp_path / "franklin-cache.sqlite3"
|
| 261 |
+
monkeypatch.setenv("FRANKLIN_CACHE_DB_PATH", str(cache_path))
|
| 262 |
+
|
| 263 |
+
failed_payload = {
|
| 264 |
+
"variant": {"key": "chr5-125423848-128107072-DUP-hg38"},
|
| 265 |
+
"tabs": {
|
| 266 |
+
"variant_assessment": {
|
| 267 |
+
"summary": {"ok": False, "status": 502, "data": {"variant_type": "SV", "genes": []}},
|
| 268 |
+
"region_viewer": {"region_data": {"ok": True, "status": 200, "data": {"region_data": {}}}},
|
| 269 |
+
"population_frequencies": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 270 |
+
"clinical_evidence": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 271 |
+
"variant_details": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 272 |
+
},
|
| 273 |
+
"alternate_reference": {"ok": False, "status": 502, "error": "[Errno 8]"},
|
| 274 |
+
},
|
| 275 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 276 |
+
}
|
| 277 |
+
franklin_service._save_cached_sv_assessment(
|
| 278 |
+
"chr5-125423848-128107072-DUP-hg38",
|
| 279 |
+
"DUP:Chr5:125423848-128107072",
|
| 280 |
+
"hg38",
|
| 281 |
+
failed_payload,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
fetched_payload = self._cacheable_sv_payload()
|
| 285 |
+
fetch_calls = []
|
| 286 |
+
|
| 287 |
+
async def fake_fetch(context, query):
|
| 288 |
+
fetch_calls.append((context.variant_key, query))
|
| 289 |
+
return fetched_payload
|
| 290 |
+
|
| 291 |
+
monkeypatch.setattr(franklin_service, "_fetch_structural_variant_assessment", fake_fetch)
|
| 292 |
+
|
| 293 |
+
result = asyncio.run(
|
| 294 |
+
franklin_service.get_franklin_variant_assessment(
|
| 295 |
+
"DUP:Chr5:125423848-128107072",
|
| 296 |
+
reference_version="hg38",
|
| 297 |
+
)
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
assert result["cache"]["source"] == "franklin-live"
|
| 301 |
+
assert fetch_calls == [("chr5-125423848-128107072-DUP-hg38", "DUP:Chr5:125423848-128107072")]
|
tests/test_models.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from pydantic import ValidationError
|
| 3 |
+
from app.models.variant import (
|
| 4 |
+
VariantSearchRequest,
|
| 5 |
+
VariantInfo,
|
| 6 |
+
ClinVarInfo,
|
| 7 |
+
GnomADInfo,
|
| 8 |
+
ACMGInfo,
|
| 9 |
+
VariantResponse,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestVariantModels:
|
| 14 |
+
def test_variant_search_request_defaults(self):
|
| 15 |
+
req = VariantSearchRequest(query="test")
|
| 16 |
+
assert req.genome_build == "hg38"
|
| 17 |
+
|
| 18 |
+
def test_variant_search_request_custom_genome(self):
|
| 19 |
+
req = VariantSearchRequest(query="test", genome_build="hg19")
|
| 20 |
+
assert req.genome_build == "hg19"
|
| 21 |
+
|
| 22 |
+
def test_variant_info_required_fields(self):
|
| 23 |
+
v = VariantInfo(
|
| 24 |
+
id="9-135800978-A-G",
|
| 25 |
+
chromosome="9",
|
| 26 |
+
position=135800978,
|
| 27 |
+
ref="A",
|
| 28 |
+
alt="G"
|
| 29 |
+
)
|
| 30 |
+
assert v.id == "9-135800978-A-G"
|
| 31 |
+
assert v.chromosome == "9"
|
| 32 |
+
|
| 33 |
+
def test_variant_info_optional_fields(self):
|
| 34 |
+
v = VariantInfo(
|
| 35 |
+
id="test",
|
| 36 |
+
chromosome="1",
|
| 37 |
+
position=100,
|
| 38 |
+
ref="A",
|
| 39 |
+
alt="G",
|
| 40 |
+
gene="BRCA1",
|
| 41 |
+
protein_change="p.Arg1234Ser"
|
| 42 |
+
)
|
| 43 |
+
assert v.gene == "BRCA1"
|
| 44 |
+
assert v.protein_change == "p.Arg1234Ser"
|
| 45 |
+
|
| 46 |
+
def test_clinvar_info(self):
|
| 47 |
+
c = ClinVarInfo(
|
| 48 |
+
classification="Pathogenic",
|
| 49 |
+
disease="Breast cancer",
|
| 50 |
+
accession="RCV000123456"
|
| 51 |
+
)
|
| 52 |
+
assert c.classification == "Pathogenic"
|
| 53 |
+
assert c.disease == "Breast cancer"
|
| 54 |
+
|
| 55 |
+
def test_gnomad_info(self):
|
| 56 |
+
g = GnomADInfo(
|
| 57 |
+
exomes_af=0.001,
|
| 58 |
+
genomes_af=0.0005,
|
| 59 |
+
exomes_ac=100,
|
| 60 |
+
genomes_ac=50
|
| 61 |
+
)
|
| 62 |
+
assert g.exomes_af == 0.001
|
| 63 |
+
assert g.exomes_ac == 100
|
| 64 |
+
|
| 65 |
+
def test_acmg_info(self):
|
| 66 |
+
a = ACMGInfo(
|
| 67 |
+
classification="Pathogenic",
|
| 68 |
+
criteria="PS1,PM2,PP3"
|
| 69 |
+
)
|
| 70 |
+
assert a.classification == "Pathogenic"
|
| 71 |
+
assert "PS1" in a.criteria
|
| 72 |
+
|
| 73 |
+
def test_variant_response_full(self):
|
| 74 |
+
v = VariantInfo(id="test", chromosome="1", position=100, ref="A", alt="G")
|
| 75 |
+
c = ClinVarInfo(classification="Pathogenic")
|
| 76 |
+
g = GnomADInfo(exomes_af=0.001)
|
| 77 |
+
a = ACMGInfo(classification="Pathogenic")
|
| 78 |
+
|
| 79 |
+
response = VariantResponse(
|
| 80 |
+
variant=v,
|
| 81 |
+
clinvar=c,
|
| 82 |
+
gnomad=g,
|
| 83 |
+
acmg=a
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
assert response.variant.id == "test"
|
| 87 |
+
assert response.clinvar.classification == "Pathogenic"
|
| 88 |
+
assert response.gnomad.exomes_af == 0.001
|
| 89 |
+
assert response.acmg.classification == "Pathogenic"
|
| 90 |
+
|
| 91 |
+
def test_variant_response_minimal(self):
|
| 92 |
+
v = VariantInfo(id="test", chromosome="1", position=100, ref="A", alt="G")
|
| 93 |
+
response = VariantResponse(variant=v)
|
| 94 |
+
|
| 95 |
+
assert response.variant.id == "test"
|
| 96 |
+
assert response.clinvar is None
|
| 97 |
+
assert response.gnomad is None
|
| 98 |
+
assert response.acmg is None
|
tests/test_variant_service.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from unittest.mock import AsyncMock, Mock
|
| 3 |
+
from app.services.variant_service import parse_variant_query, hgvs_to_coordinates, _parse_vep_to_coordinates
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestVariantService:
|
| 7 |
+
def test_parse_coordinates_with_chr(self):
|
| 8 |
+
result = parse_variant_query("chr9-135800978-A-G")
|
| 9 |
+
assert result["type"] == "coordinates"
|
| 10 |
+
assert result["chromosome"] == "9"
|
| 11 |
+
assert result["position"] == 135800978
|
| 12 |
+
assert result["ref"] == "A"
|
| 13 |
+
assert result["alt"] == "G"
|
| 14 |
+
|
| 15 |
+
def test_parse_coordinates_without_chr(self):
|
| 16 |
+
result = parse_variant_query("9-135800978-A-G")
|
| 17 |
+
assert result["type"] == "coordinates"
|
| 18 |
+
assert result["chromosome"] == "9"
|
| 19 |
+
|
| 20 |
+
def test_parse_rsid(self):
|
| 21 |
+
result = parse_variant_query("rs123456")
|
| 22 |
+
assert result["type"] == "rsid"
|
| 23 |
+
assert result["value"] == "rs123456"
|
| 24 |
+
|
| 25 |
+
def test_parse_structural_variant_dup(self):
|
| 26 |
+
result = parse_variant_query("DUP:Chr5:125423848-128107072")
|
| 27 |
+
assert result["type"] == "sv"
|
| 28 |
+
assert result["chromosome"] == "5"
|
| 29 |
+
assert result["start"] == 125423848
|
| 30 |
+
assert result["end"] == 128107072
|
| 31 |
+
assert result["sv_type"] == "DUP"
|
| 32 |
+
|
| 33 |
+
def test_parse_structural_variant_franklin_style_id(self):
|
| 34 |
+
result = parse_variant_query("chr5-125423848-128107072-DUP-hg38")
|
| 35 |
+
assert result["type"] == "sv"
|
| 36 |
+
assert result["chromosome"] == "5"
|
| 37 |
+
assert result["start"] == 125423848
|
| 38 |
+
assert result["end"] == 128107072
|
| 39 |
+
assert result["sv_type"] == "DUP"
|
| 40 |
+
assert result["reference_version"] == "hg38"
|
| 41 |
+
|
| 42 |
+
def test_parse_invalid(self):
|
| 43 |
+
result = parse_variant_query("invalid")
|
| 44 |
+
assert result["type"] == "unknown"
|
| 45 |
+
|
| 46 |
+
def test_hgvs_to_coordinates_parses_spdi_and_converts_to_1_based(self):
|
| 47 |
+
mock_client = AsyncMock()
|
| 48 |
+
mock_response = Mock()
|
| 49 |
+
mock_response.status_code = 200
|
| 50 |
+
mock_response.text = "ok"
|
| 51 |
+
mock_response.json = Mock(return_value=[
|
| 52 |
+
{
|
| 53 |
+
"input": "TSC1:c.359T>C",
|
| 54 |
+
"TSC1": {
|
| 55 |
+
"spdi": ["NC_000009.12:135786501:A:G"]
|
| 56 |
+
},
|
| 57 |
+
}
|
| 58 |
+
])
|
| 59 |
+
mock_client.get.return_value = mock_response
|
| 60 |
+
|
| 61 |
+
result = asyncio.run(hgvs_to_coordinates("TSC1:c.359T>C", mock_client))
|
| 62 |
+
|
| 63 |
+
assert result is not None
|
| 64 |
+
assert result["chromosome"] == "9"
|
| 65 |
+
assert result["position"] == 135786502
|
| 66 |
+
assert result["ref"] == "A"
|
| 67 |
+
assert result["alt"] == "G"
|
| 68 |
+
|
| 69 |
+
def test_hgvs_to_coordinates_parses_genomic_hgvs_string(self):
|
| 70 |
+
mock_client = AsyncMock()
|
| 71 |
+
mock_response = Mock()
|
| 72 |
+
mock_response.status_code = 200
|
| 73 |
+
mock_response.text = "ok"
|
| 74 |
+
mock_response.json = Mock(return_value=[
|
| 75 |
+
{
|
| 76 |
+
"hgvsg": ["9:g.135800978A>G"],
|
| 77 |
+
}
|
| 78 |
+
])
|
| 79 |
+
mock_client.get.return_value = mock_response
|
| 80 |
+
|
| 81 |
+
result = asyncio.run(hgvs_to_coordinates("TSC1:c.359T>C", mock_client))
|
| 82 |
+
|
| 83 |
+
assert result is not None
|
| 84 |
+
assert result["chromosome"] == "9"
|
| 85 |
+
assert result["position"] == 135800978
|
| 86 |
+
assert result["ref"] == "A"
|
| 87 |
+
assert result["alt"] == "G"
|
| 88 |
+
|
| 89 |
+
def test_parse_vep_to_coordinates_negative_strand_complements_alleles(self):
|
| 90 |
+
data = [
|
| 91 |
+
{
|
| 92 |
+
"seq_region_name": "9",
|
| 93 |
+
"start": 132925591,
|
| 94 |
+
"allele_string": "T/C",
|
| 95 |
+
"strand": -1,
|
| 96 |
+
}
|
| 97 |
+
]
|
| 98 |
+
result = _parse_vep_to_coordinates(data, "TSC1:c.359T>C")
|
| 99 |
+
assert result is not None
|
| 100 |
+
assert result["chromosome"] == "9"
|
| 101 |
+
assert result["position"] == 132925591
|
| 102 |
+
assert result["ref"] == "A"
|
| 103 |
+
assert result["alt"] == "G"
|
| 104 |
+
|
| 105 |
+
def test_parse_vep_to_coordinates_positive_strand_uses_alleles_as_is(self):
|
| 106 |
+
data = [
|
| 107 |
+
{
|
| 108 |
+
"seq_region_name": "9",
|
| 109 |
+
"start": 132925591,
|
| 110 |
+
"allele_string": "A/G",
|
| 111 |
+
"strand": 1,
|
| 112 |
+
}
|
| 113 |
+
]
|
| 114 |
+
result = _parse_vep_to_coordinates(data, "chr9:g.132925591A>G")
|
| 115 |
+
assert result is not None
|
| 116 |
+
assert result["chromosome"] == "9"
|
| 117 |
+
assert result["position"] == 132925591
|
| 118 |
+
assert result["ref"] == "A"
|
| 119 |
+
assert result["alt"] == "G"
|