Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608import mathfrom dataclasses import dataclassimport gradio as gr"""CARPL ROI Calculator · FFR-CT AI (v4.4 — Inter + tooltips + labeled bars)- Minimal inputs (4 fields). Assumptions hidden as internal state.- Four output cards: Overall Impact, Financial, Clinical, Operational.- Inter font, HTML waterfall with inline values, percent labels on mini bars.- CSV only on click. No sticky UI."""# ------------------------- Defaults & Config -------------------------@dataclassclass Defaults:# Volumesmonthly_eligible_ccta: int = 100uptake_pct: float = 60.0# Site presets (net cost per diagnostic ICA; allow negative if profit-positive)net_cost_per_diag_ica_hospital: float = 5000.0net_cost_per_diag_ica_imaging_center: float = 2000.0net_cost_per_diag_ica_amc: float = 4000.0# Reimbursement (USD)reimb_ccta: float = 400.0 # varies by region/payerreimb_ffrct: float = 1017.0 # CMS 2025reimb_ai_qpa: float = 950.0 # CMS 2025pct_billed_ai_qpa: float = 60.0# Clinical performance (evidence-based anchors)one_test_dx_pct: float = 97.0 # 3% need additional testing with AIdec_unnec_ica_pct: float = 69.0 # reduction in unnecessary diagnostic ICAs (scaled)more_likely_revasc_pct: float = 78.0revasc_prevalence_pct: float = 10.0# Costs (USD)vendor_per_case_cost: float = 350.0platform_monthly_cost: float = 1000.0stress_test_cost: float = 400.0# Ops economics (USD)bed_hour_value: float = 100.0clinician_hour_cost: float = 150.0# Time effectsai_time_to_decision_min: float = 90.0clinician_touch_reduction_pct: float = 30.0# Baseline (without AI)baseline_diag_ica_rate_pct: float = 30.0baseline_additional_testing_rate_pct: float = 30.0DEFAULTS = Defaults()SITE_TYPES = ["Hospital / Health System","Imaging Center","Academic Medical Center",]CTA_URL = "https://carpl.ai/contact-us" # swap to your CTA if you wantCTA_LABEL = "Book a 15-min walkthrough"# ------------------------- Helpers -------------------------def _pct(x): return max(0.0, min(100.0, float(x)))def _pos(x): return max(0.0, float(x))def tooltip(label: str, tip: str) -> str:"""Returns a label with a subtle tooltip (title attribute)."""# The ℹ︎ glyph has good cross-platform support; title shows on hoverreturn (f"<span style='display:inline-flex; align-items:center; gap:6px'>"f"{label}"f"<span title=\"{tip}\" style='cursor:help; opacity:.75'>ℹ︎</span>"f"</span>")# ------------------------- Core computation -------------------------def compute_roi(site_type,monthly_eligible_ccta,uptake_pct,avg_time_to_decision_today_hours, # minimal input #1baseline_clinician_touch_min, # minimal input #2# Hidden assumptions (States)reimb_ccta,reimb_ffrct,reimb_ai_qpa,pct_billed_ai_qpa,one_test_dx_pct,dec_unnec_ica_pct,more_likely_revasc_pct,revasc_prevalence_pct,vendor_per_case_cost,platform_monthly_cost,stress_test_cost,bed_hour_value,clinician_hour_cost,ai_time_to_decision_min,clinician_touch_reduction_pct,baseline_diag_ica_rate_pct,baseline_additional_testing_rate_pct,# Sensitivitysens_uptake_factor_pct,sens_dec_unnec_ica_factor_pct,sens_vendor_cost_factor_pct,):# Site-driven ICA economicsif site_type == SITE_TYPES[0]:net_cost_per_diag_ica = DEFAULTS.net_cost_per_diag_ica_hospitalelif site_type == SITE_TYPES[1]:net_cost_per_diag_ica = DEFAULTS.net_cost_per_diag_ica_imaging_centerelse:net_cost_per_diag_ica = DEFAULTS.net_cost_per_diag_ica_amc# Sanitize + derivemonthly_eligible_ccta = _pos(monthly_eligible_ccta)uptake = _pct(uptake_pct) / 100.0 * (_pct(sens_uptake_factor_pct) / 100.0)reimb_ccta = float(reimb_ccta)reimb_ffrct = float(reimb_ffrct)reimb_ai_qpa = float(reimb_ai_qpa)pct_billed_ai_qpa = _pct(pct_billed_ai_qpa) / 100.0one_test_dx = _pct(one_test_dx_pct) / 100.0need_addl_with_ai = 1.0 - one_test_dxbase_dec_unnec_ica = _pct(dec_unnec_ica_pct) / 100.0dec_unnec_ica = base_dec_unnec_ica * (_pct(sens_dec_unnec_ica_factor_pct) / 100.0)more_likely_revasc = _pct(more_likely_revasc_pct) / 100.0revasc_prev = _pct(revasc_prevalence_pct) / 100.0vendor_per_case_cost = float(vendor_per_case_cost) * (_pct(sens_vendor_cost_factor_pct) / 100.0)platform_monthly_cost = float(platform_monthly_cost)stress_test_cost = float(stress_test_cost)bed_hour_value = float(bed_hour_value)clinician_hour_cost = float(clinician_hour_cost)ai_time_to_decision_min = _pos(ai_time_to_decision_min)clinician_touch_reduction_pct = _pct(clinician_touch_reduction_pct) / 100.0baseline_diag_ica_rate = _pct(baseline_diag_ica_rate_pct) / 100.0baseline_additional_testing_rate = _pct(baseline_additional_testing_rate_pct) / 100.0# Volumesannual_eligible = monthly_eligible_ccta * 12.0annual_uptake_cases = annual_eligible * uptake# -------- Baseline (without AI) --------baseline_revenue = annual_eligible * reimb_cctabaseline_additional_tests = annual_eligible * baseline_additional_testing_ratebaseline_additional_tests_cost = baseline_additional_tests * stress_test_costbaseline_diag_ica_total = annual_eligible * baseline_diag_ica_ratebaseline_revasc_true = annual_eligible * revasc_prevbaseline_unnecessary_ica = max(0.0, baseline_diag_ica_total - baseline_revasc_true)baseline_unnecessary_ica_cost = baseline_unnecessary_ica * net_cost_per_diag_icabaseline_ops_value = 0.0baseline_costs = baseline_additional_tests_cost + baseline_unnecessary_ica_costbaseline_net = baseline_revenue - baseline_costs + baseline_ops_value# -------- With AI --------with_ai_revenue = (annual_eligible * reimb_ccta+ annual_uptake_cases * reimb_ffrct+ annual_uptake_cases * pct_billed_ai_qpa * reimb_ai_qpa)with_ai_vendor_costs = annual_uptake_cases * vendor_per_case_costwith_ai_platform_costs = platform_monthly_cost * 12.0# Additional testing (compare baseline rate vs one-test Dx for AI cohort only)baseline_addl_tests_in_ai_cohort = annual_uptake_cases * baseline_additional_testing_ratewith_ai_additional_tests = annual_uptake_cases * need_addl_with_aiwith_ai_additional_tests_cost = with_ai_additional_tests * stress_test_costavoided_additional_tests = max(0.0, baseline_addl_tests_in_ai_cohort - with_ai_additional_tests)# Unnecessary diagnostic ICAsavoided_unnec_ica = baseline_unnecessary_ica * dec_unnec_ica * (annual_uptake_cases / annual_eligible if annual_eligible > 0 else 0)with_ai_unnecessary_ica = max(0.0, baseline_unnecessary_ica - avoided_unnec_ica)with_ai_unnecessary_ica_cost = with_ai_unnecessary_ica * net_cost_per_diag_ica# Revasc candidate identification (est., scaled by prevalence & uptake)addl_revasc_candidates = annual_eligible * revasc_prev * uptake * more_likely_revasc# Ops value (from just 2 inputs)avg_time_to_decision_today_hours = _pos(avg_time_to_decision_today_hours)baseline_clinician_touch_min = _pos(baseline_clinician_touch_min)ai_saved_hours_per_case = min(ai_time_to_decision_min / 60.0, avg_time_to_decision_today_hours)bed_hours_saved = annual_uptake_cases * ai_saved_hours_per_casebed_hours_value = bed_hours_saved * bed_hour_valueclinician_hours_saved = annual_uptake_cases * (baseline_clinician_touch_min / 60.0) * clinician_touch_reduction_pctclinician_hours_value = clinician_hours_saved * clinician_hour_costwith_ai_ops_value = bed_hours_value + clinician_hours_valuewith_ai_costs = (with_ai_vendor_costs+ with_ai_platform_costs+ with_ai_additional_tests_cost+ with_ai_unnecessary_ica_cost)with_ai_net = with_ai_revenue - with_ai_costs + with_ai_ops_value# -------- Incremental --------incr_revenue = with_ai_revenue - baseline_revenueincr_costs = with_ai_costs - baseline_costsincr_ops_value = with_ai_ops_value - baseline_ops_valuenet_impact = incr_revenue - incr_costs + incr_ops_valueai_program_costs = with_ai_vendor_costs + with_ai_platform_costsroi_pct = (net_impact / ai_program_costs * 100.0) if ai_program_costs > 0 else 0.0per_case_net_impact = (net_impact / annual_uptake_cases) if annual_uptake_cases > 0 else 0.0cases_to_payback = (ai_program_costs / per_case_net_impact) if per_case_net_impact > 0 else math.infmonths_to_payback = ((cases_to_payback / (monthly_eligible_ccta * uptake))if (monthly_eligible_ccta * uptake) > 0 and cases_to_payback != math.inf else math.inf)# -------- Card builders --------def money(x, digits=0):if x == math.inf: return "∞"return f"${x:,.{digits}f}" if digits else f"${x:,.0f}"def num(x, digits=1):if x == math.inf: return "∞"return f"{x:,.{digits}f}"def card(title, subtitle, items, bars=None):rows = "".join(f"<div class='kpi-row'><span class='kpi-label'>{lab}</span><span class='kpi-val{' emph' if emph else ''}'>{val}</span></div>"for (lab, val, emph) in items)# bars with right-aligned % labelsbars_html = ""if bars:for (lab, pct) in bars:pct = max(0, min(100, pct))bars_html += ("<div class='bar'>"f"<div class='bar-label' style=\"display:flex;align-items:center;justify-content:space-between;\">"f"<span>{lab}</span>"f"<span style=\"font-variant-numeric:tabular-nums;\">{pct:.0f}%</span>""</div>""<div class='bar-track'><div class='bar-fill' style='width:"f"{pct}%'></div></div></div>")return ("<div class='card'>""<div class='card-head'>"f"<div class='card-title'>{title}</div>"f"<div class='card-sub'>{subtitle}</div>""</div>"f"<div class='kpi-grid'>{rows}</div>"f"{bars_html}""</div>")# Labels with tooltips where it helpsroi_label_tt = tooltip("ROI % (on AI program)","ROI = Net Impact ÷ (Platform + Per-case vendor costs), annualized.")payback_label_tt = tooltip("Months to payback","Payback months = (AI program costs ÷ net impact per AI case) ÷ monthly AI cases.")incr_rev_label_tt = tooltip("Incremental revenue","Additional CCTA+FFR-CT+AI-QPA revenue from AI cohort vs baseline.")incr_costs_label_tt = tooltip("Incremental costs","Vendor per-case + platform + testing/cath costs in AI cohort minus baseline costs.")ops_value_label_tt = tooltip("Operational value","Value of faster time-to-decision (bed-hours) + clinician hours saved.")overall_html = card("Overall Impact","Incremental (annual)",[(incr_rev_label_tt, money(incr_revenue), False),(incr_costs_label_tt, money(incr_costs), False),(ops_value_label_tt, money(incr_ops_value), False),("Net impact", money(net_impact), True),(roi_label_tt, f"{roi_pct:,.1f}%", True),(payback_label_tt, num(months_to_payback, 1), False),],)# Inline explanation of paybackoverall_html += ("<div class='muted' style='margin-top:4px; font-size:.85rem'>""Payback = (AI program costs ÷ net impact per AI case) ÷ monthly AI cases.""</div>")financial_html = card("Financial","Incremental economics",[(incr_rev_label_tt, money(incr_revenue), False),(incr_costs_label_tt, money(incr_costs), False),("Net impact", money(net_impact), True),("AI program costs", money(ai_program_costs), False),(roi_label_tt, f"{roi_pct:,.1f}%", True),(payback_label_tt, num(months_to_payback, 1), False),],)clinical_html = card("Clinical","Modeled impact (AI cohort)",[("Avoided unnecessary ICAs", f"{int(round(avoided_unnec_ica)):,} /yr", True),("One-test diagnosis rate", f"{one_test_dx*100:,.0f}% of AI cases", False),("Added revasc candidates (est.)", f"{int(round(addl_revasc_candidates)):,} /yr", False),("Avoided extra non-invasive tests", f"{int(round(avoided_additional_tests)):,} /yr", False),],bars=[("Unnecessary ICA reduction", base_dec_unnec_ica * 100),("One-test diagnosis", one_test_dx * 100),],)operational_html = card("Operational","Throughput & staff time (AI cohort)",[("Avg hours saved per case", num(ai_saved_hours_per_case, 2), False),("Bed-hours saved", f"{int(round(bed_hours_saved)):,} hrs/yr", True),("Value of bed-hours", money(bed_hours_value), False),("Clinician hours saved", f"{int(round(clinician_hours_saved)):,} hrs/yr", False),("Value of clinician time", money(clinician_hours_value), False),],)# Evidence (neutral language)evidence = """<div class='card'><div class='card-head'><div class='card-title'>Evidence snapshot</div><div class='card-sub'>Published guidance & trials</div></div><ul style='margin:6px 0 0 1.1rem; line-height:1.45;'><li>PRECISE (RCT): Reduced composite of death/MI or ICA without obstructive CAD vs. traditional testing.</li><li>FORECAST (RCT): Fewer ICAs and fewer unnecessary ICAs; similar revascularization; no NHS cost increase.</li><li>PLATFORM: Fewer non-therapeutic ICAs; many planned ICAs cancelled; lower 1-yr costs.</li><li>NICE MTG32: CCTA-first with selective FFR-CT recommended; modeled per-patient savings.</li></ul><div class='muted' style='margin-top:6px;'>Note: Site results vary by policy, mix, and operations.</div></div>"""# Contextual CTA (richer line)cases_per_year = int(round(annual_uptake_cases))cta_line = (f"Based on your {cases_per_year:,} AI cases/yr: "f"net impact {money(net_impact)}, ROI {roi_pct:,.1f}%, payback {num(months_to_payback,1)} mo; "f"avoids ~{int(round(avoided_unnec_ica)):,} diagnostic ICAs & ~{int(round(avoided_additional_tests)):,} extra tests; "f"frees ~{int(round(bed_hours_saved)):,} bed-hrs & ~{int(round(clinician_hours_saved)):,} clinician-hrs annually.")cta_html = f"""<div class='cta-card'><div class='cta-line'>{cta_line}</div><a class='cta-btn' href='{CTA_URL}' target='_blank' rel='noopener'>{CTA_LABEL}</a></div>"""# Return cards + numbers for waterfall / CSVreturn (overall_html, financial_html, clinical_html, operational_html,evidence, cta_html,incr_revenue, incr_costs, incr_ops_value, net_impact, roi_pct, months_to_payback)# ------------------------- UI -------------------------def build_ui():with gr.Blocks(theme=gr.themes.Soft(), css="""@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');:root { --card-bg:#ffffff; --muted:#6b7280; }* { font-family: 'Inter', ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, 'Apple Color Emoji', 'Segoe UI Emoji'; }.header { display:flex; align-items:center; justify-content:space-between; padding:12px 0; }.app-title { font-weight:800; font-size:1.4rem; }.pill { background:#ecfdf5; color:#065f46; padding:4px 10px; border-radius:999px; font-weight:700; font-size:.85rem; }.card { background:var(--card-bg); border-radius:18px; padding:18px; box-shadow:0 8px 24px rgba(0,0,0,.08); border:1px solid #eef2f7; }.card-head { margin-bottom:8px; display:flex; align-items:baseline; gap:8px; }.card-title { font-weight:800; font-size:1.05rem; }.card-sub { color:var(--muted); font-size:.9rem; }.kpi-grid { display:grid; grid-template-columns:1fr auto; gap:6px 12px; align-items:center; margin-bottom:8px; }.kpi-row { display:contents; }.kpi-label { color:#4b5563; }.kpi-val { font-variant-numeric:tabular-nums; font-weight:600; }.kpi-val.emph { font-weight:900; font-size:1.06rem; }.bar { margin-top:8px; }.bar-label { font-size:.85rem; color:#374151; margin-bottom:2px; }.bar-track { background:#f1f5f9; border-radius:999px; height:8px; position:relative; overflow:hidden; }.bar-fill { background:linear-gradient(90deg,#14b8a6,#06b6d4); height:8px; border-radius:999px; }.muted { color:var(--muted); }.cta-card { margin-top:8px; padding:12px; border:1px dashed #d1fae5; border-radius:12px; display:flex; align-items:center; justify-content:space-between; gap:10px; }.cta-line { font-weight:700; }.cta-btn { background:#0ea5e9; color:white; padding:8px 12px; border-radius:10px; text-decoration:none; font-weight:700; }.wf { margin-top:8px; }.wf-row { display:flex; align-items:center; gap:10px; margin:6px 0; }.wf-label { width:160px; color:#334155; font-size:.9rem; }.wf-bar { height:12px; border-radius:999px; background:#f1f5f9; flex:1; position:relative; overflow:hidden; }.wf-fill.pos { position:absolute; left:0; top:0; bottom:0; border-radius:999px; background:linear-gradient(90deg,#22c55e,#16a34a); color:rgba(255,255,255,.95); }.wf-fill.neg { position:absolute; right:0; top:0; bottom:0; border-radius:999px; background:linear-gradient(90deg,#ef4444,#dc2626); color:rgba(255,255,255,.95); }.wf-val { width:140px; text-align:right; font-variant-numeric:tabular-nums; }""") as demo:# Headerwith gr.Row(elem_classes=["header"]):gr.Markdown("""<div class='app-title'>CARPL ROI Calculator · FFR-CT AI</div><div class='pill'>Clinical · Financial · Operational</div>""")with gr.Row():# -------- Left: inputs --------with gr.Column(scale=1):site_type = gr.Dropdown(SITE_TYPES, value=SITE_TYPES[0], label="Site type")monthly_eligible_ccta = gr.Slider(0, 2000, value=DEFAULTS.monthly_eligible_ccta, step=10,label="Monthly eligible CCTA volume")uptake_pct = gr.Slider(0, 100, value=DEFAULTS.uptake_pct, step=1,label="Uptake (eligible receiving FFR-CT, %)")avg_time_to_decision_today_hours = gr.Number(label="Average time-to-decision today (hours)", value=8.0)baseline_clinician_touch_min = gr.Number(label="Clinician touch-time per case (min)", value=30.0)# Hidden internal assumptions (States) — not displayedreimb_ccta = gr.State(DEFAULTS.reimb_ccta)reimb_ffrct = gr.State(DEFAULTS.reimb_ffrct)reimb_ai_qpa = gr.State(DEFAULTS.reimb_ai_qpa)pct_billed_ai_qpa = gr.State(DEFAULTS.pct_billed_ai_qpa)one_test_dx_pct_state = gr.State(DEFAULTS.one_test_dx_pct)dec_unnec_ica_pct_state = gr.State(DEFAULTS.dec_unnec_ica_pct)more_likely_revasc_pct_state = gr.State(DEFAULTS.more_likely_revasc_pct)revasc_prevalence_pct_state = gr.State(DEFAULTS.revasc_prevalence_pct)vendor_per_case_cost = gr.State(DEFAULTS.vendor_per_case_cost)platform_monthly_cost = gr.State(DEFAULTS.platform_monthly_cost)stress_test_cost = gr.State(DEFAULTS.stress_test_cost)bed_hour_value = gr.State(DEFAULTS.bed_hour_value)clinician_hour_cost = gr.State(DEFAULTS.clinician_hour_cost)ai_time_to_decision_min = gr.State(DEFAULTS.ai_time_to_decision_min)clinician_touch_reduction_pct = gr.State(DEFAULTS.clinician_touch_reduction_pct)baseline_diag_ica_rate_pct = gr.State(DEFAULTS.baseline_diag_ica_rate_pct)baseline_additional_testing_rate_pct = gr.State(DEFAULTS.baseline_additional_testing_rate_pct)with gr.Accordion("Sensitivity (what-if)", open=False):sens_uptake_factor_pct = gr.Slider(0, 200, 100, step=5, label="Uptake factor (%)")sens_dec_unnec_ica_factor_pct = gr.Slider(0, 200, 100, step=5, label="ICA reduction factor (%)")sens_vendor_cost_factor_pct = gr.Slider(25, 200, 100, step=5, label="Vendor per-case cost factor (%)")# -------- Right: outputs --------with gr.Column(scale=1):overall_card = gr.HTML()financial_card = gr.HTML()clinical_card = gr.HTML()operational_card = gr.HTML()waterfall_panel = gr.HTML(label="ROI Waterfall")cta_panel = gr.HTML()kpi_copy = gr.Textbox(label="Copy KPIs", interactive=False, lines=6)csv_button = gr.DownloadButton(label="Download CSV", value=None)evidence_panel = gr.HTML()# Bundle inputs (order matters!)inputs = [site_type,monthly_eligible_ccta,uptake_pct,avg_time_to_decision_today_hours,baseline_clinician_touch_min,reimb_ccta,reimb_ffrct,reimb_ai_qpa,pct_billed_ai_qpa,one_test_dx_pct_state,dec_unnec_ica_pct_state,more_likely_revasc_pct_state,revasc_prevalence_pct_state,vendor_per_case_cost,platform_monthly_cost,stress_test_cost,bed_hour_value,clinician_hour_cost,ai_time_to_decision_min,clinician_touch_reduction_pct,baseline_diag_ica_rate_pct,baseline_additional_testing_rate_pct,sens_uptake_factor_pct,sens_dec_unnec_ica_factor_pct,sens_vendor_cost_factor_pct,]# HTML waterfall (dep-free) with inline valuesdef waterfall_html(incr_rev, incr_costs, incr_ops, net):maxv = max(abs(incr_rev), abs(incr_costs), abs(incr_ops), abs(net), 1)def row(label, val):pct = int(abs(val) / maxv * 100)cls = 'pos' if val >= 0 else 'neg'inner_val = f"${val:,.0f}"inner = ("<div style='position:absolute;inset:0;display:flex;align-items:center;padding:0 8px;""font-size:.82rem;opacity:.95;'>"f"{inner_val}</div>"if pct >= 24 else "")return ("<div class='wf-row'>"f"<div class='wf-label'>{label}</div>""<div class='wf-bar'>"f"<div class='wf-fill {cls}' style='width:{pct}%'>{inner}</div>""</div>"f"<div class='wf-val'>{inner_val}</div>""</div>")return ("<div class='wf'>"+ row("Incr. Revenue", incr_rev)+ row("Incr. Costs", -abs(incr_costs))+ row("Ops Value", incr_ops)+ row("Net Impact", net)+ "</div>")def kpi_text(incr_rev, incr_costs, incr_ops, net, roi, payback):return (f"Incremental revenue: ${incr_rev:,.0f}\n"f"Incremental costs: ${incr_costs:,.0f}\n"f"Operational value: ${incr_ops:,.0f}\n"f"Net impact: ${net:,.0f}\n"f"ROI (on AI program): {roi:,.1f}%\n"f"Months to payback: {payback:,.1f}\n")def post_compute(*args):(overall_html, financial_html, clinical_html, operational_html,evidence_html, cta_html,incr_rev, incr_costs, incr_ops, net, roi, payback) = compute_roi(*args)wf = waterfall_html(incr_rev, incr_costs, incr_ops, net)kpis = kpi_text(incr_rev, incr_costs, incr_ops, net, roi, payback)return (overall_html, financial_html, clinical_html, operational_html,evidence_html, cta_html, wf, kpis)# Bind changes (DON’T include csv_button here)for comp in inputs[:5]:comp.change(post_compute, inputs=inputs,outputs=[overall_card, financial_card, clinical_card, operational_card,evidence_panel, cta_panel, waterfall_panel, kpi_copy])for comp in inputs[-3:]:comp.change(post_compute, inputs=inputs,outputs=[overall_card, financial_card, clinical_card, operational_card,evidence_panel, cta_panel, waterfall_panel, kpi_copy])# Init on loaddemo.load(post_compute, inputs=inputs,outputs=[overall_card, financial_card, clinical_card, operational_card,evidence_panel, cta_panel, waterfall_panel, kpi_copy])# CSV on click onlydef make_csv(*args):import csv, tempfile(overall_html, financial_html, clinical_html, operational_html,evidence_html, cta_html,incr_rev, incr_costs, incr_ops, net, roi, payback) = compute_roi(*args)headers = ["Metric", "Value"]rows = [["Incremental revenue", f"${incr_rev:,.0f}"],["Incremental costs", f"${incr_costs:,.0f}"],["Operational value", f"${incr_ops:,.0f}"],["Net impact", f"${net:,.0f}"],["ROI %", f"{roi:,.1f}%"],["Months to payback", f"{payback:,.1f}"],]fd, path = tempfile.mkstemp(suffix="_roi.csv")with open(path, "w", newline="") as f:writer = csv.writer(f)writer.writerow(headers)writer.writerows(rows)return pathcsv_button.click(make_csv, inputs=inputs, outputs=csv_button)gr.Markdown("> Enter the four inputs on the left. We apply published evidence and CMS-2025 assumptions under the hood for a site-specific clinical, financial, and operational view.")return demo# ------------------------- Entrypoint -------------------------def main():demo = build_ui()demo.queue().launch()if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import gradio as grimport pandas as pdimport plotly.graph_objects as go# ===== Baseline Constants =====REIMBURSEMENT_FFRCT = 1017REIMBURSEMENT_AI_QPA = 950PCT_BILLED_AI_QPA = 0.60UPTAKE_DEFAULT = 0.60ONE_TEST_DIAGNOSIS = 0.97UNNECESSARY_ICA_REDUCTION = 0.69MORE_LIKELY_REVASC = 0.78REVASC_PREVALENCE = 0.10VENDOR_COST_PER_CASE = 350PLATFORM_COST_ANNUAL = 12000 # Updated to annual feeSTRESS_TEST_COST = 400NET_ICA_COST = 5000BED_HOUR_VALUE = 100CLINICIAN_HOUR_COST = 150TOUCH_TIME_REDUCTION_PCT = 0.30AI_TIME_TO_DECISION_MIN = 90# ===== Helper Calculations =====def calculate_roi(eligible_cases, uptake, time_to_decision, clinician_touch_time):ai_cases = eligible_cases * uptake# Financialai_revenue_per_case = REIMBURSEMENT_FFRCT + (REIMBURSEMENT_AI_QPA * PCT_BILLED_AI_QPA)baseline_revenue_per_case = REIMBURSEMENT_FFRCTincr_revenue = ai_cases * (ai_revenue_per_case - baseline_revenue_per_case)total_ai_costs = (VENDOR_COST_PER_CASE * ai_cases) + PLATFORM_COST_ANNUALincr_costs = total_ai_costs# Operationaltime_saved_per_case_hr = (time_to_decision - (AI_TIME_TO_DECISION_MIN)) / 60bed_hours_saved = max(time_saved_per_case_hr, 0) * ai_casesclinician_time_saved_hr = (clinician_touch_time * TOUCH_TIME_REDUCTION_PCT) / 60 * ai_casesops_value = (bed_hours_saved * BED_HOUR_VALUE) + (clinician_time_saved_hr * CLINICIAN_HOUR_COST)# Clinicalicas_avoided = ai_cases * UNNECESSARY_ICA_REDUCTIONextra_tests_avoided = ai_cases * (1 - ONE_TEST_DIAGNOSIS)revacs_identified = ai_cases * REVASC_PREVALENCE * MORE_LIKELY_REVASC# Net + ROInet_impact = incr_revenue - incr_costs + ops_valueroi_pct = (net_impact / total_ai_costs) * 100 if total_ai_costs > 0 else 0net_monthly_impact = net_impact / 12payback_months = total_ai_costs / net_monthly_impact if net_monthly_impact > 0 else Nonereturn {"ai_cases": ai_cases,"incr_revenue": incr_revenue,"incr_costs": incr_costs,"ops_value": ops_value,"net_impact": net_impact,"roi_pct": roi_pct,"payback_months": payback_months,"icas_avoided": icas_avoided,"extra_tests_avoided": extra_tests_avoided,"revacs_identified": revacs_identified,"bed_hours_saved": bed_hours_saved,"clinician_hours_saved": clinician_time_saved_hr}# ===== Visual Components =====def waterfall_chart(incr_revenue, incr_costs, ops_value, net_impact):fig = go.Figure(go.Waterfall(name="ROI",orientation="v",measure=["relative", "relative", "relative", "total"],x=["Incremental Revenue", "Operational Value", "Incremental Costs", "Net Impact"],text=[f"${incr_revenue:,.0f}", f"${ops_value:,.0f}", f"-${incr_costs:,.0f}", f"${net_impact:,.0f}"],y=[incr_revenue, ops_value, -incr_costs, net_impact],connector={"line": {"color": "rgb(63, 63, 63)"}}))fig.update_layout(title="ROI Breakdown",showlegend=False,height=400,margin=dict(l=40, r=40, t=40, b=40))return fig# ===== Main Function =====def run_calculator(eligible_cases, uptake, time_to_decision, clinician_touch_time):results = calculate_roi(eligible_cases, uptake, time_to_decision, clinician_touch_time)# Summary Textcta_text = (f"Based on your {results['ai_cases']:.0f} AI cases/yr: "f"net impact ${results['net_impact']:,.0f}, ROI {results['roi_pct']:.0f}%, "f"payback {results['payback_months']:.1f} mo; "f"avoids ~{results['icas_avoided']:.0f} ICAs, "f"~{results['extra_tests_avoided']:.0f} extra tests; "f"frees ~{results['bed_hours_saved']:.0f} bed-hrs, "f"~{results['clinician_hours_saved']:.0f} clinician-hrs annually.")return (f"${results['incr_revenue']:,.0f}",f"${results['incr_costs']:,.0f}",f"${results['ops_value']:,.0f}",f"${results['net_impact']:,.0f}",f"{results['roi_pct']:.0f}%",f"{results['payback_months']:.1f} months",waterfall_chart(results['incr_revenue'], results['incr_costs'], results['ops_value'], results['net_impact']),cta_text)# ===== Gradio UI =====custom_css = """@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');* { font-family: 'Inter', sans-serif; }"""with gr.Blocks(css=custom_css, title="CARPL FFR-CT AI ROI Calculator") as demo:gr.Markdown("## CARPL FFR-CT AI ROI Calculator")gr.Markdown("Enter basic site metrics — we’ll calculate financial, clinical, and operational ROI.")with gr.Row():eligible_cases = gr.Number(label="Annual Eligible Cases", value=1200, info="Patients eligible for FFR-CT annually")uptake = gr.Slider(label="AI Uptake (%)", minimum=0, maximum=1, step=0.05, value=UPTAKE_DEFAULT, info="Fraction of eligible cases using AI")with gr.Row():time_to_decision = gr.Number(label="Avg Time to Decision Today (min)", value=180)clinician_touch_time = gr.Number(label="Avg Clinician Touch Time per Case (min)", value=30)with gr.Row():incr_revenue_out = gr.Textbox(label="Incremental Revenue", interactive=False)incr_costs_out = gr.Textbox(label="Incremental Costs", interactive=False)ops_value_out = gr.Textbox(label="Operational Value", interactive=False)net_impact_out = gr.Textbox(label="Net Impact", interactive=False)roi_pct_out = gr.Textbox(label="ROI (%)", interactive=False)payback_out = gr.Textbox(label="Payback (months)", interactive=False)waterfall_plot = gr.Plot()cta_output = gr.Markdown()run_btn = gr.Button("Calculate ROI", variant="primary")run_btn.click(run_calculator,inputs=[eligible_cases, uptake, time_to_decision, clinician_touch_time],outputs=[incr_revenue_out, incr_costs_out, ops_value_out, net_impact_out, roi_pct_out, payback_out, waterfall_plot, cta_output])demo.launch()
app.py+141-604