"""Echo Report QA — EchoGemma (report generation) + EchoPrime (views + measurements) on echo studies. Runs on Hugging Face ZeroGPU. Heavy models are loaded on CPU at startup (no GPU is attached at startup on ZeroGPU); the report-generation pass runs inside a @spaces.GPU-decorated generator that streams the text back as it is written. Models / code: - EchoGemma: milosvuk/echogemma (Apache-2.0), official loader adapted from github.com/echonet/Medgemma-challenge (vendored in ./echogemma). - EchoPrime: github.com/echonet/EchoPrime (MIT), official code + weights (release v1.0.0 model_data.zip), used for view classification and measurements. Disclaimer: research prototype for demonstration and review-assistance only. NOT a medical device. Output must be reviewed by a qualified physician. """ import csv import gc import glob import html import os import re import shutil import subprocess import sys import tempfile import threading import time import urllib.request import zipfile from collections import Counter # Must be set before torch initializes CUDA: reduces fragmentation in the # mixed fp32/bf16 report-generation pass (verified OOM without it on 24 GB cards). os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import cv2 import gradio as gr import imageio import numpy as np import spaces # ZeroGPU — works as a no-op decorator outside ZeroGPU runtimes import torch from huggingface_hub import hf_hub_download from transformers import TextIteratorStreamer APP_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(APP_DIR, "echo_data") ECHOPRIME_DIR = os.path.join(DATA_DIR, "EchoPrime") ECHOPRIME_RELEASE = "https://github.com/echonet/EchoPrime/releases/download/v1.0.0" EXAMPLE_STUDY_DIR = os.path.join(DATA_DIR, "model_data", "example_study") SAMPLES_DIR = os.path.join(APP_DIR, "samples") # Vendored EchoGemma package lives next to this file sys.path.insert(0, APP_DIR) from echogemma.echogemma import REPORT_SECTIONS, SECTION_HEADER_RE # noqa: E402 # EchoPrime's view classes, in the order of its classifier outputs (echo_prime utils.COARSE_VIEWS) COARSE_VIEWS = ["A2C", "A3C", "A4C", "A5C", "Apical_Doppler", "Doppler_Parasternal_Long", "Doppler_Parasternal_Short", "Parasternal_Long", "Parasternal_Short", "SSN", "Subcostal"] VIDEO_EXTS = (".mp4", ".avi", ".mov", ".mkv") # --------------------------------------------------------------------------- # Model loading (background thread, so the UI is live while ~20 GB streams in) # --------------------------------------------------------------------------- def _download_startup() -> None: """Download EchoPrime code + weights/data (the EchoGemma checkpoint is downloaded separately in the background-load thread so its progress can be reported).""" os.makedirs(DATA_DIR, exist_ok=True) # 1. EchoPrime code (for process/views/encoders) if not os.path.isdir(ECHOPRIME_DIR): subprocess.run( ["git", "clone", "--depth", "1", "https://github.com/echonet/EchoPrime", ECHOPRIME_DIR], check=True, ) # echo_prime/ imports `utils` at module level, and the package itself lives in the # cloned repo — make all of it importable (repo root, package dir, utils dir) for p in (ECHOPRIME_DIR, os.path.join(ECHOPRIME_DIR, "echo_prime"), os.path.join(ECHOPRIME_DIR, "utils")): if os.path.isdir(p) and p not in sys.path: sys.path.insert(0, p) # 2. model_data: EchoPrime encoders, candidate reports/labels + the example study model_data = os.path.join(DATA_DIR, "model_data") if not os.path.isdir(model_data): zip_path = os.path.join(DATA_DIR, "model_data.zip") if not os.path.exists(zip_path): urllib.request.urlretrieve(f"{ECHOPRIME_RELEASE}/model_data.zip", zip_path) with zipfile.ZipFile(zip_path) as z: z.extractall(DATA_DIR) cdir = os.path.join(model_data, "candidates_data") os.makedirs(cdir, exist_ok=True) for name in ("candidate_embeddings_p1.pt", "candidate_embeddings_p2.pt"): target = os.path.join(cdir, name) if not os.path.exists(target): urllib.request.urlretrieve(f"{ECHOPRIME_RELEASE}/{name}", target) # 3. EchoPrime assets (MIL weights, all_phr.json, ...) — in the git repo; copy next to model_data if not os.path.isdir(os.path.join(DATA_DIR, "assets")) and os.path.isdir( os.path.join(ECHOPRIME_DIR, "assets") ): shutil.copytree(os.path.join(ECHOPRIME_DIR, "assets"), os.path.join(DATA_DIR, "assets")) print("[load] background model loading — the UI is live while models stream in ...", flush=True) LOAD_STATE = {"stage": "Starting", "pct": 0.0, "error": None, "ready": False} echo_prime_model = None echogemma_model = None def _set_load_state(stage: str, pct: float) -> None: LOAD_STATE.update(stage=stage, pct=pct) print(f"[load] {stage} ({int(pct * 100)}%)", flush=True) def _background_load() -> None: global echo_prime_model, echogemma_model try: _set_load_state("Downloading EchoPrime model data", 0.05) _download_startup() _set_load_state("Downloading EchoGemma checkpoint (17.8 GB)", 0.35) ckpt = hf_hub_download(repo_id="milosvuk/echogemma", filename="echogemma.pt") _set_load_state("Building EchoPrime", 0.60) # EchoPrime's utils.py opens assets/*.json at MODULE IMPORT time, relative to # the CWD — so the chdir must happen BEFORE the import, not just before use. cwd0 = os.getcwd() os.chdir(DATA_DIR) from echo_prime import EchoPrime # noqa: E402 # EchoPrime auto-selects CUDA via torch.cuda.is_available() and .to('cuda')-loads # its encoders. On ZeroGPU is_available() returns True even at startup, but real # CUDA init is only permitted inside @spaces.GPU tasks — so that load raises # 'Low-level CUDA init reached'. Force CPU here; the GPU is used later by # EchoGemma's task only. _orig_is_available = torch.cuda.is_available torch.cuda.is_available = lambda: False # EchoPrime.__init__ also decodes all 1.2M candidate reports (~5 GB, ~30 s) for its own # generate_report(), which this app does not call: hand it an empty list instead. import pandas as pd _read_pickle = pd.read_pickle pd.read_pickle = lambda p, *a, **k: [] if str(p).endswith("candidate_reports.pkl") else _read_pickle(p, *a, **k) try: echo_prime_model = EchoPrime() finally: torch.cuda.is_available = _orig_is_available pd.read_pickle = _read_pickle os.chdir(cwd0) # Keep EchoPrime's encoders on CPU: EchoGemma loads the same MViT/ConvNeXt # architectures on GPU for report generation, and duplicate GPU weights plus # leftover activations caused a CUDA OOM on 24 GB cards during verification. echo_prime_model.echo_encoder.to("cpu") echo_prime_model.view_classifier.to("cpu") echo_prime_model.device = torch.device("cpu") echo_prime_model.candidate_reports = None # ZeroGPU containers have ~16 GB of RAM. The candidate labels are 21 dicts of up to # 1.2M study-name keys (~2.5 GB of Python objects); predict_metrics only needs them # by candidate index, so keep one float array per phenotype (NaN = no label). studies = echo_prime_model.candidate_studies echo_prime_model.label_arrays = { pheno: np.array([labels.get(st, np.nan) for st in studies], dtype=np.float64) for pheno, labels in echo_prime_model.candidate_labels.items() } echo_prime_model.candidate_labels = echo_prime_model.candidate_studies = None gc.collect() _set_load_state("Building EchoGemma (MedGemma 4B)", 0.75) from echogemma.echogemma import EchoGemma # noqa: E402 echogemma_model = EchoGemma(checkpoint_path=ckpt, llm_dtype=torch.bfloat16, device="cpu") LOAD_STATE.update(stage="Ready", pct=1.0, ready=True) print("[load] models ready", flush=True) except Exception as e: import traceback traceback.print_exc() LOAD_STATE.update(stage="Load failed", error=str(e)) threading.Thread(target=_background_load, daemon=True, name="model-loader").start() # --------------------------------------------------------------------------- # Inference # --------------------------------------------------------------------------- # ZeroGPU multiplies the declared duration by a platform factor (spaces.zero.client: # duration_factor, 1.5 for the default "large" size at the time of writing) for both the time # limit and the quota pre-check, so the values below are the measured limits divided by 1.5. ZEROGPU_DURATION_FACTOR = 1.5 def _report_duration(stack): """Declared GPU time for the report. ZeroGPU refuses a call when the scaled request exceeds the visitor's remaining daily quota (2 min anonymous, 5 min free accounts), so it is an upper bound from measured runs (single clip ≤ 47 s, 50 clips 68 s on an L40S): ~75 s for one clip, ~100 s for a full study once scaled.""" return int((75 + 0.5 * stack.shape[0]) / ZEROGPU_DURATION_FACTOR) def _translation_budget(text): """max_new_tokens for a translation pass: Macedonian ran 1.2–1.7x the English tokens in tests.""" return int(1.9 * len(echogemma_model.tokenizer.encode(text))) + 64 def _english_report(sections): return "\n\n".join(f"{name}: {text}" for name, text in sections) def _translate_duration(sections): # 19–34 tokens/s measured for the adapter-free pass; budget at 16.7 tokens/s plus a cold start return int((25 + 0.06 * _translation_budget(_english_report(sections))) / ZEROGPU_DURATION_FACTOR) def _stream(fn, *args, **kwargs): """Run a generate-style call in a worker thread and yield the accumulated text as tokens arrive (at most ~6 updates per second).""" streamer = TextIteratorStreamer(echogemma_model.tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=300) errors = [] def _run(): try: fn(*args, streamer=streamer, **kwargs) except BaseException as e: # surface errors from the worker thread errors.append(e) streamer.end() worker = threading.Thread(target=_run, daemon=True) worker.start() text, last = "", 0.0 for chunk in streamer: text += chunk if time.monotonic() - last > 0.15: last = time.monotonic() yield text worker.join() if errors: raise errors[0] yield text @spaces.GPU(duration=_report_duration) def generate_report_gpu(stack): """GPU task 1: move EchoGemma to CUDA (lazily) and stream the report text.""" t0 = time.monotonic() echogemma_model.ensure_on_device(torch.device("cuda")) torch.cuda.empty_cache() t_ready = time.monotonic() raw = "" # bin_size=25 halves the MViT activation peak vs the default 50 (OOM headroom) for raw in _stream(echogemma_model.generate, stack, max_tokens=1024, temperature=0.0, bin_size=25): yield raw print(f"[gpu] report: {stack.shape[0]} clips | to-device {t_ready - t0:.1f}s | " f"{len(echogemma_model.tokenizer.encode(raw))} tok in {time.monotonic() - t_ready:.1f}s", flush=True) @spaces.GPU(duration=_translate_duration) def translate_gpu(sections): """GPU task 2 (separate, so a quota or time-out failure here never costs the English report): the whole report in one pass, which keeps the wording consistent; a section the model skips is then translated on its own. Yields [(section, Macedonian text)].""" t0 = time.monotonic() echogemma_model.ensure_on_device(torch.device("cuda")) english = _english_report(sections) text = "" for text in _stream(echogemma_model.translate_to_macedonian, english, max_tokens=_translation_budget(english)): yield match_translation(text, sections) pairs = match_translation(text, sections) done = {name for name, _ in pairs} for name, en in sections: if name not in done: one = _english_report([(name, en)]) body = echogemma_model.translate_to_macedonian(one, max_tokens=_translation_budget(one)) pairs = pairs + [(name, (match_translation(body, [(name, en)]) or [(name, body)])[0][1])] order = [name for name, _ in sections] pairs.sort(key=lambda p: order.index(p[0])) yield pairs print(f"[gpu] translation: {len(sections)} sections ({len(sections) - len(done)} re-done singly) | " f"{len(echogemma_model.tokenizer.encode(text))} tok in {time.monotonic() - t0:.1f}s", flush=True) def process_videos(paths): """Preprocess MP4/AVI clips like the DICOM path: RGB -> BGR (the channel order process_dicoms produces and the models were trained on; it matters for colour Doppler) -> crop/scale -> normalize -> pad to 32 frames -> every 2nd frame, giving (N, 3, 16, 224, 224). Decoding uses imageio-ffmpeg.""" stacks = [] for p in paths: reader = imageio.get_reader(p) # ffmpeg plugin try: frames = np.stack([np.asarray(f[..., :3]) for f in reader]) finally: reader.close() x = np.zeros((len(frames), 224, 224, 3), dtype=np.float32) for i in range(len(x)): x[i] = echogemma_model.crop_and_scale(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR)) xt = torch.as_tensor(x, dtype=torch.float).permute([3, 0, 1, 2]) xt.sub_(echogemma_model.mean).div_(echogemma_model.std) if xt.shape[1] < echogemma_model.frames_to_take: padding = torch.zeros( (3, echogemma_model.frames_to_take - xt.shape[1], echogemma_model.video_size, echogemma_model.video_size), dtype=torch.float, ) xt = torch.cat((xt, padding), dim=1) stacks.append(xt[:, 0 : echogemma_model.frames_to_take : echogemma_model.frame_stride, :, :]) return torch.stack(stacks) def encode_study(stack, chunk=2): """EchoPrime clip embeddings + view one-hots, a few clips at a time. Upstream encode_study pushes the whole study through MViT in one batch (bin_size=50): ~0.3 GB of CPU activations per clip, which for a full study overruns the 16 GB container.""" return torch.cat([echo_prime_model.encode_study(stack[i:i + chunk]) for i in range(0, stack.shape[0], chunk)]) def _ticking(fn, *args): """Run a slow CPU step in a worker thread; yield None about once a second (so the UI clock keeps moving), then the step's result.""" result, error = [], [] def target(): try: result.append(fn(*args)) except BaseException as e: error.append(e) worker = threading.Thread(target=target, daemon=True) worker.start() while worker.is_alive(): worker.join(1.0) if worker.is_alive(): yield None if error: raise error[0] yield result[0] @torch.no_grad() def predict_metrics(ep, study_embedding, k=50): """EchoPrime.predict_metrics with the section lookup fixed. Upstream indexes the 15 per-section embeddings (MIL_weights order) by the position of the section in section_to_phenotypes (11 sections), so every phenotype after the Left Ventricle group reads a neighbouring section's retrieval (e.g. pericardial effusion from the Aortic Valve neighbours). Here each phenotype uses its own section. Sections no clip view contributes to (weight 0) return NaN instead of the labels of arbitrary studies. Labels come from ep.label_arrays (see _background_load): the nanmean over them equals upstream's mean over the labelled neighbours.""" emb = study_embedding.cpu().float() feats, views = emb[:, :512], emb[:, 512:].argmax(dim=1) weights = torch.tensor(ep.section_weights, dtype=torch.float)[:, views] # (15, N) per_section = torch.nn.functional.normalize(weights @ feats) # (15, 512) top = torch.topk(per_section @ ep.candidate_embeddings.T, k=k, dim=1).indices.numpy() row = {s: i for i, s in enumerate(ep.non_empty_sections)} preds = {} for section, phenotypes in ep.section_to_phenotypes.items(): r = row[section] for pheno in phenotypes: vals = ep.label_arrays[pheno][top[r]] covered = float(weights[r].sum()) > 0 and not np.all(np.isnan(vals)) preds[pheno] = float(np.nanmean(vals)) if covered else float("nan") return preds # --------------------------------------------------------------------------- # Report parsing / rendering # --------------------------------------------------------------------------- def parse_report(raw: str): """Split the model output into [(section, text)] in clinical order. The model writes 'Section: text' blocks separated by literal [SEP] markers, prefixed by an echo of its input ('The user uploaded N videos, and the corresponding views are: ...'). Only the first occurrence of each section is kept (if generation ran on into a second pass). Returns (sections, in_progress_section_or_None).""" matches = list(SECTION_HEADER_RE.finditer(raw)) found = {} for i, m in enumerate(matches): end = matches[i + 1].start() if i + 1 < len(matches) else len(raw) name = m.group(1) if name in found: continue text = raw[m.end():end].replace("[SEP]", " ").replace("`", "'") found[name] = re.sub(r"\s+", " ", text).strip() last = matches[-1].group(1) if matches else None ordered = [(name, found[name]) for name in REPORT_SECTIONS if found.get(name)] return ordered, last def _esc(s): return html.escape(str(s)) def render_report(raw, n_clips=None, streaming=False, meta=""): sections, writing = parse_report(raw) if not sections: body = '
Writing the report…
' if streaming else "" else: rows = [] for name, text in sections: cursor = '' if streaming and name == writing else "" rows.append(f'
{_esc(name)}
' f'
{_esc(text)}{cursor}
') body = '
' + "".join(rows) + "
" note = "" if n_clips is not None and n_clips < 5: note = (f'
Based on {n_clips} clip{"s" if n_clips != 1 else ""}. EchoGemma always writes ' "every section; sections whose structures are not visible in these views are not grounded in the " "images. Use the complete study for a representative report.
") return (f'
AI-drafted report · EchoGemma
' f'
Transthoracic echocardiogram
{_esc(meta)}
' f"{note}{body}
") # Section headings in Macedonian (fixed, so the model only translates the findings) MK_SECTIONS = { "Left Ventricle": "Лева комора", "Resting Segmental Wall Motion Analysis": "Сегментна анализа на ѕидната подвижност во мирување", "Right Ventricle": "Десна комора", "Left Atrium": "Лева преткомора", "Right Atrium": "Десна преткомора", "Atrial Septum": "Интератријален септум", "Mitral Valve": "Митрална валвула", "Aortic Valve": "Аортна валвула", "Tricuspid Valve": "Трикуспидна валвула", "Pulmonic Valve": "Пулмонална валвула", "Pericardium": "Перикард", "Aorta": "Аорта", "IVC": "Долна шуплива вена (VCI)", "Pulmonary Artery": "Пулмонална артерија", "Pulmonary Veins": "Пулмонални вени", "Postoperative Findings": "Постоперативен наод", } # Which English section a Macedonian heading belongs to (order matters: specific first) MK_HEADING_KEYS = [ ("Resting Segmental Wall Motion Analysis", r"сегмент|ѕидн"), ("Left Ventricle", r"лев\w* комор"), ("Right Ventricle", r"десн\w* комор"), ("Left Atrium", r"лев\w* (?:преткомор|атри)"), ("Right Atrium", r"десн\w* (?:преткомор|атри)"), ("Atrial Septum", r"септ"), ("Mitral Valve", r"митрал"), ("Aortic Valve", r"аортн\w* (?:валв|залист|клап)"), ("Tricuspid Valve", r"трикусп"), ("Pulmonic Valve", r"пулмонал\w* (?:валв|залист|клап)"), ("Pericardium", r"перикард"), ("Pulmonary Artery", r"(?:пулмонал|белодроб)\w* артер"), ("IVC", r"шуплив|vci|ivc|кава"), ("Pulmonary Veins", r"(?:пулмонал|белодроб)\w* вен"), ("Aorta", r"аорт"), ("Postoperative Findings", r"постоперат"), ] def match_translation(text, sections): """Map the model's 'Heading: text' lines onto the English sections, so every section is shown under its fixed Macedonian heading (MK_SECTIONS). Lines without a recognisable heading continue the previous section.""" wanted = [name for name, _ in sections] pairs = [] for line in text.replace("[SEP]", "\n").splitlines(): line = line.strip() if not line: continue m = re.match(r"^[*#\s]*([^:*\n]{2,80}?)[*\s]*:[*\s]*(.*)$", line) name = None if m: heading = m.group(1).lower() name = next((n for n, pat in MK_HEADING_KEYS if n in wanted and re.search(pat, heading)), None) if name is None and m.group(1).strip() in wanted: # left in English name = m.group(1).strip() if name and name not in [p[0] for p in pairs]: pairs.append((name, m.group(2).replace("**", "").strip())) elif pairs: pairs[-1] = (pairs[-1][0], (pairs[-1][1] + " " + line.replace("**", "")).strip()) return pairs def render_translation(pairs, streaming=False, error=None): if not pairs and not error: return ('
Translating…
' if streaming else "") rows = [] for i, (name, text) in enumerate(pairs or []): cursor = '' if streaming and i == len(pairs) - 1 else "" rows.append(f'
{_esc(MK_SECTIONS.get(name, name))}
' f'
{_esc(text)}{cursor}
') err = f'
Translation stopped: {_esc(error)}
' if error else "" return ('
Machine translation · MedGemma
' '
Извештај на македонски
' '
Machine translation of the English report — a native-speaking physician must ' f'review it before any clinical use.
{err}' f'
{"".join(rows)}
') # (key, label, unit) grouped by EchoPrime report section. Values with a unit are continuous # estimates; the rest are 0–1 scores: the share of the 50 most similar reference studies # (out of 1.2M) whose report has that finding. METRIC_GROUPS = [ ("Left ventricle", [("ejection_fraction", "Ejection fraction", "%"), ("impella", "Impella device", None)]), ("Right ventricle", [("rv_systolic_function_depressed", "Reduced RV systolic function", None), ("right_ventricle_dilation", "RV dilation", None), ("pacemaker", "Pacemaker / ICD lead", None)]), ("Left atrium", [("left_atrium_dilation", "LA dilation", None)]), ("Right atrium", [("right_atrium_dilation", "RA dilation", None)]), ("Mitral valve", [("mitral_regurgitation", "Mitral regurgitation", None), ("mitral_stenosis", "Mitral stenosis", None), ("mitral_annular_calcification", "Mitral annular calcification", None), ("mitraclip", "MitraClip", None)]), ("Aortic valve", [("aortic_stenosis", "Aortic stenosis", None), ("aortic_regurgitation", "Aortic regurgitation", None), ("bicuspid_aov_morphology", "Bicuspid aortic valve", None), ("tavr", "TAVR prosthesis", None)]), ("Tricuspid valve", [("tricuspid_valve_regurgitation", "Tricuspid regurgitation", None), ("tricuspid_stenosis", "Tricuspid stenosis", None)]), ("Pericardium", [("pericardial_effusion", "Pericardial effusion", None)]), ("Aorta", [("aortic_root_dilation", "Aortic root dilation", None)]), ("IVC", [("dilated_ivc", "Dilated IVC", None)]), ("Pulmonary artery", [("pulmonary_artery_pressure_continuous", "PA systolic pressure", "mmHg")]), ] # Continuous estimates: (is_abnormal, reference shown) CONTINUOUS_REF = { "ejection_fraction": (lambda v: v < 50, "≥ 50 %"), "pulmonary_artery_pressure_continuous": (lambda v: v > 35, "≤ 35 mmHg"), } def _roc_thresholds(): """EchoPrime's published ROC thresholds (assets/roc_thresholds.csv); 0.5 where none is published.""" path = os.path.join(DATA_DIR, "assets", "roc_thresholds.csv") try: with open(path) as f: return {r["feature"]: float(r["threshold"]) for r in csv.DictReader(f)} except Exception: return {} # Numbers the report states, as (pattern, ...) tried in order; the first match wins. REPORT_NUMBERS = { "ejection_fraction": [r"ejection fraction[^%]{0,80}?(\d{1,2}(?:\.\d+)?)\s*%"], "pulmonary_artery_pressure_continuous": [ r"(?:pulmonary artery|PA)(?: systolic)? pressure[^.]{0,40}?(\d{1,3}(?:\.\d+)?)\s*mm ?Hg", r"PASP[^.]{0,40}?(\d{1,3}(?:\.\d+)?)\s*mm ?Hg", r"RVSP[^.]{0,40}?(\d{1,3}(?:\.\d+)?)\s*mm ?Hg", ], } def report_number(text, key): for pattern in REPORT_NUMBERS[key]: m = re.search(pattern, text, re.I) if m: return float(m.group(1)) return None def cross_check(report_text, metrics): """Compare the numbers the report states with EchoPrime's independent estimates.""" checks = [] for label, key, unit, tol in (("Ejection fraction", "ejection_fraction", "%", 5), ("PA systolic pressure", "pulmonary_artery_pressure_continuous", "mmHg", 5)): stated, est = report_number(report_text, key), metrics.get(key) if stated is None or est is None or est != est: continue checks.append((label, stated, est, unit, abs(stated - est) <= tol)) return checks def render_metrics(metrics, report_text="", n_clips=None): if not metrics: return "" thresholds = _roc_thresholds() rows, flagged = [], [] for section, items in METRIC_GROUPS: for i, (key, label, unit) in enumerate(items): v = metrics.get(key) sec = f'{_esc(section)}' if i == 0 else "" if v is None or v != v: rows.append(f'{sec}{_esc(label)}not covered by these views') continue if unit: bad, ref = CONTINUOUS_REF[key] value, ref_txt, flag = f"{v:.0f} {unit}", f"normal {ref}", bad(v) else: thr = thresholds.get(key, 0.5) value, ref_txt, flag = f"{v:.2f}", f"flag at ≥ {thr:g}", v >= thr if flag: flagged.append(label) badge = 'Review' if flag else '—' rows.append(f'{sec}{_esc(label)}' f'{value}{ref_txt}{badge}') if flagged: summary = f'
{len(flagged)} finding{"s" if len(flagged) > 1 else ""} to review: {_esc(", ".join(flagged))}
' else: summary = '
No findings flagged by EchoPrime\'s estimates.
' xc = cross_check(report_text, metrics) if report_text else [] xc_html = "" if xc: items = "".join( f'
{_esc(lbl)}report {s:g} {u} · EchoPrime {e:.0f} {u}' f'{"Consistent" if ok else "Differs — check"}
' for lbl, s, e, u, ok in xc) xc_html = f'
Cross-check: report vs EchoPrime
{items}
' note = "" if n_clips is not None and n_clips < 5: note = ('
Few clips: each estimate comes from the views available, so treat these as rough. ' 'Rows marked "not covered" have no contributing view.
') return (f'
{summary}{xc_html}{note}' f'{"".join(rows)}
SectionFindingEstimateReference
' '
EchoPrime retrieves the 50 reference studies (out of 1.2M) whose embeddings are closest ' "to this study for each anatomical section and averages their report labels: scores are the share of " "similar studies with that finding. Flag thresholds are EchoPrime's published ROC thresholds (0.5 where none " "is published).
") def render_views(views): if not views: return "" counts = Counter(views) chips = "".join(f'{_esc(v.replace("_", " "))}×{n}' for v, n in counts.most_common()) per_clip = "".join(f"
  • Clip {i + 1}{_esc(v.replace('_', ' '))}
  • " for i, v in enumerate(views)) return (f'
    {len(views)} clip{"s" if len(views) != 1 else ""} · ' f'{len(counts)} view type{"s" if len(counts) != 1 else ""}
    {chips}
    ' f'
    View of each clip
      {per_clip}
    ' '
    Views are classified by EchoPrime from the first frame of each clip. They weight ' "which clips inform each section of the measurements.
    ") STEPS = [("prepare", "Prepare clips"), ("echoprime", "Views & measurements"), ("report", "Write report"), ("translate", "Translate")] def render_progress(step, elapsed, translate=True, detail="", error=None): """Stepper card. step: index into STEPS of the active step (len(STEPS) = finished).""" items = [] for i, (_, label) in enumerate(STEPS): if label == "Translate" and not translate: continue if error and i == step: cls, dot = "ep-step-error", "!" elif i < step: cls, dot = "ep-step-done", "✓" elif i == step: cls, dot = "ep-step-active", '' else: cls, dot = "", str(i + 1) items.append(f'
    {dot}{label}
    ') done = step >= len(STEPS) head = ("Report ready" if done else "Report ready · translation failed" if error and step == 3 else "Failed" if error else "Working…") sub = _esc(error) if error else _esc(detail) return (f'
    ' f'
    {head}{elapsed}
    ' f'
    {"".join(items)}
    ' f'{f"
    {sub}
    " if sub else ""}
    ') EMPTY_PROGRESS = ('
    No study analysed yet
    ' '
    Upload a clip — or all clips of a study — on the left and press ' 'Generate report, or click an example clip to see it next to its reference.
    ') def _report_txt(sections, mk, metrics, views, n_clips, ref_rows=()): lines = ["ECHOCARDIOGRAPHY REPORT — AI DRAFT (EchoGemma)", f"Clips analysed: {n_clips}", "Views: " + ", ".join(f"{v} x{n}" for v, n in Counter(views).most_common()), ""] lines += [f"{name}: {text}" for name, text in sections] if mk: lines += ["", "МАКЕДОНСКИ (машински превод)", ""] + [f"{MK_SECTIONS.get(n, n)}: {t}" for n, t in mk] lines += ["", "ECHOPRIME ESTIMATES"] for section, items in METRIC_GROUPS: for key, label, unit in items: v = metrics.get(key) shown = "n/a" if v is None or v != v else (f"{v:.0f} {unit}" if unit else f"{v:.2f}") lines.append(f" {section} — {label}: {shown}") if ref_rows: ok, total = _check_score(ref_rows) lines += ["", f"REFERENCE CHECK ({ok}/{total} match)"] lines += [f" {c}: {r}" + (f" [reference: {ref}]" if ref else "") + f" -> {st}" for c, r, ref, st in ref_rows] lines += ["", "Research prototype — NOT a medical device. Must be reviewed by a qualified physician."] path = os.path.join(tempfile.mkdtemp(prefix="echo_report_"), "echo_report.txt") with open(path, "w", encoding="utf-8") as f: f.write("\n".join(lines) + "\n") return path # --------------------------------------------------------------------------- # Pipeline (generator: every stage shows up in the UI as soon as it starts) # --------------------------------------------------------------------------- def _check_ready(): if LOAD_STATE.get("error"): raise gr.Error(f"Model loading failed: {LOAD_STATE['error']}") if not LOAD_STATE.get("ready"): raise gr.Error(f"Models are still loading — {LOAD_STATE['stage']} ({int(LOAD_STATE['pct'] * 100)}%). " "Please try again in a minute.") OUTPUT_KEYS = ("progress", "report", "mk", "metrics", "views", "download", "check", "clip", "mosaic", "reference") def run_pipeline(dicom_dir, video_paths, translate, n_files_label, ref_key=None, preview=None): """preview: (clip video, mosaic image, reference card) updates shown for this run, so the clip and reference on screen always belong to the report being generated.""" t0 = time.monotonic() state = {"step": 0} keep = gr.skip() out = {k: keep for k in OUTPUT_KEYS} def elapsed(): s = int(time.monotonic() - t0) return f"{s // 60}:{s % 60:02d}" def emit(step=None, detail="", **kw): if step is not None: state["step"] = step kw["progress"] = render_progress(step, elapsed(), translate, detail) out.update(kw) return tuple(out[k] for k in OUTPUT_KEYS) clip, mosaic, reference = preview or (gr.Video(visible=False), gr.Image(visible=False), gr.HTML(visible=False)) yield emit(0, f"Reading {n_files_label}…", report="", mk="", metrics="", views="", download=gr.DownloadButton(visible=False), check=render_reference_check(ref_key, []), clip=clip, mosaic=mosaic, reference=reference) try: _check_ready() yield from _pipeline_stages(emit, dicom_dir, video_paths, translate, n_files_label, elapsed, ref_key) except Exception as e: out["progress"] = render_progress(state["step"], elapsed(), translate, error=str(e) or e.__class__.__name__) yield emit() raise def _pipeline_stages(emit, dicom_dir, video_paths, translate, n_files_label, elapsed, ref_key): # 1. preprocessing (CPU) def preprocess(): stacks = [] if dicom_dir: stacks.append(echogemma_model.process_dicoms(dicom_dir)) if video_paths: stacks.append(process_videos(video_paths)) return torch.cat(stacks, dim=0) if len(stacks) > 1 else stacks[0] for stack in _ticking(preprocess): if stack is None: yield emit(0, f"Reading {n_files_label}…") n = stack.shape[0] clips = f"{n} clip{'s' if n != 1 else ''}" # 2. EchoPrime views + measurements (CPU) yield emit(1, f"{clips} ready · classifying views and estimating measurements…") for encoded in _ticking(encode_study, stack): if encoded is None: yield emit(1, f"{clips} ready · classifying views and estimating measurements…") views = [COARSE_VIEWS[i] for i in encoded[:, 512:].argmax(dim=1).tolist()] metrics = predict_metrics(echo_prime_model, encoded) yield emit(2, f"{clips} · {len(set(views))} view types · waiting for a GPU…", views=render_views(views), metrics=render_metrics(metrics, n_clips=n), report=render_report("", n, streaming=True), check=render_reference_check(ref_key, reference_check(ref_key, views, metrics, None))) # 3. report streamed from GPU task 1 raw = "" for raw in generate_report_gpu(stack): yield emit(2, "EchoGemma is writing the report…", report=render_report(raw, n, streaming=True)) sections, _ = parse_report(raw) report_text = " ".join(t for _, t in sections) checks = cross_check(report_text, metrics) xc = " · ".join(f"{lbl}: {'consistent' if ok else 'differs'}" for lbl, *_, ok in checks) ref_rows = reference_check(ref_key, views, metrics, sections) if ref_rows: ok, total = _check_score(ref_rows) xc = f"reference check {ok}/{total}" + (f" · {xc}" if xc else "") print(f"[check] {ref_key}: {ok}/{total} | " + " | ".join(f"{c}: {r} ({st})" for c, r, _, st in ref_rows), flush=True) summary = f"{clips} · {len(set(views))} view types" + (f" · {xc}" if xc else "") report_done = dict(report=render_report(raw, n, meta=f"{clips} · {elapsed()}"), metrics=render_metrics(metrics, report_text, n), check=render_reference_check(ref_key, ref_rows)) print(f"[run] report finished: {n} clips, {len(sections)} sections, {elapsed()}", flush=True) if not translate: yield emit(len(STEPS), summary, download=gr.DownloadButton( value=_report_txt(sections, [], metrics, views, n, ref_rows), visible=True), **report_done) return # 4. Macedonian translation from GPU task 2 — everything above is already on screen yield emit(3, summary + " · translating…", mk=render_translation([], streaming=True), download=gr.DownloadButton( value=_report_txt(sections, [], metrics, views, n, ref_rows), visible=True), **report_done) pairs = [] try: for pairs in translate_gpu(sections): yield emit(3, summary + " · translating…", mk=render_translation(pairs, streaming=True)) except Exception as e: yield emit(3, summary, mk=render_translation(pairs, error=str(e) or e.__class__.__name__)) raise yield emit(len(STEPS), summary, mk=render_translation(pairs), download=gr.DownloadButton( value=_report_txt(sections, pairs, metrics, views, n, ref_rows), visible=True)) def run_upload(files, translate): if not files: raise gr.Error("Upload one or more DICOM (.dcm) clips or echo videos (MP4/AVI) — or pick an example.") paths = [f if isinstance(f, str) else f.name for f in files] dcm = [p for p in paths if p.lower().endswith(".dcm")] vids = [p for p in paths if p.lower().endswith(VIDEO_EXTS)] if not dcm and not vids: raise gr.Error("Unsupported file types — please upload .dcm files or MP4/AVI videos.") print(f"[run] upload: {len(dcm)} dcm, {len(vids)} video", flush=True) study_dir = None if dcm: study_dir = tempfile.mkdtemp(prefix="echo_study_") for p in dcm: shutil.copy(p, os.path.join(study_dir, os.path.basename(p))) try: preview = (gr.Video(vids[0], visible=True) if vids else gr.Video(visible=False), gr.Image(visible=False), gr.HTML(visible=False)) yield from run_pipeline(study_dir, vids, translate, f"{len(paths)} file{'s' if len(paths) != 1 else ''}", preview=preview) finally: if study_dir: shutil.rmtree(study_dir, ignore_errors=True) # --------------------------------------------------------------------------- # Examples # --------------------------------------------------------------------------- # Reference ("ground truth") for the bundled examples. EchoPrime's public example study ships # without its clinical report; what is known about it is # - the view of every clip: EchoPrime's view classifier on the original DICOMs (each sample clip # >= 0.99 confidence), which a reviewer can confirm by watching the clip, and # - the study values the EchoPrime authors publish for it in EchoPrimeDemo.ipynb: EF 56 %, # PA systolic pressure 22 mmHg and every finding score <= 0.02, i.e. a normal study. REFERENCE_SOURCE = ("EchoPrime's public example study has no published clinical report. Views: EchoPrime's " "classification of the original DICOM clips (≥ 0.99 confidence for each sample) — check them " "on the clip. Study values: published by the EchoPrime authors for this study (EchoPrimeDemo.ipynb).") STUDY_REFERENCE = {"ejection_fraction": 56.3, "pulmonary_artery_pressure_continuous": 22.1} FULL_STUDY_VIEWS = {"Apical_Doppler": 13, "Parasternal_Short": 7, "A4C": 6, "Parasternal_Long": 5, "A3C": 4, "Doppler_Parasternal_Short": 4, "A2C": 3, "Subcostal": 3, "SSN": 2, "Doppler_Parasternal_Long": 2, "A5C": 1} # (id, title, short description, reference view, what the view shows). "full_study" is EchoPrime's # 50-clip example study (downloaded at startup); the rest are single clips from it (samples/). EXAMPLES = [ ("full_study", "Complete study", "The full report, all views", None, "All standard transthoracic views"), ("plax", "Parasternal long axis", "LV, mitral & aortic valves", "Parasternal_Long", "LV size and walls, mitral and aortic valves, aortic root, left atrium"), ("psax", "Parasternal short axis", "LV cross-section, wall motion", "Parasternal_Short", "LV in cross-section (wall thickness, regional wall motion), RV"), ("a4c", "Apical 4-chamber", "All four chambers, LV & RV", "A4C", "All four chambers, LV and RV function, mitral and tricuspid valves, atrial septum"), ("a2c", "Apical 2-chamber", "LV walls and left atrium", "A2C", "LV anterior and inferior walls, left atrium, mitral valve"), ("apical_doppler", "Apical colour Doppler", "Flow across the valves", "Apical_Doppler", "Colour-flow Doppler from the apical window: flow across the valves"), ("subcostal", "Subcostal", "RV, atrial septum, pericardium", "Subcostal", "Heart seen from below the ribs: RV, atria, atrial septum, pericardium"), ] EXAMPLE_KEYS = [e[0] for e in EXAMPLES] def _view_name(v): return v.replace("_", " ") CLIP_EXAMPLES = [e for e in EXAMPLES if e[0] != "full_study"] def _example_samples(): # Gradio's table cells truncate Markdown at ~60 characters: keep title + description short return [[os.path.join(SAMPLES_DIR, "thumbs", f"{key}.jpg"), f"**{title}** \n{desc}"] for key, title, desc, _, _ in CLIP_EXAMPLES] def render_reference(key): _, title, _, view, shows = EXAMPLES[EXAMPLE_KEYS.index(key)] if view: view_txt = f"{_esc(_view_name(view))} (1 clip)" scope = ('
    One view cannot show the whole heart: report sections about structures ' "outside this view are not supported by the images.
    ") else: view_txt = "50 clips: " + ", ".join(f"{_esc(_view_name(v))} ×{n}" for v, n in FULL_STUDY_VIEWS.items()) scope = "" return (f'
    Reference (ground truth) · {_esc(title)}
    ' f'
    View
    {view_txt}
    ' f'
    Shows
    {_esc(shows)}
    ' '
    Study
    EF 56 % · PA systolic pressure 22 mmHg · ' "no abnormal findings (normal study)
    " f'{scope}
    {_esc(REFERENCE_SOURCE)}
    ') ABNORMAL_RE = re.compile(r"\b(mild(?:ly)?|moderate(?:ly)?|severe(?:ly)?|dilat\w*|enlarg\w*|reduced|depressed|" r"impaired|hypokines\w*|akines\w*|dyskines\w*|hypertroph\w*|thicken\w*|effusion|stenosis|" r"regurgitation|calcif\w*|prolapse|vegetation|thromb\w*|elevated|abnormal\w*)\b", re.I) NEGATED_RE = re.compile(r"^\s*(?:no|there is no|there was no|without|not)\b|\bno\b|\bnormal\b|\btrivial\b|" r"\btrace\b|\bphysiologic", re.I) # A device or prosthesis is a finding however neutrally it is described ("the prosthesis is well seated") DEVICE_RE = re.compile(r"prosthe|\bTAVR\b|\bTAVI\b|valve replacement|pacemaker|\bICD\b|pacing (?:wire|lead)|" r"impella|mitraclip|mitral clip|annuloplasty", re.I) # Statements the reference rules out: (pattern, phenotype EchoPrime scores ~0 for this study, label) REFERENCE_RULES = [ (r"prosthe|\bTAVR\b|\bTAVI\b|valve replacement", "tavr", "Prosthetic aortic valve"), (r"pacemaker|\bICD\b|pacing (?:wire|lead)", "pacemaker", "Pacemaker / ICD lead"), (r"impella", "impella", "Impella device"), (r"mitraclip|mitral clip|annuloplasty", "mitraclip", "Mitral device"), (r"aortic root|ascending aort|sinus of valsalva", "aortic_root_dilation", "Aortic root dilation"), (r"left atri", "left_atrium_dilation", "LA dilation"), (r"right atri", "right_atrium_dilation", "RA dilation"), (r"right ventric\w*.{0,30}(?:systolic|function)|RV (?:systolic )?dysfunction", "rv_systolic_function_depressed", "Reduced RV function"), (r"right ventric|\bRV\b", "right_ventricle_dilation", "RV dilation"), (r"pericardial effusion", "pericardial_effusion", "Pericardial effusion"), (r"inferior vena cava|\bIVC\b", "dilated_ivc", "Dilated IVC"), (r"annular calcification", "mitral_annular_calcification", "Mitral annular calcification"), (r"mitral.{0,20}stenosis", "mitral_stenosis", "Mitral stenosis"), (r"mitral.{0,20}(?:regurgitation|insufficiency)", "mitral_regurgitation", "Mitral regurgitation"), (r"bicuspid", "bicuspid_aov_morphology", "Bicuspid aortic valve"), (r"aortic.{0,20}stenosis", "aortic_stenosis", "Aortic stenosis"), (r"aortic.{0,20}(?:regurgitation|insufficiency)", "aortic_regurgitation", "Aortic regurgitation"), (r"tricuspid.{0,20}stenosis", "tricuspid_stenosis", "Tricuspid stenosis"), (r"tricuspid.{0,20}(?:regurgitation|insufficiency)", "tricuspid_valve_regurgitation", "Tricuspid regurgitation"), ] def abnormal_statements(sections): """Report phrases that describe an abnormality or a device, split into those the reference rules out ({label: [phrases]}) and the rest ([(section, phrase)]), which the reference does not cover (e.g. LV hypertrophy, diastolic function). The model often runs phrases together without full stops, so text is split before a capitalised word (not "A" in "E to A") as well as at sentence ends.""" contradicted, other = {}, [] for name, text in sections: for phrase in re.split(r"(?<=[.;])\s+|(?<=[a-z0-9%)])\s+(?=[A-Z][a-z])", text): phrase = phrase.strip() device = DEVICE_RE.search(phrase) and not re.match(r"^\s*(?:no|there is no|without)\b", phrase, re.I) if not device and not (ABNORMAL_RE.search(phrase) and not NEGATED_RE.search(phrase)): continue where = f"{name} {phrase}" rule = next((r for r in REFERENCE_RULES if re.search(r[0], where, re.I)), None) if rule: contradicted.setdefault(rule[2], []).append(phrase) else: other.append((name, phrase)) return contradicted, other def reference_check(key, views, metrics, sections): """Rows (check, result, reference, status) comparing a run on a bundled example with its reference. status: pass | fail | pending | info. sections=None while the report is pending.""" if key not in EXAMPLE_KEYS: return [] _, _, _, ref_view, _ = EXAMPLES[EXAMPLE_KEYS.index(key)] rows = [] if ref_view: got = views[0] if views else "—" rows.append(("View (EchoPrime)", _view_name(got), _view_name(ref_view), "pass" if got == ref_view else "fail")) else: counts = Counter(views) match = sum(min(counts.get(v, 0), n) for v, n in FULL_STUDY_VIEWS.items()) rows.append(("Views (EchoPrime)", f"{match}/{sum(FULL_STUDY_VIEWS.values())} clips match", "the 50 reference views", "pass" if match >= 0.9 * sum(FULL_STUDY_VIEWS.values()) else "fail")) for key_m, label, unit in (("ejection_fraction", "Ejection fraction", "%"), ("pulmonary_artery_pressure_continuous", "PA systolic pressure", "mmHg")): ref = STUDY_REFERENCE[key_m] est = metrics.get(key_m) if est is None or est != est: rows.append((f"{label} — EchoPrime", "not estimated", f"{ref:.0f} {unit}", "info")) else: rows.append((f"{label} — EchoPrime", f"{est:.0f} {unit}", f"{ref:.0f} {unit}", "pass" if abs(est - ref) <= 5 else "fail")) thresholds = _roc_thresholds() flagged = [label for _, items in METRIC_GROUPS for k, label, unit in items if unit is None and metrics.get(k) == metrics.get(k) and metrics.get(k) is not None and metrics[k] >= thresholds.get(k, 0.5)] rows.append(("Findings flagged — EchoPrime", ", ".join(flagged) or "none", "none", "fail" if flagged else "pass")) if sections is None: for label in ("Ejection fraction — report", "PA systolic pressure — report", "Findings the reference rules out — report"): rows.append((label, "waiting for the report…", "", "pending")) return rows text = " ".join(t for _, t in sections) for key_m, label, unit in (("ejection_fraction", "Ejection fraction — report", "%"), ("pulmonary_artery_pressure_continuous", "PA systolic pressure — report", "mmHg")): ref, stated = STUDY_REFERENCE[key_m], report_number(text, key_m) if stated is None: rows.append((label, "not stated", f"{ref:.0f} {unit}", "info")) else: rows.append((label, f"{stated:g} {unit}", f"{ref:.0f} {unit}", "pass" if abs(stated - ref) <= 5 else "fail")) contradicted, other = abnormal_statements(sections) rows.append(("Findings the reference rules out — report", "; ".join(f"{lbl}: “{ps[0]}”" + (f" (+{len(ps) - 1} more)" if len(ps) > 1 else "") for lbl, ps in contradicted.items()) or "none", "none (normal study)", "fail" if contradicted else "pass")) if other: rows.append(("Other abnormal statements — report", "; ".join(f"{n}: “{p}”" for n, p in other), "not covered by the reference — your judgement", "info")) return rows def _check_score(rows): scored = [r for r in rows if r[3] in ("pass", "fail")] return sum(r[3] == "pass" for r in scored), len(scored) def render_reference_check(key, rows): if key not in EXAMPLE_KEYS: return ('
    Reference check
    ' "

    Reference checks run on the bundled examples, which have known views and published study values. " "For your own study, compare the report with your own reading of the clips — the Measurements tab " "cross-checks the report against EchoPrime's independent estimates.

    ") if not rows: return "" badge = {"pass": 'Match', "fail": 'Differs', "pending": '', "info": '—'} ok, total = _check_score(rows) body = "".join(f'{_esc(c)}{_esc(r)}' f'{_esc(ref)}{badge[st]}' for c, r, ref, st in rows) title = EXAMPLES[EXAMPLE_KEYS.index(key)][1] pending = any(r[3] == "pending" for r in rows) summary_cls = "ep-summary-ok" if ok == total and not pending else "ep-summary-warn" if not pending else "" summary = (f'
    {ok} of {total} checks match the reference' f'{" so far" if pending else ""} · {_esc(title)}
    ') return (f'
    {summary}' f'{body}
    CheckThis runReference
    ' f'
    {_esc(REFERENCE_SOURCE)} Numbers match within ±5. "Findings the reference rules out" ' "are report statements about a finding or device that EchoPrime scores as absent in this normal study; " "other abnormal statements concern things the reference does not cover, so they are listed for your " "judgement but not scored.
    ") def run_example_key(key, translate): """Run a bundled example; its clip (or the study mosaic) and reference card come up with it.""" title = EXAMPLES[EXAMPLE_KEYS.index(key)][1] reference = gr.HTML(render_reference(key), visible=True) print(f"[run] example: {key}", flush=True) if key == "full_study": if not glob.glob(os.path.join(EXAMPLE_STUDY_DIR, "*.dcm")): raise gr.Error("The example study is not available (download failed at startup?).") preview = (gr.Video(visible=False), gr.Image(os.path.join(SAMPLES_DIR, "thumbs", "full_study.jpg"), visible=True), reference) yield from run_pipeline(EXAMPLE_STUDY_DIR, [], translate, "the 50-clip example study", key, preview) else: clip = os.path.join(SAMPLES_DIR, f"{key}.mp4") preview = (gr.Video(clip, visible=True), gr.Image(visible=False), reference) yield from run_pipeline(None, [clip], translate, f"the {title} clip", key, preview) def run_clip_example(index, translate): yield from run_example_key(CLIP_EXAMPLES[int(index)][0], translate) def run_full_study(translate): yield from run_example_key("full_study", translate) # --------------------------------------------------------------------------- # UI # --------------------------------------------------------------------------- def _status_pill(): s = LOAD_STATE if s["error"]: return '● Model load failed — restart the Space' if s["ready"]: return '● Models ready' return f' Loading models · {int(s["pct"] * 100)}%' def _status(): """Status pill + polling timer (stops once loading ends) + run button state.""" busy = not LOAD_STATE["ready"] and not LOAD_STATE["error"] return (_status_pill(), gr.Timer(active=busy), gr.Button("Loading models…" if busy else "Generate report", interactive=not busy), gr.Button(interactive=not busy)) HEADER = """

    Echo Report QA

    Draft an echocardiography report from the video clips of a study, then cross-check it. EchoGemma writes the report; EchoPrime independently classifies views and estimates measurements.

    """ DISCLAIMER = ('
    Research prototype — not a medical device. All output must be ' "reviewed and verified by a qualified physician. Uploaded files are processed in temporary storage " "and not kept.
    ") HOW_IT_WORKS = """ 1. **Preprocess.** DICOM clips are masked to the ultrasound sector; every clip is cropped and scaled to 224×224 and sampled to 16 frames. 2. **Encode.** An MViT-v2 video encoder (trained with EchoPrime on more than 12M video–report pairs) turns each clip into a 512-d embedding, and a ConvNeXt classifier names its view (A4C, PLAX, …). 3. **EchoPrime → measurements.** Clip embeddings are weighted by how informative each view is for each anatomical section, pooled per section, and matched against 1.2M reference studies. Each estimate is the average label of the 50 closest studies. This is independent of the generated text, which is what makes it a cross-check. 4. **EchoGemma → report.** The same kind of clip embeddings, plus each clip's view, are projected into the language model and placed before the prompt as visual tokens. A LoRA-tuned MedGemma-4B then writes the report section by section. 5. **Cross-check.** Where the report states a number that EchoPrime also estimates (ejection fraction, PA systolic pressure), the two are compared. Disagreements, and any flagged findings, are where a reviewing physician should look first. The Macedonian version is a second, text-only MedGemma pass over the English report. """ CSS = """ .gradio-container { max-width: 1280px !important; margin: 0 auto !important; } .ep-header { display: flex; gap: 14px; align-items: flex-start; } .ep-logo { font-size: 30px; line-height: 1; padding: 10px; border-radius: 14px; background: var(--color-accent-soft); } .ep-header h1 { margin: 0 0 4px; font-size: 26px; font-weight: 700; letter-spacing: -0.01em; } .ep-header p { margin: 0; color: var(--body-text-color-subdued); max-width: 760px; line-height: 1.5; } .ep-header a { color: var(--color-accent); text-decoration: none; font-weight: 600; padding: 0 !important; } #ep-status { display: flex; justify-content: flex-end; align-items: flex-start; } .ep-pill { display: inline-flex; align-items: center; gap: 6px; padding: 5px 12px; border-radius: 999px; font-size: 13px; font-weight: 600; white-space: nowrap; } .ep-pill-ok { background: rgba(22,163,74,.12); color: #15803d; } .ep-pill-wait { background: rgba(217,119,6,.12); color: #b45309; } .ep-pill-error { background: rgba(220,38,38,.12); color: #b91c1c; } .ep-disclaimer { font-size: 13px; padding: 9px 14px; border-radius: 10px; border: 1px solid var(--border-color-primary); color: var(--body-text-color-subdued); background: var(--block-background-fill); } .ep-label { font-size: 12px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; color: var(--body-text-color-subdued); margin: 4px 0 -4px; } #ep-examples table { width: 100%; } #ep-examples thead { display: none; } #ep-examples td { padding: 6px 10px !important; text-align: left !important; vertical-align: middle !important; } #ep-examples td.image { width: 92px; padding-right: 0 !important; } #ep-examples td.image .container { width: 80px !important; height: 60px !important; border: 0 !important; } #ep-examples img { width: 80px !important; height: 60px !important; object-fit: cover; border-radius: 8px; } #ep-examples td.markdown .prose { text-align: left; font-size: 14px; } #ep-examples td.markdown p { margin: 0; line-height: 1.4; color: var(--body-text-color-subdued); } #ep-examples td.markdown strong { color: var(--body-text-color); } #ep-full { padding: 12px; border-radius: 12px; } #ep-full p { margin: 0; font-size: 13.5px; line-height: 1.45; color: var(--body-text-color-subdued); } #ep-full strong { color: var(--body-text-color); } .ep-full-row { gap: 14px !important; align-items: center !important; margin-bottom: 10px; } .ep-full-row img { width: 104px !important; height: 78px !important; border-radius: 8px; object-fit: cover; } #ep-examples tr.tr-body { cursor: pointer; } #ep-examples tr.tr-body:hover td { background: var(--color-accent-soft) !important; } .ep-progress { border: 1px solid var(--border-color-primary); border-radius: 14px; padding: 14px 16px; background: var(--block-background-fill); } .ep-progress-head { display: flex; justify-content: space-between; align-items: center; font-size: 15px; } .ep-time { font-variant-numeric: tabular-nums; color: var(--body-text-color-subdued); font-size: 13px; } .ep-steps { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-top: 10px; } .ep-step { display: flex; align-items: center; gap: 7px; font-size: 13px; color: var(--body-text-color-subdued); } .ep-dot { width: 20px; height: 20px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; border: 1.5px solid var(--border-color-primary); } .ep-step-done { color: var(--body-text-color); } .ep-step-done .ep-dot { background: #16a34a; border-color: #16a34a; color: #fff; } .ep-step-active { color: var(--body-text-color); font-weight: 600; } .ep-step-active .ep-dot { border-color: var(--color-accent); } .ep-step-error { color: #b91c1c; font-weight: 600; } .ep-step-error .ep-dot { background: #dc2626; border-color: #dc2626; color: #fff; } .ep-progress-sub { margin-top: 8px; font-size: 13px; color: var(--body-text-color-subdued); } .ep-progress-error .ep-progress-sub { color: #b91c1c; } .ep-progress-done { border-color: rgba(22,163,74,.45); } .ep-spin { width: 12px; height: 12px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent; display: inline-block; animation: ep-rot .8s linear infinite; } .ep-dot .ep-spin { color: var(--color-accent); } @keyframes ep-rot { to { transform: rotate(360deg); } } .ep-cursor { display: inline-block; width: 7px; height: 1em; margin-left: 2px; vertical-align: text-bottom; background: var(--color-accent); animation: ep-blink 1s steps(1) infinite; } @keyframes ep-blink { 50% { opacity: 0; } } .ep-card { border: 1px solid var(--border-color-primary); border-radius: 14px; padding: 16px 18px; background: var(--block-background-fill); } .ep-card-head { display: flex; justify-content: space-between; align-items: flex-end; gap: 12px; padding-bottom: 12px; margin-bottom: 4px; border-bottom: 1px solid var(--border-color-primary); } .ep-card-title { font-size: 18px; font-weight: 700; } .ep-kicker { font-size: 11px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; color: var(--color-accent); margin-bottom: 2px; } .ep-meta { font-size: 13px; color: var(--body-text-color-subdued); white-space: nowrap; } .ep-secs { display: flex; flex-direction: column; } .ep-sec { display: grid; grid-template-columns: 190px 1fr; gap: 14px; padding: 9px 0; border-bottom: 1px dashed var(--border-color-primary); } .ep-sec:last-child { border-bottom: 0; } .ep-sec-wide { grid-template-columns: 1fr; } .ep-sec-name { font-weight: 600; font-size: 14px; } .ep-sec-text { font-size: 14px; line-height: 1.55; } @media (max-width: 640px) { .ep-sec { grid-template-columns: 1fr; gap: 2px; } } .ep-callout { font-size: 13px; margin: 10px 0 6px; padding: 9px 12px; border-radius: 10px; background: rgba(217,119,6,.10); color: var(--body-text-color); border-left: 3px solid #d97706; } .ep-empty-inline { display: flex; align-items: center; gap: 8px; padding: 14px 0; color: var(--body-text-color-subdued); } .ep-summary { padding: 10px 12px; border-radius: 10px; font-size: 14px; margin-bottom: 10px; } .ep-summary-ok { background: rgba(22,163,74,.10); } .ep-summary-warn { background: rgba(217,119,6,.12); } .ep-xc { margin: 4px 0 12px; } .ep-xc-item { display: grid; grid-template-columns: 170px 1fr auto; gap: 10px; align-items: center; font-size: 14px; padding: 6px 0; border-bottom: 1px dashed var(--border-color-primary); } .ep-table { width: 100%; border-collapse: collapse; font-size: 13.5px; } .ep-table th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--body-text-color-subdued); padding: 6px 8px; border-bottom: 1px solid var(--border-color-primary); } .ep-table td { padding: 6px 8px; border: 0 !important; border-bottom: 1px solid var(--border-color-primary) !important; } .ep-table th { border: 0 !important; border-bottom: 1px solid var(--border-color-primary) !important; } .ep-td-sec { font-weight: 600; vertical-align: top; } .ep-check td:first-child { width: 34%; font-weight: 600; } .ep-check td:nth-child(3) { width: 22%; } .ep-num { font-variant-numeric: tabular-nums; font-weight: 600; } .ep-ref { color: var(--body-text-color-subdued); font-size: 12.5px; } .ep-na { color: var(--body-text-color-subdued); font-style: italic; } .ep-flag td:not(.ep-td-sec) { background: rgba(217,119,6,.08); } .ep-ok { color: var(--body-text-color-subdued); } .ep-badge { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: 12px; font-weight: 600; white-space: nowrap; } .ep-badge-warn { background: rgba(217,119,6,.16); color: #b45309; } .ep-badge-ok { background: rgba(22,163,74,.14); color: #15803d; } .ep-foot { margin-top: 12px; font-size: 12.5px; color: var(--body-text-color-subdued); line-height: 1.5; } .ep-kv { display: grid; grid-template-columns: 54px 1fr; gap: 10px; font-size: 13.5px; padding: 6px 0; border-bottom: 1px dashed var(--border-color-primary); } .ep-kv > span { color: var(--body-text-color-subdued); font-size: 12px; text-transform: uppercase; letter-spacing: .05em; padding-top: 1px; } .ep-chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0; } .ep-chip { display: inline-flex; gap: 6px; padding: 5px 11px; border-radius: 999px; border: 1px solid var(--border-color-primary); font-size: 13px; } .ep-chip b { color: var(--color-accent); } .ep-details summary { cursor: pointer; font-size: 13px; color: var(--body-text-color-subdued); } .ep-clips { columns: 2; font-size: 13px; padding-left: 0; list-style: none; } .ep-clips li span { display: inline-block; width: 64px; color: var(--body-text-color-subdued); } """ THEME = gr.themes.Soft( primary_hue="rose", secondary_hue="slate", neutral_hue="slate", font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"], ) with gr.Blocks(title="Echo Report QA") as demo: with gr.Row(equal_height=False): with gr.Column(scale=5): gr.HTML(HEADER) with gr.Column(scale=1, min_width=200): status = gr.HTML(_status_pill(), elem_id="ep-status") gr.HTML(DISCLAIMER) with gr.Row(equal_height=False): with gr.Column(scale=5, min_width=340): gr.HTML('
    Your own study — one clip or all clips of a study
    ') file_input = gr.File(label="DICOM clips (.dcm) or echo videos (MP4/AVI)", file_count="multiple", file_types=[".dcm", *VIDEO_EXTS], height=140) translate_cb = gr.Checkbox(True, label="Add Macedonian translation (≈ +45 s, also for the examples)") run_btn = gr.Button("Generate report", variant="primary", size="lg") gr.HTML('
    Or try an example clip — click to generate and compare with its reference
    ') examples = gr.Dataset( components=[gr.Image(render=False), gr.Markdown(render=False)], samples=_example_samples(), type="index", layout="table", samples_per_page=10, elem_id="ep-examples", show_label=False, ) preview_video = gr.Video(visible=False, autoplay=True, loop=True, interactive=False, show_label=False, height=260) preview_image = gr.Image(visible=False, interactive=False, show_label=False, height=200) reference_html = gr.HTML(visible=False) gr.HTML('
    Complete example study
    ') with gr.Group(elem_id="ep-full"): with gr.Row(equal_height=True, elem_classes="ep-full-row"): gr.Image(os.path.join(SAMPLES_DIR, "thumbs", "full_study.jpg"), interactive=False, show_label=False, container=False, height=78, width=104, scale=0, min_width=104, buttons=[]) gr.Markdown("**All 50 clips of the example study** — every standard view, so the report and the " "reference check are the most representative. Takes 2–3 minutes.") full_btn = gr.Button("Generate report for the complete study (50 clips)", variant="secondary") with gr.Column(scale=7, min_width=380): progress_html = gr.HTML(EMPTY_PROGRESS) with gr.Tabs(): with gr.Tab("Report"): report_html = gr.HTML() with gr.Tab("Reference check"): check_html = gr.HTML() with gr.Tab("Measurements"): metrics_html = gr.HTML() with gr.Tab("Views"): views_html = gr.HTML() with gr.Tab("Македонски"): mk_html = gr.HTML() download_btn = gr.DownloadButton("Download report (.txt)", visible=False, size="sm", variant="secondary") with gr.Accordion("How it works", open=False): gr.Markdown(HOW_IT_WORKS) outputs = [progress_html, report_html, mk_html, metrics_html, views_html, download_btn, check_html, preview_video, preview_image, reference_html] # order of OUTPUT_KEYS run_btn.click(run_upload, inputs=[file_input, translate_cb], outputs=outputs, show_progress_on=progress_html, concurrency_id="pipeline", api_name="analyse") examples.click(run_clip_example, inputs=[examples, translate_cb], outputs=outputs, show_progress_on=progress_html, concurrency_id="pipeline", api_name="analyse_example") full_btn.click(run_full_study, inputs=[translate_cb], outputs=outputs, show_progress_on=progress_html, concurrency_id="pipeline", api_name="analyse_full_study") timer = gr.Timer(3) timer.tick(_status, outputs=[status, timer, run_btn, full_btn], show_progress="hidden", api_visibility="private") demo.load(_status, outputs=[status, timer, run_btn, full_btn], show_progress="hidden", api_visibility="private") if __name__ == "__main__": # SSR must stay ENABLED on ZeroGPU: the ZeroGPU client-side GPU SDK is built on the # SSR event transport — with SSR disabled every click died silently before reaching # the server. show_error=True still surfaces server-side tracebacks as UI toasts. demo.launch(show_error=True, theme=THEME, css=CSS)