Spaces:
Runtime error
Runtime error
Upload 51 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- app/__init__.py +1 -0
- app/api/__init__.py +1 -0
- app/api/__pycache__/__init__.cpython-314.pyc +0 -0
- app/api/__pycache__/algorithms.cpython-314.pyc +0 -0
- app/api/__pycache__/datasets.cpython-314.pyc +0 -0
- app/api/__pycache__/runs.cpython-314.pyc +0 -0
- app/api/algorithms.py +37 -0
- app/api/datasets.py +157 -0
- app/api/docs.py +38 -0
- app/api/jobs.py +144 -0
- app/api/results.py +275 -0
- app/api/runs.py +149 -0
- app/config.py +0 -0
- app/core/__init__.py +1 -0
- app/core/config.py +110 -0
- app/core/logging.py +146 -0
- app/core/tasks.py +60 -0
- app/main.py +435 -0
- app/models/__init__.py +1 -0
- app/models/compare.py +0 -0
- app/models/dashboard.py +0 -0
- app/models/dataset.py +87 -0
- app/models/datasets.py +0 -0
- app/models/explorer.py +0 -0
- app/models/job.py +88 -0
- app/models/result.py +82 -0
- app/models/run.py +0 -0
- app/registry/__init__.py +0 -0
- app/registry/catalog.py +29 -0
- app/registry/runs.py +106 -0
- app/services/__init__.py +1 -0
- app/services/__pycache__/__init__.cpython-314.pyc +0 -0
- app/services/__pycache__/beeline_runner.cpython-314.pyc +0 -0
- app/services/__pycache__/hf_datasets.cpython-314.pyc +0 -0
- app/services/__pycache__/storage.cpython-314.pyc +0 -0
- app/services/beeline.py +141 -0
- app/services/beeline_runner.py +38 -0
- app/services/datasets.py +37 -0
- app/services/datasets_service.py +249 -0
- app/services/hf_datasets.py +232 -0
- app/services/inference_service.py +256 -0
- app/services/jobs_service.py +273 -0
- app/services/metrics.py +47 -0
- app/services/results_parser.py +39 -0
- app/services/runners/__init__.py +1 -0
- app/services/runners/generic_runner.py +101 -0
- app/services/runners/utils.py +179 -0
- app/services/runs.py +61 -0
- app/services/storage.py +101 -0
- app/workers/__init__.py +1 -0
app/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""App module init."""
|
app/api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""API module init."""
|
app/api/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (159 Bytes). View file
|
|
|
app/api/__pycache__/algorithms.cpython-314.pyc
ADDED
|
Binary file (466 Bytes). View file
|
|
|
app/api/__pycache__/datasets.cpython-314.pyc
ADDED
|
Binary file (490 Bytes). View file
|
|
|
app/api/__pycache__/runs.cpython-314.pyc
ADDED
|
Binary file (990 Bytes). View file
|
|
|
app/api/algorithms.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter
|
| 2 |
+
from app.registry.catalog import ALGORITHMS
|
| 3 |
+
|
| 4 |
+
router = APIRouter(prefix="/algorithms", tags=["Algorithms"])
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
BEELINE_ALGORITHMS = [
|
| 8 |
+
"grnboost2",
|
| 9 |
+
"genie3",
|
| 10 |
+
"clr",
|
| 11 |
+
"aracne",
|
| 12 |
+
"mrnet",
|
| 13 |
+
"pearson",
|
| 14 |
+
"spearman",
|
| 15 |
+
"pidc",
|
| 16 |
+
"inferelator",
|
| 17 |
+
"tigress",
|
| 18 |
+
"pcc",
|
| 19 |
+
"glasso"
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
@router.get("/")
|
| 23 |
+
def list_algorithms():
|
| 24 |
+
"""
|
| 25 |
+
List all BEELINE Docker algorithms
|
| 26 |
+
"""
|
| 27 |
+
return [
|
| 28 |
+
{
|
| 29 |
+
"name": alg,
|
| 30 |
+
"docker_image": f"grnbeeline/{alg}"
|
| 31 |
+
}
|
| 32 |
+
for alg in BEELINE_ALGORITHMS
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
@router.get("/", summary="List BEELINE algorithms")
|
| 36 |
+
def list_algorithms():
|
| 37 |
+
return ALGORITHMS
|
app/api/datasets.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
API endpoints for dataset management.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from fastapi import APIRouter, Query, HTTPException, status
|
| 7 |
+
from fastapi.responses import FileResponse
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
from app.models.dataset import (
|
| 11 |
+
DatasetCreate,
|
| 12 |
+
DatasetResponse,
|
| 13 |
+
DatasetListResponse,
|
| 14 |
+
DatasetPreview,
|
| 15 |
+
DatasetUpdate,
|
| 16 |
+
)
|
| 17 |
+
from app.services.datasets_service import dataset_service
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
router = APIRouter(prefix="/datasets", tags=["datasets"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@router.post("/register", response_model=DatasetResponse, status_code=status.HTTP_201_CREATED)
|
| 24 |
+
async def register_dataset(dataset: DatasetCreate) -> DatasetResponse:
|
| 25 |
+
"""Register a new dataset."""
|
| 26 |
+
try:
|
| 27 |
+
result = await dataset_service.register_dataset(
|
| 28 |
+
name=dataset.name,
|
| 29 |
+
description=dataset.description,
|
| 30 |
+
source=dataset.source,
|
| 31 |
+
schema=dataset.schema,
|
| 32 |
+
species=dataset.species,
|
| 33 |
+
tissue=dataset.tissue,
|
| 34 |
+
)
|
| 35 |
+
return result
|
| 36 |
+
except Exception as e:
|
| 37 |
+
logger.error(f"Failed to register dataset: {str(e)}")
|
| 38 |
+
raise HTTPException(
|
| 39 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 40 |
+
detail=f"Failed to register dataset: {str(e)}",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@router.get("", response_model=DatasetListResponse)
|
| 45 |
+
async def list_datasets(
|
| 46 |
+
skip: int = Query(0, ge=0),
|
| 47 |
+
limit: int = Query(10, ge=1, le=100),
|
| 48 |
+
) -> DatasetListResponse:
|
| 49 |
+
"""List all registered datasets."""
|
| 50 |
+
try:
|
| 51 |
+
result = await dataset_service.list_datasets(skip=skip, limit=limit)
|
| 52 |
+
return DatasetListResponse(**result)
|
| 53 |
+
except Exception as e:
|
| 54 |
+
logger.error(f"Failed to list datasets: {str(e)}")
|
| 55 |
+
raise HTTPException(
|
| 56 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 57 |
+
detail="Failed to list datasets",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@router.get("/{dataset_id}", response_model=DatasetResponse)
|
| 62 |
+
async def get_dataset(dataset_id: str) -> DatasetResponse:
|
| 63 |
+
"""Get dataset by ID."""
|
| 64 |
+
try:
|
| 65 |
+
dataset = await dataset_service.get_dataset(dataset_id)
|
| 66 |
+
if not dataset:
|
| 67 |
+
raise HTTPException(
|
| 68 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 69 |
+
detail=f"Dataset {dataset_id} not found",
|
| 70 |
+
)
|
| 71 |
+
return dataset
|
| 72 |
+
except HTTPException:
|
| 73 |
+
raise
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"Failed to get dataset: {str(e)}")
|
| 76 |
+
raise HTTPException(
|
| 77 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 78 |
+
detail="Failed to get dataset",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@router.get("/{dataset_id}/preview", response_model=DatasetPreview)
|
| 83 |
+
async def get_dataset_preview(
|
| 84 |
+
dataset_id: str,
|
| 85 |
+
num_rows: int = Query(5, ge=1, le=100),
|
| 86 |
+
) -> DatasetPreview:
|
| 87 |
+
"""Get preview of dataset."""
|
| 88 |
+
try:
|
| 89 |
+
preview = await dataset_service.get_dataset_preview(
|
| 90 |
+
dataset_id=dataset_id,
|
| 91 |
+
num_rows=num_rows,
|
| 92 |
+
)
|
| 93 |
+
if not preview:
|
| 94 |
+
raise HTTPException(
|
| 95 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 96 |
+
detail=f"Cannot preview dataset {dataset_id}",
|
| 97 |
+
)
|
| 98 |
+
return DatasetPreview(**preview)
|
| 99 |
+
except HTTPException:
|
| 100 |
+
raise
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Failed to preview dataset: {str(e)}")
|
| 103 |
+
raise HTTPException(
|
| 104 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 105 |
+
detail="Failed to preview dataset",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@router.patch("/{dataset_id}", response_model=DatasetResponse)
|
| 110 |
+
async def update_dataset(
|
| 111 |
+
dataset_id: str,
|
| 112 |
+
dataset_update: DatasetUpdate,
|
| 113 |
+
) -> DatasetResponse:
|
| 114 |
+
"""Update dataset metadata."""
|
| 115 |
+
try:
|
| 116 |
+
if dataset_update.metadata:
|
| 117 |
+
result = await dataset_service.update_dataset_metadata(
|
| 118 |
+
dataset_id=dataset_id,
|
| 119 |
+
metadata=dataset_update.metadata,
|
| 120 |
+
)
|
| 121 |
+
return result
|
| 122 |
+
else:
|
| 123 |
+
dataset = await dataset_service.get_dataset(dataset_id)
|
| 124 |
+
if not dataset:
|
| 125 |
+
raise HTTPException(
|
| 126 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 127 |
+
detail=f"Dataset {dataset_id} not found",
|
| 128 |
+
)
|
| 129 |
+
return dataset
|
| 130 |
+
except HTTPException:
|
| 131 |
+
raise
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.error(f"Failed to update dataset: {str(e)}")
|
| 134 |
+
raise HTTPException(
|
| 135 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 136 |
+
detail="Failed to update dataset",
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@router.delete("/{dataset_id}", status_code=status.HTTP_204_NO_CONTENT)
|
| 141 |
+
async def delete_dataset(dataset_id: str):
|
| 142 |
+
"""Delete a dataset."""
|
| 143 |
+
try:
|
| 144 |
+
success = await dataset_service.delete_dataset(dataset_id)
|
| 145 |
+
if not success:
|
| 146 |
+
raise HTTPException(
|
| 147 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 148 |
+
detail=f"Dataset {dataset_id} not found",
|
| 149 |
+
)
|
| 150 |
+
except HTTPException:
|
| 151 |
+
raise
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logger.error(f"Failed to delete dataset: {str(e)}")
|
| 154 |
+
raise HTTPException(
|
| 155 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 156 |
+
detail="Failed to delete dataset",
|
| 157 |
+
)
|
app/api/docs.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter
|
| 2 |
+
from app.registry.catalog import DATASETS, ALGORITHMS
|
| 3 |
+
|
| 4 |
+
router = APIRouter(prefix="/docs", tags=["Documentation"])
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@router.get("/", summary="System overview and API guide")
|
| 8 |
+
def system_docs():
|
| 9 |
+
return {
|
| 10 |
+
"name": "WebGenie BEELINE Platform",
|
| 11 |
+
"description": (
|
| 12 |
+
"A web-based execution, benchmarking, and comparison platform "
|
| 13 |
+
"for BEELINE GRN inference algorithms."
|
| 14 |
+
),
|
| 15 |
+
"concepts": {
|
| 16 |
+
"datasets": "scRNA-seq benchmark datasets hosted on Hugging Face",
|
| 17 |
+
"algorithms": "BEELINE GRN inference algorithms executed via Docker",
|
| 18 |
+
"runs": "Asynchronous benchmark executions",
|
| 19 |
+
"metrics": ["AUROC", "AUPRC", "F1"]
|
| 20 |
+
},
|
| 21 |
+
"canonical_dataset_ids": "Hugging Face dataset IDs (not UI aliases)",
|
| 22 |
+
"example_dataset_id": DATASETS[0]["id"],
|
| 23 |
+
"workflow": [
|
| 24 |
+
"GET /datasets",
|
| 25 |
+
"GET /algorithms",
|
| 26 |
+
"POST /runs",
|
| 27 |
+
"GET /runs/{run_id}",
|
| 28 |
+
"GET /runs/{run_id}/metrics"
|
| 29 |
+
],
|
| 30 |
+
"example_run_payload": {
|
| 31 |
+
"dataset_id": DATASETS[0]["id"],
|
| 32 |
+
"algorithms": ["grnbeeline/genie3"],
|
| 33 |
+
"params": {
|
| 34 |
+
"num_trees": 100
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
+
"frontend": "https://github.com/ukanduchimeremezejames/WebGenieDark"
|
| 38 |
+
}
|
app/api/jobs.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
API endpoints for job management.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from fastapi import APIRouter, Query, HTTPException, status
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
from app.models.job import (
|
| 10 |
+
JobCreate,
|
| 11 |
+
JobResponse,
|
| 12 |
+
JobListResponse,
|
| 13 |
+
JobStatusEnum,
|
| 14 |
+
JobLogResponse,
|
| 15 |
+
JobCancellationResponse,
|
| 16 |
+
)
|
| 17 |
+
from app.services.jobs_service import job_service
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@router.post("", response_model=JobResponse, status_code=status.HTTP_201_CREATED)
|
| 24 |
+
async def submit_job(job: JobCreate) -> JobResponse:
|
| 25 |
+
"""Submit a new inference job."""
|
| 26 |
+
try:
|
| 27 |
+
result = await job_service.submit_job(
|
| 28 |
+
dataset_id=job.dataset_id,
|
| 29 |
+
algorithm=job.algorithm,
|
| 30 |
+
parameters=job.parameters,
|
| 31 |
+
name=job.name,
|
| 32 |
+
description=job.description,
|
| 33 |
+
)
|
| 34 |
+
return result
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.error(f"Failed to submit job: {str(e)}")
|
| 37 |
+
raise HTTPException(
|
| 38 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 39 |
+
detail=f"Failed to submit job: {str(e)}",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@router.get("", response_model=JobListResponse)
|
| 44 |
+
async def list_jobs(
|
| 45 |
+
skip: int = Query(0, ge=0),
|
| 46 |
+
limit: int = Query(10, ge=1, le=100),
|
| 47 |
+
status_filter: Optional[JobStatusEnum] = Query(None, alias="status"),
|
| 48 |
+
dataset_id: Optional[str] = None,
|
| 49 |
+
algorithm: Optional[str] = None,
|
| 50 |
+
) -> JobListResponse:
|
| 51 |
+
"""List jobs with optional filters."""
|
| 52 |
+
try:
|
| 53 |
+
result = await job_service.list_jobs(
|
| 54 |
+
skip=skip,
|
| 55 |
+
limit=limit,
|
| 56 |
+
status=status_filter,
|
| 57 |
+
dataset_id=dataset_id,
|
| 58 |
+
algorithm=algorithm,
|
| 59 |
+
)
|
| 60 |
+
return JobListResponse(**result)
|
| 61 |
+
except Exception as e:
|
| 62 |
+
logger.error(f"Failed to list jobs: {str(e)}")
|
| 63 |
+
raise HTTPException(
|
| 64 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 65 |
+
detail="Failed to list jobs",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@router.get("/{job_id}", response_model=JobResponse)
|
| 70 |
+
async def get_job(job_id: str) -> JobResponse:
|
| 71 |
+
"""Get job by ID."""
|
| 72 |
+
try:
|
| 73 |
+
job = await job_service.get_job(job_id)
|
| 74 |
+
if not job:
|
| 75 |
+
raise HTTPException(
|
| 76 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 77 |
+
detail=f"Job {job_id} not found",
|
| 78 |
+
)
|
| 79 |
+
return job
|
| 80 |
+
except HTTPException:
|
| 81 |
+
raise
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.error(f"Failed to get job: {str(e)}")
|
| 84 |
+
raise HTTPException(
|
| 85 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 86 |
+
detail="Failed to get job",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@router.get("/{job_id}/logs", response_model=JobLogResponse)
|
| 91 |
+
async def get_job_logs(job_id: str) -> JobLogResponse:
|
| 92 |
+
"""Get job execution logs."""
|
| 93 |
+
try:
|
| 94 |
+
job = await job_service.get_job(job_id)
|
| 95 |
+
if not job:
|
| 96 |
+
raise HTTPException(
|
| 97 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 98 |
+
detail=f"Job {job_id} not found",
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
logs = await job_service.get_job_logs(job_id)
|
| 102 |
+
if logs is None:
|
| 103 |
+
logs = "No logs available"
|
| 104 |
+
|
| 105 |
+
return JobLogResponse(
|
| 106 |
+
job_id=job_id,
|
| 107 |
+
logs=logs,
|
| 108 |
+
timestamp=job.updated_at or job.started_at,
|
| 109 |
+
)
|
| 110 |
+
except HTTPException:
|
| 111 |
+
raise
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logger.error(f"Failed to get job logs: {str(e)}")
|
| 114 |
+
raise HTTPException(
|
| 115 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 116 |
+
detail="Failed to retrieve logs",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@router.delete("/{job_id}", response_model=JobCancellationResponse)
|
| 121 |
+
async def cancel_job(job_id: str) -> JobCancellationResponse:
|
| 122 |
+
"""Cancel a job."""
|
| 123 |
+
try:
|
| 124 |
+
success = await job_service.cancel_job(job_id)
|
| 125 |
+
|
| 126 |
+
if not success:
|
| 127 |
+
raise HTTPException(
|
| 128 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 129 |
+
detail=f"Cannot cancel job {job_id}",
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
return JobCancellationResponse(
|
| 133 |
+
job_id=job_id,
|
| 134 |
+
cancelled=True,
|
| 135 |
+
message=f"Job {job_id} cancellation requested",
|
| 136 |
+
)
|
| 137 |
+
except HTTPException:
|
| 138 |
+
raise
|
| 139 |
+
except Exception as e:
|
| 140 |
+
logger.error(f"Failed to cancel job: {str(e)}")
|
| 141 |
+
raise HTTPException(
|
| 142 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 143 |
+
detail="Failed to cancel job",
|
| 144 |
+
)
|
app/api/results.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
API endpoints for result management.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from fastapi import APIRouter, Query, HTTPException, status, FileResponse
|
| 7 |
+
from fastapi.responses import StreamingResponse
|
| 8 |
+
import logging
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from app.models.result import (
|
| 12 |
+
ResultResponse,
|
| 13 |
+
ResultListResponse,
|
| 14 |
+
NetworkComparison,
|
| 15 |
+
ResultSummary,
|
| 16 |
+
)
|
| 17 |
+
from app.workers.tasks import compute_metrics, compare_networks, export_results
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
router = APIRouter(prefix="/results", tags=["results"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@router.get("/job/{job_id}", response_model=ResultResponse)
|
| 24 |
+
async def get_job_result(job_id: str) -> ResultResponse:
|
| 25 |
+
"""Get result for a job."""
|
| 26 |
+
try:
|
| 27 |
+
from app.core.config import settings
|
| 28 |
+
|
| 29 |
+
job_dir = settings.RESULTS_DIR / job_id
|
| 30 |
+
if not job_dir.exists():
|
| 31 |
+
raise HTTPException(
|
| 32 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 33 |
+
detail=f"Result for job {job_id} not found",
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Find network file
|
| 37 |
+
network_file = None
|
| 38 |
+
for f in job_dir.glob("*_network.*"):
|
| 39 |
+
if f.is_file():
|
| 40 |
+
network_file = f
|
| 41 |
+
break
|
| 42 |
+
|
| 43 |
+
if not network_file:
|
| 44 |
+
raise HTTPException(
|
| 45 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 46 |
+
detail="Network file not found",
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
result_data = {
|
| 50 |
+
"id": job_id,
|
| 51 |
+
"job_id": job_id,
|
| 52 |
+
"dataset_id": "unknown",
|
| 53 |
+
"algorithm": "unknown",
|
| 54 |
+
"network_file": str(network_file),
|
| 55 |
+
"created_at": datetime.utcnow(),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
return ResultResponse(**result_data)
|
| 59 |
+
|
| 60 |
+
except HTTPException:
|
| 61 |
+
raise
|
| 62 |
+
except Exception as e:
|
| 63 |
+
logger.error(f"Failed to get result: {str(e)}")
|
| 64 |
+
raise HTTPException(
|
| 65 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 66 |
+
detail="Failed to get result",
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@router.get("/job/{job_id}/summary", response_model=ResultSummary)
|
| 71 |
+
async def get_result_summary(job_id: str) -> ResultSummary:
|
| 72 |
+
"""Get result summary."""
|
| 73 |
+
try:
|
| 74 |
+
from app.core.config import settings
|
| 75 |
+
import pandas as pd
|
| 76 |
+
|
| 77 |
+
job_dir = settings.RESULTS_DIR / job_id
|
| 78 |
+
|
| 79 |
+
# Find network file
|
| 80 |
+
network_file = None
|
| 81 |
+
for f in job_dir.glob("*_network.*"):
|
| 82 |
+
if f.is_file():
|
| 83 |
+
network_file = f
|
| 84 |
+
break
|
| 85 |
+
|
| 86 |
+
if not network_file:
|
| 87 |
+
raise HTTPException(
|
| 88 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 89 |
+
detail="Network file not found",
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Compute metrics
|
| 93 |
+
network = pd.read_csv(network_file, sep="\t", header=None)
|
| 94 |
+
num_edges = len(network)
|
| 95 |
+
nodes = set(network[0]) | set(network[1])
|
| 96 |
+
num_nodes = len(nodes)
|
| 97 |
+
|
| 98 |
+
# Compute density
|
| 99 |
+
density = (2 * num_edges) / (num_nodes * (num_nodes - 1)) if num_nodes > 1 else 0
|
| 100 |
+
|
| 101 |
+
# Compute degree statistics
|
| 102 |
+
degree_dict = {}
|
| 103 |
+
for _, row in network.iterrows():
|
| 104 |
+
degree_dict[row[0]] = degree_dict.get(row[0], 0) + 1
|
| 105 |
+
degree_dict[row[1]] = degree_dict.get(row[1], 0) + 1
|
| 106 |
+
|
| 107 |
+
degrees = list(degree_dict.values())
|
| 108 |
+
avg_degree = sum(degrees) / len(degrees) if degrees else 0
|
| 109 |
+
max_degree = max(degrees) if degrees else 0
|
| 110 |
+
|
| 111 |
+
summary = ResultSummary(
|
| 112 |
+
total_edges=num_edges,
|
| 113 |
+
num_nodes=num_nodes,
|
| 114 |
+
density=float(density),
|
| 115 |
+
avg_degree=float(avg_degree),
|
| 116 |
+
max_degree=int(max_degree),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
return summary
|
| 120 |
+
|
| 121 |
+
except HTTPException:
|
| 122 |
+
raise
|
| 123 |
+
except Exception as e:
|
| 124 |
+
logger.error(f"Failed to compute summary: {str(e)}")
|
| 125 |
+
raise HTTPException(
|
| 126 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 127 |
+
detail="Failed to compute summary",
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@router.post("/compare", response_model=NetworkComparison)
|
| 132 |
+
async def compare_result_networks(
|
| 133 |
+
job_id_1: str,
|
| 134 |
+
job_id_2: str,
|
| 135 |
+
) -> NetworkComparison:
|
| 136 |
+
"""Compare two result networks."""
|
| 137 |
+
try:
|
| 138 |
+
from app.core.config import settings
|
| 139 |
+
import pandas as pd
|
| 140 |
+
|
| 141 |
+
# Find network files
|
| 142 |
+
def get_network_file(job_id: str) -> Path:
|
| 143 |
+
job_dir = settings.RESULTS_DIR / job_id
|
| 144 |
+
for f in job_dir.glob("*_network.*"):
|
| 145 |
+
if f.is_file():
|
| 146 |
+
return f
|
| 147 |
+
raise FileNotFoundError(f"Network file for job {job_id}")
|
| 148 |
+
|
| 149 |
+
network_file_1 = get_network_file(job_id_1)
|
| 150 |
+
network_file_2 = get_network_file(job_id_2)
|
| 151 |
+
|
| 152 |
+
# Load networks
|
| 153 |
+
net1 = pd.read_csv(network_file_1, sep="\t", header=None)
|
| 154 |
+
net2 = pd.read_csv(network_file_2, sep="\t", header=None)
|
| 155 |
+
|
| 156 |
+
# Convert to edge sets
|
| 157 |
+
edges1 = set(zip(net1[0], net1[1]))
|
| 158 |
+
edges2 = set(zip(net2[0], net2[1]))
|
| 159 |
+
|
| 160 |
+
# Compute metrics
|
| 161 |
+
intersection = edges1 & edges2
|
| 162 |
+
union = edges1 | edges2
|
| 163 |
+
jaccard_index = len(intersection) / len(union) if len(union) > 0 else 0
|
| 164 |
+
|
| 165 |
+
comparison = NetworkComparison(
|
| 166 |
+
network1_id=job_id_1,
|
| 167 |
+
network2_id=job_id_2,
|
| 168 |
+
jaccard_index=float(jaccard_index),
|
| 169 |
+
overlap_edges=len(intersection),
|
| 170 |
+
edges_only_in_1=len(edges1 - edges2),
|
| 171 |
+
edges_only_in_2=len(edges2 - edges1),
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
return comparison
|
| 175 |
+
|
| 176 |
+
except Exception as e:
|
| 177 |
+
logger.error(f"Failed to compare networks: {str(e)}")
|
| 178 |
+
raise HTTPException(
|
| 179 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 180 |
+
detail="Failed to compare networks",
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@router.get("/job/{job_id}/network/download")
|
| 185 |
+
async def download_network(job_id: str, format: str = "tsv"):
|
| 186 |
+
"""Download network file."""
|
| 187 |
+
try:
|
| 188 |
+
from app.core.config import settings
|
| 189 |
+
|
| 190 |
+
job_dir = settings.RESULTS_DIR / job_id
|
| 191 |
+
|
| 192 |
+
# Find network file
|
| 193 |
+
network_file = None
|
| 194 |
+
for f in job_dir.glob("*_network.*"):
|
| 195 |
+
if f.is_file():
|
| 196 |
+
network_file = f
|
| 197 |
+
break
|
| 198 |
+
|
| 199 |
+
if not network_file:
|
| 200 |
+
raise HTTPException(
|
| 201 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 202 |
+
detail="Network file not found",
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
if format.lower() == "json":
|
| 206 |
+
import pandas as pd
|
| 207 |
+
import json
|
| 208 |
+
|
| 209 |
+
network = pd.read_csv(network_file, sep="\t", header=None)
|
| 210 |
+
data = {
|
| 211 |
+
"edges": [
|
| 212 |
+
{
|
| 213 |
+
"source": row[0],
|
| 214 |
+
"target": row[1],
|
| 215 |
+
"weight": float(row[2]) if len(row) > 2 else 1.0,
|
| 216 |
+
}
|
| 217 |
+
for _, row in network.iterrows()
|
| 218 |
+
]
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
from io import BytesIO
|
| 222 |
+
|
| 223 |
+
output = BytesIO()
|
| 224 |
+
output.write(json.dumps(data).encode())
|
| 225 |
+
output.seek(0)
|
| 226 |
+
|
| 227 |
+
return StreamingResponse(
|
| 228 |
+
iter([output.getvalue()]),
|
| 229 |
+
media_type="application/json",
|
| 230 |
+
headers={
|
| 231 |
+
"Content-Disposition": f"attachment; filename=network.json"
|
| 232 |
+
},
|
| 233 |
+
)
|
| 234 |
+
else:
|
| 235 |
+
return FileResponse(
|
| 236 |
+
network_file,
|
| 237 |
+
media_type="text/tab-separated-values",
|
| 238 |
+
filename=f"network.tsv",
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
except HTTPException:
|
| 242 |
+
raise
|
| 243 |
+
except Exception as e:
|
| 244 |
+
logger.error(f"Failed to download network: {str(e)}")
|
| 245 |
+
raise HTTPException(
|
| 246 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 247 |
+
detail="Failed to download network",
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@router.post("/job/{job_id}/export")
|
| 252 |
+
async def export_job_results(
|
| 253 |
+
job_id: str,
|
| 254 |
+
export_format: str = Query("json", regex="^(json|graphml|csv)$"),
|
| 255 |
+
):
|
| 256 |
+
"""Export job results in specified format."""
|
| 257 |
+
try:
|
| 258 |
+
task = export_results.delay(job_id=job_id, export_format=export_format)
|
| 259 |
+
|
| 260 |
+
return {
|
| 261 |
+
"task_id": task.id,
|
| 262 |
+
"job_id": job_id,
|
| 263 |
+
"export_format": export_format,
|
| 264 |
+
"status": "processing",
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
except Exception as e:
|
| 268 |
+
logger.error(f"Failed to export results: {str(e)}")
|
| 269 |
+
raise HTTPException(
|
| 270 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 271 |
+
detail="Failed to export results",
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
from datetime import datetime
|
app/api/runs.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, BackgroundTasks, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from app.services.hf_datasets import prepare_expression_matrix
|
| 4 |
+
from app.registry.runs import create_run
|
| 5 |
+
from app.services.storage import (
|
| 6 |
+
create_run,
|
| 7 |
+
get_run,
|
| 8 |
+
get_run_metrics,
|
| 9 |
+
update_run
|
| 10 |
+
)
|
| 11 |
+
from app.services.datasets import stage_dataset
|
| 12 |
+
from app.services.beeline_runner import execute_run
|
| 13 |
+
from threading import Thread
|
| 14 |
+
from app.services.runs import execute_run
|
| 15 |
+
|
| 16 |
+
router = APIRouter(prefix="/runs", tags=["Runs"])
|
| 17 |
+
|
| 18 |
+
@router.post("/")
|
| 19 |
+
def start_run(payload: dict, background: BackgroundTasks):
|
| 20 |
+
dataset_id = payload.get("dataset_id")
|
| 21 |
+
algorithms = payload.get("algorithms", [])
|
| 22 |
+
|
| 23 |
+
if not dataset_id:
|
| 24 |
+
raise HTTPException(status_code=422, detail="dataset_id is required")
|
| 25 |
+
return {"error": "No Dataset selected"}
|
| 26 |
+
|
| 27 |
+
if not algorithms:
|
| 28 |
+
raise HTTPException(status_code=422, detail="algorithms must be a non-empty array")
|
| 29 |
+
return {"error": "No Algorithm selected"}
|
| 30 |
+
|
| 31 |
+
# algorithm = algorithms[0]
|
| 32 |
+
algorithm = algorithms[0].lower()
|
| 33 |
+
|
| 34 |
+
params = payload.get("params", {})
|
| 35 |
+
|
| 36 |
+
run_id = create_run(dataset_id, algorithm)
|
| 37 |
+
|
| 38 |
+
dataset_path = stage_dataset(dataset_id)
|
| 39 |
+
|
| 40 |
+
background.add_task(
|
| 41 |
+
execute_run,
|
| 42 |
+
run_id,
|
| 43 |
+
dataset_path,
|
| 44 |
+
algorithm,
|
| 45 |
+
params
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
return {
|
| 49 |
+
"run_id": run_id,
|
| 50 |
+
"status": "running"
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
@router.post("/")
|
| 54 |
+
def start_run(payload: dict, background: BackgroundTasks):
|
| 55 |
+
dataset_id = payload.get("dataset_id")
|
| 56 |
+
algorithms = payload.get("algorithms", [])
|
| 57 |
+
params = payload.get("params", {})
|
| 58 |
+
|
| 59 |
+
if not dataset_id:
|
| 60 |
+
raise HTTPException(status_code=422, detail="dataset_id is required")
|
| 61 |
+
|
| 62 |
+
if not algorithms:
|
| 63 |
+
raise HTTPException(status_code=422, detail="algorithms must be non-empty")
|
| 64 |
+
|
| 65 |
+
algorithm = algorithms[0].lower()
|
| 66 |
+
|
| 67 |
+
run_id = create_run(dataset_id, algorithm)
|
| 68 |
+
|
| 69 |
+
dataset_path = stage_dataset(dataset_id)
|
| 70 |
+
|
| 71 |
+
background.add_task(
|
| 72 |
+
execute_run,
|
| 73 |
+
run_id,
|
| 74 |
+
dataset_path,
|
| 75 |
+
algorithm,
|
| 76 |
+
params
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
return {
|
| 80 |
+
"run_id": run_id,
|
| 81 |
+
"status": "running"
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
@router.post("/")
|
| 85 |
+
def start_run(payload: dict):
|
| 86 |
+
run_id = payload["run_id"]
|
| 87 |
+
|
| 88 |
+
Thread(
|
| 89 |
+
target=execute_run,
|
| 90 |
+
args=(
|
| 91 |
+
run_id,
|
| 92 |
+
payload["dataset_path"],
|
| 93 |
+
payload["algorithm"],
|
| 94 |
+
payload.get("params", {})
|
| 95 |
+
),
|
| 96 |
+
daemon=True
|
| 97 |
+
).start()
|
| 98 |
+
|
| 99 |
+
return {
|
| 100 |
+
"run_id": run_id,
|
| 101 |
+
"status": "queued"
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RunRequest(BaseModel):
|
| 106 |
+
dataset_id: str
|
| 107 |
+
algorithm: str
|
| 108 |
+
params: dict = {}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@router.post("/")
|
| 112 |
+
def start_run(payload: RunRequest, background: BackgroundTasks):
|
| 113 |
+
run_id = create_run(
|
| 114 |
+
dataset=payload.dataset_id,
|
| 115 |
+
algorithm=payload.algorithm
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
dataset_path = prepare_expression_matrix(payload.dataset_id)
|
| 120 |
+
except Exception as e:
|
| 121 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 122 |
+
|
| 123 |
+
background.add_task(
|
| 124 |
+
execute_run,
|
| 125 |
+
run_id,
|
| 126 |
+
dataset_path,
|
| 127 |
+
payload.algorithm,
|
| 128 |
+
payload.params
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
return {
|
| 132 |
+
"run_id": run_id,
|
| 133 |
+
"status": "running"
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@router.get("/{run_id}")
|
| 138 |
+
def run_status(run_id: str):
|
| 139 |
+
run = get_run(run_id)
|
| 140 |
+
|
| 141 |
+
if not run:
|
| 142 |
+
return {"error": "Run not found"}
|
| 143 |
+
|
| 144 |
+
return run
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@router.get("/{run_id}/metrics")
|
| 148 |
+
def run_metrics(run_id: str):
|
| 149 |
+
return get_run_metrics(run_id)
|
app/config.py
ADDED
|
File without changes
|
app/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""App core module init."""
|
app/core/config.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration management using Pydantic BaseSettings.
|
| 3 |
+
Supports environment variables and .env files.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
from pydantic import Field
|
| 8 |
+
from pydantic_settings import BaseSettings
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Settings(BaseSettings):
|
| 13 |
+
"""Application settings with environment variable support."""
|
| 14 |
+
|
| 15 |
+
# Project Info
|
| 16 |
+
PROJECT_NAME: str = "WebGenie - Beeline GRN Inference Backend"
|
| 17 |
+
PROJECT_VERSION: str = "1.0.0"
|
| 18 |
+
PROJECT_DESCRIPTION: str = "FastAPI backend for Gene Regulatory Network inference"
|
| 19 |
+
|
| 20 |
+
# Server Configuration
|
| 21 |
+
API_V1_PREFIX: str = "/api/v1"
|
| 22 |
+
DEBUG: bool = Field(default=False, env="DEBUG")
|
| 23 |
+
LOG_LEVEL: str = Field(default="INFO", env="LOG_LEVEL")
|
| 24 |
+
|
| 25 |
+
# CORS Configuration
|
| 26 |
+
CORS_ORIGINS: List[str] = Field(
|
| 27 |
+
default=[
|
| 28 |
+
"http://localhost",
|
| 29 |
+
"http://localhost:3000",
|
| 30 |
+
"http://localhost:5173",
|
| 31 |
+
"http://127.0.0.1",
|
| 32 |
+
"http://127.0.0.1:3000",
|
| 33 |
+
"http://127.0.0.1:5173",
|
| 34 |
+
],
|
| 35 |
+
env="CORS_ORIGINS",
|
| 36 |
+
)
|
| 37 |
+
CORS_CREDENTIALS: bool = True
|
| 38 |
+
CORS_METHODS: List[str] = ["*"]
|
| 39 |
+
CORS_HEADERS: List[str] = ["*"]
|
| 40 |
+
|
| 41 |
+
# Database Configuration
|
| 42 |
+
DATABASE_URL: str = Field(
|
| 43 |
+
default="sqlite:///./webgenie.db", env="DATABASE_URL"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Redis Configuration (for Celery)
|
| 47 |
+
REDIS_URL: str = Field(
|
| 48 |
+
default="redis://localhost:6379/0", env="REDIS_URL"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Celery Configuration
|
| 52 |
+
CELERY_BROKER_URL: str = Field(
|
| 53 |
+
default="redis://localhost:6379/1", env="CELERY_BROKER_URL"
|
| 54 |
+
)
|
| 55 |
+
CELERY_RESULT_BACKEND: str = Field(
|
| 56 |
+
default="redis://localhost:6379/2", env="CELERY_RESULT_BACKEND"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# File Paths
|
| 60 |
+
BASE_DIR: Path = Path(__file__).resolve().parent.parent.parent
|
| 61 |
+
DATA_DIR: Path = Field(default=Path("/data"), env="DATA_DIR")
|
| 62 |
+
RESULTS_DIR: Path = Field(default=Path("/data/results"), env="RESULTS_DIR")
|
| 63 |
+
DATASETS_DIR: Path = Field(default=Path("/data/datasets"), env="DATASETS_DIR")
|
| 64 |
+
TEMP_DIR: Path = Field(default=Path("/tmp/webgenie"), env="TEMP_DIR")
|
| 65 |
+
|
| 66 |
+
# Job Configuration
|
| 67 |
+
MAX_CONCURRENT_JOBS: int = Field(default=4, env="MAX_CONCURRENT_JOBS")
|
| 68 |
+
JOB_TIMEOUT_SECONDS: int = Field(default=86400, env="JOB_TIMEOUT_SECONDS") # 24 hours
|
| 69 |
+
POLL_INTERVAL_SECONDS: int = 5
|
| 70 |
+
|
| 71 |
+
# API Configuration
|
| 72 |
+
MAX_UPLOAD_SIZE: int = Field(
|
| 73 |
+
default=1024 * 1024 * 500, env="MAX_UPLOAD_SIZE" # 500MB
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Algorithm Configuration
|
| 77 |
+
ALGORITHM_TIMEOUT: int = Field(default=86400, env="ALGORITHM_TIMEOUT")
|
| 78 |
+
ALGORITHM_MEMORY_LIMIT: str = Field(default="8g", env="ALGORITHM_MEMORY_LIMIT")
|
| 79 |
+
|
| 80 |
+
# HuggingFace Configuration
|
| 81 |
+
HF_TOKEN: Optional[str] = Field(default=None, env="HF_TOKEN")
|
| 82 |
+
HF_DATASET_ORG: str = "cskokgibbs"
|
| 83 |
+
HF_DATASET_PREFIX: str = "datasets"
|
| 84 |
+
|
| 85 |
+
# Docker Configuration
|
| 86 |
+
DOCKER_REGISTRY: str = Field(default="grnbeeline", env="DOCKER_REGISTRY")
|
| 87 |
+
USE_DOCKER: bool = Field(default=True, env="USE_DOCKER")
|
| 88 |
+
|
| 89 |
+
# Logging Configuration
|
| 90 |
+
LOG_FORMAT: str = "json" # json or text
|
| 91 |
+
LOG_FILE: Path = Field(default=Path("/var/log/webgenie/app.log"))
|
| 92 |
+
|
| 93 |
+
class Config:
|
| 94 |
+
"""Pydantic config."""
|
| 95 |
+
|
| 96 |
+
env_file = ".env"
|
| 97 |
+
env_file_encoding = "utf-8"
|
| 98 |
+
case_sensitive = True
|
| 99 |
+
extra = "ignore"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# Global settings instance
|
| 103 |
+
settings = Settings()
|
| 104 |
+
|
| 105 |
+
# Ensure required directories exist
|
| 106 |
+
settings.DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
settings.RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
| 108 |
+
settings.DATASETS_DIR.mkdir(parents=True, exist_ok=True)
|
| 109 |
+
settings.TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 110 |
+
settings.LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
app/core/logging.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Structured logging configuration with JSON output support.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import logging.config
|
| 7 |
+
import json
|
| 8 |
+
from typing import Any, Dict
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from pythonjsonlogger import jsonlogger
|
| 12 |
+
|
| 13 |
+
from app.core.config import settings
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CustomJsonFormatter(jsonlogger.JsonFormatter):
|
| 17 |
+
"""Custom JSON formatter with additional context."""
|
| 18 |
+
|
| 19 |
+
def add_fields(
|
| 20 |
+
self,
|
| 21 |
+
log_record: Dict[str, Any],
|
| 22 |
+
record: logging.LogRecord,
|
| 23 |
+
message_dict: Dict[str, Any],
|
| 24 |
+
) -> None:
|
| 25 |
+
"""Add custom fields to log record."""
|
| 26 |
+
super().add_fields(log_record, record, message_dict)
|
| 27 |
+
log_record["timestamp"] = datetime.utcnow().isoformat()
|
| 28 |
+
log_record["level"] = record.levelname
|
| 29 |
+
log_record["logger"] = record.name
|
| 30 |
+
log_record["module"] = record.module
|
| 31 |
+
log_record["function"] = record.funcName
|
| 32 |
+
log_record["line"] = record.lineno
|
| 33 |
+
|
| 34 |
+
# Add job_id if available in extra
|
| 35 |
+
if hasattr(record, "job_id"):
|
| 36 |
+
log_record["job_id"] = record.job_id
|
| 37 |
+
if hasattr(record, "dataset_id"):
|
| 38 |
+
log_record["dataset_id"] = record.dataset_id
|
| 39 |
+
if hasattr(record, "algorithm"):
|
| 40 |
+
log_record["algorithm"] = record.algorithm
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def setup_logging() -> None:
|
| 44 |
+
"""Configure application logging."""
|
| 45 |
+
|
| 46 |
+
# Ensure log directory exists
|
| 47 |
+
log_dir = settings.LOG_FILE.parent
|
| 48 |
+
log_dir.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
|
| 50 |
+
if settings.LOG_FORMAT == "json":
|
| 51 |
+
formatter_class = CustomJsonFormatter
|
| 52 |
+
formatter_kwargs = {"format": "%(message)s"}
|
| 53 |
+
else:
|
| 54 |
+
formatter_class = logging.Formatter
|
| 55 |
+
formatter_kwargs = {
|
| 56 |
+
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
config = {
|
| 60 |
+
"version": 1,
|
| 61 |
+
"disable_existing_loggers": False,
|
| 62 |
+
"formatters": {
|
| 63 |
+
"default": {
|
| 64 |
+
"()": formatter_class,
|
| 65 |
+
**formatter_kwargs,
|
| 66 |
+
},
|
| 67 |
+
"detailed": {
|
| 68 |
+
"format": (
|
| 69 |
+
"%(asctime)s - %(name)s - %(levelname)s - "
|
| 70 |
+
"%(funcName)s:%(lineno)d - %(message)s"
|
| 71 |
+
)
|
| 72 |
+
},
|
| 73 |
+
},
|
| 74 |
+
"handlers": {
|
| 75 |
+
"console": {
|
| 76 |
+
"class": "logging.StreamHandler",
|
| 77 |
+
"level": settings.LOG_LEVEL,
|
| 78 |
+
"formatter": "default",
|
| 79 |
+
"stream": "ext://sys.stdout",
|
| 80 |
+
},
|
| 81 |
+
"file": {
|
| 82 |
+
"class": "logging.handlers.RotatingFileHandler",
|
| 83 |
+
"level": settings.LOG_LEVEL,
|
| 84 |
+
"formatter": "default",
|
| 85 |
+
"filename": str(settings.LOG_FILE),
|
| 86 |
+
"maxBytes": 10485760, # 10MB
|
| 87 |
+
"backupCount": 10,
|
| 88 |
+
},
|
| 89 |
+
},
|
| 90 |
+
"loggers": {
|
| 91 |
+
"app": {
|
| 92 |
+
"level": settings.LOG_LEVEL,
|
| 93 |
+
"handlers": ["console", "file"],
|
| 94 |
+
"propagate": False,
|
| 95 |
+
},
|
| 96 |
+
"uvicorn": {
|
| 97 |
+
"level": settings.LOG_LEVEL,
|
| 98 |
+
"handlers": ["console", "file"],
|
| 99 |
+
"propagate": False,
|
| 100 |
+
},
|
| 101 |
+
"uvicorn.access": {
|
| 102 |
+
"level": settings.LOG_LEVEL,
|
| 103 |
+
"handlers": ["console", "file"],
|
| 104 |
+
"propagate": False,
|
| 105 |
+
},
|
| 106 |
+
"celery": {
|
| 107 |
+
"level": settings.LOG_LEVEL,
|
| 108 |
+
"handlers": ["console", "file"],
|
| 109 |
+
"propagate": False,
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
"root": {
|
| 113 |
+
"level": settings.LOG_LEVEL,
|
| 114 |
+
"handlers": ["console", "file"],
|
| 115 |
+
},
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
logging.config.dictConfig(config)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_logger(name: str) -> logging.Logger:
|
| 122 |
+
"""Get configured logger instance."""
|
| 123 |
+
return logging.getLogger(name)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def log_with_context(
|
| 127 |
+
logger: logging.Logger,
|
| 128 |
+
level: str,
|
| 129 |
+
message: str,
|
| 130 |
+
job_id: str = None,
|
| 131 |
+
dataset_id: str = None,
|
| 132 |
+
algorithm: str = None,
|
| 133 |
+
**kwargs,
|
| 134 |
+
) -> None:
|
| 135 |
+
"""Log message with context information."""
|
| 136 |
+
extra = {}
|
| 137 |
+
if job_id:
|
| 138 |
+
extra["job_id"] = job_id
|
| 139 |
+
if dataset_id:
|
| 140 |
+
extra["dataset_id"] = dataset_id
|
| 141 |
+
if algorithm:
|
| 142 |
+
extra["algorithm"] = algorithm
|
| 143 |
+
extra.update(kwargs)
|
| 144 |
+
|
| 145 |
+
log_func = getattr(logger, level.lower(), logger.info)
|
| 146 |
+
log_func(message, extra=extra)
|
app/core/tasks.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Celery task configuration for asynchronous job execution.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from celery import Celery
|
| 6 |
+
from celery.utils.log import get_task_logger
|
| 7 |
+
from kombu import Exchange, Queue
|
| 8 |
+
from datetime import timedelta
|
| 9 |
+
|
| 10 |
+
from app.core.config import settings
|
| 11 |
+
|
| 12 |
+
# Initialize Celery app
|
| 13 |
+
celery_app = Celery(
|
| 14 |
+
settings.PROJECT_NAME.lower().replace(" ", "-"),
|
| 15 |
+
broker=settings.CELERY_BROKER_URL,
|
| 16 |
+
backend=settings.CELERY_RESULT_BACKEND,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# Configure Celery
|
| 20 |
+
celery_app.conf.update(
|
| 21 |
+
# Task configuration
|
| 22 |
+
task_serializer="json",
|
| 23 |
+
accept_content=["json"],
|
| 24 |
+
result_serializer="json",
|
| 25 |
+
timezone="UTC",
|
| 26 |
+
enable_utc=True,
|
| 27 |
+
# Task execution
|
| 28 |
+
task_track_started=True,
|
| 29 |
+
task_time_limit=settings.JOB_TIMEOUT_SECONDS,
|
| 30 |
+
task_soft_time_limit=settings.JOB_TIMEOUT_SECONDS - 60,
|
| 31 |
+
worker_prefetch_multiplier=1,
|
| 32 |
+
worker_max_tasks_per_child=1000,
|
| 33 |
+
# Result backend
|
| 34 |
+
result_expires=86400, # 24 hours
|
| 35 |
+
# Queue configuration
|
| 36 |
+
task_default_queue="default",
|
| 37 |
+
task_queues=(
|
| 38 |
+
Queue("default", Exchange("tasks"), routing_key="tasks.#"),
|
| 39 |
+
Queue("priority", Exchange("priority"), routing_key="priority.#"),
|
| 40 |
+
Queue("inference", Exchange("inference"), routing_key="inference.#"),
|
| 41 |
+
),
|
| 42 |
+
task_default_exchange="tasks",
|
| 43 |
+
task_default_exchange_type="topic",
|
| 44 |
+
# Retry configuration
|
| 45 |
+
task_acks_late=True,
|
| 46 |
+
task_reject_on_worker_lost=True,
|
| 47 |
+
# Rate limiting
|
| 48 |
+
task_default_rate_limit="100/m",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Set up periodic tasks if needed
|
| 52 |
+
celery_app.conf.beat_schedule = {
|
| 53 |
+
"cleanup-old-results": {
|
| 54 |
+
"task": "app.workers.tasks.cleanup_old_results",
|
| 55 |
+
"schedule": timedelta(hours=6), # Every 6 hours
|
| 56 |
+
"kwargs": {"days": 7}, # Clean results older than 7 days
|
| 57 |
+
},
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
logger = get_task_logger(__name__)
|
app/main.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from ast import If
|
| 2 |
+
from fastapi import FastAPI, Query, HTTPException
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from app.registry.catalog import DATASETS, ALGORITHMS
|
| 5 |
+
from app.services.hf_datasets import (
|
| 6 |
+
list_beeline_datasets,
|
| 7 |
+
extract_metadata,
|
| 8 |
+
get_dataset_metadata
|
| 9 |
+
)
|
| 10 |
+
from huggingface_hub import HfApi
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
import os
|
| 13 |
+
from contextlib import asynccontextmanager
|
| 14 |
+
from fastapi.responses import JSONResponse
|
| 15 |
+
import logging
|
| 16 |
+
from app.core.config import settings
|
| 17 |
+
from app.core.logging import setup_logging, get_logger
|
| 18 |
+
from app.api import datasets, jobs, compare, explorer, algorithm, runs, results, docs
|
| 19 |
+
from typing import List, Dict
|
| 20 |
+
from pydantic import BaseModel
|
| 21 |
+
import json
|
| 22 |
+
import duckdb
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from datetime import datetime
|
| 25 |
+
|
| 26 |
+
# Creating the App
|
| 27 |
+
app = FastAPI(
|
| 28 |
+
title="WebGenie BEELINE API",
|
| 29 |
+
description="Compute and cache dataset metadata from Hugging Face datasets, run Beeline Algorithms on it and produce runs result as AUROC, AUPRC and F1 Score.",
|
| 30 |
+
version="1.0.0",
|
| 31 |
+
)
|
| 32 |
+
log = logging
|
| 33 |
+
beeline_datasets = list_beeline_datasets
|
| 34 |
+
beeline_datasets_metadat = extract_metadata
|
| 35 |
+
|
| 36 |
+
# Setting up logging
|
| 37 |
+
setup_logging()
|
| 38 |
+
logger = get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
@asynccontextmanager
|
| 41 |
+
async def lifespan(app: FastAPI):
|
| 42 |
+
"""Application lifespan context manager."""
|
| 43 |
+
# Starting uup
|
| 44 |
+
logger.info(f"Starting {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}")
|
| 45 |
+
logger.info(f"Debug mode: {settings.DEBUG}")
|
| 46 |
+
logger.info(f"Log level: {settings.LOG_LEVEL}")
|
| 47 |
+
logger.info(f"CORS origins: {settings.CORS_ORIGINS}")
|
| 48 |
+
|
| 49 |
+
# Verifying directories
|
| 50 |
+
logger.info(f"Data directory: {settings.DATA_DIR}")
|
| 51 |
+
logger.info(f"Results directory: {settings.RESULTS_DIR}")
|
| 52 |
+
logger.info(f"Datasets directory: {settings.DATASETS_DIR}")
|
| 53 |
+
logger.info(f"Temp directory: {settings.TEMP_DIR}")
|
| 54 |
+
|
| 55 |
+
yield
|
| 56 |
+
|
| 57 |
+
# Shuting ddown
|
| 58 |
+
logger.info(f"Shutting down {settings.PROJECT_NAME}")
|
| 59 |
+
|
| 60 |
+
# Creating FastAPI app
|
| 61 |
+
app = FastAPI(
|
| 62 |
+
title=settings.PROJECT_NAME,
|
| 63 |
+
description=settings.PROJECT_DESCRIPTION,
|
| 64 |
+
version=settings.PROJECT_VERSION,
|
| 65 |
+
debug=settings.DEBUG,
|
| 66 |
+
lifespan=lifespan,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Adding CORS middleware now, right after app creation
|
| 70 |
+
if not HfApi:
|
| 71 |
+
app.add_middleware(
|
| 72 |
+
CORSMiddleware,
|
| 73 |
+
allow_origins=settings.CORS_ORIGINS,
|
| 74 |
+
allow_credentials=settings.CORS_CREDENTIALS,
|
| 75 |
+
allow_methods=settings.CORS_METHODS,
|
| 76 |
+
allow_headers=settings.CORS_HEADERS,
|
| 77 |
+
)
|
| 78 |
+
else:
|
| 79 |
+
app.add_middleware(
|
| 80 |
+
CORSMiddleware,
|
| 81 |
+
allow_origins=["*"],
|
| 82 |
+
allow_credentials=True,
|
| 83 |
+
allow_methods=["*"],
|
| 84 |
+
allow_headers=["*"],
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
class Edge(BaseModel):
|
| 88 |
+
job_id: str
|
| 89 |
+
edge_id: str
|
| 90 |
+
source: str
|
| 91 |
+
target: str
|
| 92 |
+
supporting_algorithms: List[str]
|
| 93 |
+
scores_by_algorithm: Dict[str, float]
|
| 94 |
+
support_count: int
|
| 95 |
+
consensus_score: float
|
| 96 |
+
|
| 97 |
+
# Custom exception handlers
|
| 98 |
+
@app.exception_handler(ValueError)
|
| 99 |
+
async def value_error_handler(request, exc):
|
| 100 |
+
"""Handle ValueError exceptions."""
|
| 101 |
+
logger.error(f"ValueError: {str(exc)}")
|
| 102 |
+
return JSONResponse(
|
| 103 |
+
status_code=400,
|
| 104 |
+
content={"detail": str(exc)},
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
@app.exception_handler(Exception)
|
| 108 |
+
async def general_exception_handler(request, exc):
|
| 109 |
+
"""Handle general exceptions."""
|
| 110 |
+
logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
|
| 111 |
+
return JSONResponse(
|
| 112 |
+
status_code=500,
|
| 113 |
+
content={"detail": "Internal server error"},
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
class DatasetMetadata(BaseModel):
|
| 117 |
+
id: str
|
| 118 |
+
name: str
|
| 119 |
+
organism: str
|
| 120 |
+
type: str
|
| 121 |
+
genes: int
|
| 122 |
+
cells: int
|
| 123 |
+
edges: int | None
|
| 124 |
+
source: str
|
| 125 |
+
last_updated: datetime
|
| 126 |
+
|
| 127 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 128 |
+
if not HF_TOKEN:
|
| 129 |
+
raise RuntimeError("HF_TOKEN environment variable not set")
|
| 130 |
+
|
| 131 |
+
OWNER = "ukandu"
|
| 132 |
+
|
| 133 |
+
api = HfApi(token=HF_TOKEN)
|
| 134 |
+
DEFAULT_DATASET_ID = "ukandu/BEELINE-mCAD"
|
| 135 |
+
|
| 136 |
+
class DatasetMetadata(BaseModel):
|
| 137 |
+
id: str
|
| 138 |
+
name: str
|
| 139 |
+
organism: str
|
| 140 |
+
type: str
|
| 141 |
+
genes: int
|
| 142 |
+
cells: int
|
| 143 |
+
edges: int | None
|
| 144 |
+
source: str
|
| 145 |
+
last_updated: str
|
| 146 |
+
|
| 147 |
+
CACHE_DB = Path("data/hf_datasets.duckdb")
|
| 148 |
+
CACHE_DB.parent.mkdir(exist_ok=True)
|
| 149 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 150 |
+
|
| 151 |
+
conn = duckdb.connect(CACHE_DB.as_posix())
|
| 152 |
+
def get_conn():
|
| 153 |
+
return duckdb.connect(CACHE_DB.as_posix())
|
| 154 |
+
|
| 155 |
+
# Initializing DB schema at startup
|
| 156 |
+
with get_conn() as conn:
|
| 157 |
+
conn.execute("""
|
| 158 |
+
CREATE TABLE IF NOT EXISTS datasets (
|
| 159 |
+
id TEXT PRIMARY KEY,
|
| 160 |
+
name TEXT,
|
| 161 |
+
organism TEXT,
|
| 162 |
+
type TEXT,
|
| 163 |
+
genes INTEGER,
|
| 164 |
+
cells INTEGER,
|
| 165 |
+
edges INTEGER,
|
| 166 |
+
source TEXT,
|
| 167 |
+
last_updated TEXT
|
| 168 |
+
)
|
| 169 |
+
""")
|
| 170 |
+
conn.close()
|
| 171 |
+
|
| 172 |
+
# Including routers
|
| 173 |
+
app.include_router(
|
| 174 |
+
datasets.router,
|
| 175 |
+
prefix=settings.API_V1_PREFIX,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
app.include_router(
|
| 179 |
+
jobs.router,
|
| 180 |
+
prefix=settings.API_V1_PREFIX,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
app.include_router(
|
| 184 |
+
explorer.router,
|
| 185 |
+
prefix=settings.API_V1_PREFIX,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
app.include_router(
|
| 189 |
+
compare.router,
|
| 190 |
+
prefix=settings.API_V1_PREFIX,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
app.include_router(
|
| 194 |
+
algorithm.router,
|
| 195 |
+
prefix=settings.API_V1_PREFIX,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
app.include_router(
|
| 199 |
+
runs.router,
|
| 200 |
+
prefix=settings.API_V1_PREFIX,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
app.include_router(
|
| 204 |
+
results.router,
|
| 205 |
+
prefix=settings.API_V1_PREFIX,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
app.include_router(
|
| 209 |
+
docs.router,
|
| 210 |
+
prefix=settings.API_V1_PREFIX,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Health check endpoint
|
| 214 |
+
@app.get("/health")
|
| 215 |
+
async def health_check() -> dict:
|
| 216 |
+
"""Health check endpoint."""
|
| 217 |
+
# datasets = api.list_datasets(author="ukandu")
|
| 218 |
+
|
| 219 |
+
return {
|
| 220 |
+
"status": "Ok (App is Healthy)",
|
| 221 |
+
"title": "WebGenie BEELINE API",
|
| 222 |
+
"description": (
|
| 223 |
+
"Compute and cache dataset metadata from Hugging Face datasets, "
|
| 224 |
+
"run Beeline algorithms on it and produce results such as "
|
| 225 |
+
"AUROC, AUPRC, and F1 score."
|
| 226 |
+
),
|
| 227 |
+
"version": settings.PROJECT_VERSION,
|
| 228 |
+
"version": settings.PROJECT_VERSION,
|
| 229 |
+
"debug": settings.DEBUG,
|
| 230 |
+
"datasets": DATASETS,
|
| 231 |
+
"algorithms": ALGORITHMS
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
# Listing all
|
| 235 |
+
@app.get("/all")
|
| 236 |
+
def list_beeline_datasets_route():
|
| 237 |
+
datasets = api.list_datasets(author="ukandu")
|
| 238 |
+
return [
|
| 239 |
+
d.id for d in datasets
|
| 240 |
+
if d.id.startswith("ukandu/BEELINE")
|
| 241 |
+
and not d.id.endswith("-cache")
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
# Root endpoint
|
| 245 |
+
@app.get("/")
|
| 246 |
+
async def root() -> dict:
|
| 247 |
+
"""Root endpoint."""
|
| 248 |
+
return {
|
| 249 |
+
"name": settings.PROJECT_NAME,
|
| 250 |
+
"version": settings.PROJECT_VERSION,
|
| 251 |
+
"api_prefix": settings.API_V1_PREFIX,
|
| 252 |
+
"docs": f"{settings.API_V1_PREFIX}/docs",
|
| 253 |
+
"health": "/health",
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
# Single Algorithm
|
| 257 |
+
@app.get(f"{settings.API_V1_PREFIX}/algorithms")
|
| 258 |
+
async def get_algorithms() -> dict:
|
| 259 |
+
"""Get list of available algorithms."""
|
| 260 |
+
algorithms = [
|
| 261 |
+
{
|
| 262 |
+
"name": "SCODE",
|
| 263 |
+
"description": "Single-Cell Optimal Experiment Design",
|
| 264 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/scode",
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"name": "SCNS",
|
| 268 |
+
"description": "Single-Cell Network Synthesis",
|
| 269 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/scns",
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"name": "SINCERITIES",
|
| 273 |
+
"description": "Simultaneous Circuit Inference and Clustering",
|
| 274 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/sincerities",
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"name": "PIDC",
|
| 278 |
+
"description": "Partial Information Decomposition and Context",
|
| 279 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/pidc",
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"name": "GRNVBEM",
|
| 283 |
+
"description": "Gene Regulatory Network Variational Bayes EM",
|
| 284 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/grnvbem",
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"name": "GENIE3",
|
| 288 |
+
"description": "GRN Inference using Ensemble trees",
|
| 289 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/genie3",
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"name": "GRNBOOST2",
|
| 293 |
+
"description": "GRN inference using Gradient Boosting",
|
| 294 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/grnboost2",
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"name": "LEAP",
|
| 298 |
+
"description": "Laplacian Eigenmaps",
|
| 299 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/leap",
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"name": "JUMP3",
|
| 303 |
+
"description": "Jump3: Gene Regulatory Network Inference from Multi-Platform Data",
|
| 304 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/jump3",
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"name": "PPCOR",
|
| 308 |
+
"description": "Partial Pearson Correlation",
|
| 309 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/ppcor",
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"name": "GRISLI",
|
| 313 |
+
"description": "Gene Regulatory Inference from Single-cell Lineages",
|
| 314 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/grisli",
|
| 315 |
+
},
|
| 316 |
+
{
|
| 317 |
+
"name": "SINGE",
|
| 318 |
+
"description": "Single-cell Inference of Networks using Granger Ensembles",
|
| 319 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/singe",
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"name": "SCRIBE",
|
| 323 |
+
"description": "Single-Cell Regulation through Iterative Back-Edges",
|
| 324 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/scribe",
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"name": "SCSGL",
|
| 328 |
+
"description": "Single-Cell Sparse Graphical Lasso",
|
| 329 |
+
"docker_image": f"{settings.DOCKER_REGISTRY}/scsgl",
|
| 330 |
+
},
|
| 331 |
+
]
|
| 332 |
+
return {
|
| 333 |
+
"algorithms": algorithms,
|
| 334 |
+
"total": len(algorithms),
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
# Single Job
|
| 338 |
+
@app.get("/grn/{job_id}", response_model=List[Edge])
|
| 339 |
+
async def get_grn(job_id: str):
|
| 340 |
+
with CACHE_DB.open() as f:
|
| 341 |
+
data = json.load(f)
|
| 342 |
+
|
| 343 |
+
# Attaching job_id to each edge
|
| 344 |
+
return [
|
| 345 |
+
{
|
| 346 |
+
**edge,
|
| 347 |
+
"job_id": job_id,
|
| 348 |
+
}
|
| 349 |
+
for edge in data
|
| 350 |
+
]
|
| 351 |
+
|
| 352 |
+
# Single Datset
|
| 353 |
+
@app.get("/dataset/{dataset_id}", response_model=DatasetMetadata)
|
| 354 |
+
def get_dataset_metadata(
|
| 355 |
+
dataset_id: str = Query(
|
| 356 |
+
DEFAULT_DATASET_ID,
|
| 357 |
+
description=datasets.desc
|
| 358 |
+
)
|
| 359 |
+
):
|
| 360 |
+
"""
|
| 361 |
+
Fetch dataset metadata from cache or compute it from Hugging Face.
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
# Checking cache
|
| 365 |
+
cached = conn.execute(
|
| 366 |
+
"SELECT * FROM datasets WHERE id = ?",
|
| 367 |
+
(dataset_id,)
|
| 368 |
+
).fetchone()
|
| 369 |
+
|
| 370 |
+
if cached:
|
| 371 |
+
return dict(zip(
|
| 372 |
+
["id", "name", "organism", "type", "genes", "cells", "edges", "source", "last_updated"],
|
| 373 |
+
cached
|
| 374 |
+
))
|
| 375 |
+
|
| 376 |
+
# Loading dataset
|
| 377 |
+
try:
|
| 378 |
+
ds = load_dataset(dataset_id)
|
| 379 |
+
except Exception as e:
|
| 380 |
+
raise HTTPException(status_code=404, detail=f"Dataset not found: {e}")
|
| 381 |
+
|
| 382 |
+
# Expressing matrix stats
|
| 383 |
+
try:
|
| 384 |
+
expr = ds["train"]
|
| 385 |
+
genes = len(expr.column_names) - 1 # excluding cell_id
|
| 386 |
+
cells = expr.num_rows
|
| 387 |
+
except Exception:
|
| 388 |
+
raise HTTPException(status_code=400, detail="Dataset missing a valid train split")
|
| 389 |
+
|
| 390 |
+
# Gold standard edges
|
| 391 |
+
edges = None
|
| 392 |
+
if "gold_standard" in ds:
|
| 393 |
+
edges = ds["gold_standard"].num_rows
|
| 394 |
+
|
| 395 |
+
# Including Dataset card metadata
|
| 396 |
+
try:
|
| 397 |
+
info = api.dataset_info(dataset_id)
|
| 398 |
+
card = info.cardData or {}
|
| 399 |
+
except Exception:
|
| 400 |
+
card = {}
|
| 401 |
+
|
| 402 |
+
organism = card.get("organism", "unknown")
|
| 403 |
+
dataset_type = card.get("dataset_type", "scRNA-seq")
|
| 404 |
+
|
| 405 |
+
record = {
|
| 406 |
+
"id": dataset_id,
|
| 407 |
+
"name": dataset_id.split("/")[-1],
|
| 408 |
+
"organism": organism,
|
| 409 |
+
"type": dataset_type,
|
| 410 |
+
"genes": genes,
|
| 411 |
+
"cells": cells,
|
| 412 |
+
"edges": edges,
|
| 413 |
+
"source": "huggingface",
|
| 414 |
+
"last_updated": info.last_modified if "info" in locals() else None,
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
# Caching result
|
| 418 |
+
conn.execute(
|
| 419 |
+
"INSERT INTO datasets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
| 420 |
+
tuple(record.values())
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
return record
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
if __name__ == "__main__":
|
| 427 |
+
import uvicorn
|
| 428 |
+
|
| 429 |
+
uvicorn.run(
|
| 430 |
+
"app.main:app",
|
| 431 |
+
host="0.0.0.0",
|
| 432 |
+
port=8000,
|
| 433 |
+
reload=settings.DEBUG,
|
| 434 |
+
log_level=settings.LOG_LEVEL.lower(),
|
| 435 |
+
)
|
app/models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Models module init."""
|
app/models/compare.py
ADDED
|
File without changes
|
app/models/dashboard.py
ADDED
|
File without changes
|
app/models/dataset.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic models for Dataset management.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional, List, Dict, Any
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class DatasetSource(BaseModel):
|
| 11 |
+
"""Dataset source information."""
|
| 12 |
+
|
| 13 |
+
source_type: str = Field(..., description="Source type (huggingface, local, etc.)")
|
| 14 |
+
url: str = Field(..., description="Dataset URL or path")
|
| 15 |
+
metadata: Dict[str, Any] = Field(default_factory=dict, description="Source metadata")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DatasetSchema(BaseModel):
|
| 19 |
+
"""Dataset schema information."""
|
| 20 |
+
|
| 21 |
+
gene_column: str = Field(..., description="Column name for genes")
|
| 22 |
+
cell_column: str = Field(..., description="Column name for cells")
|
| 23 |
+
expression_column: str = Field(..., description="Column name for expression values")
|
| 24 |
+
metadata_columns: List[str] = Field(default_factory=list, description="Metadata columns")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DatasetBase(BaseModel):
|
| 28 |
+
"""Base dataset model."""
|
| 29 |
+
|
| 30 |
+
name: str = Field(..., description="Dataset name")
|
| 31 |
+
description: Optional[str] = Field(default=None, description="Dataset description")
|
| 32 |
+
species: Optional[str] = Field(default=None, description="Species name")
|
| 33 |
+
tissue: Optional[str] = Field(default=None, description="Tissue type")
|
| 34 |
+
num_genes: Optional[int] = Field(default=None, description="Number of genes")
|
| 35 |
+
num_cells: Optional[int] = Field(default=None, description="Number of cells")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DatasetCreate(DatasetBase):
|
| 39 |
+
"""Model for creating a dataset."""
|
| 40 |
+
|
| 41 |
+
source: DatasetSource = Field(..., description="Dataset source")
|
| 42 |
+
schema: DatasetSchema = Field(..., description="Dataset schema")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DatasetUpdate(BaseModel):
|
| 46 |
+
"""Model for updating a dataset."""
|
| 47 |
+
|
| 48 |
+
description: Optional[str] = None
|
| 49 |
+
metadata: Optional[Dict[str, Any]] = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class DatasetResponse(DatasetBase):
|
| 53 |
+
"""Model for dataset response."""
|
| 54 |
+
|
| 55 |
+
id: str = Field(..., description="Dataset unique identifier")
|
| 56 |
+
source: DatasetSource = Field(..., description="Dataset source")
|
| 57 |
+
schema: DatasetSchema = Field(..., description="Dataset schema")
|
| 58 |
+
file_path: Optional[str] = Field(default=None, description="Path to dataset file")
|
| 59 |
+
file_size: Optional[int] = Field(default=None, description="Dataset file size in bytes")
|
| 60 |
+
created_at: datetime = Field(..., description="Creation timestamp")
|
| 61 |
+
updated_at: datetime = Field(..., description="Last update timestamp")
|
| 62 |
+
metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata")
|
| 63 |
+
|
| 64 |
+
class Config:
|
| 65 |
+
"""Model config."""
|
| 66 |
+
|
| 67 |
+
from_attributes = True
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class DatasetListResponse(BaseModel):
|
| 71 |
+
"""Model for dataset list response."""
|
| 72 |
+
|
| 73 |
+
total: int = Field(..., description="Total number of datasets")
|
| 74 |
+
items: List[DatasetResponse] = Field(..., description="Dataset list")
|
| 75 |
+
page: int = Field(..., description="Current page")
|
| 76 |
+
per_page: int = Field(..., description="Items per page")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class DatasetPreview(BaseModel):
|
| 80 |
+
"""Model for dataset preview."""
|
| 81 |
+
|
| 82 |
+
id: str = Field(..., description="Dataset ID")
|
| 83 |
+
name: str = Field(..., description="Dataset name")
|
| 84 |
+
num_rows: int = Field(..., description="Number of rows")
|
| 85 |
+
num_columns: int = Field(..., description="Number of columns")
|
| 86 |
+
columns: List[str] = Field(..., description="Column names")
|
| 87 |
+
sample_data: List[Dict[str, Any]] = Field(..., description="Sample data rows")
|
app/models/datasets.py
ADDED
|
File without changes
|
app/models/explorer.py
ADDED
|
File without changes
|
app/models/job.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic models for Job management.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from typing import Optional, List, Dict, Any
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from pydantic import BaseModel, Field
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class JobStatusEnum(str, Enum):
|
| 12 |
+
"""Job status enumeration."""
|
| 13 |
+
|
| 14 |
+
PENDING = "pending"
|
| 15 |
+
SUBMITTED = "submitted"
|
| 16 |
+
RUNNING = "running"
|
| 17 |
+
COMPLETED = "completed"
|
| 18 |
+
FAILED = "failed"
|
| 19 |
+
CANCELLED = "cancelled"
|
| 20 |
+
PAUSED = "paused"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class JobBase(BaseModel):
|
| 24 |
+
"""Base job model."""
|
| 25 |
+
|
| 26 |
+
dataset_id: str = Field(..., description="Dataset identifier")
|
| 27 |
+
algorithm: str = Field(..., description="Algorithm name")
|
| 28 |
+
parameters: Dict[str, Any] = Field(default_factory=dict, description="Algorithm parameters")
|
| 29 |
+
name: Optional[str] = Field(default=None, description="Human-readable job name")
|
| 30 |
+
description: Optional[str] = Field(default=None, description="Job description")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class JobCreate(JobBase):
|
| 34 |
+
"""Model for creating a job."""
|
| 35 |
+
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class JobUpdate(BaseModel):
|
| 40 |
+
"""Model for updating a job."""
|
| 41 |
+
|
| 42 |
+
status: Optional[JobStatusEnum] = None
|
| 43 |
+
progress: Optional[float] = None
|
| 44 |
+
error_message: Optional[str] = None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class JobResponse(JobBase):
|
| 48 |
+
"""Model for job response."""
|
| 49 |
+
|
| 50 |
+
id: str = Field(..., description="Job unique identifier")
|
| 51 |
+
status: JobStatusEnum = Field(..., description="Current job status")
|
| 52 |
+
progress: float = Field(default=0.0, description="Progress percentage (0-100)")
|
| 53 |
+
started_at: Optional[datetime] = Field(default=None, description="Job start timestamp")
|
| 54 |
+
ended_at: Optional[datetime] = Field(default=None, description="Job end timestamp")
|
| 55 |
+
error_message: Optional[str] = Field(default=None, description="Error message if failed")
|
| 56 |
+
celery_task_id: Optional[str] = Field(default=None, description="Celery task ID")
|
| 57 |
+
result_path: Optional[str] = Field(default=None, description="Path to result files")
|
| 58 |
+
log_file: Optional[str] = Field(default=None, description="Path to log file")
|
| 59 |
+
|
| 60 |
+
class Config:
|
| 61 |
+
"""Model config."""
|
| 62 |
+
|
| 63 |
+
from_attributes = True
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class JobListResponse(BaseModel):
|
| 67 |
+
"""Model for job list response."""
|
| 68 |
+
|
| 69 |
+
total: int = Field(..., description="Total number of jobs")
|
| 70 |
+
items: List[JobResponse] = Field(..., description="Job list")
|
| 71 |
+
page: int = Field(..., description="Current page")
|
| 72 |
+
per_page: int = Field(..., description="Items per page")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class JobLogResponse(BaseModel):
|
| 76 |
+
"""Model for job logs response."""
|
| 77 |
+
|
| 78 |
+
job_id: str = Field(..., description="Job ID")
|
| 79 |
+
logs: str = Field(..., description="Log content")
|
| 80 |
+
timestamp: datetime = Field(..., description="Log timestamp")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class JobCancellationResponse(BaseModel):
|
| 84 |
+
"""Model for job cancellation response."""
|
| 85 |
+
|
| 86 |
+
job_id: str = Field(..., description="Job ID")
|
| 87 |
+
cancelled: bool = Field(..., description="Whether cancellation was successful")
|
| 88 |
+
message: str = Field(..., description="Cancellation message")
|
app/models/result.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic models for Result management.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional, List, Dict, Any
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ResultMetrics(BaseModel):
|
| 11 |
+
"""Result metrics."""
|
| 12 |
+
|
| 13 |
+
auc_roc: Optional[float] = Field(default=None, description="AUC-ROC score")
|
| 14 |
+
auc_pr: Optional[float] = Field(default=None, description="AUC-PR score")
|
| 15 |
+
mcc: Optional[float] = Field(default=None, description="Matthew's correlation coefficient")
|
| 16 |
+
precision: Optional[float] = Field(default=None, description="Precision")
|
| 17 |
+
recall: Optional[float] = Field(default=None, description="Recall")
|
| 18 |
+
f1_score: Optional[float] = Field(default=None, description="F1 score")
|
| 19 |
+
execution_time: Optional[float] = Field(default=None, description="Execution time in seconds")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ResultBase(BaseModel):
|
| 23 |
+
"""Base result model."""
|
| 24 |
+
|
| 25 |
+
job_id: str = Field(..., description="Associated job ID")
|
| 26 |
+
dataset_id: str = Field(..., description="Associated dataset ID")
|
| 27 |
+
algorithm: str = Field(..., description="Algorithm name")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ResultCreate(ResultBase):
|
| 31 |
+
"""Model for creating a result."""
|
| 32 |
+
|
| 33 |
+
network_file: str = Field(..., description="Path to network file")
|
| 34 |
+
summary: Optional[Dict[str, Any]] = Field(default=None, description="Result summary")
|
| 35 |
+
metrics: Optional[ResultMetrics] = Field(default=None, description="Computed metrics")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ResultResponse(ResultBase):
|
| 39 |
+
"""Model for result response."""
|
| 40 |
+
|
| 41 |
+
id: str = Field(..., description="Result unique identifier")
|
| 42 |
+
network_file: str = Field(..., description="Path to network file")
|
| 43 |
+
summary: Optional[Dict[str, Any]] = Field(default=None, description="Result summary")
|
| 44 |
+
metrics: Optional[ResultMetrics] = Field(default=None, description="Computed metrics")
|
| 45 |
+
created_at: datetime = Field(..., description="Creation timestamp")
|
| 46 |
+
file_size: Optional[int] = Field(default=None, description="Network file size in bytes")
|
| 47 |
+
metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata")
|
| 48 |
+
|
| 49 |
+
class Config:
|
| 50 |
+
"""Model config."""
|
| 51 |
+
|
| 52 |
+
from_attributes = True
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ResultListResponse(BaseModel):
|
| 56 |
+
"""Model for result list response."""
|
| 57 |
+
|
| 58 |
+
total: int = Field(..., description="Total number of results")
|
| 59 |
+
items: List[ResultResponse] = Field(..., description="Result list")
|
| 60 |
+
page: int = Field(..., description="Current page")
|
| 61 |
+
per_page: int = Field(..., description="Items per page")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class NetworkComparison(BaseModel):
|
| 65 |
+
"""Network comparison result."""
|
| 66 |
+
|
| 67 |
+
network1_id: str = Field(..., description="First network result ID")
|
| 68 |
+
network2_id: str = Field(..., description="Second network result ID")
|
| 69 |
+
jaccard_index: float = Field(..., description="Jaccard similarity index")
|
| 70 |
+
overlap_edges: int = Field(..., description="Number of overlapping edges")
|
| 71 |
+
edges_only_in_1: int = Field(..., description="Edges only in first network")
|
| 72 |
+
edges_only_in_2: int = Field(..., description="Edges only in second network")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ResultSummary(BaseModel):
|
| 76 |
+
"""Summary of result statistics."""
|
| 77 |
+
|
| 78 |
+
total_edges: int = Field(..., description="Total number of edges")
|
| 79 |
+
num_nodes: int = Field(..., description="Number of nodes")
|
| 80 |
+
density: float = Field(..., description="Network density")
|
| 81 |
+
avg_degree: float = Field(..., description="Average degree")
|
| 82 |
+
max_degree: int = Field(..., description="Maximum degree")
|
app/models/run.py
ADDED
|
File without changes
|
app/registry/__init__.py
ADDED
|
File without changes
|
app/registry/catalog.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from hg_os_cache import dataset, algorithm
|
| 3 |
+
|
| 4 |
+
DATASETS = [
|
| 5 |
+
{
|
| 6 |
+
"id": dataset.i,
|
| 7 |
+
"slug": dataset.l,
|
| 8 |
+
"name": dataset.n,
|
| 9 |
+
"organism": dataset.o,
|
| 10 |
+
"type": dataset.t
|
| 11 |
+
"genes": dataset.g,
|
| 12 |
+
"cells": dataset.c,
|
| 13 |
+
"edges": dataset.e,
|
| 14 |
+
"source": dataset.s,
|
| 15 |
+
"lastUpdated": dataset.u,
|
| 16 |
+
"sparklineData": dataset.d
|
| 17 |
+
}
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
ALGORITHMS = [
|
| 21 |
+
{
|
| 22 |
+
"id": algorithm.i,
|
| 23 |
+
"name": algorithm.n,
|
| 24 |
+
"family": algorithm.f,
|
| 25 |
+
"docker_image": algorithm.d,
|
| 26 |
+
"supports_weighted": algorithm.w
|
| 27 |
+
}
|
| 28 |
+
]
|
| 29 |
+
|
app/registry/runs.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import duckdb
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import uuid
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
DB_PATH = Path("data/runs.duckdb")
|
| 8 |
+
DB_PATH.parent.mkdir(exist_ok=True)
|
| 9 |
+
|
| 10 |
+
conn = duckdb.connect(DB_PATH.as_posix())
|
| 11 |
+
|
| 12 |
+
conn.execute("""
|
| 13 |
+
CREATE TABLE IF NOT EXISTS runs (
|
| 14 |
+
run_id TEXT PRIMARY KEY,
|
| 15 |
+
dataset_id TEXT,
|
| 16 |
+
algorithm TEXT,
|
| 17 |
+
status TEXT,
|
| 18 |
+
progress INTEGER,
|
| 19 |
+
metrics JSON,
|
| 20 |
+
error TEXT,
|
| 21 |
+
created_at TIMESTAMP,
|
| 22 |
+
updated_at TIMESTAMP
|
| 23 |
+
)
|
| 24 |
+
""")
|
| 25 |
+
|
| 26 |
+
def create_run(dataset_id: str, algorithm: str) -> str:
|
| 27 |
+
run_id = str(uuid.uuid4())
|
| 28 |
+
now = datetime.utcnow()
|
| 29 |
+
|
| 30 |
+
conn.execute(
|
| 31 |
+
"""
|
| 32 |
+
INSERT INTO runs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 33 |
+
""",
|
| 34 |
+
(
|
| 35 |
+
run_id,
|
| 36 |
+
dataset_id,
|
| 37 |
+
algorithm,
|
| 38 |
+
"queued",
|
| 39 |
+
0,
|
| 40 |
+
None,
|
| 41 |
+
None,
|
| 42 |
+
now,
|
| 43 |
+
now
|
| 44 |
+
)
|
| 45 |
+
)
|
| 46 |
+
return run_id
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def update_run(
|
| 50 |
+
run_id: str,
|
| 51 |
+
status: str = None,
|
| 52 |
+
progress: int = None,
|
| 53 |
+
metrics: dict = None,
|
| 54 |
+
error: str = None
|
| 55 |
+
):
|
| 56 |
+
now = datetime.utcnow()
|
| 57 |
+
|
| 58 |
+
row = conn.execute(
|
| 59 |
+
"SELECT * FROM runs WHERE run_id = ?",
|
| 60 |
+
(run_id,)
|
| 61 |
+
).fetchone()
|
| 62 |
+
|
| 63 |
+
if not row:
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
conn.execute(
|
| 67 |
+
"""
|
| 68 |
+
UPDATE runs SET
|
| 69 |
+
status = COALESCE(?, status),
|
| 70 |
+
progress = COALESCE(?, progress),
|
| 71 |
+
metrics = COALESCE(?, metrics),
|
| 72 |
+
error = COALESCE(?, error),
|
| 73 |
+
updated_at = ?
|
| 74 |
+
WHERE run_id = ?
|
| 75 |
+
""",
|
| 76 |
+
(
|
| 77 |
+
status,
|
| 78 |
+
progress,
|
| 79 |
+
json.dumps(metrics) if metrics else None,
|
| 80 |
+
error,
|
| 81 |
+
now,
|
| 82 |
+
run_id
|
| 83 |
+
)
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_run(run_id: str) -> dict | None:
|
| 88 |
+
row = conn.execute(
|
| 89 |
+
"SELECT * FROM runs WHERE run_id = ?",
|
| 90 |
+
(run_id,)
|
| 91 |
+
).fetchone()
|
| 92 |
+
|
| 93 |
+
if not row:
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
keys = [
|
| 97 |
+
"run_id", "dataset_id", "algorithm", "status",
|
| 98 |
+
"progress", "metrics", "error",
|
| 99 |
+
"created_at", "updated_at"
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
record = dict(zip(keys, row))
|
| 103 |
+
if record["metrics"]:
|
| 104 |
+
record["metrics"] = json.loads(record["metrics"])
|
| 105 |
+
|
| 106 |
+
return record
|
app/services/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Services module init."""
|
app/services/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (164 Bytes). View file
|
|
|
app/services/__pycache__/beeline_runner.cpython-314.pyc
ADDED
|
Binary file (1.15 kB). View file
|
|
|
app/services/__pycache__/hf_datasets.cpython-314.pyc
ADDED
|
Binary file (762 Bytes). View file
|
|
|
app/services/__pycache__/storage.cpython-314.pyc
ADDED
|
Binary file (1.06 kB). View file
|
|
|
app/services/beeline.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from sklearn.metrics import roc_auc_score, average_precision_score
|
| 4 |
+
from scipy.stats import pearsonr, spearmanr
|
| 5 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def run_beeline_algorithm(
|
| 9 |
+
algorithm: str,
|
| 10 |
+
dataset_path: str,
|
| 11 |
+
params: dict
|
| 12 |
+
) -> pd.DataFrame:
|
| 13 |
+
"""
|
| 14 |
+
Returns inferred network as DataFrame:
|
| 15 |
+
[regulator, target, weight]
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
expr = pd.read_parquet(dataset_path)
|
| 19 |
+
|
| 20 |
+
genes = expr.columns.tolist()
|
| 21 |
+
X = expr.values
|
| 22 |
+
|
| 23 |
+
edges = []
|
| 24 |
+
|
| 25 |
+
if algorithm == "pearson":
|
| 26 |
+
for i, g1 in enumerate(genes):
|
| 27 |
+
for j, g2 in enumerate(genes):
|
| 28 |
+
if i >= j:
|
| 29 |
+
continue
|
| 30 |
+
w, _ = pearsonr(X[:, i], X[:, j])
|
| 31 |
+
edges.append((g1, g2, abs(w)))
|
| 32 |
+
|
| 33 |
+
elif algorithm == "spearman":
|
| 34 |
+
for i, g1 in enumerate(genes):
|
| 35 |
+
for j, g2 in enumerate(genes):
|
| 36 |
+
if i >= j:
|
| 37 |
+
continue
|
| 38 |
+
w, _ = spearmanr(X[:, i], X[:, j])
|
| 39 |
+
edges.append((g1, g2, abs(w)))
|
| 40 |
+
|
| 41 |
+
elif algorithm == "genie3":
|
| 42 |
+
n_trees = params.get("n_estimators", 100)
|
| 43 |
+
|
| 44 |
+
for target_idx, target in enumerate(genes):
|
| 45 |
+
X_other = np.delete(X, target_idx, axis=1)
|
| 46 |
+
y = X[:, target_idx]
|
| 47 |
+
|
| 48 |
+
model = RandomForestRegressor(
|
| 49 |
+
n_estimators=n_trees,
|
| 50 |
+
n_jobs=-1
|
| 51 |
+
)
|
| 52 |
+
model.fit(X_other, y)
|
| 53 |
+
|
| 54 |
+
importances = model.feature_importances_
|
| 55 |
+
regulators = [g for g in genes if g != target]
|
| 56 |
+
|
| 57 |
+
for r, w in zip(regulators, importances):
|
| 58 |
+
edges.append((r, target, w))
|
| 59 |
+
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(f"Unsupported algorithm: {algorithm}")
|
| 62 |
+
|
| 63 |
+
return pd.DataFrame(edges, columns=["regulator", "target", "weight"])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def run_beeline_algorithm(
|
| 68 |
+
algorithm: str,
|
| 69 |
+
dataset_path: str,
|
| 70 |
+
params: dict
|
| 71 |
+
) -> pd.DataFrame:
|
| 72 |
+
"""
|
| 73 |
+
Run a BEELINE-style GRN inference algorithm.
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
DataFrame with columns:
|
| 77 |
+
[regulator, target, weight]
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
# Expect dataset_path to be a parquet or csv expression matrix
|
| 81 |
+
if dataset_path.endswith(".parquet"):
|
| 82 |
+
expr = pd.read_parquet(dataset_path)
|
| 83 |
+
else:
|
| 84 |
+
expr = pd.read_csv(dataset_path)
|
| 85 |
+
|
| 86 |
+
genes = expr.columns.tolist()
|
| 87 |
+
X = expr.values
|
| 88 |
+
|
| 89 |
+
edges = []
|
| 90 |
+
|
| 91 |
+
algorithm = algorithm.lower()
|
| 92 |
+
|
| 93 |
+
# ------------------------
|
| 94 |
+
# Pearson Correlation
|
| 95 |
+
# ------------------------
|
| 96 |
+
if algorithm == "pearson":
|
| 97 |
+
for i, g1 in enumerate(genes):
|
| 98 |
+
for j, g2 in enumerate(genes):
|
| 99 |
+
if i >= j:
|
| 100 |
+
continue
|
| 101 |
+
w, _ = pearsonr(X[:, i], X[:, j])
|
| 102 |
+
edges.append((g1, g2, abs(float(w))))
|
| 103 |
+
|
| 104 |
+
# ------------------------
|
| 105 |
+
# Spearman Correlation
|
| 106 |
+
# ------------------------
|
| 107 |
+
elif algorithm == "spearman":
|
| 108 |
+
for i, g1 in enumerate(genes):
|
| 109 |
+
for j, g2 in enumerate(genes):
|
| 110 |
+
if i >= j:
|
| 111 |
+
continue
|
| 112 |
+
w, _ = spearmanr(X[:, i], X[:, j])
|
| 113 |
+
edges.append((g1, g2, abs(float(w))))
|
| 114 |
+
|
| 115 |
+
# ------------------------
|
| 116 |
+
# GENIE3 (Random Forest)
|
| 117 |
+
# ------------------------
|
| 118 |
+
elif algorithm == "genie3":
|
| 119 |
+
n_estimators = params.get("n_estimators", 100)
|
| 120 |
+
|
| 121 |
+
for target_idx, target in enumerate(genes):
|
| 122 |
+
X_other = np.delete(X, target_idx, axis=1)
|
| 123 |
+
y = X[:, target_idx]
|
| 124 |
+
|
| 125 |
+
model = RandomForestRegressor(
|
| 126 |
+
n_estimators=n_estimators,
|
| 127 |
+
n_jobs=-1,
|
| 128 |
+
random_state=0
|
| 129 |
+
)
|
| 130 |
+
model.fit(X_other, y)
|
| 131 |
+
|
| 132 |
+
regulators = [g for g in genes if g != target]
|
| 133 |
+
importances = model.feature_importances_
|
| 134 |
+
|
| 135 |
+
for r, w in zip(regulators, importances):
|
| 136 |
+
edges.append((r, target, float(w)))
|
| 137 |
+
|
| 138 |
+
else:
|
| 139 |
+
raise ValueError(f"Unsupported BEELINE algorithm: {algorithm}")
|
| 140 |
+
|
| 141 |
+
return pd.DataFrame(edges, columns=["regulator", "target", "weight"])
|
app/services/beeline_runner.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from app.services.results_parser import parse_results
|
| 5 |
+
from app.services.storage import save_metrics, update_run
|
| 6 |
+
|
| 7 |
+
RUNS_DIR = Path("data/runs")
|
| 8 |
+
RUNS_DIR.mkdir(parents=True, exist_ok=True)
|
| 9 |
+
|
| 10 |
+
def execute_run(run_id, dataset_path, algorithm, params):
|
| 11 |
+
output_dir = RUNS_DIR / run_id
|
| 12 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 13 |
+
|
| 14 |
+
update_run(run_id, "running", 10)
|
| 15 |
+
|
| 16 |
+
cmd = [
|
| 17 |
+
"docker", "run", "--rm",
|
| 18 |
+
"-v", f"{dataset_path}:/input",
|
| 19 |
+
"-v", f"{output_dir}:/output",
|
| 20 |
+
f"grnbeeline/{algorithm}",
|
| 21 |
+
"--input", "/input",
|
| 22 |
+
"--output", "/output"
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
for k, v in params.items():
|
| 26 |
+
cmd.extend([f"--{k}", str(v)])
|
| 27 |
+
|
| 28 |
+
update_run(run_id, "running", 30)
|
| 29 |
+
subprocess.run(cmd, check=True)
|
| 30 |
+
|
| 31 |
+
update_run(run_id, "running", 70)
|
| 32 |
+
|
| 33 |
+
metrics = parse_results(
|
| 34 |
+
pred_path=output_dir / "inferred_network.tsv",
|
| 35 |
+
gold_path=output_dir / "gold_standard.tsv"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
save_metrics(run_id, metrics)
|
app/services/datasets.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datasets import load_dataset
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
DATASETS_DIR = Path("data/datasets")
|
| 5 |
+
DATASETS_DIR.mkdir(parents=True, exist_ok=True)
|
| 6 |
+
|
| 7 |
+
HF_REPO = "ukandu"
|
| 8 |
+
|
| 9 |
+
def stage_dataset(dataset_id: str) -> Path:
|
| 10 |
+
ds = load_dataset(f"{HF_REPO}/{dataset_id}")
|
| 11 |
+
|
| 12 |
+
out_dir = DATASETS_DIR / dataset_id
|
| 13 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
expr_path = out_dir / "expression.tsv"
|
| 16 |
+
gold_path = out_dir / "gold_standard.tsv"
|
| 17 |
+
|
| 18 |
+
ds["train"].to_pandas().to_csv(expr_path, sep="\t", index=False)
|
| 19 |
+
ds["gold"].to_pandas().to_csv(gold_path, sep="\t", index=False)
|
| 20 |
+
|
| 21 |
+
return out_dir
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def exec_data(dataset_id: str) -> Path:
|
| 25 |
+
ds = load_dataset(dataset_id)
|
| 26 |
+
|
| 27 |
+
out_dir = DATA_ROOT / dataset_id.replace("/", "__")
|
| 28 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
|
| 30 |
+
# Save expression matrix
|
| 31 |
+
ds["train"].to_csv(out_dir / "expression.csv", index=False)
|
| 32 |
+
|
| 33 |
+
# Save gold standard if exists
|
| 34 |
+
if "gold_standard" in ds:
|
| 35 |
+
ds["gold_standard"].to_csv(out_dir / "gold_standard.csv", index=False)
|
| 36 |
+
|
| 37 |
+
return out_dir
|
app/services/datasets_service.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dataset management service.
|
| 3 |
+
Handles dataset registration, validation, and metadata management.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
import hashlib
|
| 9 |
+
from typing import Optional, List, Dict, Any
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import logging
|
| 14 |
+
|
| 15 |
+
from app.core.config import settings
|
| 16 |
+
from app.models.dataset import DatasetResponse, DatasetSchema, DatasetSource
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DatasetService:
|
| 22 |
+
"""Service for managing datasets."""
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
"""Initialize dataset service."""
|
| 26 |
+
self.datasets_dir = settings.DATASETS_DIR
|
| 27 |
+
self.datasets_dir.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
self.metadata_file = self.datasets_dir / "metadata.json"
|
| 29 |
+
self._load_metadata()
|
| 30 |
+
|
| 31 |
+
def _load_metadata(self) -> None:
|
| 32 |
+
"""Load datasets metadata from file."""
|
| 33 |
+
if self.metadata_file.exists():
|
| 34 |
+
with open(self.metadata_file, "r") as f:
|
| 35 |
+
self.metadata = json.load(f)
|
| 36 |
+
else:
|
| 37 |
+
self.metadata = {}
|
| 38 |
+
|
| 39 |
+
def _save_metadata(self) -> None:
|
| 40 |
+
"""Save datasets metadata to file."""
|
| 41 |
+
with open(self.metadata_file, "w") as f:
|
| 42 |
+
json.dump(self.metadata, f, indent=2, default=str)
|
| 43 |
+
|
| 44 |
+
def _generate_dataset_id(self, name: str) -> str:
|
| 45 |
+
"""Generate unique dataset ID."""
|
| 46 |
+
timestamp = datetime.utcnow().isoformat()
|
| 47 |
+
hash_input = f"{name}:{timestamp}"
|
| 48 |
+
hash_id = hashlib.md5(hash_input.encode()).hexdigest()[:12]
|
| 49 |
+
return f"{name.lower().replace(' ', '-')}-{hash_id}"
|
| 50 |
+
|
| 51 |
+
def _compute_file_hash(self, file_path: Path) -> str:
|
| 52 |
+
"""Compute SHA256 hash of file."""
|
| 53 |
+
sha256_hash = hashlib.sha256()
|
| 54 |
+
with open(file_path, "rb") as f:
|
| 55 |
+
for byte_block in iter(lambda: f.read(4096), b""):
|
| 56 |
+
sha256_hash.update(byte_block)
|
| 57 |
+
return sha256_hash.hexdigest()
|
| 58 |
+
|
| 59 |
+
async def register_dataset(
|
| 60 |
+
self,
|
| 61 |
+
name: str,
|
| 62 |
+
source: DatasetSource,
|
| 63 |
+
schema: DatasetSchema,
|
| 64 |
+
description: Optional[str] = None,
|
| 65 |
+
species: Optional[str] = None,
|
| 66 |
+
tissue: Optional[str] = None,
|
| 67 |
+
metadata: Optional[Dict[str, Any]] = None,
|
| 68 |
+
) -> DatasetResponse:
|
| 69 |
+
"""Register a new dataset."""
|
| 70 |
+
try:
|
| 71 |
+
dataset_id = self._generate_dataset_id(name)
|
| 72 |
+
|
| 73 |
+
# Create dataset directory
|
| 74 |
+
dataset_dir = self.datasets_dir / dataset_id
|
| 75 |
+
dataset_dir.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
|
| 77 |
+
# Store source information
|
| 78 |
+
source_info = {
|
| 79 |
+
**source.dict(),
|
| 80 |
+
"registered_at": datetime.utcnow().isoformat(),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# Save metadata
|
| 84 |
+
dataset_metadata = {
|
| 85 |
+
"id": dataset_id,
|
| 86 |
+
"name": name,
|
| 87 |
+
"description": description,
|
| 88 |
+
"species": species,
|
| 89 |
+
"tissue": tissue,
|
| 90 |
+
"source": source_info,
|
| 91 |
+
"schema": schema.dict(),
|
| 92 |
+
"created_at": datetime.utcnow().isoformat(),
|
| 93 |
+
"updated_at": datetime.utcnow().isoformat(),
|
| 94 |
+
"metadata": metadata or {},
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
self.metadata[dataset_id] = dataset_metadata
|
| 98 |
+
self._save_metadata()
|
| 99 |
+
|
| 100 |
+
logger.info(
|
| 101 |
+
f"Dataset registered: {dataset_id}",
|
| 102 |
+
extra={"dataset_id": dataset_id, "name": name},
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
return DatasetResponse(**dataset_metadata)
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logger.error(
|
| 109 |
+
f"Failed to register dataset: {str(e)}",
|
| 110 |
+
extra={"dataset_id": name},
|
| 111 |
+
)
|
| 112 |
+
raise
|
| 113 |
+
|
| 114 |
+
async def get_dataset(self, dataset_id: str) -> Optional[DatasetResponse]:
|
| 115 |
+
"""Get dataset by ID."""
|
| 116 |
+
if dataset_id not in self.metadata:
|
| 117 |
+
logger.warning(f"Dataset not found: {dataset_id}")
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
return DatasetResponse(**self.metadata[dataset_id])
|
| 121 |
+
|
| 122 |
+
async def list_datasets(
|
| 123 |
+
self, skip: int = 0, limit: int = 10
|
| 124 |
+
) -> Dict[str, Any]:
|
| 125 |
+
"""List all registered datasets."""
|
| 126 |
+
all_datasets = list(self.metadata.values())
|
| 127 |
+
total = len(all_datasets)
|
| 128 |
+
items = [DatasetResponse(**d) for d in all_datasets[skip : skip + limit]]
|
| 129 |
+
|
| 130 |
+
return {
|
| 131 |
+
"total": total,
|
| 132 |
+
"items": items,
|
| 133 |
+
"page": skip // limit + 1,
|
| 134 |
+
"per_page": limit,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
async def delete_dataset(self, dataset_id: str) -> bool:
|
| 138 |
+
"""Delete a dataset."""
|
| 139 |
+
try:
|
| 140 |
+
if dataset_id not in self.metadata:
|
| 141 |
+
logger.warning(f"Dataset not found: {dataset_id}")
|
| 142 |
+
return False
|
| 143 |
+
|
| 144 |
+
# Remove metadata
|
| 145 |
+
del self.metadata[dataset_id]
|
| 146 |
+
self._save_metadata()
|
| 147 |
+
|
| 148 |
+
# Remove dataset directory
|
| 149 |
+
dataset_dir = self.datasets_dir / dataset_id
|
| 150 |
+
if dataset_dir.exists():
|
| 151 |
+
import shutil
|
| 152 |
+
|
| 153 |
+
shutil.rmtree(dataset_dir)
|
| 154 |
+
|
| 155 |
+
logger.info(f"Dataset deleted: {dataset_id}")
|
| 156 |
+
return True
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
logger.error(f"Failed to delete dataset: {str(e)}")
|
| 160 |
+
raise
|
| 161 |
+
|
| 162 |
+
async def update_dataset_metadata(
|
| 163 |
+
self, dataset_id: str, metadata: Dict[str, Any]
|
| 164 |
+
) -> DatasetResponse:
|
| 165 |
+
"""Update dataset metadata."""
|
| 166 |
+
if dataset_id not in self.metadata:
|
| 167 |
+
logger.warning(f"Dataset not found: {dataset_id}")
|
| 168 |
+
raise ValueError(f"Dataset {dataset_id} not found")
|
| 169 |
+
|
| 170 |
+
dataset = self.metadata[dataset_id]
|
| 171 |
+
dataset["metadata"].update(metadata)
|
| 172 |
+
dataset["updated_at"] = datetime.utcnow().isoformat()
|
| 173 |
+
|
| 174 |
+
self._save_metadata()
|
| 175 |
+
logger.info(f"Dataset metadata updated: {dataset_id}")
|
| 176 |
+
|
| 177 |
+
return DatasetResponse(**dataset)
|
| 178 |
+
|
| 179 |
+
async def get_dataset_preview(
|
| 180 |
+
self, dataset_id: str, num_rows: int = 5
|
| 181 |
+
) -> Optional[Dict[str, Any]]:
|
| 182 |
+
"""Get preview of dataset."""
|
| 183 |
+
dataset = await self.get_dataset(dataset_id)
|
| 184 |
+
if not dataset:
|
| 185 |
+
return None
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
# Try to load and preview the dataset file
|
| 189 |
+
dataset_dir = self.datasets_dir / dataset_id
|
| 190 |
+
dataset_file = dataset_dir / "data.csv"
|
| 191 |
+
|
| 192 |
+
if not dataset_file.exists():
|
| 193 |
+
logger.warning(f"Dataset file not found: {dataset_file}")
|
| 194 |
+
return None
|
| 195 |
+
|
| 196 |
+
df = pd.read_csv(dataset_file, nrows=num_rows)
|
| 197 |
+
|
| 198 |
+
return {
|
| 199 |
+
"id": dataset_id,
|
| 200 |
+
"name": dataset.name,
|
| 201 |
+
"num_rows": len(df),
|
| 202 |
+
"num_columns": len(df.columns),
|
| 203 |
+
"columns": df.columns.tolist(),
|
| 204 |
+
"sample_data": df.head(num_rows).to_dict("records"),
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
except Exception as e:
|
| 208 |
+
logger.error(f"Failed to preview dataset: {str(e)}")
|
| 209 |
+
return None
|
| 210 |
+
|
| 211 |
+
async def validate_dataset_schema(
|
| 212 |
+
self, dataset_id: str, file_path: Path
|
| 213 |
+
) -> bool:
|
| 214 |
+
"""Validate dataset schema."""
|
| 215 |
+
try:
|
| 216 |
+
dataset = await self.get_dataset(dataset_id)
|
| 217 |
+
if not dataset:
|
| 218 |
+
return False
|
| 219 |
+
|
| 220 |
+
df = pd.read_csv(file_path)
|
| 221 |
+
|
| 222 |
+
# Check required columns
|
| 223 |
+
required_columns = [
|
| 224 |
+
dataset.schema.gene_column,
|
| 225 |
+
dataset.schema.cell_column,
|
| 226 |
+
dataset.schema.expression_column,
|
| 227 |
+
]
|
| 228 |
+
|
| 229 |
+
for col in required_columns:
|
| 230 |
+
if col not in df.columns:
|
| 231 |
+
logger.error(
|
| 232 |
+
f"Missing required column: {col}",
|
| 233 |
+
extra={"dataset_id": dataset_id},
|
| 234 |
+
)
|
| 235 |
+
return False
|
| 236 |
+
|
| 237 |
+
logger.info(
|
| 238 |
+
f"Dataset schema validation passed",
|
| 239 |
+
extra={"dataset_id": dataset_id},
|
| 240 |
+
)
|
| 241 |
+
return True
|
| 242 |
+
|
| 243 |
+
except Exception as e:
|
| 244 |
+
logger.error(f"Schema validation failed: {str(e)}")
|
| 245 |
+
return False
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# Global service instance
|
| 249 |
+
dataset_service = DatasetService()
|
app/services/hf_datasets.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from typing import List, Dict
|
| 4 |
+
from huggingface_hub import HfApi
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
import duckdb
|
| 7 |
+
from functools import lru_cache
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 11 |
+
|
| 12 |
+
CACHE_DB = Path("data/hf_datasets.duckdb")
|
| 13 |
+
CACHE_DB.parent.mkdir(exist_ok=True)
|
| 14 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
OWNER = "Ukandu Chimeremeze James"
|
| 17 |
+
HF_ORG = "ukandu"
|
| 18 |
+
|
| 19 |
+
api = HfApi(token=HF_TOKEN)
|
| 20 |
+
|
| 21 |
+
conn = duckdb.connect(CACHE_DB.as_posix())
|
| 22 |
+
|
| 23 |
+
conn.execute("""
|
| 24 |
+
CREATE TABLE IF NOT EXISTS datasets (
|
| 25 |
+
id TEXT PRIMARY KEY,
|
| 26 |
+
name TEXT,
|
| 27 |
+
organism TEXT,
|
| 28 |
+
type TEXT,
|
| 29 |
+
genes INTEGER,
|
| 30 |
+
cells INTEGER,
|
| 31 |
+
edges INTEGER,
|
| 32 |
+
source TEXT,
|
| 33 |
+
last_updated TEXT
|
| 34 |
+
)
|
| 35 |
+
""")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def stage_dataset(dataset_id: str):
|
| 39 |
+
"""
|
| 40 |
+
Download dataset contents locally for execution
|
| 41 |
+
"""
|
| 42 |
+
return load_dataset(
|
| 43 |
+
f"{OWNER}/{dataset_id}",
|
| 44 |
+
token=HF_TOKEN
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@lru_cache(maxsize=1)
|
| 49 |
+
|
| 50 |
+
def add_dataset(name: str, data: dict):
|
| 51 |
+
"""
|
| 52 |
+
Placeholder for dataset upload
|
| 53 |
+
(requires push_to_hub implementation)
|
| 54 |
+
"""
|
| 55 |
+
return {
|
| 56 |
+
"status": "not_implemented",
|
| 57 |
+
"dataset": name
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
def list_beeline_datasets():
|
| 61 |
+
"""
|
| 62 |
+
Discover BEELINE datasets from HF Hub
|
| 63 |
+
"""
|
| 64 |
+
repos = api.list_datasets(author=HF_ORG)
|
| 65 |
+
|
| 66 |
+
return [
|
| 67 |
+
repo.id
|
| 68 |
+
for repo in repos
|
| 69 |
+
if "BEELINE" in repo.id
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
def list_beeline_datasets():
|
| 73 |
+
datasets = api.list_datasets(author="cskokgibbs")
|
| 74 |
+
|
| 75 |
+
return [
|
| 76 |
+
d.id
|
| 77 |
+
for d in datasets
|
| 78 |
+
if d.id.startswith("cskokgibbs/BEELINE")
|
| 79 |
+
and not d.id.endswith("-cache")
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
def get_all_dataset_metadata(dataset_id: str) -> Dict:
|
| 83 |
+
"""
|
| 84 |
+
Detailed metadata for a single dataset
|
| 85 |
+
"""
|
| 86 |
+
info = api.dataset_info(f"{OWNER}/{dataset_id}")
|
| 87 |
+
|
| 88 |
+
return {
|
| 89 |
+
"id": info.id,
|
| 90 |
+
"description": info.description,
|
| 91 |
+
"downloads": info.downloads,
|
| 92 |
+
"likes": info.likes,
|
| 93 |
+
"tags": info.tags,
|
| 94 |
+
"configs": info.configs,
|
| 95 |
+
"last_modified": info.last_modified
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
def extract_metadata(dataset_id: str):
|
| 99 |
+
"""
|
| 100 |
+
Extract metadata from HF Data Studio + files
|
| 101 |
+
"""
|
| 102 |
+
ds = load_dataset(dataset_id, split="train")
|
| 103 |
+
|
| 104 |
+
genes = ds.num_columns
|
| 105 |
+
cells = ds.num_rows
|
| 106 |
+
|
| 107 |
+
# Heuristics (safe defaults)
|
| 108 |
+
organism = "Unknown"
|
| 109 |
+
data_type = "scRNA-seq"
|
| 110 |
+
|
| 111 |
+
if "mouse" in dataset_id.lower() or "mdc" in dataset_id.lower():
|
| 112 |
+
organism = "Mus musculus"
|
| 113 |
+
elif "hep" in dataset_id.lower() or "human" in dataset_id.lower():
|
| 114 |
+
organism = "Homo sapiens"
|
| 115 |
+
|
| 116 |
+
return {
|
| 117 |
+
"id": dataset_id,
|
| 118 |
+
"slug": dataset_id.split("/")[-1],
|
| 119 |
+
"name": dataset_id.split("/")[-1].replace("-", " "),
|
| 120 |
+
"organism": organism,
|
| 121 |
+
"type": data_type,
|
| 122 |
+
"genes": genes,
|
| 123 |
+
"cells": cells,
|
| 124 |
+
"source": "huggingface",
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
def list_beeline_datasets():
|
| 128 |
+
datasets = api.list_datasets(author="cskokgibbs")
|
| 129 |
+
return [
|
| 130 |
+
d.id for d in datasets
|
| 131 |
+
if d.id.startswith("cskokgibbs/BEELINE")
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
def compute_dataset_stats(dataset_id: str):
|
| 135 |
+
ds = load_dataset(dataset_id)
|
| 136 |
+
|
| 137 |
+
# Expression matrix
|
| 138 |
+
expr = ds["train"]
|
| 139 |
+
genes = len(expr.column_names) - 1 # excluding cell_id
|
| 140 |
+
cells = expr.num_rows
|
| 141 |
+
|
| 142 |
+
# Gold standard edges
|
| 143 |
+
try:
|
| 144 |
+
gs = ds["gold_standard"]
|
| 145 |
+
edges = gs.num_rows
|
| 146 |
+
except:
|
| 147 |
+
edges = None
|
| 148 |
+
|
| 149 |
+
return genes, cells, edges
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def extract_card_metadata(dataset_id: str):
|
| 153 |
+
info = api.dataset_info(dataset_id)
|
| 154 |
+
card = info.cardData or {}
|
| 155 |
+
|
| 156 |
+
return {
|
| 157 |
+
"organism": card.get("organism", "unknown"),
|
| 158 |
+
"type": card.get("dataset_type", "scRNA-seq"),
|
| 159 |
+
"last_updated": info.last_modified
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def list_available_datasets() -> List[Dict]:
|
| 164 |
+
"""
|
| 165 |
+
List all dataset repos under cskokgibbs
|
| 166 |
+
"""
|
| 167 |
+
datasets = api.list_datasets(author=OWNER)
|
| 168 |
+
|
| 169 |
+
return [
|
| 170 |
+
{
|
| 171 |
+
"id": ds.id,
|
| 172 |
+
"private": ds.private,
|
| 173 |
+
"downloads": ds.downloads,
|
| 174 |
+
"likes": ds.likes,
|
| 175 |
+
"last_modified": ds.last_modified
|
| 176 |
+
}
|
| 177 |
+
for ds in datasets
|
| 178 |
+
]
|
| 179 |
+
|
| 180 |
+
def prepare_expression_matrix(dataset_id: str) -> str:
|
| 181 |
+
"""
|
| 182 |
+
Downloads a BEELINE dataset from HF and returns
|
| 183 |
+
a local parquet path usable by algorithms.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
ds = load_dataset(dataset_id)
|
| 187 |
+
|
| 188 |
+
if "train" not in ds:
|
| 189 |
+
raise ValueError("Dataset has no train split")
|
| 190 |
+
|
| 191 |
+
expr = ds["train"].to_pandas()
|
| 192 |
+
|
| 193 |
+
path = DATA_DIR / f"{dataset_id.split('/')[-1]}.parquet"
|
| 194 |
+
expr.to_parquet(path)
|
| 195 |
+
|
| 196 |
+
return path.as_posix()
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_dataset_metadata(dataset_id: str):
|
| 200 |
+
cached = conn.execute(
|
| 201 |
+
"SELECT * FROM datasets WHERE id = ?",
|
| 202 |
+
(dataset_id,)
|
| 203 |
+
).fetchone()
|
| 204 |
+
|
| 205 |
+
if cached:
|
| 206 |
+
return dict(zip(
|
| 207 |
+
["id","name","organism","type","genes","cells","edges","source","last_updated"],
|
| 208 |
+
cached
|
| 209 |
+
))
|
| 210 |
+
|
| 211 |
+
genes, cells, edges = compute_dataset_stats(dataset_id)
|
| 212 |
+
card = extract_card_metadata(dataset_id)
|
| 213 |
+
|
| 214 |
+
record = {
|
| 215 |
+
"id": dataset_id,
|
| 216 |
+
"name": dataset_id.split("/")[-1],
|
| 217 |
+
"organism": card["organism"],
|
| 218 |
+
"type": card["type"],
|
| 219 |
+
"genes": genes,
|
| 220 |
+
"cells": cells,
|
| 221 |
+
"edges": edges,
|
| 222 |
+
"source": "huggingface",
|
| 223 |
+
"last_updated": card["last_updated"]
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
conn.execute(
|
| 227 |
+
"INSERT INTO datasets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
| 228 |
+
tuple(record.values())
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
return record
|
| 232 |
+
|
app/services/inference_service.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference service for running GRN algorithms.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import subprocess
|
| 8 |
+
import logging
|
| 9 |
+
from typing import Dict, Any, Optional
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
from app.core.config import settings
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class InferenceService:
|
| 19 |
+
"""Service for running GRN inference algorithms."""
|
| 20 |
+
|
| 21 |
+
def __init__(self):
|
| 22 |
+
"""Initialize inference service."""
|
| 23 |
+
self.results_dir = settings.RESULTS_DIR
|
| 24 |
+
self.temp_dir = settings.TEMP_DIR
|
| 25 |
+
self.docker_registry = settings.DOCKER_REGISTRY
|
| 26 |
+
self.use_docker = settings.USE_DOCKER
|
| 27 |
+
|
| 28 |
+
def _get_docker_image(self, algorithm: str) -> str:
|
| 29 |
+
"""Get Docker image name for algorithm."""
|
| 30 |
+
algorithm_lower = algorithm.lower()
|
| 31 |
+
return f"{self.docker_registry}/{algorithm_lower}"
|
| 32 |
+
|
| 33 |
+
def _create_job_directory(self, job_id: str) -> Path:
|
| 34 |
+
"""Create job-specific directory."""
|
| 35 |
+
job_dir = self.results_dir / job_id
|
| 36 |
+
job_dir.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
return job_dir
|
| 38 |
+
|
| 39 |
+
async def run_algorithm(
|
| 40 |
+
self,
|
| 41 |
+
job_id: str,
|
| 42 |
+
dataset_id: str,
|
| 43 |
+
algorithm: str,
|
| 44 |
+
dataset_path: str,
|
| 45 |
+
parameters: Dict[str, Any],
|
| 46 |
+
) -> Dict[str, Any]:
|
| 47 |
+
"""Run a GRN inference algorithm."""
|
| 48 |
+
try:
|
| 49 |
+
job_dir = self._create_job_directory(job_id)
|
| 50 |
+
log_file = job_dir / "execution.log"
|
| 51 |
+
output_file = job_dir / f"{algorithm.lower()}_network.tsv"
|
| 52 |
+
|
| 53 |
+
logger.info(
|
| 54 |
+
f"Starting inference with {algorithm}",
|
| 55 |
+
extra={"job_id": job_id, "algorithm": algorithm, "dataset_id": dataset_id},
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Prepare command based on algorithm
|
| 59 |
+
cmd = self._prepare_algorithm_command(
|
| 60 |
+
algorithm=algorithm,
|
| 61 |
+
dataset_path=dataset_path,
|
| 62 |
+
output_path=str(output_file),
|
| 63 |
+
parameters=parameters,
|
| 64 |
+
job_dir=str(job_dir),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Run algorithm
|
| 68 |
+
with open(log_file, "w") as lf:
|
| 69 |
+
process = await self._execute_command(cmd, lf)
|
| 70 |
+
|
| 71 |
+
if process.returncode != 0:
|
| 72 |
+
error_msg = f"Algorithm execution failed with code {process.returncode}"
|
| 73 |
+
logger.error(
|
| 74 |
+
error_msg,
|
| 75 |
+
extra={"job_id": job_id, "algorithm": algorithm},
|
| 76 |
+
)
|
| 77 |
+
raise RuntimeError(error_msg)
|
| 78 |
+
|
| 79 |
+
# Validate output
|
| 80 |
+
if not output_file.exists():
|
| 81 |
+
raise RuntimeError(f"Output file not created: {output_file}")
|
| 82 |
+
|
| 83 |
+
# Generate result summary
|
| 84 |
+
result = {
|
| 85 |
+
"job_id": job_id,
|
| 86 |
+
"dataset_id": dataset_id,
|
| 87 |
+
"algorithm": algorithm,
|
| 88 |
+
"status": "completed",
|
| 89 |
+
"output_file": str(output_file),
|
| 90 |
+
"log_file": str(log_file),
|
| 91 |
+
"completed_at": datetime.utcnow().isoformat(),
|
| 92 |
+
"metrics": await self._compute_metrics(output_file, dataset_path),
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
logger.info(
|
| 96 |
+
f"Algorithm execution completed",
|
| 97 |
+
extra={"job_id": job_id, "algorithm": algorithm},
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
return result
|
| 101 |
+
|
| 102 |
+
except Exception as e:
|
| 103 |
+
logger.error(
|
| 104 |
+
f"Algorithm execution failed: {str(e)}",
|
| 105 |
+
extra={"job_id": job_id, "algorithm": algorithm},
|
| 106 |
+
)
|
| 107 |
+
raise
|
| 108 |
+
|
| 109 |
+
def _prepare_algorithm_command(
|
| 110 |
+
self,
|
| 111 |
+
algorithm: str,
|
| 112 |
+
dataset_path: str,
|
| 113 |
+
output_path: str,
|
| 114 |
+
parameters: Dict[str, Any],
|
| 115 |
+
job_dir: str,
|
| 116 |
+
) -> list:
|
| 117 |
+
"""Prepare command for algorithm execution."""
|
| 118 |
+
if self.use_docker:
|
| 119 |
+
return self._prepare_docker_command(
|
| 120 |
+
algorithm, dataset_path, output_path, parameters, job_dir
|
| 121 |
+
)
|
| 122 |
+
else:
|
| 123 |
+
return self._prepare_python_command(
|
| 124 |
+
algorithm, dataset_path, output_path, parameters, job_dir
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
def _prepare_docker_command(
|
| 128 |
+
self,
|
| 129 |
+
algorithm: str,
|
| 130 |
+
dataset_path: str,
|
| 131 |
+
output_path: str,
|
| 132 |
+
parameters: Dict[str, Any],
|
| 133 |
+
job_dir: str,
|
| 134 |
+
) -> list:
|
| 135 |
+
"""Prepare Docker command for algorithm."""
|
| 136 |
+
docker_image = self._get_docker_image(algorithm)
|
| 137 |
+
|
| 138 |
+
# Volume mappings
|
| 139 |
+
volumes = [
|
| 140 |
+
f"{dataset_path}:/data/input:ro",
|
| 141 |
+
f"{output_path}:/data/output/network.tsv",
|
| 142 |
+
f"{job_dir}:/data/logs",
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
# Base docker command
|
| 146 |
+
cmd = ["docker", "run", "--rm"]
|
| 147 |
+
|
| 148 |
+
# Add volume mounts
|
| 149 |
+
for volume in volumes:
|
| 150 |
+
cmd.extend(["-v", volume])
|
| 151 |
+
|
| 152 |
+
# Add memory limit
|
| 153 |
+
cmd.extend(["-m", settings.ALGORITHM_MEMORY_LIMIT])
|
| 154 |
+
|
| 155 |
+
# Add image and default script
|
| 156 |
+
cmd.append(docker_image)
|
| 157 |
+
|
| 158 |
+
# Algorithm-specific parameters would be added here
|
| 159 |
+
# This is a generic template
|
| 160 |
+
cmd.extend([
|
| 161 |
+
"bash", "-c",
|
| 162 |
+
f"cd /data && python run{algorithm}.py --input /data/input --output /data/output"
|
| 163 |
+
])
|
| 164 |
+
|
| 165 |
+
return cmd
|
| 166 |
+
|
| 167 |
+
def _prepare_python_command(
|
| 168 |
+
self,
|
| 169 |
+
algorithm: str,
|
| 170 |
+
dataset_path: str,
|
| 171 |
+
output_path: str,
|
| 172 |
+
parameters: Dict[str, Any],
|
| 173 |
+
job_dir: str,
|
| 174 |
+
) -> list:
|
| 175 |
+
"""Prepare Python command for algorithm."""
|
| 176 |
+
# This would use the refactored Python runners from BLRun
|
| 177 |
+
runner_module = self._get_python_runner(algorithm)
|
| 178 |
+
|
| 179 |
+
cmd = [
|
| 180 |
+
"python",
|
| 181 |
+
"-m",
|
| 182 |
+
runner_module,
|
| 183 |
+
"--input",
|
| 184 |
+
dataset_path,
|
| 185 |
+
"--output",
|
| 186 |
+
output_path,
|
| 187 |
+
"--log",
|
| 188 |
+
str(Path(job_dir) / "execution.log"),
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
# Add parameters
|
| 192 |
+
for key, value in parameters.items():
|
| 193 |
+
cmd.extend([f"--{key}", str(value)])
|
| 194 |
+
|
| 195 |
+
return cmd
|
| 196 |
+
|
| 197 |
+
def _get_python_runner(self, algorithm: str) -> str:
|
| 198 |
+
"""Get Python runner module for algorithm."""
|
| 199 |
+
runner_map = {
|
| 200 |
+
"SCODE": "app.services.runners.scode_runner",
|
| 201 |
+
"SCNS": "app.services.runners.scns_runner",
|
| 202 |
+
"SINCERITIES": "app.services.runners.sincerities_runner",
|
| 203 |
+
"PIDC": "app.services.runners.pidc_runner",
|
| 204 |
+
"GRNVBEM": "app.services.runners.grnvbem_runner",
|
| 205 |
+
"GENIE3": "app.services.runners.genie3_runner",
|
| 206 |
+
"GRNBOOST2": "app.services.runners.grnboost2_runner",
|
| 207 |
+
"LEAP": "app.services.runners.leap_runner",
|
| 208 |
+
"JUMP3": "app.services.runners.jump3_runner",
|
| 209 |
+
"PPCOR": "app.services.runners.ppcor_runner",
|
| 210 |
+
"GRISLI": "app.services.runners.grisli_runner",
|
| 211 |
+
"SINGE": "app.services.runners.singe_runner",
|
| 212 |
+
"SCRIBE": "app.services.runners.scribe_runner",
|
| 213 |
+
"SCSGL": "app.services.runners.scsgl_runner",
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
return runner_map.get(algorithm.upper(), "app.services.runners.generic_runner")
|
| 217 |
+
|
| 218 |
+
async def _execute_command(self, cmd: list, log_file) -> subprocess.CompletedProcess:
|
| 219 |
+
"""Execute command and capture output."""
|
| 220 |
+
try:
|
| 221 |
+
process = subprocess.run(
|
| 222 |
+
cmd,
|
| 223 |
+
stdout=log_file,
|
| 224 |
+
stderr=subprocess.STDOUT,
|
| 225 |
+
timeout=settings.ALGORITHM_TIMEOUT,
|
| 226 |
+
)
|
| 227 |
+
return process
|
| 228 |
+
except subprocess.TimeoutExpired:
|
| 229 |
+
logger.error("Algorithm execution timeout")
|
| 230 |
+
raise RuntimeError("Algorithm execution timed out")
|
| 231 |
+
|
| 232 |
+
async def _compute_metrics(
|
| 233 |
+
self,
|
| 234 |
+
output_file: Path,
|
| 235 |
+
dataset_path: str,
|
| 236 |
+
) -> Dict[str, Any]:
|
| 237 |
+
"""Compute metrics for result."""
|
| 238 |
+
try:
|
| 239 |
+
# Parse network file
|
| 240 |
+
import pandas as pd
|
| 241 |
+
|
| 242 |
+
network_df = pd.read_csv(output_file, sep="\t", header=None)
|
| 243 |
+
|
| 244 |
+
metrics = {
|
| 245 |
+
"total_edges": len(network_df),
|
| 246 |
+
"num_unique_genes": len(set(network_df[0]) | set(network_df[1])),
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
return metrics
|
| 250 |
+
except Exception as e:
|
| 251 |
+
logger.warning(f"Failed to compute metrics: {str(e)}")
|
| 252 |
+
return {}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# Global service instance
|
| 256 |
+
inference_service = InferenceService()
|
app/services/jobs_service.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Job management service.
|
| 3 |
+
Handles job lifecycle, persistence, and monitoring.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
import uuid
|
| 9 |
+
import logging
|
| 10 |
+
from typing import Optional, List, Dict, Any
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
from app.core.config import settings
|
| 15 |
+
from app.models.job import JobStatusEnum, JobResponse
|
| 16 |
+
from app.workers.tasks import run_inference_job
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class JobService:
|
| 22 |
+
"""Service for managing jobs."""
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
"""Initialize job service."""
|
| 26 |
+
self.jobs_dir = settings.RESULTS_DIR
|
| 27 |
+
self.jobs_dir.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
self.metadata_file = self.jobs_dir / "jobs_metadata.json"
|
| 29 |
+
self._load_jobs_metadata()
|
| 30 |
+
|
| 31 |
+
def _load_jobs_metadata(self) -> None:
|
| 32 |
+
"""Load jobs metadata from file."""
|
| 33 |
+
if self.metadata_file.exists():
|
| 34 |
+
try:
|
| 35 |
+
with open(self.metadata_file, "r") as f:
|
| 36 |
+
self.jobs = json.load(f)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.error(f"Failed to load jobs metadata: {str(e)}")
|
| 39 |
+
self.jobs = {}
|
| 40 |
+
else:
|
| 41 |
+
self.jobs = {}
|
| 42 |
+
|
| 43 |
+
def _save_jobs_metadata(self) -> None:
|
| 44 |
+
"""Save jobs metadata to file."""
|
| 45 |
+
try:
|
| 46 |
+
with open(self.metadata_file, "w") as f:
|
| 47 |
+
json.dump(self.jobs, f, indent=2, default=str)
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logger.error(f"Failed to save jobs metadata: {str(e)}")
|
| 50 |
+
|
| 51 |
+
def _generate_job_id(self) -> str:
|
| 52 |
+
"""Generate unique job ID."""
|
| 53 |
+
return f"job-{uuid.uuid4().hex[:12]}"
|
| 54 |
+
|
| 55 |
+
def _create_job_directory(self, job_id: str) -> Path:
|
| 56 |
+
"""Create job-specific directory."""
|
| 57 |
+
job_dir = self.jobs_dir / job_id
|
| 58 |
+
job_dir.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
return job_dir
|
| 60 |
+
|
| 61 |
+
async def submit_job(
|
| 62 |
+
self,
|
| 63 |
+
dataset_id: str,
|
| 64 |
+
algorithm: str,
|
| 65 |
+
parameters: Dict[str, Any],
|
| 66 |
+
name: Optional[str] = None,
|
| 67 |
+
description: Optional[str] = None,
|
| 68 |
+
) -> JobResponse:
|
| 69 |
+
"""Submit a new inference job."""
|
| 70 |
+
try:
|
| 71 |
+
job_id = self._generate_job_id()
|
| 72 |
+
job_dir = self._create_job_directory(job_id)
|
| 73 |
+
|
| 74 |
+
# Create job metadata
|
| 75 |
+
job_metadata = {
|
| 76 |
+
"id": job_id,
|
| 77 |
+
"dataset_id": dataset_id,
|
| 78 |
+
"algorithm": algorithm,
|
| 79 |
+
"parameters": parameters,
|
| 80 |
+
"name": name or f"{algorithm} on {dataset_id}",
|
| 81 |
+
"description": description,
|
| 82 |
+
"status": JobStatusEnum.SUBMITTED.value,
|
| 83 |
+
"progress": 0.0,
|
| 84 |
+
"started_at": None,
|
| 85 |
+
"ended_at": None,
|
| 86 |
+
"error_message": None,
|
| 87 |
+
"celery_task_id": None,
|
| 88 |
+
"result_path": str(job_dir),
|
| 89 |
+
"log_file": str(job_dir / "execution.log"),
|
| 90 |
+
"created_at": datetime.utcnow().isoformat(),
|
| 91 |
+
"updated_at": datetime.utcnow().isoformat(),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# Store metadata
|
| 95 |
+
self.jobs[job_id] = job_metadata
|
| 96 |
+
self._save_jobs_metadata()
|
| 97 |
+
|
| 98 |
+
# Submit async task
|
| 99 |
+
dataset_path = settings.DATASETS_DIR / dataset_id / "data.csv"
|
| 100 |
+
|
| 101 |
+
task = run_inference_job.delay(
|
| 102 |
+
job_id=job_id,
|
| 103 |
+
dataset_id=dataset_id,
|
| 104 |
+
algorithm=algorithm,
|
| 105 |
+
dataset_path=str(dataset_path),
|
| 106 |
+
parameters=parameters,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Update with task ID
|
| 110 |
+
self.jobs[job_id]["celery_task_id"] = task.id
|
| 111 |
+
self.jobs[job_id]["status"] = JobStatusEnum.RUNNING.value
|
| 112 |
+
self.jobs[job_id]["started_at"] = datetime.utcnow().isoformat()
|
| 113 |
+
self._save_jobs_metadata()
|
| 114 |
+
|
| 115 |
+
logger.info(
|
| 116 |
+
f"Job submitted",
|
| 117 |
+
extra={
|
| 118 |
+
"job_id": job_id,
|
| 119 |
+
"algorithm": algorithm,
|
| 120 |
+
"dataset_id": dataset_id,
|
| 121 |
+
"task_id": task.id,
|
| 122 |
+
},
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
return JobResponse(**self.jobs[job_id])
|
| 126 |
+
|
| 127 |
+
except Exception as e:
|
| 128 |
+
logger.error(f"Failed to submit job: {str(e)}")
|
| 129 |
+
raise
|
| 130 |
+
|
| 131 |
+
async def get_job(self, job_id: str) -> Optional[JobResponse]:
|
| 132 |
+
"""Get job by ID."""
|
| 133 |
+
if job_id not in self.jobs:
|
| 134 |
+
logger.warning(f"Job not found: {job_id}")
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
job_data = self.jobs[job_id]
|
| 138 |
+
|
| 139 |
+
# Check if associated Celery task exists and update status
|
| 140 |
+
if job_data.get("celery_task_id"):
|
| 141 |
+
task_id = job_data["celery_task_id"]
|
| 142 |
+
# Could check Celery task state here to update status
|
| 143 |
+
# For now, returning stored metadata
|
| 144 |
+
|
| 145 |
+
return JobResponse(**job_data)
|
| 146 |
+
|
| 147 |
+
async def list_jobs(
|
| 148 |
+
self,
|
| 149 |
+
skip: int = 0,
|
| 150 |
+
limit: int = 10,
|
| 151 |
+
status: Optional[JobStatusEnum] = None,
|
| 152 |
+
dataset_id: Optional[str] = None,
|
| 153 |
+
algorithm: Optional[str] = None,
|
| 154 |
+
) -> Dict[str, Any]:
|
| 155 |
+
"""List jobs with optional filters."""
|
| 156 |
+
all_jobs = list(self.jobs.values())
|
| 157 |
+
|
| 158 |
+
# Apply filters
|
| 159 |
+
if status:
|
| 160 |
+
all_jobs = [j for j in all_jobs if j["status"] == status.value]
|
| 161 |
+
if dataset_id:
|
| 162 |
+
all_jobs = [j for j in all_jobs if j["dataset_id"] == dataset_id]
|
| 163 |
+
if algorithm:
|
| 164 |
+
all_jobs = [j for j in all_jobs if j["algorithm"] == algorithm]
|
| 165 |
+
|
| 166 |
+
# Sort by creation date (newest first)
|
| 167 |
+
all_jobs.sort(key=lambda x: x["created_at"], reverse=True)
|
| 168 |
+
|
| 169 |
+
total = len(all_jobs)
|
| 170 |
+
items = [JobResponse(**j) for j in all_jobs[skip : skip + limit]]
|
| 171 |
+
|
| 172 |
+
return {
|
| 173 |
+
"total": total,
|
| 174 |
+
"items": items,
|
| 175 |
+
"page": skip // limit + 1,
|
| 176 |
+
"per_page": limit,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
async def cancel_job(self, job_id: str) -> bool:
|
| 180 |
+
"""Cancel a job."""
|
| 181 |
+
try:
|
| 182 |
+
if job_id not in self.jobs:
|
| 183 |
+
logger.warning(f"Job not found: {job_id}")
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
job_data = self.jobs[job_id]
|
| 187 |
+
|
| 188 |
+
# Check if job is still running
|
| 189 |
+
if job_data["status"] not in [
|
| 190 |
+
JobStatusEnum.PENDING.value,
|
| 191 |
+
JobStatusEnum.SUBMITTED.value,
|
| 192 |
+
JobStatusEnum.RUNNING.value,
|
| 193 |
+
]:
|
| 194 |
+
logger.warning(f"Cannot cancel job with status: {job_data['status']}")
|
| 195 |
+
return False
|
| 196 |
+
|
| 197 |
+
# Try to revoke Celery task
|
| 198 |
+
if job_data.get("celery_task_id"):
|
| 199 |
+
from celery import current_app
|
| 200 |
+
|
| 201 |
+
current_app.control.revoke(job_data["celery_task_id"], terminate=True)
|
| 202 |
+
|
| 203 |
+
# Update job status
|
| 204 |
+
self.jobs[job_id]["status"] = JobStatusEnum.CANCELLED.value
|
| 205 |
+
self.jobs[job_id]["ended_at"] = datetime.utcnow().isoformat()
|
| 206 |
+
self._save_jobs_metadata()
|
| 207 |
+
|
| 208 |
+
logger.info(f"Job cancelled: {job_id}")
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
except Exception as e:
|
| 212 |
+
logger.error(f"Failed to cancel job: {str(e)}")
|
| 213 |
+
raise
|
| 214 |
+
|
| 215 |
+
async def get_job_logs(self, job_id: str) -> Optional[str]:
|
| 216 |
+
"""Get job execution logs."""
|
| 217 |
+
try:
|
| 218 |
+
if job_id not in self.jobs:
|
| 219 |
+
logger.warning(f"Job not found: {job_id}")
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
log_file = Path(self.jobs[job_id]["log_file"])
|
| 223 |
+
|
| 224 |
+
if not log_file.exists():
|
| 225 |
+
logger.warning(f"Log file not found: {log_file}")
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
with open(log_file, "r") as f:
|
| 229 |
+
return f.read()
|
| 230 |
+
|
| 231 |
+
except Exception as e:
|
| 232 |
+
logger.error(f"Failed to retrieve logs: {str(e)}")
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
async def update_job_status(
|
| 236 |
+
self,
|
| 237 |
+
job_id: str,
|
| 238 |
+
status: JobStatusEnum,
|
| 239 |
+
progress: Optional[float] = None,
|
| 240 |
+
error_message: Optional[str] = None,
|
| 241 |
+
) -> bool:
|
| 242 |
+
"""Update job status."""
|
| 243 |
+
try:
|
| 244 |
+
if job_id not in self.jobs:
|
| 245 |
+
logger.warning(f"Job not found: {job_id}")
|
| 246 |
+
return False
|
| 247 |
+
|
| 248 |
+
self.jobs[job_id]["status"] = status.value
|
| 249 |
+
self.jobs[job_id]["updated_at"] = datetime.utcnow().isoformat()
|
| 250 |
+
|
| 251 |
+
if progress is not None:
|
| 252 |
+
self.jobs[job_id]["progress"] = max(0, min(100, progress))
|
| 253 |
+
|
| 254 |
+
if error_message:
|
| 255 |
+
self.jobs[job_id]["error_message"] = error_message
|
| 256 |
+
|
| 257 |
+
if status in [
|
| 258 |
+
JobStatusEnum.COMPLETED,
|
| 259 |
+
JobStatusEnum.FAILED,
|
| 260 |
+
JobStatusEnum.CANCELLED,
|
| 261 |
+
]:
|
| 262 |
+
self.jobs[job_id]["ended_at"] = datetime.utcnow().isoformat()
|
| 263 |
+
|
| 264 |
+
self._save_jobs_metadata()
|
| 265 |
+
return True
|
| 266 |
+
|
| 267 |
+
except Exception as e:
|
| 268 |
+
logger.error(f"Failed to update job status: {str(e)}")
|
| 269 |
+
raise
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# Global service instance
|
| 273 |
+
job_service = JobService()
|
app/services/metrics.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score
|
| 3 |
+
|
| 4 |
+
def compute_metrics(inferred: pd.DataFrame, gold_path: str) -> dict:
|
| 5 |
+
gold = pd.read_parquet(gold_path)
|
| 6 |
+
|
| 7 |
+
inferred["edge"] = inferred["regulator"] + "→" + inferred["target"]
|
| 8 |
+
gold["edge"] = gold["regulator"] + "→" + gold["target"]
|
| 9 |
+
|
| 10 |
+
merged = inferred.merge(
|
| 11 |
+
gold[["edge"]],
|
| 12 |
+
on="edge",
|
| 13 |
+
how="left",
|
| 14 |
+
indicator=True
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
y_true = (merged["_merge"] == "both").astype(int)
|
| 18 |
+
y_score = merged["weight"].values
|
| 19 |
+
|
| 20 |
+
return {
|
| 21 |
+
"auroc": float(roc_auc_score(y_true, y_score)),
|
| 22 |
+
"auprc": float(average_precision_score(y_true, y_score)),
|
| 23 |
+
"f1": float(f1_score(y_true, y_score > y_score.mean()))
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
def expose_metrics(inferred: pd.DataFrame) -> dict:
|
| 27 |
+
"""
|
| 28 |
+
Exposing placeholder metrics for now.
|
| 29 |
+
These will later be replaced by real AUROC/AUPRC/F1
|
| 30 |
+
once gold standards are wired.
|
| 31 |
+
|
| 32 |
+
This prevents refactors.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
if inferred.empty:
|
| 36 |
+
return {
|
| 37 |
+
"edges": 0,
|
| 38 |
+
"mean_weight": 0.0,
|
| 39 |
+
"max_weight": 0.0
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
return {
|
| 43 |
+
"edges": int(len(inferred)),
|
| 44 |
+
"mean_weight": float(inferred["weight"].mean()),
|
| 45 |
+
"max_weight": float(inferred["weight"].max())
|
| 46 |
+
}
|
| 47 |
+
|
app/services/results_parser.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sklearn.metrics import (
|
| 3 |
+
roc_auc_score,
|
| 4 |
+
average_precision_score,
|
| 5 |
+
f1_score,
|
| 6 |
+
precision_recall_curve
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
def parse_results(pred_path, gold_path, threshold=0.5):
|
| 10 |
+
pred = pd.read_csv(pred_path, sep="\t")
|
| 11 |
+
gold = pd.read_csv(gold_path, sep="\t")
|
| 12 |
+
|
| 13 |
+
gold_edges = set(
|
| 14 |
+
zip(gold.iloc[:, 0], gold.iloc[:, 1])
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
y_true = []
|
| 18 |
+
y_score = []
|
| 19 |
+
|
| 20 |
+
for _, row in pred.iterrows():
|
| 21 |
+
edge = (row[0], row[1])
|
| 22 |
+
y_true.append(1 if edge in gold_edges else 0)
|
| 23 |
+
y_score.append(row[2])
|
| 24 |
+
|
| 25 |
+
auroc = roc_auc_score(y_true, y_score)
|
| 26 |
+
auprc = average_precision_score(y_true, y_score)
|
| 27 |
+
|
| 28 |
+
y_pred = [1 if s >= threshold else 0 for s in y_score]
|
| 29 |
+
f1 = f1_score(y_true, y_pred)
|
| 30 |
+
|
| 31 |
+
precision, recall, _ = precision_recall_curve(y_true, y_score)
|
| 32 |
+
|
| 33 |
+
return {
|
| 34 |
+
"auroc": auroc,
|
| 35 |
+
"auprc": auprc,
|
| 36 |
+
"f1": f1,
|
| 37 |
+
"precision_curve": precision.tolist(),
|
| 38 |
+
"recall_curve": recall.tolist()
|
| 39 |
+
}
|
app/services/runners/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Runners module init."""
|
app/services/runners/generic_runner.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generic algorithm runner that can be extended for specific algorithms.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Dict, Any, Optional
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
from app.services.runners.utils import BaseRunner, load_expression_data, save_network
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class GenericGRNRunner(BaseRunner):
|
| 15 |
+
"""Generic GRN inference runner."""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
"""Initialize generic runner."""
|
| 19 |
+
super().__init__("generic")
|
| 20 |
+
|
| 21 |
+
def run(
|
| 22 |
+
self,
|
| 23 |
+
input_file: str,
|
| 24 |
+
output_file: str,
|
| 25 |
+
parameters: Dict[str, Any],
|
| 26 |
+
**kwargs,
|
| 27 |
+
) -> Dict[str, Any]:
|
| 28 |
+
"""Run generic GRN inference."""
|
| 29 |
+
try:
|
| 30 |
+
# Validate input
|
| 31 |
+
if not self.validate_input(input_file):
|
| 32 |
+
raise RuntimeError("Input validation failed")
|
| 33 |
+
|
| 34 |
+
# Load data
|
| 35 |
+
data = load_expression_data(input_file)
|
| 36 |
+
if data is None:
|
| 37 |
+
raise RuntimeError("Failed to load expression data")
|
| 38 |
+
|
| 39 |
+
self.logger.info(f"Loaded data: {data.shape}")
|
| 40 |
+
|
| 41 |
+
# Run inference (basic correlation)
|
| 42 |
+
network = self._infer_network(data, parameters)
|
| 43 |
+
|
| 44 |
+
# Save output
|
| 45 |
+
if not save_network(network, output_file):
|
| 46 |
+
raise RuntimeError("Failed to save network")
|
| 47 |
+
|
| 48 |
+
# Validate output
|
| 49 |
+
if not self.validate_output(output_file):
|
| 50 |
+
raise RuntimeError("Output validation failed")
|
| 51 |
+
|
| 52 |
+
return {
|
| 53 |
+
"status": "completed",
|
| 54 |
+
"output_file": output_file,
|
| 55 |
+
"metrics": {
|
| 56 |
+
"num_edges": len(network),
|
| 57 |
+
"num_genes": len(set(network[0]) | set(network[1])),
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
self.logger.error(f"Execution failed: {str(e)}")
|
| 63 |
+
raise
|
| 64 |
+
|
| 65 |
+
def _infer_network(
|
| 66 |
+
self,
|
| 67 |
+
data: pd.DataFrame,
|
| 68 |
+
parameters: Dict[str, Any],
|
| 69 |
+
) -> pd.DataFrame:
|
| 70 |
+
"""Infer GRN using correlation."""
|
| 71 |
+
from app.services.runners.utils import compute_correlation
|
| 72 |
+
|
| 73 |
+
correlation = compute_correlation(data)
|
| 74 |
+
|
| 75 |
+
# Get threshold
|
| 76 |
+
threshold = parameters.get("correlation_threshold", 0.5)
|
| 77 |
+
|
| 78 |
+
# Extract edges
|
| 79 |
+
edges = []
|
| 80 |
+
for i in range(len(correlation)):
|
| 81 |
+
for j in range(i + 1, len(correlation)):
|
| 82 |
+
corr_value = abs(correlation.iloc[i, j])
|
| 83 |
+
if corr_value >= threshold:
|
| 84 |
+
edges.append([
|
| 85 |
+
correlation.index[i],
|
| 86 |
+
correlation.columns[j],
|
| 87 |
+
corr_value,
|
| 88 |
+
])
|
| 89 |
+
|
| 90 |
+
return pd.DataFrame(edges, columns=["TF", "Target", "Score"])
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# Convenience function for running
|
| 94 |
+
async def run_generic(
|
| 95 |
+
input_file: str,
|
| 96 |
+
output_file: str,
|
| 97 |
+
parameters: Dict[str, Any],
|
| 98 |
+
) -> Dict[str, Any]:
|
| 99 |
+
"""Run generic GRN inference."""
|
| 100 |
+
runner = GenericGRNRunner()
|
| 101 |
+
return runner.run(input_file, output_file, parameters)
|
app/services/runners/utils.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generic runner template and utilities for algorithm execution.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Dict, Any, Optional
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BaseRunner:
|
| 15 |
+
"""Base class for algorithm runners."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, algorithm_name: str):
|
| 18 |
+
"""Initialize runner."""
|
| 19 |
+
self.algorithm_name = algorithm_name
|
| 20 |
+
self.logger = logging.getLogger(f"runners.{algorithm_name.lower()}")
|
| 21 |
+
|
| 22 |
+
def run(
|
| 23 |
+
self,
|
| 24 |
+
input_file: str,
|
| 25 |
+
output_file: str,
|
| 26 |
+
parameters: Dict[str, Any],
|
| 27 |
+
**kwargs,
|
| 28 |
+
) -> Dict[str, Any]:
|
| 29 |
+
"""Run algorithm. Must be implemented by subclasses."""
|
| 30 |
+
raise NotImplementedError
|
| 31 |
+
|
| 32 |
+
def validate_input(self, input_file: str) -> bool:
|
| 33 |
+
"""Validate input file."""
|
| 34 |
+
try:
|
| 35 |
+
if not Path(input_file).exists():
|
| 36 |
+
self.logger.error(f"Input file not found: {input_file}")
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
df = pd.read_csv(input_file)
|
| 40 |
+
if df.empty:
|
| 41 |
+
self.logger.error("Input file is empty")
|
| 42 |
+
return False
|
| 43 |
+
|
| 44 |
+
self.logger.info(f"Input validation passed: {input_file}")
|
| 45 |
+
return True
|
| 46 |
+
|
| 47 |
+
except Exception as e:
|
| 48 |
+
self.logger.error(f"Input validation failed: {str(e)}")
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
def validate_output(self, output_file: str) -> bool:
|
| 52 |
+
"""Validate output file."""
|
| 53 |
+
try:
|
| 54 |
+
if not Path(output_file).exists():
|
| 55 |
+
self.logger.error(f"Output file not found: {output_file}")
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
df = pd.read_csv(output_file, sep="\t", header=None)
|
| 59 |
+
if df.empty:
|
| 60 |
+
self.logger.error("Output file is empty")
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
self.logger.info(f"Output validation passed: {output_file}")
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
except Exception as e:
|
| 67 |
+
self.logger.error(f"Output validation failed: {str(e)}")
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
def parse_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
|
| 71 |
+
"""Parse and validate algorithm parameters."""
|
| 72 |
+
return parameters
|
| 73 |
+
|
| 74 |
+
def get_default_parameters(self) -> Dict[str, Any]:
|
| 75 |
+
"""Get default parameters for algorithm."""
|
| 76 |
+
return {}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def load_expression_data(file_path: str) -> Optional[pd.DataFrame]:
|
| 80 |
+
"""Load expression data from file."""
|
| 81 |
+
try:
|
| 82 |
+
if file_path.endswith(".csv"):
|
| 83 |
+
return pd.read_csv(file_path, index_col=0)
|
| 84 |
+
elif file_path.endswith(".tsv"):
|
| 85 |
+
return pd.read_csv(file_path, sep="\t", index_col=0)
|
| 86 |
+
elif file_path.endswith(".h5ad"):
|
| 87 |
+
try:
|
| 88 |
+
import anndata
|
| 89 |
+
adata = anndata.read_h5ad(file_path)
|
| 90 |
+
return pd.DataFrame(
|
| 91 |
+
adata.X.T,
|
| 92 |
+
index=adata.var_names,
|
| 93 |
+
columns=adata.obs_names,
|
| 94 |
+
)
|
| 95 |
+
except ImportError:
|
| 96 |
+
logger.error("anndata not installed, cannot read h5ad files")
|
| 97 |
+
return None
|
| 98 |
+
else:
|
| 99 |
+
logger.warning(f"Unknown file format: {file_path}")
|
| 100 |
+
return None
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Failed to load expression data: {str(e)}")
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def save_network(
|
| 107 |
+
network_df: pd.DataFrame,
|
| 108 |
+
output_file: str,
|
| 109 |
+
format: str = "tsv",
|
| 110 |
+
) -> bool:
|
| 111 |
+
"""Save network to file."""
|
| 112 |
+
try:
|
| 113 |
+
output_path = Path(output_file)
|
| 114 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 115 |
+
|
| 116 |
+
if format == "tsv":
|
| 117 |
+
network_df.to_csv(
|
| 118 |
+
output_file,
|
| 119 |
+
sep="\t",
|
| 120 |
+
index=False,
|
| 121 |
+
header=False,
|
| 122 |
+
)
|
| 123 |
+
elif format == "csv":
|
| 124 |
+
network_df.to_csv(output_file, index=False)
|
| 125 |
+
else:
|
| 126 |
+
logger.warning(f"Unknown format: {format}, using TSV")
|
| 127 |
+
network_df.to_csv(
|
| 128 |
+
output_file,
|
| 129 |
+
sep="\t",
|
| 130 |
+
index=False,
|
| 131 |
+
header=False,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
logger.info(f"Network saved: {output_file}")
|
| 135 |
+
return True
|
| 136 |
+
|
| 137 |
+
except Exception as e:
|
| 138 |
+
logger.error(f"Failed to save network: {str(e)}")
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def compute_correlation(data: pd.DataFrame) -> pd.DataFrame:
|
| 143 |
+
"""Compute Pearson correlation matrix."""
|
| 144 |
+
return data.T.corr()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def compute_mutual_information(data: pd.DataFrame) -> pd.DataFrame:
|
| 148 |
+
"""Compute mutual information matrix."""
|
| 149 |
+
from sklearn.preprocessing import scale
|
| 150 |
+
from scipy.stats import entropy
|
| 151 |
+
import numpy as np
|
| 152 |
+
|
| 153 |
+
n_genes = data.shape[0]
|
| 154 |
+
mi_matrix = np.zeros((n_genes, n_genes))
|
| 155 |
+
|
| 156 |
+
scaled_data = scale(data.T, axis=0).T
|
| 157 |
+
|
| 158 |
+
for i in range(n_genes):
|
| 159 |
+
for j in range(i + 1, n_genes):
|
| 160 |
+
gene_i = scaled_data[i]
|
| 161 |
+
gene_j = scaled_data[j]
|
| 162 |
+
|
| 163 |
+
# Digitize to 10 bins
|
| 164 |
+
digitized_i = np.digitize(gene_i, np.linspace(-3, 3, 10))
|
| 165 |
+
digitized_j = np.digitize(gene_j, np.linspace(-3, 3, 10))
|
| 166 |
+
|
| 167 |
+
# Compute MI
|
| 168 |
+
pxy = np.histogram2d(digitized_i, digitized_j, bins=10)[0] / len(gene_i)
|
| 169 |
+
px = np.histogram(digitized_i, bins=10)[0] / len(gene_i)
|
| 170 |
+
py = np.histogram(digitized_j, bins=10)[0] / len(gene_j)
|
| 171 |
+
|
| 172 |
+
px_py = np.outer(px, py)
|
| 173 |
+
nz = pxy > 0
|
| 174 |
+
|
| 175 |
+
mi = np.sum(pxy[nz] * np.log(pxy[nz] / (px_py[nz] + 1e-10)))
|
| 176 |
+
mi_matrix[i, j] = mi
|
| 177 |
+
mi_matrix[j, i] = mi
|
| 178 |
+
|
| 179 |
+
return pd.DataFrame(mi_matrix)
|
app/services/runs.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.services.beeline import run_beeline_algorithm
|
| 2 |
+
from app.services.metrics import compute_metrics
|
| 3 |
+
from app.registry.runs import update_run
|
| 4 |
+
|
| 5 |
+
def execute_run(run_id, dataset_path, algorithm, params):
|
| 6 |
+
try:
|
| 7 |
+
update_run(run_id, status="running", progress=10)
|
| 8 |
+
|
| 9 |
+
output = run_beeline_algorithm(
|
| 10 |
+
algorithm=algorithm,
|
| 11 |
+
dataset_path=dataset_path,
|
| 12 |
+
params=params
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
metrics = compute_metrics(output)
|
| 16 |
+
|
| 17 |
+
update_run(
|
| 18 |
+
run_id,
|
| 19 |
+
status="completed",
|
| 20 |
+
progress=100,
|
| 21 |
+
metrics=metrics
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
except Exception as e:
|
| 25 |
+
update_run(
|
| 26 |
+
run_id,
|
| 27 |
+
status="failed",
|
| 28 |
+
error=str(e),
|
| 29 |
+
progress=0
|
| 30 |
+
)
|
| 31 |
+
raise
|
| 32 |
+
|
| 33 |
+
def execute_runs_params(run_id, dataset_path, gold_path, algorithm, params):
|
| 34 |
+
try:
|
| 35 |
+
update_run(run_id, status="running", progress=10)
|
| 36 |
+
|
| 37 |
+
inferred = run_beeline_algorithm(
|
| 38 |
+
algorithm=algorithm,
|
| 39 |
+
dataset_path=dataset_path,
|
| 40 |
+
params=params
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
update_run(run_id, progress=70)
|
| 44 |
+
|
| 45 |
+
metrics = compute_metrics(inferred, gold_path)
|
| 46 |
+
|
| 47 |
+
update_run(
|
| 48 |
+
run_id,
|
| 49 |
+
status="completed",
|
| 50 |
+
progress=100,
|
| 51 |
+
metrics=metrics
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
except Exception as e:
|
| 55 |
+
update_run(
|
| 56 |
+
run_id,
|
| 57 |
+
status="failed",
|
| 58 |
+
progress=0,
|
| 59 |
+
error=str(e)
|
| 60 |
+
)
|
| 61 |
+
raise
|
app/services/storage.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import duckdb
|
| 2 |
+
import uuid
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
DB_PATH = Path("data/beeline.duckdb")
|
| 7 |
+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 8 |
+
|
| 9 |
+
conn = duckdb.connect(DB_PATH.as_posix())
|
| 10 |
+
|
| 11 |
+
conn.execute("""
|
| 12 |
+
CREATE TABLE IF NOT EXISTS runs (
|
| 13 |
+
run_id TEXT PRIMARY KEY,
|
| 14 |
+
dataset TEXT,
|
| 15 |
+
algorithm TEXT,
|
| 16 |
+
status TEXT,
|
| 17 |
+
progress INT,
|
| 18 |
+
created_at TIMESTAMP
|
| 19 |
+
)
|
| 20 |
+
""")
|
| 21 |
+
|
| 22 |
+
conn.execute("""
|
| 23 |
+
CREATE TABLE IF NOT EXISTS metrics (
|
| 24 |
+
run_id TEXT,
|
| 25 |
+
auroc DOUBLE,
|
| 26 |
+
auprc DOUBLE,
|
| 27 |
+
f1 DOUBLE
|
| 28 |
+
)
|
| 29 |
+
""")
|
| 30 |
+
|
| 31 |
+
def create_run(dataset: str, algorithm: str) -> str:
|
| 32 |
+
run_id = str(uuid.uuid4())
|
| 33 |
+
conn.execute(
|
| 34 |
+
"""
|
| 35 |
+
INSERT INTO runs VALUES (?, ?, ?, ?, ?, ?)
|
| 36 |
+
""",
|
| 37 |
+
(
|
| 38 |
+
run_id,
|
| 39 |
+
dataset,
|
| 40 |
+
algorithm,
|
| 41 |
+
"running",
|
| 42 |
+
0,
|
| 43 |
+
datetime.utcnow()
|
| 44 |
+
)
|
| 45 |
+
)
|
| 46 |
+
return run_id
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def update_run(run_id: str, status: str, progress: int):
|
| 50 |
+
conn.execute(
|
| 51 |
+
"""
|
| 52 |
+
UPDATE runs SET status = ?, progress = ?
|
| 53 |
+
WHERE run_id = ?
|
| 54 |
+
""",
|
| 55 |
+
(status, progress, run_id)
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def save_metrics(run_id: str, metrics: dict):
|
| 60 |
+
conn.execute(
|
| 61 |
+
"INSERT INTO metrics VALUES (?, ?, ?, ?)",
|
| 62 |
+
(
|
| 63 |
+
run_id,
|
| 64 |
+
metrics["auroc"],
|
| 65 |
+
metrics["auprc"],
|
| 66 |
+
metrics["f1"]
|
| 67 |
+
)
|
| 68 |
+
)
|
| 69 |
+
update_run(run_id, "completed", 100)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_run(run_id: str):
|
| 73 |
+
row = conn.execute(
|
| 74 |
+
"SELECT run_id, status, progress FROM runs WHERE run_id = ?",
|
| 75 |
+
(run_id,)
|
| 76 |
+
).fetchone()
|
| 77 |
+
|
| 78 |
+
if not row:
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"run_id": row[0],
|
| 83 |
+
"status": row[1],
|
| 84 |
+
"progress": row[2]
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def get_run_metrics(run_id: str):
|
| 89 |
+
row = conn.execute(
|
| 90 |
+
"SELECT auroc, auprc, f1 FROM metrics WHERE run_id = ?",
|
| 91 |
+
(run_id,)
|
| 92 |
+
).fetchone()
|
| 93 |
+
|
| 94 |
+
if row is None:
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
return {
|
| 98 |
+
"auroc": row[0],
|
| 99 |
+
"auprc": row[1],
|
| 100 |
+
"f1": row[2]
|
| 101 |
+
}
|
app/workers/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Workers module init."""
|