Spaces:
Running
Running
Sprint 1-2: JWT auth middleware + UniProt dedicated page
Browse files- bioai-platform/backend/app/main.py +2 -1
- bioai-platform/backend/app/routers/jobs.py +16 -6
- bioai-platform/backend/app/routers/pipelines.py +3 -1
- bioai-platform/backend/app/routers/profile.py +4 -3
- bioai-platform/backend/app/routers/uniprot.py +47 -0
- bioai-platform/backend/app/services/auth.py +42 -0
- bioai-platform/backend/app/services/rate_limit.py +2 -2
- bioai-platform/frontend/src/app/(dashboard)/analyze/page.tsx +2 -2
- bioai-platform/frontend/src/app/(dashboard)/analyze/uniprot/page.tsx +296 -0
- bioai-platform/frontend/src/lib/api.ts +31 -0
- bioai-platform/frontend/src/types/pipeline.ts +1 -0
bioai-platform/backend/app/main.py
CHANGED
|
@@ -9,7 +9,7 @@ from slowapi import Limiter, _rate_limit_exceeded_handler
|
|
| 9 |
from slowapi.util import get_remote_address
|
| 10 |
from slowapi.errors import RateLimitExceeded
|
| 11 |
from app.config import settings
|
| 12 |
-
from app.routers import pipelines, results, ai, jobs, export, share, waitlist, profile, sequences
|
| 13 |
from app.services.cache import init_redis
|
| 14 |
from app.tools.registration import register_all_tools
|
| 15 |
|
|
@@ -44,6 +44,7 @@ app.include_router(share.router, prefix="/api/share", tags=["share"])
|
|
| 44 |
app.include_router(waitlist.router, prefix="/api/waitlist", tags=["waitlist"])
|
| 45 |
app.include_router(profile.router, prefix="/api/profile", tags=["profile"])
|
| 46 |
app.include_router(sequences.router, prefix="/api/sequences", tags=["sequences"])
|
|
|
|
| 47 |
|
| 48 |
TERMINAL_STATUSES = {"complete", "failed"}
|
| 49 |
NON_TERMINAL_STATUSES = {
|
|
|
|
| 9 |
from slowapi.util import get_remote_address
|
| 10 |
from slowapi.errors import RateLimitExceeded
|
| 11 |
from app.config import settings
|
| 12 |
+
from app.routers import pipelines, results, ai, jobs, export, share, waitlist, profile, sequences, uniprot
|
| 13 |
from app.services.cache import init_redis
|
| 14 |
from app.tools.registration import register_all_tools
|
| 15 |
|
|
|
|
| 44 |
app.include_router(waitlist.router, prefix="/api/waitlist", tags=["waitlist"])
|
| 45 |
app.include_router(profile.router, prefix="/api/profile", tags=["profile"])
|
| 46 |
app.include_router(sequences.router, prefix="/api/sequences", tags=["sequences"])
|
| 47 |
+
app.include_router(uniprot.router, prefix="/api/uniprot", tags=["uniprot"])
|
| 48 |
|
| 49 |
TERMINAL_STATUSES = {"complete", "failed"}
|
| 50 |
NON_TERMINAL_STATUSES = {
|
bioai-platform/backend/app/routers/jobs.py
CHANGED
|
@@ -2,24 +2,31 @@ from fastapi import APIRouter, HTTPException, Depends
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from datetime import datetime, timezone
|
| 4 |
from app.services.supabase import get_supabase
|
|
|
|
| 5 |
from app.models.responses import JobCountResponse, JobDeleteResponse
|
| 6 |
|
| 7 |
router = APIRouter()
|
| 8 |
|
| 9 |
|
| 10 |
@router.get("/count", response_model=JobCountResponse)
|
| 11 |
-
async def job_count(user_id: str =
|
| 12 |
supabase = get_supabase()
|
| 13 |
today = datetime.now(timezone.utc).date().isoformat()
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
count = result.count or 0
|
| 16 |
return {"count": count, "limit": 10, "remaining": max(0, 10 - count)}
|
| 17 |
|
| 18 |
|
| 19 |
@router.get("")
|
| 20 |
-
async def list_jobs(user_id: str =
|
| 21 |
supabase = get_supabase()
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
return {"jobs": result.data or []}
|
| 24 |
|
| 25 |
|
|
@@ -33,7 +40,10 @@ async def get_job(job_id: str):
|
|
| 33 |
|
| 34 |
|
| 35 |
@router.delete("/{job_id}", response_model=JobDeleteResponse)
|
| 36 |
-
async def delete_job(job_id: str):
|
| 37 |
supabase = get_supabase()
|
| 38 |
-
supabase.table("jobs").delete().eq("id", job_id)
|
|
|
|
|
|
|
|
|
|
| 39 |
return {"status": "deleted"}
|
|
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from datetime import datetime, timezone
|
| 4 |
from app.services.supabase import get_supabase
|
| 5 |
+
from app.services.auth import get_user_id
|
| 6 |
from app.models.responses import JobCountResponse, JobDeleteResponse
|
| 7 |
|
| 8 |
router = APIRouter()
|
| 9 |
|
| 10 |
|
| 11 |
@router.get("/count", response_model=JobCountResponse)
|
| 12 |
+
async def job_count(user_id: str | None = Depends(get_user_id)):
|
| 13 |
supabase = get_supabase()
|
| 14 |
today = datetime.now(timezone.utc).date().isoformat()
|
| 15 |
+
query = supabase.table("jobs").select("id", count="exact").gte("created_at", today)
|
| 16 |
+
if user_id:
|
| 17 |
+
query = query.eq("user_id", user_id)
|
| 18 |
+
result = query.execute()
|
| 19 |
count = result.count or 0
|
| 20 |
return {"count": count, "limit": 10, "remaining": max(0, 10 - count)}
|
| 21 |
|
| 22 |
|
| 23 |
@router.get("")
|
| 24 |
+
async def list_jobs(user_id: str | None = Depends(get_user_id)):
|
| 25 |
supabase = get_supabase()
|
| 26 |
+
query = supabase.table("jobs").select("*").order("created_at", desc=True).limit(50)
|
| 27 |
+
if user_id:
|
| 28 |
+
query = query.eq("user_id", user_id)
|
| 29 |
+
result = query.execute()
|
| 30 |
return {"jobs": result.data or []}
|
| 31 |
|
| 32 |
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
@router.delete("/{job_id}", response_model=JobDeleteResponse)
|
| 43 |
+
async def delete_job(job_id: str, user_id: str | None = Depends(get_user_id)):
|
| 44 |
supabase = get_supabase()
|
| 45 |
+
query = supabase.table("jobs").delete().eq("id", job_id)
|
| 46 |
+
if user_id:
|
| 47 |
+
query = query.eq("user_id", user_id)
|
| 48 |
+
query.execute()
|
| 49 |
return {"status": "deleted"}
|
bioai-platform/backend/app/routers/pipelines.py
CHANGED
|
@@ -4,6 +4,7 @@ from app.services.validators import validate_fasta
|
|
| 4 |
from app.pipeline.definitions.protein_analysis import get_pipeline_definition
|
| 5 |
from app.services.supabase import get_supabase
|
| 6 |
from app.services.rate_limit import check_daily_limit
|
|
|
|
| 7 |
from app.workers.pipeline_worker import run_pipeline_sync
|
| 8 |
from app.models.responses import PipelineRunResponse, PipelineDefinitionResponse
|
| 9 |
from datetime import datetime, timezone
|
|
@@ -20,7 +21,7 @@ class PipelineRunRequest(BaseModel):
|
|
| 20 |
|
| 21 |
|
| 22 |
@router.post("/run", response_model=PipelineRunResponse, dependencies=[Depends(check_daily_limit)])
|
| 23 |
-
async def run_pipeline(req: PipelineRunRequest):
|
| 24 |
validation = validate_fasta(req.sequence, "blast")
|
| 25 |
if not validation.valid:
|
| 26 |
raise HTTPException(status_code=400, detail=validation.error)
|
|
@@ -33,6 +34,7 @@ async def run_pipeline(req: PipelineRunRequest):
|
|
| 33 |
|
| 34 |
supabase.table("jobs").insert({
|
| 35 |
"id": job_id,
|
|
|
|
| 36 |
"tool": "pipeline",
|
| 37 |
"query_preview": clean[:100],
|
| 38 |
"status": "queued",
|
|
|
|
| 4 |
from app.pipeline.definitions.protein_analysis import get_pipeline_definition
|
| 5 |
from app.services.supabase import get_supabase
|
| 6 |
from app.services.rate_limit import check_daily_limit
|
| 7 |
+
from app.services.auth import get_user_id
|
| 8 |
from app.workers.pipeline_worker import run_pipeline_sync
|
| 9 |
from app.models.responses import PipelineRunResponse, PipelineDefinitionResponse
|
| 10 |
from datetime import datetime, timezone
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
@router.post("/run", response_model=PipelineRunResponse, dependencies=[Depends(check_daily_limit)])
|
| 24 |
+
async def run_pipeline(req: PipelineRunRequest, user_id: str | None = Depends(get_user_id)):
|
| 25 |
validation = validate_fasta(req.sequence, "blast")
|
| 26 |
if not validation.valid:
|
| 27 |
raise HTTPException(status_code=400, detail=validation.error)
|
|
|
|
| 34 |
|
| 35 |
supabase.table("jobs").insert({
|
| 36 |
"id": job_id,
|
| 37 |
+
"user_id": user_id,
|
| 38 |
"tool": "pipeline",
|
| 39 |
"query_preview": clean[:100],
|
| 40 |
"status": "queued",
|
bioai-platform/backend/app/routers/profile.py
CHANGED
|
@@ -2,6 +2,7 @@ from fastapi import APIRouter, HTTPException, Depends
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from typing import Any, Optional
|
| 4 |
from app.services.supabase import get_supabase
|
|
|
|
| 5 |
from app.models.responses import ProfileUpdateResponse
|
| 6 |
|
| 7 |
router = APIRouter()
|
|
@@ -11,15 +12,15 @@ class ProfileUpdate(BaseModel):
|
|
| 11 |
institution: str = ""
|
| 12 |
|
| 13 |
@router.get("")
|
| 14 |
-
async def get_profile(user_id: str =
|
| 15 |
supabase = get_supabase()
|
| 16 |
-
result = supabase.table("profiles").select("*").
|
| 17 |
if result.data:
|
| 18 |
return result.data[0]
|
| 19 |
return {"error": "Profile not found"}
|
| 20 |
|
| 21 |
@router.put("", response_model=ProfileUpdateResponse)
|
| 22 |
-
async def update_profile(profile: ProfileUpdate, user_id: str =
|
| 23 |
supabase = get_supabase()
|
| 24 |
data = {}
|
| 25 |
if profile.full_name: data["full_name"] = profile.full_name
|
|
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from typing import Any, Optional
|
| 4 |
from app.services.supabase import get_supabase
|
| 5 |
+
from app.services.auth import get_user_id, require_user_id
|
| 6 |
from app.models.responses import ProfileUpdateResponse
|
| 7 |
|
| 8 |
router = APIRouter()
|
|
|
|
| 12 |
institution: str = ""
|
| 13 |
|
| 14 |
@router.get("")
|
| 15 |
+
async def get_profile(user_id: str = Depends(require_user_id)):
|
| 16 |
supabase = get_supabase()
|
| 17 |
+
result = supabase.table("profiles").select("*").eq("id", user_id).execute()
|
| 18 |
if result.data:
|
| 19 |
return result.data[0]
|
| 20 |
return {"error": "Profile not found"}
|
| 21 |
|
| 22 |
@router.put("", response_model=ProfileUpdateResponse)
|
| 23 |
+
async def update_profile(profile: ProfileUpdate, user_id: str = Depends(require_user_id)):
|
| 24 |
supabase = get_supabase()
|
| 25 |
data = {}
|
| 26 |
if profile.full_name: data["full_name"] = profile.full_name
|
bioai-platform/backend/app/routers/uniprot.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException
|
| 2 |
+
from pydantic import BaseModel, Field
|
| 3 |
+
from app.tools.uniprot import UniprotTool
|
| 4 |
+
import httpx
|
| 5 |
+
from app.config import settings
|
| 6 |
+
|
| 7 |
+
router = APIRouter()
|
| 8 |
+
uniprot_tool = UniprotTool()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class UniprotSearchRequest(BaseModel):
|
| 12 |
+
query: str = Field(..., min_length=2, description="Free-text search (gene name, protein name, keyword)")
|
| 13 |
+
max_results: int = Field(20, ge=1, le=50)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class UniprotAccessionRequest(BaseModel):
|
| 17 |
+
accession: str = Field(..., min_length=1, description="UniProt accession (e.g. P04637)")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@router.post("/search")
|
| 21 |
+
async def search_uniprot(req: UniprotSearchRequest):
|
| 22 |
+
url = f"{settings.UNIPROT_BASE_URL}/search"
|
| 23 |
+
params = {"query": req.query, "format": "json", "size": req.max_results}
|
| 24 |
+
async with httpx.AsyncClient(timeout=15) as client:
|
| 25 |
+
resp = await client.get(url, params=params)
|
| 26 |
+
if resp.status_code != 200:
|
| 27 |
+
raise HTTPException(status_code=502, detail="UniProt search failed")
|
| 28 |
+
data = resp.json()
|
| 29 |
+
results = data.get("results", [])
|
| 30 |
+
out = []
|
| 31 |
+
for r in results:
|
| 32 |
+
out.append({
|
| 33 |
+
"accession": r.get("primaryAccession", ""),
|
| 34 |
+
"name": ((r.get("proteinDescription", {}) or {}).get("recommendedName", {}) or {}).get("fullName", {}).get("value", ""),
|
| 35 |
+
"gene_names": [g.get("geneName", {}).get("value", "") for g in (r.get("genes") or []) if g.get("geneName")],
|
| 36 |
+
"organism": (r.get("organism", {}) or {}).get("scientificName", ""),
|
| 37 |
+
"length": ((r.get("sequence", {}) or {}).get("length", 0)),
|
| 38 |
+
})
|
| 39 |
+
return {"results": out, "count": len(out)}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@router.post("/detail")
|
| 43 |
+
async def uniprot_detail(req: UniprotAccessionRequest):
|
| 44 |
+
result = await uniprot_tool.run({"accession": req.accession})
|
| 45 |
+
if "error" in result:
|
| 46 |
+
raise HTTPException(status_code=404, detail=result["error"])
|
| 47 |
+
return result
|
bioai-platform/backend/app/services/auth.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
from fastapi import Depends, HTTPException, Request
|
| 6 |
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
security = HTTPBearer(auto_error=False)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
async def get_user_id(
|
| 14 |
+
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
| 15 |
+
) -> str | None:
|
| 16 |
+
"""Extract Supabase user_id from the Bearer JWT, or None for anonymous users."""
|
| 17 |
+
if credentials is None:
|
| 18 |
+
return None
|
| 19 |
+
try:
|
| 20 |
+
parts = credentials.credentials.split(".")
|
| 21 |
+
if len(parts) != 3:
|
| 22 |
+
return None
|
| 23 |
+
payload = parts[1]
|
| 24 |
+
padding = 4 - len(payload) % 4
|
| 25 |
+
if padding != 4:
|
| 26 |
+
payload += "=" * padding
|
| 27 |
+
decoded = base64.urlsafe_b64decode(payload)
|
| 28 |
+
claims = json.loads(decoded)
|
| 29 |
+
return claims.get("sub")
|
| 30 |
+
except Exception:
|
| 31 |
+
logger.debug("Failed to decode JWT", exc_info=True)
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
async def require_user_id(
|
| 36 |
+
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
| 37 |
+
) -> str:
|
| 38 |
+
"""Like get_user_id but raises 401 if no valid JWT is present."""
|
| 39 |
+
uid = await get_user_id(credentials)
|
| 40 |
+
if not uid:
|
| 41 |
+
raise HTTPException(status_code=401, detail="Authentication required")
|
| 42 |
+
return uid
|
bioai-platform/backend/app/services/rate_limit.py
CHANGED
|
@@ -11,7 +11,7 @@ from app.config import settings
|
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
|
| 14 |
-
def
|
| 15 |
auth = request.headers.get("Authorization", "")
|
| 16 |
if not auth.startswith("Bearer "):
|
| 17 |
return None
|
|
@@ -32,7 +32,7 @@ def _extract_user_id(request: Request) -> str | None:
|
|
| 32 |
|
| 33 |
|
| 34 |
async def check_daily_limit(request: Request) -> None:
|
| 35 |
-
user_id =
|
| 36 |
if not user_id:
|
| 37 |
logger.info("Rate limit check skipped: no authenticated user session")
|
| 38 |
return
|
|
|
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
|
| 14 |
+
def _extract_user_id_from_request(request: Request) -> str | None:
|
| 15 |
auth = request.headers.get("Authorization", "")
|
| 16 |
if not auth.startswith("Bearer "):
|
| 17 |
return None
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
async def check_daily_limit(request: Request) -> None:
|
| 35 |
+
user_id = _extract_user_id_from_request(request)
|
| 36 |
if not user_id:
|
| 37 |
logger.info("Rate limit check skipped: no authenticated user session")
|
| 38 |
return
|
bioai-platform/frontend/src/app/(dashboard)/analyze/page.tsx
CHANGED
|
@@ -19,8 +19,8 @@ const operations = [
|
|
| 19 |
name: 'UniProt Lookup',
|
| 20 |
description: 'Retrieve detailed annotations, functions, and features for a known protein.',
|
| 21 |
icon: Globe,
|
| 22 |
-
active:
|
| 23 |
-
badge:
|
| 24 |
},
|
| 25 |
{
|
| 26 |
id: 'msa',
|
|
|
|
| 19 |
name: 'UniProt Lookup',
|
| 20 |
description: 'Retrieve detailed annotations, functions, and features for a known protein.',
|
| 21 |
icon: Globe,
|
| 22 |
+
active: true,
|
| 23 |
+
badge: null,
|
| 24 |
},
|
| 25 |
{
|
| 26 |
id: 'msa',
|
bioai-platform/frontend/src/app/(dashboard)/analyze/uniprot/page.tsx
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import { useState } from 'react';
|
| 4 |
+
import { useRouter } from 'next/navigation';
|
| 5 |
+
import { motion } from 'framer-motion';
|
| 6 |
+
import { Search, ArrowLeft, LoaderCircle, Globe, Dna, Beaker, ChevronRight, ExternalLink, BookOpen } from 'lucide-react';
|
| 7 |
+
import { fadeUp } from '@/lib/animations';
|
| 8 |
+
import { searchUniprot, getUniprotDetail } from '@/lib/api';
|
| 9 |
+
import type { UniprotSummary } from '@/types/pipeline';
|
| 10 |
+
|
| 11 |
+
type SearchResult = {
|
| 12 |
+
accession: string;
|
| 13 |
+
name: string;
|
| 14 |
+
gene_names: string[];
|
| 15 |
+
organism: string;
|
| 16 |
+
length: number;
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
export default function UniprotLookupPage() {
|
| 20 |
+
const router = useRouter();
|
| 21 |
+
const [query, setQuery] = useState('');
|
| 22 |
+
const [results, setResults] = useState<SearchResult[] | null>(null);
|
| 23 |
+
const [detail, setDetail] = useState<UniprotSummary | null>(null);
|
| 24 |
+
const [loading, setLoading] = useState(false);
|
| 25 |
+
const [detailLoading, setDetailLoading] = useState(false);
|
| 26 |
+
const [error, setError] = useState<string | null>(null);
|
| 27 |
+
|
| 28 |
+
const handleSearch = async () => {
|
| 29 |
+
if (!query.trim()) return;
|
| 30 |
+
setLoading(true);
|
| 31 |
+
setError(null);
|
| 32 |
+
setResults(null);
|
| 33 |
+
setDetail(null);
|
| 34 |
+
try {
|
| 35 |
+
const res = await searchUniprot(query.trim());
|
| 36 |
+
setResults(res.results);
|
| 37 |
+
} catch {
|
| 38 |
+
setError('Search failed');
|
| 39 |
+
} finally {
|
| 40 |
+
setLoading(false);
|
| 41 |
+
}
|
| 42 |
+
};
|
| 43 |
+
|
| 44 |
+
const handleSelect = async (accession: string) => {
|
| 45 |
+
setDetailLoading(true);
|
| 46 |
+
setError(null);
|
| 47 |
+
setDetail(null);
|
| 48 |
+
try {
|
| 49 |
+
const res = await getUniprotDetail(accession);
|
| 50 |
+
setDetail(res);
|
| 51 |
+
} catch {
|
| 52 |
+
setError('Failed to fetch details');
|
| 53 |
+
} finally {
|
| 54 |
+
setDetailLoading(false);
|
| 55 |
+
}
|
| 56 |
+
};
|
| 57 |
+
|
| 58 |
+
const handleSendToBlast = (accession: string, seq: string) => {
|
| 59 |
+
sessionStorage.setItem('blast_sequence', `>${accession}\n${seq}`);
|
| 60 |
+
router.push('/analyze/blast');
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
return (
|
| 64 |
+
<div className="max-w-3xl">
|
| 65 |
+
<button
|
| 66 |
+
onClick={() => router.push('/analyze')}
|
| 67 |
+
className="flex items-center gap-1 text-sm text-text-muted hover:text-text-primary mb-6 transition-colors"
|
| 68 |
+
>
|
| 69 |
+
<ArrowLeft className="w-4 h-4" />
|
| 70 |
+
Choose a different operation
|
| 71 |
+
</button>
|
| 72 |
+
|
| 73 |
+
<motion.div variants={fadeUp} initial="hidden" animate="show" className="mb-8">
|
| 74 |
+
<h1 className="text-2xl font-bold text-text-primary mb-1">UniProt Lookup</h1>
|
| 75 |
+
<p className="text-sm text-text-secondary">
|
| 76 |
+
Search by gene name, protein name, or keyword to retrieve comprehensive annotations.
|
| 77 |
+
</p>
|
| 78 |
+
</motion.div>
|
| 79 |
+
|
| 80 |
+
<motion.div variants={fadeUp} initial="hidden" animate="show" className="glass-card p-5 mb-6">
|
| 81 |
+
<div className="flex gap-3">
|
| 82 |
+
<input
|
| 83 |
+
type="text"
|
| 84 |
+
value={query}
|
| 85 |
+
onChange={(e) => setQuery(e.target.value)}
|
| 86 |
+
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
|
| 87 |
+
placeholder="e.g. p53, BRCA1, TP53 human, kinase"
|
| 88 |
+
className="flex-1 px-4 py-3 rounded-xl border border-glass-border focus:border-accent-cyan/40 focus:ring-2 focus:ring-accent-cyan/10 outline-none transition text-sm"
|
| 89 |
+
/>
|
| 90 |
+
<button
|
| 91 |
+
onClick={handleSearch}
|
| 92 |
+
disabled={loading || !query.trim()}
|
| 93 |
+
className="btn-primary px-6 py-3 flex items-center gap-2 disabled:opacity-50"
|
| 94 |
+
>
|
| 95 |
+
{loading ? <LoaderCircle className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
|
| 96 |
+
Search
|
| 97 |
+
</button>
|
| 98 |
+
</div>
|
| 99 |
+
</motion.div>
|
| 100 |
+
|
| 101 |
+
{error && (
|
| 102 |
+
<motion.div variants={fadeUp} initial="hidden" animate="show" className="glass-card p-4 border border-error/20">
|
| 103 |
+
<p className="text-sm text-error">{error}</p>
|
| 104 |
+
</motion.div>
|
| 105 |
+
)}
|
| 106 |
+
|
| 107 |
+
{results && !detail && (
|
| 108 |
+
<motion.div variants={fadeUp} initial="hidden" animate="show" className="space-y-3">
|
| 109 |
+
<p className="text-xs text-text-muted mb-2">{results.length} result{results.length !== 1 ? 's' : ''}</p>
|
| 110 |
+
{results.length === 0 ? (
|
| 111 |
+
<div className="glass-card p-6 text-center">
|
| 112 |
+
<p className="text-sm text-text-secondary">No results found</p>
|
| 113 |
+
</div>
|
| 114 |
+
) : (
|
| 115 |
+
results.map((r) => (
|
| 116 |
+
<button
|
| 117 |
+
key={r.accession}
|
| 118 |
+
onClick={() => handleSelect(r.accession)}
|
| 119 |
+
className="glass-card p-4 w-full text-left hover:bg-surface-2 transition cursor-pointer"
|
| 120 |
+
>
|
| 121 |
+
<div className="flex items-start justify-between gap-4">
|
| 122 |
+
<div className="min-w-0">
|
| 123 |
+
<div className="flex items-center gap-2 mb-1">
|
| 124 |
+
<code className="text-sm font-mono text-accent-cyan">{r.accession}</code>
|
| 125 |
+
<span className="badge bg-accent-cyan/10 text-accent-cyan text-[10px]">{r.length} aa</span>
|
| 126 |
+
</div>
|
| 127 |
+
<p className="text-sm text-text-primary line-clamp-1">{r.name}</p>
|
| 128 |
+
{r.gene_names.length > 0 && (
|
| 129 |
+
<div className="flex flex-wrap gap-1.5 mt-1.5">
|
| 130 |
+
{r.gene_names.map((g) => (
|
| 131 |
+
<span key={g} className="text-[10px] font-mono text-accent-purple bg-accent-purple/10 px-1.5 py-0.5 rounded">{g}</span>
|
| 132 |
+
))}
|
| 133 |
+
</div>
|
| 134 |
+
)}
|
| 135 |
+
<p className="text-xs text-text-muted mt-1">{r.organism}</p>
|
| 136 |
+
</div>
|
| 137 |
+
<ChevronRight className="w-4 h-4 text-text-muted shrink-0 mt-1" />
|
| 138 |
+
</div>
|
| 139 |
+
</button>
|
| 140 |
+
))
|
| 141 |
+
)}
|
| 142 |
+
</motion.div>
|
| 143 |
+
)}
|
| 144 |
+
|
| 145 |
+
{detailLoading && (
|
| 146 |
+
<motion.div variants={fadeUp} initial="hidden" animate="show" className="glass-card p-8 text-center">
|
| 147 |
+
<LoaderCircle className="w-6 h-6 animate-spin text-accent-cyan mx-auto mb-3" />
|
| 148 |
+
<p className="text-sm text-text-secondary">Loading UniProt entry...</p>
|
| 149 |
+
</motion.div>
|
| 150 |
+
)}
|
| 151 |
+
|
| 152 |
+
{detail && (
|
| 153 |
+
<motion.div variants={fadeUp} initial="hidden" animate="show" className="space-y-4">
|
| 154 |
+
<div className="glass-card divide-y divide-glass-border">
|
| 155 |
+
<div className="p-6">
|
| 156 |
+
<div className="flex items-start justify-between mb-4">
|
| 157 |
+
<div>
|
| 158 |
+
<div className="flex items-center gap-3 mb-2">
|
| 159 |
+
<code className="text-lg font-mono font-bold text-accent-cyan">{detail.accession}</code>
|
| 160 |
+
<Globe className="w-4 h-4 text-accent-cyan/60" />
|
| 161 |
+
</div>
|
| 162 |
+
<h2 className="text-lg font-semibold text-text-primary">{detail.full_name}</h2>
|
| 163 |
+
<p className="text-sm text-text-muted mt-1">{detail.organism}</p>
|
| 164 |
+
</div>
|
| 165 |
+
<div className="text-right">
|
| 166 |
+
<div className="text-2xl font-bold text-text-primary">{detail.sequence_length}</div>
|
| 167 |
+
<div className="text-xs text-text-muted">residues</div>
|
| 168 |
+
</div>
|
| 169 |
+
</div>
|
| 170 |
+
|
| 171 |
+
{detail.gene_names.length > 0 && (
|
| 172 |
+
<div className="mb-4">
|
| 173 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-1.5">Gene Names</p>
|
| 174 |
+
<div className="flex flex-wrap gap-2">
|
| 175 |
+
{detail.gene_names.map((g) => (
|
| 176 |
+
<span key={g} className="badge bg-accent-purple/10 text-accent-purple">{g}</span>
|
| 177 |
+
))}
|
| 178 |
+
</div>
|
| 179 |
+
</div>
|
| 180 |
+
)}
|
| 181 |
+
|
| 182 |
+
{detail.functions.length > 0 && (
|
| 183 |
+
<div className="mb-4">
|
| 184 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-1.5">Functions</p>
|
| 185 |
+
{detail.functions.map((f, i) => (
|
| 186 |
+
<p key={i} className="text-sm text-text-secondary mb-1 leading-relaxed">{f}</p>
|
| 187 |
+
))}
|
| 188 |
+
</div>
|
| 189 |
+
)}
|
| 190 |
+
</div>
|
| 191 |
+
|
| 192 |
+
{detail.keywords.length > 0 && (
|
| 193 |
+
<div className="px-6 py-4">
|
| 194 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-2">Keywords</p>
|
| 195 |
+
<div className="flex flex-wrap gap-1.5">
|
| 196 |
+
{detail.keywords.map((kw) => (
|
| 197 |
+
<span key={kw} className="text-xs bg-surface-2 text-text-secondary px-2 py-0.5 rounded-full">{kw}</span>
|
| 198 |
+
))}
|
| 199 |
+
</div>
|
| 200 |
+
</div>
|
| 201 |
+
)}
|
| 202 |
+
|
| 203 |
+
{detail.subcellular_locations.length > 0 && (
|
| 204 |
+
<div className="px-6 py-4">
|
| 205 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-2">Subcellular Locations</p>
|
| 206 |
+
{detail.subcellular_locations.map((loc, i) => (
|
| 207 |
+
<p key={i} className="text-sm text-text-secondary">{loc}</p>
|
| 208 |
+
))}
|
| 209 |
+
</div>
|
| 210 |
+
)}
|
| 211 |
+
|
| 212 |
+
{detail.go_terms.length > 0 && (
|
| 213 |
+
<div className="px-6 py-4">
|
| 214 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-2">GO Terms</p>
|
| 215 |
+
<div className="flex flex-wrap gap-1.5">
|
| 216 |
+
{detail.go_terms.map((go) => (
|
| 217 |
+
<span key={go} className="text-xs font-mono text-accent-amber bg-accent-amber/10 px-2 py-0.5 rounded-full">{go}</span>
|
| 218 |
+
))}
|
| 219 |
+
</div>
|
| 220 |
+
</div>
|
| 221 |
+
)}
|
| 222 |
+
|
| 223 |
+
{detail.features.length > 0 && (
|
| 224 |
+
<div className="px-6 py-4">
|
| 225 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-2">Features</p>
|
| 226 |
+
<div className="space-y-1 max-h-48 overflow-y-auto">
|
| 227 |
+
{detail.features.slice(0, 20).map((f, i) => (
|
| 228 |
+
<div key={i} className="flex items-center gap-3 text-sm py-0.5">
|
| 229 |
+
<span className="badge bg-surface-2 text-text-secondary text-[10px]">{f.type}</span>
|
| 230 |
+
<span className="text-text-secondary truncate">{f.description}</span>
|
| 231 |
+
{f.begin && f.end && (
|
| 232 |
+
<span className="text-xs text-text-muted ml-auto shrink-0">{f.begin}–{f.end}</span>
|
| 233 |
+
)}
|
| 234 |
+
</div>
|
| 235 |
+
))}
|
| 236 |
+
{detail.features.length > 20 && (
|
| 237 |
+
<p className="text-xs text-text-muted mt-1">+{detail.features.length - 20} more features</p>
|
| 238 |
+
)}
|
| 239 |
+
</div>
|
| 240 |
+
</div>
|
| 241 |
+
)}
|
| 242 |
+
|
| 243 |
+
{detail.pdb_ids.length > 0 && (
|
| 244 |
+
<div className="px-6 py-4">
|
| 245 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-2">PDB Structures</p>
|
| 246 |
+
<div className="flex flex-wrap gap-2">
|
| 247 |
+
{detail.pdb_ids.map((pdb) => (
|
| 248 |
+
<a
|
| 249 |
+
key={pdb}
|
| 250 |
+
href={`https://www.rcsb.org/structure/${pdb}`}
|
| 251 |
+
target="_blank"
|
| 252 |
+
rel="noopener noreferrer"
|
| 253 |
+
className="badge bg-accent-cyan/10 text-accent-cyan hover:bg-accent-cyan/20 transition flex items-center gap-1"
|
| 254 |
+
>
|
| 255 |
+
{pdb}
|
| 256 |
+
<ExternalLink className="w-3 h-3" />
|
| 257 |
+
</a>
|
| 258 |
+
))}
|
| 259 |
+
</div>
|
| 260 |
+
</div>
|
| 261 |
+
)}
|
| 262 |
+
|
| 263 |
+
{detail.sequence && (
|
| 264 |
+
<div className="px-6 py-4">
|
| 265 |
+
<p className="text-xs font-medium text-text-muted uppercase tracking-wider mb-2">Sequence</p>
|
| 266 |
+
<pre className="font-mono text-xs text-text-secondary bg-surface-0 rounded-xl p-4 max-h-32 overflow-auto break-all whitespace-pre-wrap">
|
| 267 |
+
{detail.sequence}
|
| 268 |
+
</pre>
|
| 269 |
+
</div>
|
| 270 |
+
)}
|
| 271 |
+
|
| 272 |
+
<div className="px-6 py-4 flex items-center justify-between">
|
| 273 |
+
<a
|
| 274 |
+
href={`https://www.uniprot.org/uniprotkb/${detail.accession}`}
|
| 275 |
+
target="_blank"
|
| 276 |
+
rel="noopener noreferrer"
|
| 277 |
+
className="text-xs text-text-muted hover:text-accent-cyan transition flex items-center gap-1"
|
| 278 |
+
>
|
| 279 |
+
<BookOpen className="w-3 h-3" />
|
| 280 |
+
View on UniProt
|
| 281 |
+
<ExternalLink className="w-3 h-3" />
|
| 282 |
+
</a>
|
| 283 |
+
<button
|
| 284 |
+
onClick={() => handleSendToBlast(detail.accession, detail.sequence)}
|
| 285 |
+
className="btn-primary py-2 px-4 text-sm flex items-center gap-2"
|
| 286 |
+
>
|
| 287 |
+
<Beaker className="w-4 h-4" />
|
| 288 |
+
Analyze with BLAST
|
| 289 |
+
</button>
|
| 290 |
+
</div>
|
| 291 |
+
</div>
|
| 292 |
+
</motion.div>
|
| 293 |
+
)}
|
| 294 |
+
</div>
|
| 295 |
+
);
|
| 296 |
+
}
|
bioai-platform/frontend/src/lib/api.ts
CHANGED
|
@@ -1,10 +1,24 @@
|
|
| 1 |
import axios from 'axios';
|
| 2 |
import type { JobStatus, PipelineDefinition, AssembledContext, BlastSummary, UniprotSummary, AlphaFoldResult, SequenceResult, SequenceValidation, SequenceSearchResponse } from '@/types/pipeline';
|
|
|
|
| 3 |
|
| 4 |
const api = axios.create({
|
| 5 |
baseURL: '/api/backend',
|
| 6 |
});
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
export async function runPipeline(
|
| 9 |
sequence: string,
|
| 10 |
pipelineType: string = 'protein_analysis',
|
|
@@ -78,6 +92,23 @@ export async function validateSequence(sequence: string): Promise<SequenceValida
|
|
| 78 |
return res.data;
|
| 79 |
}
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
export async function searchSequences(query: string, db: string = 'protein', maxResults: number = 10): Promise<SequenceSearchResponse> {
|
| 82 |
const res = await api.post('/api/sequences/search', {
|
| 83 |
query,
|
|
|
|
| 1 |
import axios from 'axios';
|
| 2 |
import type { JobStatus, PipelineDefinition, AssembledContext, BlastSummary, UniprotSummary, AlphaFoldResult, SequenceResult, SequenceValidation, SequenceSearchResponse } from '@/types/pipeline';
|
| 3 |
+
import { getSupabase } from './supabase';
|
| 4 |
|
| 5 |
const api = axios.create({
|
| 6 |
baseURL: '/api/backend',
|
| 7 |
});
|
| 8 |
|
| 9 |
+
api.interceptors.request.use(async (config) => {
|
| 10 |
+
try {
|
| 11 |
+
const supabase = getSupabase();
|
| 12 |
+
const { data: { session } } = await supabase.auth.getSession();
|
| 13 |
+
if (session?.access_token) {
|
| 14 |
+
config.headers.Authorization = `Bearer ${session.access_token}`;
|
| 15 |
+
}
|
| 16 |
+
} catch {
|
| 17 |
+
// Session fetch failed silently — requests will be anonymous
|
| 18 |
+
}
|
| 19 |
+
return config;
|
| 20 |
+
});
|
| 21 |
+
|
| 22 |
export async function runPipeline(
|
| 23 |
sequence: string,
|
| 24 |
pipelineType: string = 'protein_analysis',
|
|
|
|
| 92 |
return res.data;
|
| 93 |
}
|
| 94 |
|
| 95 |
+
export async function searchUniprot(query: string, maxResults: number = 20): Promise<{ results: UniprotSearchResult[]; count: number }> {
|
| 96 |
+
const res = await api.post('/api/uniprot/search', { query, max_results: maxResults });
|
| 97 |
+
return res.data;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
export async function getUniprotDetail(accession: string): Promise<UniprotSummary> {
|
| 101 |
+
const res = await api.post('/api/uniprot/detail', { accession });
|
| 102 |
+
return res.data;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
export type UniprotSearchResult = {
|
| 106 |
+
accession: string;
|
| 107 |
+
name: string;
|
| 108 |
+
gene_names: string[];
|
| 109 |
+
organism: string;
|
| 110 |
+
length: number;
|
| 111 |
+
};
|
| 112 |
export async function searchSequences(query: string, db: string = 'protein', maxResults: number = 10): Promise<SequenceSearchResponse> {
|
| 113 |
const res = await api.post('/api/sequences/search', {
|
| 114 |
query,
|
bioai-platform/frontend/src/types/pipeline.ts
CHANGED
|
@@ -144,6 +144,7 @@ export interface UniprotSummary {
|
|
| 144 |
features: UniprotFeature[];
|
| 145 |
go_terms: string[];
|
| 146 |
sequence_length: number;
|
|
|
|
| 147 |
}
|
| 148 |
|
| 149 |
export interface UniprotFeature {
|
|
|
|
| 144 |
features: UniprotFeature[];
|
| 145 |
go_terms: string[];
|
| 146 |
sequence_length: number;
|
| 147 |
+
sequence: string;
|
| 148 |
}
|
| 149 |
|
| 150 |
export interface UniprotFeature {
|