Spaces:
Sleeping
Sleeping
Harshit Ghosh commited on
Commit Β·
65e6c8d
1
Parent(s): 8b1df1a
some correction
Browse files21 unmodified lines22232425262744 unmodified lines7273747576777 unmodified lines85868788899021 unmodified lines- [Hugging Face Model Repository](https://huggingface.co/HarshCode/eff_b4_brain)## Detailed Performance ReportDetailed performance and B4-specific analysis are documented separately in:44 unmodified lines- `ICH_FOLD_SELECTION`: `ensemble`, `best`, or fold id (`0` to `4`)- `ICH_LOCAL_MODE`: enables local directory scanning mode- `ICH_LOG_LEVEL`: `DEBUG`, `INFO`, `WARNING`, `ERROR`## Run the Application7 unmodified lineshttp://127.0.0.1:7860```## Basic Usage1. Go to the upload page.21 unmodified lines22232425262728293044 unmodified lines75767778798081827 unmodified lines9091929394959697989910010110210310410510610710810911011111211311421 unmodified lines- [Hugging Face Model Repository](https://huggingface.co/HarshCode/eff_b4_brain)When model files are not present locally (for example on Render), the app candownload required artifacts from this Hugging Face repository at runtime.## Detailed Performance ReportDetailed performance and B4-specific analysis are documented separately in:44 unmodified lines- `ICH_FOLD_SELECTION`: `ensemble`, `best`, or fold id (`0` to `4`)- `ICH_LOCAL_MODE`: enables local directory scanning mode- `ICH_LOG_LEVEL`: `DEBUG`, `INFO`, `WARNING`, `ERROR`- `ICH_HF_MODEL_REPO`: Hugging Face model repo used for runtime artifact download- `ICH_HF_TOKEN`: optional token (required only if the Hugging Face repo is private)## Run the Application7 unmodified lineshttp://127.0.0.1:7860```## Deploy on RenderThis repository includes `render.yaml` for Render deployment.1. Push the repository to GitHub.2. In Render, create a new Blueprint/Web Service from the repository.3. Ensure these environment variables are set in Render:- `ICH_HF_MODEL_REPO=HarshCode/eff_b4_brain`- `ICH_HF_TOKEN` (only if repo is private)- `ICH_SECRET_KEY` (recommended custom value)4. Deploy. The service will start with:```bashgunicorn app:app --bind 0.0.0.0:$PORT --workers 1 --timeout 180```Note: first startup can take longer because model artifacts may be downloadedfrom Hugging Face.## Basic Usage1. Go to the upload page.
26 unmodified lines272829303132332 unmodified lines363738394041424344454647484950515253545556575851 unmodified lines11011111211311411511611711811912028 unmodified lines14915015115215315415552 unmodified lines20820921021121221321498 unmodified lines3133143153163173187 unmodified lines32632732832933033140 unmodified lines37237337437537637737848 unmodified lines4274284294304314324334344354369 unmodified lines446447448449450451452314 unmodified lines76776876977077177277377477577677777810 unmodified lines78979079179279379479519 unmodified lines81581681781881982082182282382482582640 unmodified lines8678688698708718728738748758768776 unmodified lines88488588688788888989012 unmodified lines90390490590690790890926 unmodified linesimport uuidimport zipfilefrom collections import Counterfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any2 unmodified linesexcept Exception:load_dotenv = Nonetry:import blackbox_recorder as bbrexcept Exception:class _NoopRecorder:def configure(self, **_kwargs):return Nonedef start(self):return Nonedef stop(self):return Nonedef save_report(self, _path: str):return Nonedef save_json(self, _path: str):return Nonebbr = _NoopRecorder()51 unmodified linesload_dotenv(BASE_DIR / ".env")APP_DEBUG = _env_bool("ICH_APP_DEBUG", True)APP_PORT = _env_int("ICH_APP_PORT", 7860, minimum=1)MAX_UPLOAD_MB = _env_int("ICH_MAX_UPLOAD_MB", 2048, minimum=1)LOG_LEVEL_NAME = os.environ.get("ICH_LOG_LEVEL", "INFO").strip().upper()LOG_LEVEL = getattr(logging, LOG_LEVEL_NAME, logging.INFO)SECRET_KEY = os.environ.get("ICH_SECRET_KEY", "").strip()app = Flask(__name__, template_folder="templates", static_folder="static")app.secret_key = SECRET_KEY or os.urandom(24)28 unmodified lines)def _save_trace(image_id: str) -> dict:"""Save the current blackbox trace to logs/ and return metadata about it.Called immediately after bbr.stop().52 unmodified linesreturn batch_iddef _batch_update(batch_id: str, **kw):"""Thread-safe update of a batch record."""with _BATCHES_LOCK:if batch_id in _BATCHES:98 unmodified lines}def _ensure_model_loaded() -> bool:"""Lazy-load the ML model on first inference request."""if _MODEL["loaded"]:7 unmodified linesdevice = "cuda" if torch.cuda.is_available() else "cpu"fold_selection = os.environ.get("ICH_FOLD_SELECTION", "ensemble")with open(CALIB_JSON) as f:calib_cfg = json.load(f)40 unmodified linesreturn Falsedef _run_inference_on_dcm(dcm_path: Path) -> tuple[dict | None, dict | None]:"""Run inference on one .dcm file, with blackbox tracing.Returns (report_dict, trace_metadata) or (None, None) on failure.48 unmodified linesreturn report, trace_metadef _append_to_summary_csv(image_id: str, report: dict):"""Append one report row to the summary CSV."""pred = report["prediction"]row = {"image_id": image_id,"true_label": "","screening_outcome": pred["screening_outcome"],9 unmodified linesOUTPUT_DIR.mkdir(parents=True, exist_ok=True)with open(SUMMARY_CSV, "a", newline="", encoding="utf-8") as f:writer = csv.DictWriter(f, fieldnames=row.keys())if not file_exists:writer.writeheader()writer.writerow(row)314 unmodified linesreturn rowsdef load_logs() -> list[dict]:"""Scan the logs/ directory and return metadata for each trace."""if not LOGS_DIR.exists():return []log_files: dict[str, dict] = {} # base_name -> {txt_file, json_file, ...}for path in sorted(LOGS_DIR.iterdir(), reverse=True):if not path.is_file():10 unmodified lineselif path.suffix == ".json":log_files.setdefault(stem, {})["json_file"] = path.nameentries = []for stem in sorted(log_files, reverse=True):info = log_files[stem]ts_raw = info.get("timestamp", "")19 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.before_requestdef _start_timer():g._start_time = time.perf_counter()@app.after_requestdef _log_timing(response):elapsed = (time.perf_counter() - getattr(g, "_start_time", time.perf_counter())) * 1000logger.info("%s %s -> %s (%.1f ms)", request.method, request.path, response.status_code, elapsed)return response40 unmodified linestemp_dir: str | None = None # set if a zip needed extractionfor f in files:fname = f.filename.lower()if fname.endswith(".zip"):temp_dir = tempfile.mkdtemp(prefix="ich_zip_")zip_save = Path(temp_dir) / secure_filename(f.filename)f.save(str(zip_save))try:with zipfile.ZipFile(zip_save, "r") as zf:6 unmodified linesdcm_paths.extend(sorted(Path(temp_dir).rglob("*.dcm")))elif fname.endswith(".dcm"):safe = secure_filename(f.filename)save_path = UPLOAD_DIR / safef.save(str(save_path))dcm_paths.append(save_path)12 unmodified linesif len(dcm_paths) == 1 and temp_dir is None:single_path = dcm_paths[0]try:report, trace = _run_inference_on_dcm(single_path)if report is None:flash("Model failed to load. Check server logs.", "error")return redirect(url_for("upload"))26 unmodified lines272829303132332 unmodified lines36373839404142434445464748495051525354555657585960616263646551 unmodified lines11711811912012112212312412512612712812928 unmodified lines15815916016116216316452 unmodified lines21721821922022122222398 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833847 unmodified lines39239339439539639739839940040140240340440540640 unmodified lines44744844945045145245348 unmodified lines5025035045055065075085095105119 unmodified lines521522523524525526527314 unmodified lines84284384484584684784884985085185285310 unmodified lines86486586686786886987019 unmodified lines89089189289389489589689789889990090140 unmodified lines9429439449459469479489499509519529536 unmodified lines96096196296396496596612 unmodified lines97998098198298398498526 unmodified linesimport uuidimport zipfilefrom collections import Counterfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any2 unmodified linesexcept Exception:load_dotenv = Nonehf_hub_download: Any = Nonetry:import huggingface_hubhf_hub_download = getattr(huggingface_hub, "hf_hub_download", None)except Exception:hf_hub_download = Nonetry:import blackbox_recorder as bbr # type: ignore[import-untyped]except Exception:class _NoopRecorder:def configure(self, **_kwargs: Any) -> None:return Nonedef start(self) -> None:return Nonedef stop(self) -> None:return Nonedef save_report(self, _path: str) -> None:return Nonedef save_json(self, _path: str) -> None:return Nonebbr = _NoopRecorder()51 unmodified linesload_dotenv(BASE_DIR / ".env")APP_DEBUG = _env_bool("ICH_APP_DEBUG", True)APP_PORT = _env_int("ICH_APP_PORT", _env_int("PORT", 7860, minimum=1), minimum=1)MAX_UPLOAD_MB = _env_int("ICH_MAX_UPLOAD_MB", 2048, minimum=1)LOG_LEVEL_NAME = os.environ.get("ICH_LOG_LEVEL", "INFO").strip().upper()LOG_LEVEL = getattr(logging, LOG_LEVEL_NAME, logging.INFO)SECRET_KEY = os.environ.get("ICH_SECRET_KEY", "").strip()HF_MODEL_REPO = os.environ.get("ICH_HF_MODEL_REPO", os.environ.get("HF_REPO_ID", "")).strip()HF_TOKEN = os.environ.get("ICH_HF_TOKEN", os.environ.get("HF_TOKEN", "")).strip()app = Flask(__name__, template_folder="templates", static_folder="static")app.secret_key = SECRET_KEY or os.urandom(24)28 unmodified lines)def _save_trace(image_id: str) -> dict[str, str | None]:"""Save the current blackbox trace to logs/ and return metadata about it.Called immediately after bbr.stop().52 unmodified linesreturn batch_iddef _batch_update(batch_id: str, **kw: Any) -> None:"""Thread-safe update of a batch record."""with _BATCHES_LOCK:if batch_id in _BATCHES:98 unmodified lines}def _required_model_files(fold_selection: str) -> list[str]:files = ["calibration_params.json","normalization_stats.json",]raw = (fold_selection or "ensemble").strip().lower()if raw in ("", "ensemble", "all"):files.extend([f"best_model_fold{i}.pth" for i in range(5)])return filesif raw == "best":files.append("best_model_fold4.pth")return filesif raw.isdigit():files.append(f"best_model_fold{int(raw)}.pth")return files# Fallback to ensemble behavior for unknown values.files.extend([f"best_model_fold{i}.pth" for i in range(5)])return filesdef _download_runtime_artifacts_if_needed(fold_selection: str) -> bool:required_files = _required_model_files(fold_selection)missing = [name for name in required_files if not (MODEL_DIR / name).exists()]if not missing:return Trueif not HF_MODEL_REPO:logger.warning("Missing runtime model files (%s) and ICH_HF_MODEL_REPO/HF_REPO_ID is not set.",", ".join(missing),)return Falseif hf_hub_download is None:logger.error("huggingface_hub is not installed, cannot download missing model artifacts.")return FalseMODEL_DIR.mkdir(parents=True, exist_ok=True)logger.info("Downloading missing model artifacts from Hugging Face repo: %s", HF_MODEL_REPO)try:for filename in missing:hf_hub_download(repo_id=HF_MODEL_REPO,filename=filename,repo_type="model",local_dir=str(MODEL_DIR),token=HF_TOKEN or None,)logger.info("Downloaded artifact: %s", filename)return Trueexcept Exception as exc:logger.error("Failed downloading model artifacts from Hugging Face: %s", exc)return Falsedef _ensure_model_loaded() -> bool:"""Lazy-load the ML model on first inference request."""if _MODEL["loaded"]:7 unmodified linesdevice = "cuda" if torch.cuda.is_available() else "cpu"fold_selection = os.environ.get("ICH_FOLD_SELECTION", "ensemble")_download_runtime_artifacts_if_needed(fold_selection)if not CALIB_JSON.exists():logger.error("Missing calibration file at %s. Provide local files or set ICH_HF_MODEL_REPO.",CALIB_JSON,)return Falsewith open(CALIB_JSON) as f:calib_cfg = json.load(f)40 unmodified linesreturn Falsedef _run_inference_on_dcm(dcm_path: Path) -> tuple[dict[str, Any] | None, dict[str, str | None] | None]:"""Run inference on one .dcm file, with blackbox tracing.Returns (report_dict, trace_metadata) or (None, None) on failure.48 unmodified linesreturn report, trace_metadef _append_to_summary_csv(image_id: str, report: dict[str, Any]) -> None:"""Append one report row to the summary CSV."""pred = report["prediction"]row: dict[str, Any] = {"image_id": image_id,"true_label": "","screening_outcome": pred["screening_outcome"],9 unmodified linesOUTPUT_DIR.mkdir(parents=True, exist_ok=True)with open(SUMMARY_CSV, "a", newline="", encoding="utf-8") as f:writer = csv.DictWriter(f, fieldnames=list(row.keys()))if not file_exists:writer.writeheader()writer.writerow(row)314 unmodified linesreturn rowsdef load_logs() -> list[dict[str, Any]]:"""Scan the logs/ directory and return metadata for each trace."""if not LOGS_DIR.exists():return []log_files: dict[str, dict[str, Any]] = {} # base_name -> {txt_file, json_file, ...}for path in sorted(LOGS_DIR.iterdir(), reverse=True):if not path.is_file():10 unmodified lineselif path.suffix == ".json":log_files.setdefault(stem, {})["json_file"] = path.nameentries: list[dict[str, Any]] = []for stem in sorted(log_files, reverse=True):info = log_files[stem]ts_raw = info.get("timestamp", "")19 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.before_requestdef _start_timer() -> None: # pyright: ignore[reportUnusedFunction]g._start_time = time.perf_counter()@app.after_requestdef _log_timing(response: Any) -> Any: # pyright: ignore[reportUnusedFunction]elapsed = (time.perf_counter() - getattr(g, "_start_time", time.perf_counter())) * 1000logger.info("%s %s -> %s (%.1f ms)", request.method, request.path, response.status_code, elapsed)return response40 unmodified linestemp_dir: str | None = None # set if a zip needed extractionfor f in files:filename = f.filename or ""fname = filename.lower()if fname.endswith(".zip"):temp_dir = tempfile.mkdtemp(prefix="ich_zip_")zip_save = Path(temp_dir) / secure_filename(filename)f.save(str(zip_save))try:with zipfile.ZipFile(zip_save, "r") as zf:6 unmodified linesdcm_paths.extend(sorted(Path(temp_dir).rglob("*.dcm")))elif fname.endswith(".dcm"):safe = secure_filename(filename)save_path = UPLOAD_DIR / safef.save(str(save_path))dcm_paths.append(save_path)12 unmodified linesif len(dcm_paths) == 1 and temp_dir is None:single_path = dcm_paths[0]try:report, _trace = _run_inference_on_dcm(single_path)if report is None:flash("Model failed to load. Check server logs.", "error")return redirect(url_for("upload"))
README.md+24
app.py+99-23