Download src/core/api/import.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/api/import.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/api/import.py
-
curl -L -o import.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/api/import.py
13.8 kB
| """ | |
| Core API - Import/Export functionality | |
| Handles CSV import, data export, and file operations | |
| """ | |
| from typing import Optional, Dict, Any, List | |
| from fastapi import APIRouter, HTTPException, UploadFile, File, Form, Query | |
| from fastapi.responses import FileResponse | |
| import json | |
| import csv | |
| import io | |
| from pathlib import Path | |
| import uuid | |
| from datetime import datetime | |
| from core.engines.gastrectomy import GastrectomyEngine | |
| from core.persistence.repositories import CohortRepository | |
| from apps.shared.files.s3 import S3Client | |
| router = APIRouter() | |
| async def import_csv_data( | |
| file: UploadFile = File(...), | |
| mapping: str = Form(..., description="JSON mapping configuration"), | |
| cohort_name: Optional[str] = Form(None, description="Cohort name"), | |
| ): | |
| """ | |
| Import CSV data with field mapping | |
| Returns cohort ID and ingestion statistics | |
| """ | |
| try: | |
| # Parse mapping configuration | |
| try: | |
| field_mapping = json.loads(mapping) | |
| except json.JSONDecodeError: | |
| raise HTTPException(status_code=400, detail="Invalid mapping JSON") | |
| # Read CSV file | |
| content = await file.read() | |
| csv_data = content.decode("utf-8") | |
| # Parse CSV | |
| csv_reader = csv.DictReader(io.StringIO(csv_data)) | |
| rows = list(csv_reader) | |
| if not rows: | |
| raise HTTPException(status_code=400, detail="CSV file is empty") | |
| # Generate cohort ID if not provided | |
| if not cohort_name: | |
| cohort_name = f"Import_{datetime.now().strftime('%Y%m%d_%H%M%S')}" | |
| cohort_id = f"cohort_{uuid.uuid4().hex[:8]}" | |
| # Initialize repositories and engines | |
| repo = CohortRepository() | |
| gastro_engine = GastrectomyEngine() | |
| # Create cohort | |
| await repo.create_cohort(cohort_id, cohort_name) | |
| # Process and import data | |
| ingestion_stats = await _process_csv_import( | |
| rows=rows, | |
| field_mapping=field_mapping, | |
| cohort_id=cohort_id, | |
| repo=repo, | |
| engine=gastro_engine, | |
| ) | |
| # Create baseline snapshot | |
| snapshot_id = await repo.create_snapshot(cohort_id, "baseline") | |
| return { | |
| "cohort_id": cohort_id, | |
| "cohort_name": cohort_name, | |
| "snapshot_id": snapshot_id, | |
| "rows_ingested": ingestion_stats["total_rows"], | |
| "cases_created": ingestion_stats["cases_created"], | |
| "procedures_created": ingestion_stats["procedures_created"], | |
| "errors": ingestion_stats["errors"], | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"CSV import failed: {str(e)}") | |
| async def export_csv_data( | |
| cohort: str = Query(..., description="Cohort identifier"), | |
| snapshot_id: Optional[str] = Query(None, description="Snapshot ID"), | |
| format: str = Query("standard", description="Export format"), | |
| ): | |
| """ | |
| Export cohort data as CSV | |
| """ | |
| try: | |
| repo = CohortRepository() | |
| # Get cohort data | |
| if snapshot_id: | |
| cohort_data = await repo.get_snapshot_data(snapshot_id) | |
| else: | |
| cohort_data = await repo.get_cohort_with_details(cohort) | |
| if not cohort_data: | |
| raise HTTPException(status_code=404, detail="Cohort or snapshot not found") | |
| # Generate CSV | |
| csv_content = await _generate_csv_export(cohort_data, format) | |
| # Save to temporary file | |
| export_filename = f"export_{cohort}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" | |
| temp_path = Path(f"/tmp/{export_filename}") | |
| with open(temp_path, "w", newline="") as csvfile: | |
| csvfile.write(csv_content) | |
| return FileResponse(path=temp_path, filename=export_filename, media_type="text/csv") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"CSV export failed: {str(e)}") | |
| async def export_pdf_report( | |
| cohort: str = Query(..., description="Cohort identifier"), | |
| optimization_level: Optional[int] = Query(None, description="Optimization level"), | |
| template: str = Query("clinical_report", description="Report template"), | |
| ): | |
| """ | |
| Export cohort analysis as PDF report | |
| """ | |
| try: | |
| repo = CohortRepository() | |
| # Get cohort data and analysis results | |
| cohort_data = await repo.get_cohort_with_details(cohort) | |
| if not cohort_data: | |
| raise HTTPException(status_code=404, detail="Cohort not found") | |
| # Load report template configuration | |
| report_config = await _load_report_template(template) | |
| # Generate report content | |
| report_data = await _generate_report_data( | |
| cohort_data=cohort_data, | |
| optimization_level=optimization_level, | |
| template_config=report_config, | |
| ) | |
| # Generate PDF (placeholder - would use actual PDF generation library) | |
| pdf_filename = f"report_{cohort}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf" | |
| pdf_path = await _generate_pdf_report(report_data, pdf_filename) | |
| return FileResponse(path=pdf_path, filename=pdf_filename, media_type="application/pdf") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"PDF export failed: {str(e)}") | |
| async def get_cohort_snapshot(cohort_id: str): | |
| """ | |
| Get or create a snapshot of current cohort state | |
| """ | |
| try: | |
| repo = CohortRepository() | |
| # Check if cohort exists | |
| cohort = await repo.get_cohort(cohort_id) | |
| if not cohort: | |
| raise HTTPException(status_code=404, detail="Cohort not found") | |
| # Create new snapshot | |
| snapshot_id = await repo.create_snapshot(cohort_id, "manual") | |
| # Get snapshot metadata | |
| snapshot_metadata = await repo.get_snapshot_metadata(snapshot_id) | |
| return { | |
| "snapshot_id": snapshot_id, | |
| "cohort_id": cohort_id, | |
| "created_at": snapshot_metadata["created_at"], | |
| "filters": snapshot_metadata.get("filters", {}), | |
| "case_count": snapshot_metadata["case_count"], | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Snapshot creation failed: {str(e)}") | |
| # Helper functions | |
| async def _process_csv_import( | |
| rows: List[Dict], | |
| field_mapping: Dict[str, str], | |
| cohort_id: str, | |
| repo: CohortRepository, | |
| engine: GastrectomyEngine, | |
| ) -> Dict[str, int]: | |
| """Process CSV import with field mapping""" | |
| stats = { | |
| "total_rows": len(rows), | |
| "cases_created": 0, | |
| "procedures_created": 0, | |
| "chemo_records_created": 0, | |
| "errors": [], | |
| } | |
| for row_idx, row in enumerate(rows): | |
| try: | |
| # Map CSV fields to database fields | |
| mapped_row = {} | |
| for csv_field, db_field in field_mapping.items(): | |
| if csv_field in row: | |
| mapped_row[db_field] = row[csv_field] | |
| # Create case record | |
| case_data = await engine.extract_case_data(mapped_row) | |
| case_id = await repo.create_case(cohort_id, case_data) | |
| stats["cases_created"] += 1 # type: ignore[misc, operator, valid-type] | |
| # Create procedure record | |
| procedure_data = await engine.extract_procedure_data(mapped_row) | |
| if procedure_data: | |
| await repo.create_procedure(case_id, procedure_data) | |
| stats["procedures_created"] += 1 # type: ignore[misc, operator, valid-type] | |
| # Create chemotherapy record | |
| chemo_data = await engine.extract_chemo_data(mapped_row) | |
| if chemo_data: | |
| await repo.create_chemotherapy(case_id, chemo_data) | |
| stats["chemo_records_created"] += 1 # type: ignore[misc, operator, valid-type] | |
| except Exception as e: | |
| error_msg = f"Row {row_idx + 1}: {str(e)}" | |
| stats["errors"].append(error_msg) # type: ignore[attr-defined] | |
| return stats # type: ignore[name-defined, index, return-value, var-annotated] | |
| async def _generate_csv_export(cohort_data: Dict, format_type: str) -> str: | |
| """Generate CSV export content""" | |
| # Standard Oujda study format | |
| if format_type == "oujda_study": | |
| headers = [ | |
| "patient_id", | |
| "surgery_date", | |
| "procedure_type", | |
| "lymph_nodes_examined", | |
| "lymph_node_stations", | |
| "margins", | |
| "blood_loss_ml", | |
| "complications_cd", | |
| "chemo_cycles", | |
| "dose_intensity", | |
| "neo_end_date", | |
| ] | |
| else: | |
| # Standard format | |
| headers = [ | |
| "case_id", | |
| "patient_key", | |
| "surgery_date", | |
| "procedure_type", | |
| "nodes_examined", | |
| "margin_status", | |
| "survival_months", | |
| ] | |
| # Generate CSV content | |
| output = io.StringIO() | |
| writer = csv.DictWriter(output, fieldnames=headers) | |
| writer.writeheader() | |
| # Write data rows | |
| cases = cohort_data.get("cases", []) | |
| for case in cases: | |
| # Map case data to CSV format | |
| csv_row = _map_case_to_csv(case, headers) | |
| writer.writerow(csv_row) | |
| return output.getvalue() | |
| def _map_case_to_csv(case_data: Dict, headers: List[str]) -> Dict: | |
| """Map case data to CSV row format""" | |
| csv_row = {} | |
| for header in headers: | |
| # Map database fields to CSV fields | |
| if header == "case_id": | |
| csv_row[header] = case_data.get("id") | |
| elif header == "patient_key": | |
| csv_row[header] = case_data.get("patient_key") | |
| elif header == "surgery_date": | |
| csv_row[header] = case_data.get("surgery_date") | |
| else: | |
| csv_row[header] = case_data.get(header, "") | |
| return csv_row | |
| async def _load_report_template(template_name: str) -> Dict: | |
| """Load report template configuration""" | |
| template_path = Path(f"src/studies/oujda_2025_gastric_adk_ci/reports.yml") | |
| if template_path.exists(): | |
| import yaml | |
| with open(template_path, "r") as f: | |
| templates = yaml.safe_load(f) | |
| return templates.get(template_name, {}) | |
| # Default template | |
| return { | |
| "sections": ["demographics", "procedures", "outcomes", "analysis"], | |
| "charts": ["survival_curve", "compliance_metrics"], | |
| "format": "clinical_standard", | |
| } | |
| async def _generate_report_data( | |
| cohort_data: Dict, optimization_level: Optional[int], template_config: Dict | |
| ) -> Dict: | |
| """Generate report data based on template""" | |
| report_data = { | |
| "title": f"Clinical Analysis Report - {cohort_data['name']}", | |
| "generated_at": datetime.now().isoformat(), | |
| "cohort_summary": { | |
| "total_cases": len(cohort_data.get("cases", [])), | |
| "date_range": _calculate_date_range(cohort_data.get("cases", [])), | |
| }, | |
| "sections": {}, | |
| } | |
| # Generate sections based on template | |
| for section in template_config.get("sections", []): | |
| if section == "demographics": | |
| report_data["sections"][section] = await _generate_demographics_section(cohort_data) # type: ignore[name-defined, index, return-value, var-annotated] | |
| elif section == "procedures": | |
| report_data["sections"][section] = await _generate_procedures_section(cohort_data) # type: ignore[name-defined, index, return-value, var-annotated] | |
| elif section == "outcomes": | |
| report_data["sections"][section] = await _generate_outcomes_section(cohort_data) # type: ignore[name-defined, index, return-value, var-annotated] | |
| return report_data | |
| async def _generate_pdf_report(report_data: Dict, filename: str) -> Path: | |
| """Generate PDF report (placeholder implementation)""" | |
| # This would use a PDF generation library like ReportLab or WeasyPrint | |
| temp_path = Path(f"/tmp/{filename}") | |
| # For now, create a simple text file as placeholder | |
| with open(temp_path, "w") as f: | |
| f.write(f"PDF Report: {report_data['title']}\n") | |
| f.write(f"Generated: {report_data['generated_at']}\n") | |
| f.write(f"Cases: {report_data['cohort_summary']['total_cases']}\n") | |
| return temp_path | |
| def _calculate_date_range(cases: List[Dict]) -> Dict: | |
| """Calculate date range for cohort""" | |
| if not cases: | |
| return {} | |
| dates = [case.get("surgery_date") for case in cases if case.get("surgery_date")] | |
| if dates: | |
| return {"start_date": min(dates), "end_date": max(dates)} # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| return {} | |
| async def _generate_demographics_section(cohort_data: Dict) -> Dict: | |
| """Generate demographics section for report""" | |
| cases = cohort_data.get("cases", []) | |
| if not cases: | |
| return {} | |
| # Calculate basic demographics | |
| ages = [case.get("age") for case in cases if case.get("age")] | |
| return { | |
| "total_cases": len(cases), | |
| "age_statistics": { | |
| "mean": sum(ages) / len(ages) if ages else 0, | |
| "range": [min(ages), max(ages)] if ages else [0, 0], | |
| }, | |
| } | |
| async def _generate_procedures_section(cohort_data: Dict) -> Dict: | |
| """Generate procedures section for report""" | |
| procedures = cohort_data.get("procedures", []) | |
| return { | |
| "total_procedures": len(procedures), | |
| "procedure_types": {}, # Would analyze procedure types | |
| } | |
| async def _generate_outcomes_section(cohort_data: Dict) -> Dict: | |
| """Generate outcomes section for report""" | |
| outcomes = cohort_data.get("outcomes", []) | |
| return { | |
| "total_outcomes": len(outcomes), | |
| "survival_statistics": {}, # Would calculate survival metrics | |
| } | |