Harshit Ghosh commited on
Commit
c4436fb
·
1 Parent(s): 9fc36aa

refactor: migrate to modular architecture, add system documentation, and enhance batch processing stability

Browse files
Files changed (6) hide show
  1. .gitignore +1 -1
  2. System_Architecture.md +57 -0
  3. app.py +0 -1195
  4. app_new.py +61 -41
  5. auth_utils.py +3 -1
  6. static/js/batch.js +3 -2
.gitignore CHANGED
@@ -54,7 +54,7 @@ datasets/
54
 
55
  # Optional local artifact layout
56
 
57
-
58
  # Jupyter
59
  .ipynb_checkpoints/
60
 
 
54
 
55
  # Optional local artifact layout
56
 
57
+ notebool/
58
  # Jupyter
59
  .ipynb_checkpoints/
60
 
System_Architecture.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## System Architecture
2
+
3
+ Our pipeline is designed for multi-tenant medical data isolation, asynchronous batch processing, and scalable inference.
4
+
5
+ ```mermaid
6
+ graph TD
7
+ %% User Interfaces
8
+ User([Clinician/User]) -->|Upload DICOMs or ZIPs| UI[Web Interface]
9
+
10
+ %% Backend Pipeline
11
+ subgraph "Ingestion & API Layer"
12
+ UI -->|HTTP POST| Flask[Flask API Gateway]
13
+ Flask -->|Rate Limiting & Auth| Security[Security & Auth Module]
14
+ end
15
+
16
+ %% Storage Layer
17
+ subgraph "Storage Layer"
18
+ Security -->|Save Raw Scans| Storage[(Local/Cloud File Storage)]
19
+ Security -->|Log Audit & Metadata| NeonDB[(Neon PostgreSQL DB)]
20
+ end
21
+
22
+ %% Processing Layer
23
+ subgraph "Processing Layer (Asynchronous)"
24
+ Flask -->|Spawn Task| Worker[Batch Processing Worker]
25
+ Worker -->|Read DICOM| Storage
26
+ Worker -->|Inference| PyTorch[PyTorch / EffNet B4]
27
+ PyTorch -->|Output Grad-CAM & JSON| Storage
28
+ Worker -->|Save Inference Results| NeonDB
29
+ end
30
+
31
+ %% Insights Layer
32
+ subgraph "Insights Layer"
33
+ NeonDB -->|Query Aggregated Stats| Dashboard[Analytics Dashboard]
34
+ Dashboard --> User
35
+ end
36
+ ```
37
+
38
+ ### Key Code Components
39
+
40
+ If you are exploring the codebase, here are the key modules that power this pipeline:
41
+
42
+ * **Multi-Tenant Security & Data Pipeline (`data_isolation.py`):**
43
+ I built a `UserDataManager` to ensure strict data isolation between medical professionals. This guarantees that users can only access and view their own reports and uploaded DICOMs, maintaining strict privacy.
44
+ * **Database Schema & History (`models.py`):**
45
+ I designed a normalized PostgreSQL schema hosted on Neon. The `ScreeningReport` table tracks everything from raw probabilities to triage urgency, allowing the system to query historical trends and generate dashboard analytics.
46
+ * **Asynchronous Batch Processing (`app_new.py`):**
47
+ Instead of blocking the UI during heavy ML inference, I built an asynchronous worker (see `_start_batch` and `_run_batch_worker`) that processes entire directories or ZIP files of DICOMs in the background, updating the frontend batch status in real-time.
48
+ * **AI Integration (`run_interface.py`):**
49
+ This acts as the adapter layer that translates web requests into PyTorch tensor operations, generates the Grad-CAM visual heatmaps, and applies isotonic temperature calibration to the model's output probabilities.
50
+
51
+ ### System Screenshots
52
+
53
+ *(Note: Add your actual images here)*
54
+
55
+ 1. **Analytics Dashboard:** Displays the insights layer, including Total Cases, Positivity Rate, and Average Confidence across the user's history.
56
+ 2. **Batch Processing UI:** Shows the asynchronous pipeline handling a queue of multiple DICOM files without freezing the app.
57
+ 3. **Visual Report:** Displays a specific patient report featuring the generated Grad-CAM heatmap alongside Urgency and Confidence metrics.
app.py DELETED
@@ -1,1195 +0,0 @@
1
- """
2
- ICH Screening Web Application
3
- ==============================
4
- Features:
5
- 1. Upload a .dcm file -> run AI model -> display screening report
6
- 2. Browse past screening reports with date, outcome, band, urgency filters
7
- 3. View execution logs from inference runs
8
-
9
- Run:
10
- python webapp/app.py
11
- Open http://127.0.0.1:7860
12
- """
13
-
14
- from __future__ import annotations
15
- import run_interface as ri
16
- import csv
17
- import datetime
18
- import json
19
- import math
20
- import logging
21
- import os
22
- import shutil
23
- import sys
24
- import tempfile
25
- import threading
26
- import time
27
- import uuid
28
- import zipfile
29
- from collections import Counter
30
- from dataclasses import dataclass
31
- from pathlib import Path
32
- from typing import Any
33
-
34
- try:
35
- from dotenv import load_dotenv
36
- except Exception:
37
- load_dotenv = None
38
-
39
- hf_hub_download: Any = None
40
- try:
41
- import huggingface_hub
42
- hf_hub_download = getattr(huggingface_hub, "hf_hub_download", None)
43
- except Exception:
44
- hf_hub_download = None
45
-
46
- try:
47
- import blackbox_recorder as bbr # type: ignore[import-untyped]
48
- except Exception:
49
- class _NoopRecorder:
50
- def configure(self, **_kwargs: Any) -> None:
51
- return None
52
-
53
- def start(self) -> None:
54
- return None
55
-
56
- def stop(self) -> None:
57
- return None
58
-
59
- def save_report(self, _path: str) -> None:
60
- return None
61
-
62
- def save_json(self, _path: str) -> None:
63
- return None
64
-
65
- bbr = _NoopRecorder()
66
-
67
- from flask import (
68
- Flask, abort, flash, g, jsonify, redirect,
69
- render_template, request, send_from_directory, url_for,
70
- )
71
- from werkzeug.utils import secure_filename
72
-
73
-
74
- # ══════════════════════════════════════════════════════════════════════════
75
- # PATH CONFIGURATION
76
- # ══════════════════════════════════════════════════════════════════════════
77
-
78
- BASE_DIR = Path(__file__).resolve().parent # webapp/
79
- PROJECT_DIR = BASE_DIR # project root
80
- TEST_DIR = BASE_DIR
81
- MODEL_DIR = BASE_DIR / "download_imp"
82
- OUTPUT_DIR = MODEL_DIR / "outputs"
83
- REPORTS_DIR = OUTPUT_DIR / "reports"
84
- SUMMARY_CSV = OUTPUT_DIR / "report_summary.csv"
85
- CALIB_JSON = MODEL_DIR / "calibration_params.json"
86
- NORM_JSON = MODEL_DIR / "normalization_stats.json"
87
- MODEL_PATH = MODEL_DIR / "best_model_fold4.pth"
88
- UPLOAD_DIR = BASE_DIR / "uploads"
89
- LOGS_DIR = BASE_DIR / "logs"
90
-
91
-
92
- def _env_bool(name: str, default: bool) -> bool:
93
- raw = os.environ.get(name)
94
- if raw is None:
95
- return default
96
- return raw.strip().lower() in ("1", "true", "yes", "on")
97
-
98
-
99
- def _env_int(name: str, default: int, *, minimum: int | None = None) -> int:
100
- raw = os.environ.get(name)
101
- if raw is None:
102
- return default
103
- try:
104
- value = int(raw)
105
- except ValueError:
106
- return default
107
- if minimum is not None and value < minimum:
108
- return default
109
- return value
110
-
111
-
112
- # ══════════════════════════════════════════════════════════════════════════
113
- # FLASK SETUP
114
- # ══════════════════════════════════════════════════════════════════════════
115
-
116
- if load_dotenv is not None:
117
- load_dotenv(BASE_DIR / ".env")
118
-
119
- APP_DEBUG = _env_bool("ICH_APP_DEBUG", True)
120
- APP_PORT = _env_int("ICH_APP_PORT", _env_int("PORT", 7860, minimum=1), minimum=1)
121
- MAX_UPLOAD_MB = _env_int("ICH_MAX_UPLOAD_MB", 2048, minimum=1)
122
- LOG_LEVEL_NAME = os.environ.get("ICH_LOG_LEVEL", "INFO").strip().upper()
123
- LOG_LEVEL = getattr(logging, LOG_LEVEL_NAME, logging.INFO)
124
- SECRET_KEY = os.environ.get("ICH_SECRET_KEY", "").strip()
125
- HF_MODEL_REPO = os.environ.get("ICH_HF_MODEL_REPO", os.environ.get("HF_REPO_ID", "")).strip()
126
- HF_TOKEN = os.environ.get("ICH_HF_TOKEN", os.environ.get("HF_TOKEN", "")).strip()
127
-
128
- app = Flask(__name__, template_folder="templates", static_folder="static")
129
- app.secret_key = SECRET_KEY or os.urandom(24)
130
- app.config["MAX_CONTENT_LENGTH"] = MAX_UPLOAD_MB * 1024 * 1024
131
-
132
- # Local mode: enables server-side directory scanning.
133
- # Auto-detected (running from source) or forced via env var.
134
- LOCAL_MODE = _env_bool("ICH_LOCAL_MODE", True)
135
-
136
- logging.basicConfig(
137
- level=LOG_LEVEL,
138
- format="%(asctime)s | %(levelname)s | %(message)s",
139
- )
140
- logger = logging.getLogger("ich_app")
141
-
142
-
143
- # ══════════════════════════════════════════════════════════════════════════
144
- # BLACKBOX RECORDER — traces inference function calls
145
- #
146
- # We configure it once at module level. start()/stop() bracket each
147
- # inference run. After each run, the trace is saved to logs/ as both a
148
- # human-readable .txt and a structured .json.
149
- # ══════════════════════════════════════════════════════════════════════════
150
-
151
- LOGS_DIR.mkdir(parents=True, exist_ok=True)
152
-
153
- bbr.configure(
154
- include=["run_interface", "app"],
155
- capture_args=True,
156
- capture_returns=True,
157
- sampling_rate=1.0,
158
- )
159
-
160
-
161
- def _save_trace(image_id: str) -> dict[str, str | None]:
162
- """
163
- Save the current blackbox trace to logs/ and return metadata about it.
164
- Called immediately after bbr.stop().
165
- """
166
- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
167
- base = f"{ts}_{image_id}"
168
- txt_path = LOGS_DIR / f"{base}.txt"
169
- json_path = LOGS_DIR / f"{base}.json"
170
-
171
- try:
172
- bbr.save_report(str(txt_path))
173
- except Exception:
174
- logger.warning("Could not save text trace for %s", image_id)
175
-
176
- try:
177
- bbr.save_json(str(json_path))
178
- except Exception:
179
- logger.warning("Could not save JSON trace for %s", image_id)
180
-
181
- return {
182
- "timestamp": ts,
183
- "image_id": image_id,
184
- "txt_file": txt_path.name if txt_path.exists() else None,
185
- "json_file": json_path.name if json_path.exists() else None,
186
- }
187
-
188
-
189
- # ══════════════════════════════════════════════════════════════════════════
190
- # BATCH PROCESSING STATE
191
- #
192
- # Each batch job is a background thread processing a list of .dcm paths.
193
- # The UI polls /batch/status/<id> for live progress.
194
- # ══════════════════════════════════════════════════════════════════════════
195
-
196
- _BATCHES: dict[str, dict[str, Any]] = {}
197
- _BATCHES_LOCK = threading.Lock()
198
-
199
-
200
- def _new_batch(total: int, temp_dir: str | None = None) -> str:
201
- """Create a fresh batch record and return its unique ID."""
202
- batch_id = uuid.uuid4().hex[:12]
203
- with _BATCHES_LOCK:
204
- _BATCHES[batch_id] = {
205
- "status": "running", # running | completed | failed
206
- "total": total,
207
- "processed": 0,
208
- "succeeded": 0,
209
- "failed_ids": [],
210
- "current_file": "",
211
- "image_ids": [], # successfully processed IDs
212
- "started_at": datetime.datetime.now().isoformat(),
213
- "finished_at": None,
214
- "error": None,
215
- "temp_dir": temp_dir, # cleaned up after completion
216
- }
217
- return batch_id
218
-
219
-
220
- def _batch_update(batch_id: str, **kw: Any) -> None:
221
- """Thread-safe update of a batch record."""
222
- with _BATCHES_LOCK:
223
- if batch_id in _BATCHES:
224
- _BATCHES[batch_id].update(kw)
225
-
226
-
227
- def _run_batch_worker(batch_id: str, dcm_paths: list[Path]):
228
- """
229
- Background thread: process a list of .dcm files sequentially.
230
- Updates the batch record after each file for real-time UI feedback.
231
- """
232
- succeeded_ids: list[str] = []
233
- failed_ids: list[str] = []
234
-
235
- for i, path in enumerate(dcm_paths, 1):
236
- image_id = path.stem
237
- _batch_update(batch_id, current_file=image_id, processed=i - 1)
238
-
239
- try:
240
- report, _trace = _run_inference_on_dcm(path)
241
- if report is not None:
242
- succeeded_ids.append(image_id)
243
- else:
244
- failed_ids.append(image_id)
245
- except Exception as e:
246
- logger.error("Batch %s: failed %s — %s", batch_id, image_id, e)
247
- failed_ids.append(image_id)
248
-
249
- _batch_update(
250
- batch_id,
251
- processed=i,
252
- succeeded=len(succeeded_ids),
253
- image_ids=list(succeeded_ids),
254
- failed_ids=list(failed_ids),
255
- )
256
-
257
- # Clean up temp directory if one was used (ZIP extraction)
258
- with _BATCHES_LOCK:
259
- b = _BATCHES.get(batch_id, {})
260
- td = b.get("temp_dir")
261
- if td and Path(td).exists():
262
- shutil.rmtree(td, ignore_errors=True)
263
-
264
- _batch_update(
265
- batch_id,
266
- status="completed",
267
- current_file="",
268
- finished_at=datetime.datetime.now().isoformat(),
269
- )
270
- # Force cache reload on next page view
271
- _CACHE["data_signature"] = None
272
- logger.info(
273
- "Batch %s complete: %d/%d succeeded, %d failed",
274
- batch_id, len(succeeded_ids), len(dcm_paths), len(failed_ids),
275
- )
276
-
277
-
278
- def _start_batch(dcm_paths: list[Path], temp_dir: str | None = None) -> str:
279
- """Create a batch job & launch its worker thread. Returns batch_id."""
280
- batch_id = _new_batch(total=len(dcm_paths), temp_dir=temp_dir)
281
- t = threading.Thread(
282
- target=_run_batch_worker,
283
- args=(batch_id, dcm_paths),
284
- daemon=True,
285
- name=f"batch-{batch_id}",
286
- )
287
- t.start()
288
- return batch_id
289
-
290
-
291
- # ══════════════════════════════════════════════════════════════════════════
292
- # IN-MEMORY CACHE
293
- # ══════════════════════════════════════════════════════════════════════════
294
-
295
- _CACHE: dict[str, Any] = {
296
- "data_signature": None,
297
- "cases": {},
298
- "rows_sorted": [],
299
- "data_last_refresh_ms": None,
300
- "data_last_cache_hit": False,
301
- "calib_signature": None,
302
- "calib": {},
303
- "norm_signature": None,
304
- "norm": {},
305
- }
306
-
307
-
308
- # ══════════════════════════════════════════════════════════════════════════
309
- # MODEL STATE — lazy-loaded on first upload
310
- # ══════════════════════════════════════════════════════════════════════════
311
-
312
- _MODEL: dict[str, Any] = {
313
- "loaded": False,
314
- "model": None,
315
- "grad_cam": None,
316
- "loaded_folds": [],
317
- "transform": None,
318
- "device": None,
319
- "temperature": None,
320
- "calib_cfg": None,
321
- "inference_mod": None,
322
- }
323
-
324
-
325
- def _required_model_files(fold_selection: str) -> list[str]:
326
- files = [
327
- "calibration_params.json",
328
- "normalization_stats.json",
329
- ]
330
- raw = (fold_selection or "ensemble").strip().lower()
331
- if raw in ("", "ensemble", "all"):
332
- files.extend([f"best_model_fold{i}.pth" for i in range(5)])
333
- return files
334
- if raw == "best":
335
- files.append("best_model_fold4.pth")
336
- return files
337
- if raw.isdigit():
338
- files.append(f"best_model_fold{int(raw)}.pth")
339
- return files
340
- # Fallback to ensemble behavior for unknown values.
341
- files.extend([f"best_model_fold{i}.pth" for i in range(5)])
342
- return files
343
-
344
-
345
- def _download_runtime_artifacts_if_needed(fold_selection: str) -> bool:
346
- required_files = _required_model_files(fold_selection)
347
- missing = [name for name in required_files if not (MODEL_DIR / name).exists()]
348
- if not missing:
349
- return True
350
-
351
- if not HF_MODEL_REPO:
352
- logger.warning(
353
- "Missing runtime model files (%s) and ICH_HF_MODEL_REPO/HF_REPO_ID is not set.",
354
- ", ".join(missing),
355
- )
356
- return False
357
-
358
- if hf_hub_download is None:
359
- logger.error(
360
- "huggingface_hub is not installed, cannot download missing model artifacts."
361
- )
362
- return False
363
-
364
- MODEL_DIR.mkdir(parents=True, exist_ok=True)
365
- logger.info("Downloading missing model artifacts from Hugging Face repo: %s", HF_MODEL_REPO)
366
- try:
367
- for filename in missing:
368
- hf_hub_download(
369
- repo_id=HF_MODEL_REPO,
370
- filename=filename,
371
- repo_type="model",
372
- local_dir=str(MODEL_DIR),
373
- token=HF_TOKEN or None,
374
- )
375
- logger.info("Downloaded artifact: %s", filename)
376
- return True
377
- except Exception as exc:
378
- logger.error("Failed downloading model artifacts from Hugging Face: %s", exc)
379
- return False
380
-
381
-
382
- def _ensure_model_loaded() -> bool:
383
- """Lazy-load the ML model on first inference request."""
384
- if _MODEL["loaded"]:
385
- return True
386
-
387
- try:
388
- import torch
389
-
390
- sys.path.insert(0, str(BASE_DIR))
391
-
392
- device = "cuda" if torch.cuda.is_available() else "cpu"
393
- fold_selection = os.environ.get("ICH_FOLD_SELECTION", "ensemble")
394
-
395
- _download_runtime_artifacts_if_needed(fold_selection)
396
-
397
- if not CALIB_JSON.exists():
398
- logger.error(
399
- "Missing calibration file at %s. Provide local files or set ICH_HF_MODEL_REPO.",
400
- CALIB_JSON,
401
- )
402
- return False
403
-
404
- with open(CALIB_JSON) as f:
405
- calib_cfg = json.load(f)
406
-
407
- if NORM_JSON.exists():
408
- with open(NORM_JSON) as f:
409
- norm = json.load(f)
410
- mean = norm.get("mean_3ch", [0.162136, 0.141483, 0.183675])
411
- std = norm.get("std_3ch", [0.312067, 0.283885, 0.305968])
412
- else:
413
- mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
414
-
415
- models, grad_cams, loaded_folds = ri.load_runtime_models(device, fold_selection)
416
- if not models:
417
- logger.error("No fold checkpoints could be loaded from %s", MODEL_DIR)
418
- return False
419
-
420
- transform = ri.T.Compose([
421
- ri.T.ToPILImage(),
422
- ri.T.ToTensor(),
423
- ri.T.Normalize(mean=mean, std=std),
424
- ])
425
-
426
- _MODEL.update({
427
- "loaded": True,
428
- "model": models,
429
- "grad_cam": grad_cams,
430
- "loaded_folds": loaded_folds,
431
- "transform": transform,
432
- "device": device,
433
- "temperature": float(calib_cfg.get("temperature", 1.0)),
434
- "calib_cfg": calib_cfg,
435
- "inference_mod": ri,
436
- })
437
- logger.info(
438
- "Model loaded (device=%s, fold_selection=%s, folds=%s)",
439
- device,
440
- fold_selection,
441
- loaded_folds,
442
- )
443
- return True
444
-
445
- except Exception as e:
446
- logger.error("Model loading failed: %s", e, exc_info=True)
447
- return False
448
-
449
-
450
- def _run_inference_on_dcm(dcm_path: Path) -> tuple[dict[str, Any] | None, dict[str, str | None] | None]:
451
- """
452
- Run inference on one .dcm file, with blackbox tracing.
453
- Returns (report_dict, trace_metadata) or (None, None) on failure.
454
- """
455
- if not _ensure_model_loaded():
456
- return None, None
457
-
458
- ri = _MODEL["inference_mod"]
459
- image_id = dcm_path.stem
460
-
461
- # Start tracing this inference run
462
- bbr.start()
463
-
464
- try:
465
- img_rgb = ri.dicom_to_rgb(str(dcm_path), size=ri.IMG_SIZE)
466
-
467
- inference = ri.infer_single(
468
- img_rgb,
469
- _MODEL["model"],
470
- _MODEL["grad_cam"],
471
- _MODEL["transform"],
472
- _MODEL["device"],
473
- _MODEL["temperature"],
474
- )
475
-
476
- REPORTS_DIR.mkdir(parents=True, exist_ok=True)
477
- report = ri.build_report(
478
- image_id, inference, _MODEL["calib_cfg"],
479
- REPORTS_DIR, img_rgb, true_label=None,
480
- )
481
- pred = report.get("prediction", {})
482
- pred.setdefault("raw_probability", inference.get("raw_prob_any"))
483
- pred.setdefault("calibrated_probability", inference.get("cal_prob_any"))
484
- pred.setdefault("decision_threshold", pred.get("decision_threshold_any"))
485
- report["prediction"] = pred
486
-
487
- report_path = REPORTS_DIR / f"{image_id}_report.json"
488
- with open(report_path, "w") as f:
489
- json.dump(report, f, indent=2)
490
-
491
- _append_to_summary_csv(image_id, report)
492
- _CACHE["data_signature"] = None
493
-
494
- except Exception:
495
- bbr.stop()
496
- raise
497
-
498
- # Stop tracing and save the execution log
499
- bbr.stop()
500
- trace_meta = _save_trace(image_id)
501
-
502
- return report, trace_meta
503
-
504
-
505
- def _append_to_summary_csv(image_id: str, report: dict[str, Any]) -> None:
506
- """Append one report row to the summary CSV."""
507
- pred = report["prediction"]
508
- row: dict[str, Any] = {
509
- "image_id": image_id,
510
- "true_label": "",
511
- "screening_outcome": pred["screening_outcome"],
512
- "raw_prob": pred["raw_probability"],
513
- "cal_prob": pred["calibrated_probability"],
514
- "confidence_band": pred["confidence_band"],
515
- "triage_action": report["triage"]["action"],
516
- "urgency": report["triage"]["urgency"],
517
- "generated_at": report.get("generated_at", ""),
518
- }
519
-
520
- file_exists = SUMMARY_CSV.exists()
521
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
522
-
523
- with open(SUMMARY_CSV, "a", newline="", encoding="utf-8") as f:
524
- writer = csv.DictWriter(f, fieldnames=list(row.keys()))
525
- if not file_exists:
526
- writer.writeheader()
527
- writer.writerow(row)
528
-
529
-
530
- # ══════════════════════════════════════════════════════════════════════════
531
- # DATA MODEL
532
- # ══════════════════════════════════════════════════════════════════════════
533
-
534
- @dataclass
535
- class CaseRow:
536
- image_id: str = ""
537
- outcome: str = "Unknown"
538
- raw_prob: float|None = None
539
- cal_prob: float|None = None
540
- band: str = "N/A"
541
- triage: str = "N/A"
542
- urgency: str = "N/A"
543
- true_label: str = ""
544
- generated_at: str = "" # ISO timestamp from report JSON
545
- report_file: str|None = None
546
- gradcam_file: str|None = None
547
-
548
- @property
549
- def date_display(self) -> str:
550
- """Format the ISO timestamp as a short readable date."""
551
- if not self.generated_at:
552
- return "—"
553
- try:
554
- dt = datetime.datetime.fromisoformat(self.generated_at)
555
- return dt.strftime("%Y-%m-%d %H:%M")
556
- except (ValueError, TypeError):
557
- return self.generated_at[:16]
558
-
559
- @property
560
- def is_positive(self) -> bool:
561
- return "no hemorrhage" not in self.outcome.lower()
562
-
563
-
564
- # ══════════════════════════════════════════════════════════════════════════
565
- # UTILITIES
566
- # ══════════════════════════════════════════════════════════════════════════
567
-
568
- def _to_float(value: Any) -> float | None:
569
- try:
570
- return float(value) if value not in (None, "") else None
571
- except (TypeError, ValueError):
572
- return None
573
-
574
-
575
- def _file_mtime(path: Path) -> int:
576
- try:
577
- return path.stat().st_mtime_ns if path.exists() else -1
578
- except OSError:
579
- return -1
580
-
581
-
582
- def _data_signature() -> tuple[int, int]:
583
- return _file_mtime(REPORTS_DIR), _file_mtime(SUMMARY_CSV)
584
-
585
-
586
- def _parse_positive_int(value: str | None, default: int) -> int:
587
- try:
588
- n = int(value or default)
589
- return n if n > 0 else default
590
- except (TypeError, ValueError):
591
- return default
592
-
593
-
594
- # ══════════════════════════════════════════════════════════════════════════
595
- # DATA LOADING
596
- # ══════════════════════════════════════════════════════════════════════════
597
-
598
- def _load_summary_csv() -> dict[str, dict[str, Any]]:
599
- """Read report_summary.csv into memory, keyed by image_id."""
600
- if not SUMMARY_CSV.exists():
601
- return {}
602
- rows: dict[str, dict[str, Any]] = {}
603
- with SUMMARY_CSV.open("r", encoding="utf-8") as f:
604
- for row in csv.DictReader(f):
605
- iid = (row.get("image_id") or "").strip()
606
- if not iid:
607
- continue
608
- rows[iid] = {
609
- "image_id": iid,
610
- "outcome": row.get("screening_outcome", "Unknown"),
611
- "raw_prob": _to_float(row.get("raw_prob")),
612
- "cal_prob": _to_float(row.get("cal_prob")),
613
- "band": row.get("confidence_band") or "N/A",
614
- "triage": row.get("triage_action") or "N/A",
615
- "urgency": row.get("urgency") or "N/A",
616
- "true_label": row.get("true_label", ""),
617
- "generated_at": row.get("generated_at", ""),
618
- }
619
- return rows
620
-
621
-
622
- def _scan_report_assets() -> tuple[set[str], set[str]]:
623
- """One dir walk to find which image IDs have JSON and PNG files."""
624
- report_ids: set[str] = set()
625
- gradcam_ids: set[str] = set()
626
- if not REPORTS_DIR.exists():
627
- return report_ids, gradcam_ids
628
- for path in REPORTS_DIR.iterdir():
629
- if not path.is_file():
630
- continue
631
- if path.name.endswith("_report.json"):
632
- report_ids.add(path.name[:-12])
633
- elif path.name.endswith("_gradcam.png"):
634
- gradcam_ids.add(path.name[:-12])
635
- return report_ids, gradcam_ids
636
-
637
-
638
- def _read_generated_at(image_id: str) -> str:
639
- """Read the generated_at timestamp from a report JSON file."""
640
- path = REPORTS_DIR / f"{image_id}_report.json"
641
- if not path.exists():
642
- return ""
643
- try:
644
- data = json.loads(path.read_text("utf-8"))
645
- return data.get("generated_at", "")
646
- except (json.JSONDecodeError, OSError):
647
- return ""
648
-
649
-
650
- def _load_cases_from_json() -> dict[str, CaseRow]:
651
- """Fallback: read each *_report.json when CSV is unavailable."""
652
- summary = _load_summary_csv()
653
- cases: dict[str, CaseRow] = {}
654
- for rp in sorted(REPORTS_DIR.glob("*_report.json")):
655
- try:
656
- payload = json.loads(rp.read_text("utf-8"))
657
- except (json.JSONDecodeError, OSError):
658
- continue
659
- iid = str(payload.get("image_id", rp.stem.replace("_report", ""))).strip()
660
- pred = payload.get("prediction", {})
661
- tri = payload.get("triage", {})
662
- expl = payload.get("explainability", {})
663
- sr = summary.get(iid, {})
664
- gc = Path(str(expl.get("heatmap_path", ""))).name or None
665
- cases[iid] = CaseRow(
666
- image_id=iid,
667
- outcome=pred.get("screening_outcome", sr.get("outcome", "Unknown")),
668
- raw_prob=_to_float(pred.get("raw_probability", sr.get("raw_prob"))),
669
- cal_prob=_to_float(pred.get("calibrated_probability", sr.get("cal_prob"))),
670
- band=pred.get("confidence_band", sr.get("band", "N/A")),
671
- triage=tri.get("action", sr.get("triage", "N/A")),
672
- urgency=tri.get("urgency", sr.get("urgency", "N/A")),
673
- true_label=str(payload.get("ground_truth_label", sr.get("true_label", ""))),
674
- generated_at=payload.get("generated_at", ""),
675
- report_file=rp.name,
676
- gradcam_file=gc,
677
- )
678
- return cases
679
-
680
-
681
- def load_cases_cached() -> dict[str, CaseRow]:
682
- """Return all cases, re-reading from disk only when files change."""
683
- sig = _data_signature()
684
- if _CACHE["data_signature"] == sig:
685
- _CACHE["data_last_cache_hit"] = True
686
- return _CACHE["cases"]
687
-
688
- start = time.perf_counter()
689
- summary = _load_summary_csv()
690
-
691
- if summary:
692
- report_ids, gradcam_ids = _scan_report_assets()
693
- cases = {}
694
- for iid, sr in summary.items():
695
- # Resolve generated_at: prefer CSV value, fall back to JSON file
696
- gen_at = sr.get("generated_at", "")
697
- if not gen_at and iid in report_ids:
698
- gen_at = _read_generated_at(iid)
699
-
700
- cases[iid] = CaseRow(
701
- image_id=iid,
702
- outcome=sr.get("outcome", "Unknown"),
703
- raw_prob=_to_float(sr.get("raw_prob")),
704
- cal_prob=_to_float(sr.get("cal_prob")),
705
- band=sr.get("band", "N/A"),
706
- triage=sr.get("triage", "N/A"),
707
- urgency=sr.get("urgency", "N/A"),
708
- true_label=sr.get("true_label", ""),
709
- generated_at=gen_at,
710
- report_file=f"{iid}_report.json" if iid in report_ids else None,
711
- gradcam_file=f"{iid}_gradcam.png" if iid in gradcam_ids else None,
712
- )
713
- elif REPORTS_DIR.exists():
714
- cases = _load_cases_from_json()
715
- else:
716
- cases = {}
717
-
718
- elapsed_ms = (time.perf_counter() - start) * 1000
719
- _CACHE.update({
720
- "data_signature": sig,
721
- "cases": cases,
722
- "rows_sorted": sorted(cases.values(), key=lambda c: c.image_id),
723
- "data_last_refresh_ms": elapsed_ms,
724
- "data_last_cache_hit": False,
725
- })
726
- logger.info("Cache refresh: %d cases in %.1f ms", len(cases), elapsed_ms)
727
- return cases
728
-
729
-
730
- def load_case_payload(image_id: str) -> dict[str, Any] | None:
731
- """Load full JSON report for one case (Raw JSON button)."""
732
- path = REPORTS_DIR / f"{image_id}_report.json"
733
- if not path.exists():
734
- return None
735
- try:
736
- return json.loads(path.read_text("utf-8"))
737
- except (json.JSONDecodeError, OSError):
738
- return None
739
-
740
-
741
- def compute_stats(rows: list[CaseRow]) -> dict[str, Any]:
742
- """Compute summary statistics for the dashboard cards."""
743
- total = len(rows)
744
- positive = sum(1 for r in rows if r.is_positive)
745
- urgent = sum(1 for r in rows if r.urgency.upper() == "URGENT")
746
- heatmaps = sum(1 for r in rows if r.gradcam_file)
747
- cal_probs = [r.cal_prob for r in rows if r.cal_prob is not None]
748
- avg_cal = sum(cal_probs) / len(cal_probs) if cal_probs else 0.0
749
- pos_rate = (positive / total * 100) if total else 0.0
750
-
751
- # Date range
752
- dates = sorted(r.generated_at for r in rows if r.generated_at)
753
- newest = dates[-1] if dates else ""
754
- oldest = dates[0] if dates else ""
755
-
756
- return {
757
- "total": total,
758
- "positive": positive,
759
- "negative": total - positive,
760
- "urgent": urgent,
761
- "heatmaps": heatmaps,
762
- "avg_cal_prob": avg_cal,
763
- "pos_rate": pos_rate,
764
- "band_counts": dict(Counter(r.band.upper() for r in rows)),
765
- "urgency_counts": dict(Counter(r.urgency.upper() for r in rows)),
766
- "newest_date": newest,
767
- "oldest_date": oldest,
768
- }
769
-
770
-
771
- def _load_json_cached(path: Path, sig_key: str, data_key: str, label: str) -> dict[str, Any]:
772
- """Mtime-based JSON cache loader for calibration/normalization."""
773
- sig = _file_mtime(path)
774
- if _CACHE[sig_key] == sig:
775
- return _CACHE[data_key]
776
- data: dict[str, Any] = {}
777
- if path.exists():
778
- try:
779
- data = json.loads(path.read_text("utf-8"))
780
- except (json.JSONDecodeError, OSError):
781
- logger.warning("Could not read %s", path)
782
- _CACHE[sig_key] = sig
783
- _CACHE[data_key] = data
784
- return data
785
-
786
-
787
- def load_calibration() -> dict[str, Any]:
788
- calib = _load_json_cached(CALIB_JSON, "calib_signature", "calib", "Calibration")
789
- if not calib:
790
- return {}
791
- # Backward-compatible aliases expected by templates.
792
- return {
793
- **calib,
794
- "method": calib.get("method", calib.get("best_method", "N/A")),
795
- "temperature": calib.get("temperature", 1.0),
796
- "raw_ece": calib.get("ece_raw", 0.0),
797
- "cal_ece": calib.get("ece_isotonic", calib.get("ece_temp", 0.0)),
798
- "raw_brier": calib.get("brier_raw", 0.0),
799
- "cal_brier": calib.get("brier_isotonic", calib.get("brier_temp", 0.0)),
800
- "calibrated_threshold": calib.get("threshold_at_spec90", 0.5),
801
- "base_threshold": calib.get("base_threshold", 0.5),
802
- "high_threshold": calib.get("high_threshold", calib.get("triage_high_thresh", 0.7)),
803
- "low_threshold": calib.get("low_threshold", calib.get("triage_low_thresh", 0.3)),
804
- }
805
-
806
-
807
- def load_normalization() -> dict[str, Any]:
808
- return _load_json_cached(NORM_JSON, "norm_signature", "norm", "Normalization")
809
-
810
-
811
- def filter_cases(
812
- rows: list[CaseRow],
813
- q: str,
814
- band: str,
815
- urgency: str,
816
- outcome: str,
817
- sort_by: str,
818
- ) -> list[CaseRow]:
819
- """Apply text search, dropdown filters, and sorting."""
820
- if q:
821
- ql = q.lower()
822
- rows = [r for r in rows if ql in r.image_id.lower() or ql in r.outcome.lower()]
823
- if band:
824
- rows = [r for r in rows if r.band.upper() == band.upper()]
825
- if urgency:
826
- rows = [r for r in rows if r.urgency.upper() == urgency.upper()]
827
- if outcome == "POSITIVE":
828
- rows = [r for r in rows if r.is_positive]
829
- elif outcome == "NEGATIVE":
830
- rows = [r for r in rows if not r.is_positive]
831
-
832
- if sort_by == "date_desc":
833
- rows = sorted(rows, key=lambda r: r.generated_at or "", reverse=True)
834
- elif sort_by == "date_asc":
835
- rows = sorted(rows, key=lambda r: r.generated_at or "")
836
- elif sort_by == "prob_desc":
837
- rows = sorted(rows, key=lambda r: r.cal_prob or 0, reverse=True)
838
- elif sort_by == "prob_asc":
839
- rows = sorted(rows, key=lambda r: r.cal_prob or 0)
840
- # default: sorted by image_id (already the case from cache)
841
-
842
- return rows
843
-
844
-
845
- def load_logs() -> list[dict[str, Any]]:
846
- """Scan the logs/ directory and return metadata for each trace."""
847
- if not LOGS_DIR.exists():
848
- return []
849
-
850
- log_files: dict[str, dict[str, Any]] = {} # base_name -> {txt_file, json_file, ...}
851
-
852
- for path in sorted(LOGS_DIR.iterdir(), reverse=True):
853
- if not path.is_file():
854
- continue
855
- stem = path.stem # e.g. "20260228_153000_ID_abc123"
856
- if path.suffix == ".txt":
857
- log_files.setdefault(stem, {})["txt_file"] = path.name
858
- # Parse out timestamp and image_id from filename
859
- parts = stem.split("_", 2)
860
- if len(parts) >= 3:
861
- log_files[stem]["timestamp"] = f"{parts[0]}_{parts[1]}"
862
- log_files[stem]["image_id"] = parts[2]
863
- log_files[stem]["size_kb"] = round(path.stat().st_size / 1024, 1)
864
- elif path.suffix == ".json":
865
- log_files.setdefault(stem, {})["json_file"] = path.name
866
-
867
- entries: list[dict[str, Any]] = []
868
- for stem in sorted(log_files, reverse=True):
869
- info = log_files[stem]
870
- ts_raw = info.get("timestamp", "")
871
- try:
872
- dt = datetime.datetime.strptime(ts_raw, "%Y%m%d_%H%M%S")
873
- display = dt.strftime("%Y-%m-%d %H:%M:%S")
874
- except ValueError:
875
- display = ts_raw
876
- entries.append({
877
- "stem": stem,
878
- "timestamp": display,
879
- "image_id": info.get("image_id", ""),
880
- "txt_file": info.get("txt_file"),
881
- "json_file": info.get("json_file"),
882
- "size_kb": info.get("size_kb", 0),
883
- })
884
-
885
- return entries
886
-
887
-
888
- # ══════════════════════════════════════════════════════════════════════════
889
- # MIDDLEWARE
890
- # ══════════════════════════════════════════════════════════════════════════
891
-
892
- @app.before_request
893
- def _start_timer() -> None: # pyright: ignore[reportUnusedFunction]
894
- g._start_time = time.perf_counter()
895
-
896
-
897
- @app.after_request
898
- def _log_timing(response: Any) -> Any: # pyright: ignore[reportUnusedFunction]
899
- elapsed = (time.perf_counter() - getattr(g, "_start_time", time.perf_counter())) * 1000
900
- logger.info("%s %s -> %s (%.1f ms)", request.method, request.path, response.status_code, elapsed)
901
- return response
902
-
903
-
904
- # ══════════════════════════════════════════════════════════════════════════
905
- # ROUTES
906
- # ══════════════════════════════════════════════════════════════════════════
907
-
908
- @app.route("/")
909
- def home():
910
- """Landing page with quick stats and navigation."""
911
- load_cases_cached()
912
- all_rows = _CACHE["rows_sorted"]
913
- stats = compute_stats(all_rows)
914
- log_count = len(list(LOGS_DIR.glob("*.txt"))) if LOGS_DIR.exists() else 0
915
- return render_template("home.html", stats=stats, log_count=log_count)
916
-
917
-
918
- @app.route("/upload")
919
- def upload():
920
- return render_template("upload.html", local_mode=LOCAL_MODE)
921
-
922
-
923
- @app.route("/analyze", methods=["POST"])
924
- def analyze():
925
- """
926
- Accept one or more .dcm files (or a .zip) and run inference.
927
-
928
- Single file → synchronous, redirect straight to the report.
929
- Multiple → asynchronous batch, redirect to progress page.
930
- """
931
- files = request.files.getlist("file")
932
- files = [f for f in files if f.filename]
933
-
934
- if not files:
935
- flash("No files were uploaded.", "error")
936
- return redirect(url_for("upload"))
937
-
938
- UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
939
-
940
- # ── Collect all .dcm paths (expand .zip archives) ────────────────
941
- dcm_paths: list[Path] = []
942
- temp_dir: str | None = None # set if a zip needed extraction
943
-
944
- for f in files:
945
- filename = f.filename or ""
946
- fname = filename.lower()
947
-
948
- if fname.endswith(".zip"):
949
- temp_dir = tempfile.mkdtemp(prefix="ich_zip_")
950
- zip_save = Path(temp_dir) / secure_filename(filename)
951
- f.save(str(zip_save))
952
- try:
953
- with zipfile.ZipFile(zip_save, "r") as zf:
954
- zf.extractall(temp_dir)
955
- except zipfile.BadZipFile:
956
- shutil.rmtree(temp_dir, ignore_errors=True)
957
- flash("The uploaded ZIP file is corrupted.", "error")
958
- return redirect(url_for("upload"))
959
- # Recursively find .dcm inside extracted tree
960
- dcm_paths.extend(sorted(Path(temp_dir).rglob("*.dcm")))
961
-
962
- elif fname.endswith(".dcm"):
963
- safe = secure_filename(filename)
964
- save_path = UPLOAD_DIR / safe
965
- f.save(str(save_path))
966
- dcm_paths.append(save_path)
967
-
968
- else:
969
- # skip non-dcm / non-zip silently
970
- continue
971
-
972
- if not dcm_paths:
973
- flash("No .dcm files found in the upload.", "error")
974
- if temp_dir:
975
- shutil.rmtree(temp_dir, ignore_errors=True)
976
- return redirect(url_for("upload"))
977
-
978
- # ── Single file → synchronous (fast path) ────────────────────────
979
- if len(dcm_paths) == 1 and temp_dir is None:
980
- single_path = dcm_paths[0]
981
- try:
982
- report, _trace = _run_inference_on_dcm(single_path)
983
- if report is None:
984
- flash("Model failed to load. Check server logs.", "error")
985
- return redirect(url_for("upload"))
986
- return redirect(url_for("case_detail", image_id=single_path.stem))
987
- except Exception as e:
988
- logger.error("Analysis failed for %s: %s", single_path.name, e, exc_info=True)
989
- flash(f"Analysis failed: {e}", "error")
990
- return redirect(url_for("upload"))
991
- finally:
992
- if single_path.exists() and single_path.parent == UPLOAD_DIR:
993
- single_path.unlink()
994
-
995
- # ── Multiple files → asynchronous batch ──────────────────────────
996
- batch_id = _start_batch(dcm_paths, temp_dir=temp_dir)
997
- logger.info("Batch %s started: %d files", batch_id, len(dcm_paths))
998
- return redirect(url_for("batch_progress", batch_id=batch_id))
999
-
1000
-
1001
- @app.route("/analyze/directory", methods=["POST"])
1002
- def analyze_directory():
1003
- """
1004
- Local-only route: scan a server-side directory for .dcm files and
1005
- start a batch job. Disabled when LOCAL_MODE is off.
1006
- """
1007
- if not LOCAL_MODE:
1008
- abort(403)
1009
-
1010
- dir_path_str = request.form.get("dir_path", "").strip()
1011
- if not dir_path_str:
1012
- flash("Please enter a directory path.", "error")
1013
- return redirect(url_for("upload"))
1014
-
1015
- scan_dir = Path(dir_path_str)
1016
- if not scan_dir.is_dir():
1017
- flash(f"Directory not found: {dir_path_str}", "error")
1018
- return redirect(url_for("upload"))
1019
-
1020
- dcm_paths = sorted(scan_dir.rglob("*.dcm"))
1021
- if not dcm_paths:
1022
- flash(f"No .dcm files found in: {dir_path_str}", "error")
1023
- return redirect(url_for("upload"))
1024
-
1025
- batch_id = _start_batch(dcm_paths)
1026
- logger.info("Directory batch %s started: %d files from %s", batch_id, len(dcm_paths), dir_path_str)
1027
- return redirect(url_for("batch_progress", batch_id=batch_id))
1028
-
1029
-
1030
- @app.route("/batch/progress/<batch_id>")
1031
- def batch_progress(batch_id: str):
1032
- """Batch progress page — polls /batch/status/<id> via JS."""
1033
- with _BATCHES_LOCK:
1034
- batch = _BATCHES.get(batch_id)
1035
- if not batch:
1036
- abort(404)
1037
- return render_template("batch_progress.html", batch_id=batch_id, batch=batch)
1038
-
1039
-
1040
- @app.route("/batch/status/<batch_id>")
1041
- def batch_status(batch_id: str):
1042
- """JSON endpoint polled by the progress page for live updates."""
1043
- with _BATCHES_LOCK:
1044
- batch = _BATCHES.get(batch_id)
1045
- if not batch:
1046
- return jsonify({"error": "not found"}), 404
1047
- # Return a safe copy (no Path objects)
1048
- return jsonify({
1049
- "status": batch["status"],
1050
- "total": batch["total"],
1051
- "processed": batch["processed"],
1052
- "succeeded": batch["succeeded"],
1053
- "failed_count": len(batch["failed_ids"]),
1054
- "failed_ids": batch["failed_ids"][:20], # cap for payload size
1055
- "current_file": batch["current_file"],
1056
- "image_ids": batch["image_ids"][-5:], # last 5 for display
1057
- "started_at": batch["started_at"],
1058
- "finished_at": batch["finished_at"],
1059
- })
1060
-
1061
-
1062
- @app.route("/reports")
1063
- def reports():
1064
- """Past reports page with filtering, sorting, and pagination."""
1065
- route_start = time.perf_counter()
1066
-
1067
- load_cases_cached()
1068
- all_rows = _CACHE["rows_sorted"]
1069
-
1070
- # Read all filter/sort/pagination params from query string
1071
- q = request.args.get("q", "").strip()
1072
- band = request.args.get("band", "").strip()
1073
- urgency = request.args.get("urgency", "").strip()
1074
- outcome = request.args.get("outcome", "").strip()
1075
- sort_by = request.args.get("sort", "").strip()
1076
- page = _parse_positive_int(request.args.get("page"), 1)
1077
- page_size = _parse_positive_int(request.args.get("page_size"), 50)
1078
- if page_size not in (10, 50, 100):
1079
- page_size = 50
1080
-
1081
- filtered = filter_cases(all_rows, q, band, urgency, outcome, sort_by)
1082
- stats = compute_stats(filtered)
1083
- total = len(filtered)
1084
- total_pages = max(1, math.ceil(total / page_size))
1085
- page = min(page, total_pages)
1086
- start_idx = (page - 1) * page_size
1087
- rows = filtered[start_idx: start_idx + page_size]
1088
- route_ms = (time.perf_counter() - route_start) * 1000
1089
-
1090
- return render_template(
1091
- "reports.html",
1092
- rows=rows,
1093
- stats=stats,
1094
- calib=load_calibration(),
1095
- q=q, band=band, urgency=urgency, outcome=outcome, sort=sort_by,
1096
- page=page,
1097
- page_size=page_size,
1098
- page_start=start_idx,
1099
- total_pages=total_pages,
1100
- total_items=total,
1101
- total_cases=len(all_rows),
1102
- route_compute_ms=route_ms,
1103
- data_refresh_ms=_CACHE["data_last_refresh_ms"],
1104
- data_cache_hit=_CACHE["data_last_cache_hit"],
1105
- )
1106
-
1107
-
1108
- @app.route("/case/<image_id>")
1109
- def case_detail(image_id: str):
1110
- """Individual case report page."""
1111
- cases = load_cases_cached()
1112
- row = cases.get(image_id)
1113
- if not row:
1114
- abort(404)
1115
- payload = load_case_payload(image_id)
1116
- return render_template("detail.html", row=row, payload=payload)
1117
-
1118
-
1119
- @app.route("/logs")
1120
- def logs_page():
1121
- """Execution logs page."""
1122
- entries = load_logs()
1123
- return render_template("logs.html", logs=entries)
1124
-
1125
-
1126
- @app.route("/logs/view/<path:filename>")
1127
- def serve_log(filename: str):
1128
- """Serve a log file (txt or json) for viewing."""
1129
- if not LOGS_DIR.exists():
1130
- abort(404)
1131
- return send_from_directory(LOGS_DIR, filename)
1132
-
1133
-
1134
- @app.route("/evaluation")
1135
- def evaluation():
1136
- load_cases_cached()
1137
- all_rows = _CACHE["rows_sorted"]
1138
-
1139
- cal_probs = [r.cal_prob for r in all_rows if r.cal_prob is not None]
1140
- bins = [0] * 10
1141
- for p in cal_probs:
1142
- bins[min(int(p * 10), 9)] += 1
1143
-
1144
- band_data = {}
1145
- for bnd in ("HIGH", "MEDIUM", "LOW"):
1146
- subset = [r for r in all_rows if r.band.upper() == bnd]
1147
- positive = sum(1 for r in subset if r.is_positive)
1148
- band_data[bnd] = {
1149
- "total": len(subset),
1150
- "positive": positive,
1151
- "negative": len(subset) - positive,
1152
- }
1153
-
1154
- return render_template(
1155
- "evaluation.html",
1156
- stats=compute_stats(all_rows),
1157
- calib=load_calibration(),
1158
- norm=load_normalization(),
1159
- bins=bins,
1160
- band_data=band_data,
1161
- total=len(all_rows),
1162
- )
1163
-
1164
-
1165
- @app.route("/about")
1166
- def about():
1167
- return render_template("about.html", calib=load_calibration())
1168
-
1169
-
1170
- @app.route("/gradcam/<path:filename>")
1171
- def serve_gradcam(filename: str):
1172
- if not REPORTS_DIR.exists():
1173
- abort(404)
1174
- return send_from_directory(REPORTS_DIR, filename)
1175
-
1176
-
1177
- @app.route("/report-json/<path:filename>")
1178
- def serve_report_json(filename: str):
1179
- if not REPORTS_DIR.exists():
1180
- abort(404)
1181
- return send_from_directory(REPORTS_DIR, filename)
1182
-
1183
-
1184
- # ══════════════════════════════════════════════════════════════════════════
1185
- # ENTRY POINT
1186
- # ══════════════════════════════════════════════════════════════════════════
1187
-
1188
- if __name__ == "__main__":
1189
- print("=" * 60)
1190
- print(" ICH Screening Web Application")
1191
- print(f" Data -> {OUTPUT_DIR}")
1192
- print(f" Logs -> {LOGS_DIR}")
1193
- print(f" Open -> http://127.0.0.1:{APP_PORT}")
1194
- print("=" * 60)
1195
- app.run(debug=APP_DEBUG, port=APP_PORT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_new.py CHANGED
@@ -74,7 +74,7 @@ from werkzeug.middleware.proxy_fix import ProxyFix
74
  from flask_login import current_user, login_required
75
 
76
  # Import new security and auth modules
77
- from models import db, User, ScreeningReport
78
  from auth_utils import init_auth, log_audit, get_client_ip
79
  from auth_routes import auth_bp
80
  from data_isolation import UserDataManager
@@ -312,7 +312,7 @@ def _run_inference_on_dcm(dcm_path: Path, user_id: int) -> tuple[dict[str, Any]
312
 
313
  ri_mod = _MODEL["inference_mod"]
314
  image_id = dcm_path.stem
315
- user_reports_dir = UserDataManager().get_user_reports_dir(user_id)
316
 
317
  bbr.start()
318
 
@@ -343,10 +343,21 @@ def _run_inference_on_dcm(dcm_path: Path, user_id: int) -> tuple[dict[str, Any]
343
  with open(report_path, "w") as f:
344
  json.dump(report, f, indent=2)
345
 
 
 
 
 
 
 
 
 
 
 
 
346
  # Save to database
347
  screening_report = ScreeningReport(
348
  user_id=user_id,
349
- upload_id=0, # Will be set by caller if needed
350
  image_id=image_id,
351
  screening_outcome=pred.get("screening_outcome"),
352
  raw_probability=pred.get("raw_probability"),
@@ -411,45 +422,46 @@ def _batch_update(batch_id: str, **kw: Any) -> None:
411
 
412
  def _run_batch_worker(batch_id: str, dcm_paths: list[Path], user_id: int):
413
  """Process multiple DICOM files in background"""
414
- succeeded_ids = []
415
- failed_ids = []
416
-
417
- for i, path in enumerate(dcm_paths, 1):
418
- image_id = path.stem
419
- _batch_update(batch_id, current_file=image_id, processed=i - 1)
420
 
421
- try:
422
- report, _ = _run_inference_on_dcm(path, user_id)
423
- if report:
424
- succeeded_ids.append(image_id)
425
- else:
 
 
 
 
 
 
 
426
  failed_ids.append(image_id)
427
- except Exception as e:
428
- logger.error(f"Batch {batch_id}: failed {image_id} — {e}")
429
- failed_ids.append(image_id)
 
 
 
 
 
 
 
 
 
 
 
 
430
 
431
  _batch_update(
432
  batch_id,
433
- processed=i,
434
- succeeded=len(succeeded_ids),
435
- image_ids=list(succeeded_ids),
436
- failed_ids=list(failed_ids),
437
  )
438
-
439
- # Clean up
440
- with _BATCHES_LOCK:
441
- b = _BATCHES.get(batch_id, {})
442
- td = b.get("temp_dir")
443
- if td and Path(td).exists():
444
- shutil.rmtree(td, ignore_errors=True)
445
-
446
- _batch_update(
447
- batch_id,
448
- status="completed",
449
- current_file="",
450
- finished_at=datetime.datetime.now().isoformat(),
451
- )
452
- logger.info(f"Batch {batch_id} complete: {len(succeeded_ids)}/{len(dcm_paths)}, {len(failed_ids)} failed")
453
 
454
  def _start_batch(dcm_paths: list[Path], user_id: int, temp_dir: str | None = None) -> str:
455
  """Start async batch processing"""
@@ -636,7 +648,7 @@ def analyze():
636
  flash("No files were uploaded.", "error")
637
  return redirect(url_for("upload"))
638
 
639
- user_upload_dir = UserDataManager().get_user_upload_dir(current_user.id)
640
  user_upload_dir.mkdir(parents=True, exist_ok=True)
641
 
642
  dcm_paths: list[Path] = []
@@ -711,9 +723,17 @@ def analyze_directory():
711
  flash("Please enter a directory path.", "error")
712
  return redirect(url_for("upload"))
713
 
 
 
 
 
714
  scan_dir = Path(dir_path_str)
715
- if not scan_dir.is_dir():
716
- flash(f"Directory not found: {dir_path_str}", "error")
 
 
 
 
717
  return redirect(url_for("upload"))
718
 
719
  dcm_paths = sorted(scan_dir.rglob("*.dcm"))
@@ -832,7 +852,7 @@ def case_detail(image_id):
832
  if not report:
833
  abort(404)
834
 
835
- user_reports_dir = UserDataManager().get_user_reports_dir(current_user.id)
836
  report_path = user_reports_dir / f"{image_id}_report.json"
837
 
838
  if not report_path.exists():
@@ -905,7 +925,7 @@ def evaluation():
905
  def serve_gradcam(filename: str):
906
  """Serve a user's Grad-CAM image from their report directory."""
907
  safe_name = Path(filename).name
908
- reports_dir = UserDataManager().get_user_reports_dir(current_user.id)
909
  return send_from_directory(reports_dir, safe_name)
910
 
911
  @app.errorhandler(401)
 
74
  from flask_login import current_user, login_required
75
 
76
  # Import new security and auth modules
77
+ from models import db, User, ScreeningReport, ScreeningUpload
78
  from auth_utils import init_auth, log_audit, get_client_ip
79
  from auth_routes import auth_bp
80
  from data_isolation import UserDataManager
 
312
 
313
  ri_mod = _MODEL["inference_mod"]
314
  image_id = dcm_path.stem
315
+ user_reports_dir = UserDataManager(UPLOAD_BASE_DIR).get_user_reports_dir(user_id)
316
 
317
  bbr.start()
318
 
 
343
  with open(report_path, "w") as f:
344
  json.dump(report, f, indent=2)
345
 
346
+ upload = ScreeningUpload(
347
+ user_id=user_id,
348
+ file_name=dcm_path.name,
349
+ original_filename=dcm_path.name,
350
+ file_size=dcm_path.stat().st_size if dcm_path.exists() else 0,
351
+ file_path=str(dcm_path.relative_to(BASE_DIR)) if dcm_path.is_relative_to(BASE_DIR) else str(dcm_path),
352
+ processing_status='completed'
353
+ )
354
+ db.session.add(upload)
355
+ db.session.flush()
356
+
357
  # Save to database
358
  screening_report = ScreeningReport(
359
  user_id=user_id,
360
+ upload_id=upload.id,
361
  image_id=image_id,
362
  screening_outcome=pred.get("screening_outcome"),
363
  raw_probability=pred.get("raw_probability"),
 
422
 
423
  def _run_batch_worker(batch_id: str, dcm_paths: list[Path], user_id: int):
424
  """Process multiple DICOM files in background"""
425
+ with app.app_context():
426
+ succeeded_ids = []
427
+ failed_ids = []
 
 
 
428
 
429
+ for i, path in enumerate(dcm_paths, 1):
430
+ image_id = path.stem
431
+ _batch_update(batch_id, current_file=image_id, processed=i - 1)
432
+
433
+ try:
434
+ report, _ = _run_inference_on_dcm(path, user_id)
435
+ if report:
436
+ succeeded_ids.append(image_id)
437
+ else:
438
+ failed_ids.append(image_id)
439
+ except Exception as e:
440
+ logger.error(f"Batch {batch_id}: failed {image_id} — {e}")
441
  failed_ids.append(image_id)
442
+
443
+ _batch_update(
444
+ batch_id,
445
+ processed=i,
446
+ succeeded=len(succeeded_ids),
447
+ image_ids=list(succeeded_ids),
448
+ failed_ids=list(failed_ids),
449
+ )
450
+
451
+ # Clean up
452
+ with _BATCHES_LOCK:
453
+ b = _BATCHES.get(batch_id, {})
454
+ td = b.get("temp_dir")
455
+ if td and Path(td).exists():
456
+ shutil.rmtree(td, ignore_errors=True)
457
 
458
  _batch_update(
459
  batch_id,
460
+ status="completed",
461
+ current_file="",
462
+ finished_at=datetime.datetime.now().isoformat(),
 
463
  )
464
+ logger.info(f"Batch {batch_id} complete: {len(succeeded_ids)}/{len(dcm_paths)}, {len(failed_ids)} failed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
 
466
  def _start_batch(dcm_paths: list[Path], user_id: int, temp_dir: str | None = None) -> str:
467
  """Start async batch processing"""
 
648
  flash("No files were uploaded.", "error")
649
  return redirect(url_for("upload"))
650
 
651
+ user_upload_dir = UserDataManager(UPLOAD_BASE_DIR).get_user_upload_dir(current_user.id)
652
  user_upload_dir.mkdir(parents=True, exist_ok=True)
653
 
654
  dcm_paths: list[Path] = []
 
723
  flash("Please enter a directory path.", "error")
724
  return redirect(url_for("upload"))
725
 
726
+ if len(dir_path_str) > 4096:
727
+ flash("Path is too long to be a valid directory.", "error")
728
+ return redirect(url_for("upload"))
729
+
730
  scan_dir = Path(dir_path_str)
731
+ try:
732
+ if not scan_dir.is_dir():
733
+ flash(f"Directory not found: {dir_path_str}", "error")
734
+ return redirect(url_for("upload"))
735
+ except OSError:
736
+ flash("Invalid directory path format.", "error")
737
  return redirect(url_for("upload"))
738
 
739
  dcm_paths = sorted(scan_dir.rglob("*.dcm"))
 
852
  if not report:
853
  abort(404)
854
 
855
+ user_reports_dir = UserDataManager(UPLOAD_BASE_DIR).get_user_reports_dir(current_user.id)
856
  report_path = user_reports_dir / f"{image_id}_report.json"
857
 
858
  if not report_path.exists():
 
925
  def serve_gradcam(filename: str):
926
  """Serve a user's Grad-CAM image from their report directory."""
927
  safe_name = Path(filename).name
928
+ reports_dir = UserDataManager(UPLOAD_BASE_DIR).get_user_reports_dir(current_user.id)
929
  return send_from_directory(reports_dir, safe_name)
930
 
931
  @app.errorhandler(401)
auth_utils.py CHANGED
@@ -4,7 +4,7 @@ Authentication utilities and decorators for user management and security
4
  import os
5
  import logging
6
  from functools import wraps
7
- from flask import session, redirect, url_for, request, g, abort
8
  from flask_login import LoginManager, current_user
9
  from models import db, User, AuditLog
10
  from datetime import datetime
@@ -30,6 +30,8 @@ def load_user(user_id):
30
 
31
  def get_client_ip():
32
  """Extract client IP address from request"""
 
 
33
  if request.headers.get('X-Forwarded-For'):
34
  return request.headers.get('X-Forwarded-For').split(',')[0].strip()
35
  return request.remote_addr or 'unknown'
 
4
  import os
5
  import logging
6
  from functools import wraps
7
+ from flask import session, redirect, url_for, request, g, abort, has_request_context
8
  from flask_login import LoginManager, current_user
9
  from models import db, User, AuditLog
10
  from datetime import datetime
 
30
 
31
  def get_client_ip():
32
  """Extract client IP address from request"""
33
+ if not has_request_context():
34
+ return 'system'
35
  if request.headers.get('X-Forwarded-For'):
36
  return request.headers.get('X-Forwarded-For').split(',')[0].strip()
37
  return request.remote_addr or 'unknown'
static/js/batch.js CHANGED
@@ -40,7 +40,7 @@
40
  statTotal.textContent = data.total;
41
  statProc.textContent = data.processed;
42
  statOK.textContent = data.succeeded;
43
- statFail.textContent = data.failed_count;
44
 
45
  fill.style.width = pct + '%';
46
  pctLabel.textContent = pct + '%';
@@ -68,7 +68,8 @@
68
  title.textContent = 'Batch Complete';
69
  subtitle.textContent = '';
70
  donePanel.style.display = 'block';
71
- doneSummary.textContent = data.succeeded + ' of ' + data.total + ' files processed successfully' + (data.failed_count > 0 ? ', ' + data.failed_count + ' failed' : '') + '.';
 
72
 
73
  if (data.failed_ids && data.failed_ids.length) {
74
  failPanel.style.display = 'block';
 
40
  statTotal.textContent = data.total;
41
  statProc.textContent = data.processed;
42
  statOK.textContent = data.succeeded;
43
+ statFail.textContent = data.failed_ids ? data.failed_ids.length : 0;
44
 
45
  fill.style.width = pct + '%';
46
  pctLabel.textContent = pct + '%';
 
68
  title.textContent = 'Batch Complete';
69
  subtitle.textContent = '';
70
  donePanel.style.display = 'block';
71
+ var failCount = data.failed_ids ? data.failed_ids.length : 0;
72
+ doneSummary.textContent = data.succeeded + ' of ' + data.total + ' files processed successfully' + (failCount > 0 ? ', ' + failCount + ' failed' : '') + '.';
73
 
74
  if (data.failed_ids && data.failed_ids.length) {
75
  failPanel.style.display = 'block';