File size: 13,703 Bytes
07612e2 c85f9e9 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | """
Core Processing APIs
Data import, validation engines, and export functionality
"""
from fastapi import APIRouter, UploadFile, File, HTTPException, Query, BackgroundTasks
from typing import List, Dict, Any, Optional
from pydantic import BaseModel
from datetime import datetime
import uuid
import asyncio
import json
# Import shared engines
from apps.shared.engines import impact_toolkit, study_protocol_engine, data_processor
from integration.adapters import adapter_registry
from studies.oujda_2025_gastric_adk_ci import Oujda2025Protocol
router = APIRouter()
# Data Models
class ImportRequest(BaseModel):
"""CSV import request model."""
cohort: str
mapping_file: Optional[str] = None
validation_enabled: bool = True
class ImportResult(BaseModel):
"""Import operation result."""
cohort_id: str
snapshot_id: str
rows_ingested: int
validation_errors: List[str] = []
processing_time: float
status: str = "completed"
class ValidationRequest(BaseModel):
"""Validation engine request."""
cohort: str
protocols: List[str]
optimization_level: int = 80
background_processing: bool = True
class ValidationResult(BaseModel):
"""Validation engine result."""
snapshot_id: str
cohort: str
protocols: List[str]
baseline: Dict[str, Any]
optimized: Dict[str, Any]
flags: List[str] = []
processing_time: float
recommendations: List[str] = []
class ImpactComparison(BaseModel):
"""Impact analysis comparison result."""
cohort: str
optimization_level: int
survival_delta: float
complication_reduction: float
adequacy_improvement: float
cost_effectiveness: float
explanations: List[str]
class ExportRequest(BaseModel):
"""Export request model."""
cohort: str
format: str # csv, pdf, json
template: Optional[str] = None
filters: Optional[Dict[str, Any]] = None
# API Endpoints
@router.get("/")
async def get_core_api_info():
"""Get Core APIs information."""
return {
"service": "YAZ Care Core APIs",
"description": "Data processing, validation engines, and export functionality",
"version": "1.0.0",
"endpoints": [
"POST /import/csv - Import clinical data",
"POST /validation/run - Run protocol validation",
"GET /impact/compare - Compare baseline vs optimized outcomes",
"GET /exports/{format} - Export processed data",
"GET /cohorts/ - List available cohorts",
"GET /protocols/ - List available protocols",
],
}
@router.post("/import/csv", response_model=ImportResult)
async def import_csv(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
mapping: UploadFile = File(None),
cohort: str = Query(...),
):
"""Import CSV data with mapping validation."""
# TODO: Implement actual CSV import logic
snapshot_id = str(uuid.uuid4())
# Simulate processing
await asyncio.sleep(0.1)
return ImportResult(
cohort_id=cohort,
snapshot_id=snapshot_id,
rows_ingested=150, # Mock data
validation_errors=[],
processing_time=2.3,
status="completed",
)
@router.post("/validation/run", response_model=ValidationResult)
async def run_validation(request: ValidationRequest, background_tasks: BackgroundTasks):
"""Execute protocol validation across cohort."""
snapshot_id = str(uuid.uuid4())
# Use actual validation engine
try:
# Mock patient data for validation
mock_patient_data = {
"age": 62,
"ecog_ps": 1,
"clinical_stage": "T3N1M0",
"histology": "adenocarcinoma",
}
# Validate against Oujda-2025 if in protocols
validation_results = {}
if "oujda-2025" in request.protocols:
oujda_validation = Oujda2025Protocol.validate_eligibility(mock_patient_data)
validation_results["oujda_2025"] = oujda_validation
# Run Impact Toolkit validation
validation_result = impact_toolkit.validate_data(mock_patient_data, "study_enrollment")
# Mock validation results with actual engine data
baseline_metrics = {
"total_cases": 150,
"d2_adequate": 0.68,
"flot_adequate": 0.72,
"overall_survival_5y": 0.58,
"complications_rate": 0.15,
"r0_resection_rate": 0.89,
"validation_passed": validation_result.is_valid,
"validation_errors": validation_result.errors,
}
optimized_metrics = {
"total_cases": 150,
"d2_adequate": 0.85,
"flot_adequate": 0.88,
"overall_survival_5y": 0.65,
"complications_rate": 0.12,
"r0_resection_rate": 0.94,
"validation_passed": True,
"validation_errors": [],
}
flags = []
if optimized_metrics["d2_adequate"] > baseline_metrics["d2_adequate"]:
flags.append("D2_IMPROVEMENT_AVAILABLE")
if optimized_metrics["flot_adequate"] > baseline_metrics["flot_adequate"]:
flags.append("FLOT_OPTIMIZATION_POSSIBLE")
recommendations = [
"Consider enhanced lymph node dissection training",
"Implement standardized FLOT protocol adherence monitoring",
"Review cases with inadequate lymph node harvest",
]
return ValidationResult(
snapshot_id=snapshot_id,
cohort=request.cohort,
protocols=request.protocols,
baseline=baseline_metrics,
optimized=optimized_metrics,
flags=flags,
processing_time=1.8,
recommendations=recommendations,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")
@router.post("/data/process")
async def process_data(
operation: str, data: List[Dict[str, Any]], config: Optional[Dict[str, Any]] = None
):
"""Process data using shared engines."""
try:
result = data_processor.process(data, operation, config or {})
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
@router.post("/integration/sync/{adapter_name}")
async def sync_with_external_system(
adapter_name: str, data_type: str, background_tasks: BackgroundTasks
):
"""Synchronize data with external systems."""
adapter = adapter_registry.get_adapter(adapter_name)
if not adapter:
raise HTTPException(status_code=404, detail=f"Adapter {adapter_name} not found")
try:
result = await adapter.sync_data(data_type)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"Sync failed: {str(e)}")
@router.get("/integration/status")
async def get_integration_status():
"""Get status of all integration adapters."""
try:
statuses = await adapter_registry.validate_all_connections()
return {"timestamp": datetime.now().isoformat(), "adapters": statuses}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Status check failed: {str(e)}")
@router.post("/studies/oujda-2025/validate-patient")
async def validate_oujda_2025_patient(patient_data: Dict[str, Any]):
"""Validate patient eligibility for Oujda-2025 study."""
try:
validation_result = Oujda2025Protocol.validate_eligibility(patient_data)
return validation_result
except Exception as e:
raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")
@router.get("/studies/oujda-2025/protocol")
async def get_oujda_2025_protocol():
"""Get Oujda-2025 study protocol configuration."""
return {
"protocol_id": Oujda2025Protocol.PROTOCOL_ID,
"version": Oujda2025Protocol.PROTOCOL_VERSION,
"title": Oujda2025Protocol.STUDY_TITLE,
"study_type": Oujda2025Protocol.STUDY_TYPE,
"study_phase": Oujda2025Protocol.STUDY_PHASE,
"primary_endpoint": Oujda2025Protocol.PRIMARY_ENDPOINT,
"treatment_arms": Oujda2025Protocol.TREATMENT_ARMS,
"inclusion_criteria": Oujda2025Protocol.INCLUSION_CRITERIA,
"exclusion_criteria": Oujda2025Protocol.EXCLUSION_CRITERIA,
"data_collection_schedule": Oujda2025Protocol.DATA_COLLECTION_SCHEDULE,
"endpoints": Oujda2025Protocol.ENDPOINTS,
"biomarker_program": Oujda2025Protocol.BIOMARKER_PROGRAM,
"data_mapping": Oujda2025Protocol.get_data_mapping(),
}
@router.get("/impact/compare", response_model=ImpactComparison)
async def compare_impact(
cohort: str = Query(...), optimization_level: int = Query(80, ge=0, le=100)
):
"""Compare baseline vs optimized outcomes."""
# TODO: Implement actual impact analysis
return ImpactComparison(
cohort=cohort,
optimization_level=optimization_level,
survival_delta=0.07, # 7% improvement
complication_reduction=0.03, # 3% reduction
adequacy_improvement=0.17, # 17% improvement in protocol adequacy
cost_effectiveness=0.12, # 12% cost reduction per QALY
explanations=[
"5-year survival improved by 7% through optimized D2 lymphadenectomy",
"Complication rates reduced by 3% with standardized protocols",
"Protocol adequacy increased by 17% with systematic optimization",
"Cost per QALY reduced by 12% through improved outcomes",
],
)
@router.get("/exports/csv")
async def export_csv(cohort: str = Query(...), filters: Optional[str] = Query(None)):
"""Export processed clinical data as CSV."""
# TODO: Implement actual CSV export
# Mock CSV content
csv_content = """patient_id,age,gender,tumor_size,lymph_nodes_examined,survival_months
P001,65,M,3.2,18,42
P002,58,F,2.8,22,38
P003,72,M,4.1,15,31
"""
from fastapi.responses import Response
return Response(
content=csv_content,
media_type="text/csv",
headers={"Content-Disposition": f"attachment; filename={cohort}_export.csv"},
)
@router.get("/exports/pdf")
async def export_pdf(cohort: str = Query(...), template: str = Query("tumor_board")):
"""Generate clinical reports as PDF."""
# TODO: Implement actual PDF generation
# Mock PDF response
from fastapi.responses import Response
return Response(
content=b"Mock PDF content - Tumor Board Report",
media_type="application/pdf",
headers={"Content-Disposition": f"attachment; filename={cohort}_{template}.pdf"},
)
@router.get("/cohorts/")
async def list_cohorts():
"""List available patient cohorts."""
return {
"cohorts": [
{
"id": "oujda_2025_gastric_adk_ci",
"name": "Oujda ADK-CI 2025",
"description": "Gastric Adenocarcinoma Clinical Impact Study - Oujda 2025",
"total_cases": 150,
"protocols": ["Total_Gastrectomy_D2", "FLOT"],
"status": "active",
"last_updated": datetime.now().isoformat(),
},
{
"id": "test_cohort",
"name": "Test Cohort",
"description": "Development and testing cohort",
"total_cases": 25,
"protocols": ["Total_Gastrectomy_D2"],
"status": "development",
"last_updated": datetime.now().isoformat(),
},
]
}
@router.get("/protocols/")
async def list_protocols():
"""List available clinical protocols."""
return {
"protocols": [
{
"id": "Total_Gastrectomy_D2",
"name": "Total Gastrectomy with D2 Lymphadenectomy",
"category": "surgical",
"description": "Standardized protocol for total gastrectomy with extended lymph node dissection",
"adequacy_criteria": [
"≥15 lymph nodes examined",
"Adequate lymph node stations (1, 3, 4, 5, 6, 7, 8, 9, 11)",
"R0 resection achieved",
"Standardized operative technique",
],
"outcomes": ["overall_survival", "disease_free_survival", "complications"],
},
{
"id": "FLOT",
"name": "FLOT Chemotherapy Protocol",
"category": "medical",
"description": "Perioperative chemotherapy with Fluorouracil, Leucovorin, Oxaliplatin, Docetaxel",
"adequacy_criteria": [
"≥80% dose intensity achieved",
"8 cycles completed (4 neoadjuvant + 4 adjuvant)",
"Appropriate timing relative to surgery",
"Toxicity management per protocol",
],
"outcomes": ["pathological_response", "survival", "toxicity_profile"],
},
]
}
@router.get("/processing/status/{snapshot_id}")
async def get_processing_status(snapshot_id: str):
"""Get status of background processing job."""
# TODO: Implement actual job status tracking
return {
"snapshot_id": snapshot_id,
"status": "completed",
"progress": 100,
"current_step": "Analysis complete",
"started_at": datetime.now().isoformat(),
"completed_at": datetime.now().isoformat(),
"processing_time": 2.3,
"results_available": True,
}
|