Download src/apps/shared/api/core.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/shared/api/core.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/apps/shared/api/core.py
-
curl -L -o core.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/shared/api/core.py
13.7 kB
| """ | |
| 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 | |
| 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", | |
| ], | |
| } | |
| 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", | |
| ) | |
| 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)}") | |
| 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)}") | |
| 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)}") | |
| 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)}") | |
| 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)}") | |
| 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(), | |
| } | |
| 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", | |
| ], | |
| ) | |
| 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"}, | |
| ) | |
| 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"}, | |
| ) | |
| 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(), | |
| }, | |
| ] | |
| } | |
| 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"], | |
| }, | |
| ] | |
| } | |
| 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, | |
| } | |