Spaces:
Paused

File size: 13,814 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
 
 
579285c
5b36da5
07612e2
 
 
 
579285c
5b36da5
07612e2
 
 
 
579285c
5b36da5
07612e2
 
579285c
5b36da5
579285c
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
579285c
07612e2
579285c
07612e2
579285c
5b36da5
07612e2
 
5b36da5
07612e2
 
 
 
5b36da5
07612e2
5b36da5
07612e2
 
 
5b36da5
07612e2
 
5b36da5
07612e2
 
 
 
5b36da5
 
07612e2
579285c
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
409
410
411
412
413
414
415
416
"""
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()


@router.post("/import/csv")
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)}")


@router.get("/export/csv")
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)}")


@router.get("/export/pdf")
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)}")


@router.get("/cohorts/{cohort_id}/snapshot")
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
    }