"""RareDx : démo Gradio sur le VRAI système (src/), interface sobre orientée desktop. Lancer : python app.py puis ouvrir l'adresse affichée dans le terminal. Ce qui est en direct et ce qui est pré-calculé : - Le RAG, la fusion des rangs et l'agent de questions tournent en direct avec src/ (aucune clé API, aucun modèle d'embedding). - Les réponses du LLM viennent de demo/demo_cases.json, construit depuis votre cache (data/cache_llm.json). Si le fichier est absent, il est créé au premier lancement. Cas publics RareBench uniquement. Prototype de recherche, pas un dispositif médical. """ from __future__ import annotations import html import json import os import sys from pathlib import Path import gradio as gr try: # Hugging Face ZeroGPU : il exige au moins une fonction @spaces.GPU import spaces @spaces.GPU def _zerogpu_check(): """Jamais appelée : la démo tourne entièrement sur CPU (RAG, fusion, agent).""" return None except ImportError: # en local ou sur un Space CPU, le paquet n'existe pas : rien à faire pass ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) os.environ.setdefault("HPO_RELEASE", "2026-09-01") from src.demo_service import build_demo_cases, diagnosis_payload, load_light_system, update_payload # noqa: E402 DEMO_CASES = Path(os.environ.get("RAREDX_DEMO_CASES", ROOT / "demo" / "demo_cases.json")) N_QUESTIONS = 5 ANSWERS = ["Oui", "Non", "Je ne sais pas"] E = html.escape # ================================================================= données def load_cases() -> list[dict]: if not DEMO_CASES.exists(): print("demo/demo_cases.json est absent : construction depuis data/cache_llm.json (aucun appel LLM)...") build_demo_cases(DEMO_CASES) return json.loads(DEMO_CASES.read_text(encoding="utf-8")) SYSTEM, AGENT = load_light_system() CASES = {c["id"]: c for c in load_cases()} if not CASES: raise SystemExit("Aucun cas de démo : vérifiez que data/cache_llm.json, hp.json et phenotype.hpoa viennent de votre Drive.") CHOICES = [(c["label"], cid) for cid, c in CASES.items()] N_DISEASES = f"{len(SYSTEM.kb.diseases):,}".replace(",", " ") HPO_VERSION = str(SYSTEM.kb.version).rstrip("/").split("releases/")[-1].split("/")[0] LLM_NAME = SYSTEM.settings.llm_model.split("/")[-1] # ================================================================= composants HTML def card_head(label: str, title: str, subtitle: str, right: str = "") -> str: return ( '
' '
' f'
{E(label)}
' f'

{E(title)}

' f'

{E(subtitle)}

' '
' f'
{right}
' '
' ) def chips_symptoms(p: dict) -> str: chips = "".join( f'' f'{E(s["name"])}' f'{E(s["code"])}' '' for s in p["symptoms"] ) return ( '
' f'Phénotypes HPO du cas{len(p["symptoms"])}' '
' f'
{chips}
' '
' 'Signe métabolique ou biologique' 'Autre signe clinique' 'Cas public RareBench' '
' ) def routing_html(p: dict) -> str: r = p["routing"] share, thr, w = r["metabolic_share"], r["threshold"], r["llm_weight"] n_meta = sum(s["metabolic"] for s in p["symptoms"]) regime = "à parité avec le RAG" if w >= 1 else "à moitié du poids du RAG" pill_cls = "rd-pill-llm" if w >= 1 else "rd-pill-rag" return ( card_head("Étape 2", "Aiguillage métabolique", "Plus le patient présente de signes métaboliques, plus le LLM pèse dans la fusion.") + '
' '
' '
' '
Part de symptômes métaboliques
' f'
{n_meta} signe(s) métabolique(s) sur {len(p["symptoms"])} phénotypes
' '
' f'
{share:.0%}
' '
' '
' f'
' f'
Seuil {thr:.0%}
' '
' '
' '
Poids du LLM
' f'
{w:g} {regime}
' '
' '
' + f'

Les deux avis sont toujours calculés. Le seuil de {thr:.0%} modifie uniquement le poids du LLM dans la fusion.

' ) def tag_html(t: str) -> str: if t == "commun": return 'Commun' if t == "non relié": return 'Non relié' return 'Spécifique' def lists_html(p: dict) -> str: n_common = sum(x["tag"] == "commun" for x in p["rag"]) rag = "".join( '
  • ' f'{x["rank"]:02d}' f'{E(x["name"])}' f'{tag_html(x["tag"])}' '
  • ' for x in p["rag"] ) llm_rows = [] for x in p["llm"]: proposed = "" if x["code"] is None or x["proposed_name"].lower() != x["name"].lower(): proposed = f'Proposé : « {E(x["proposed_name"])} »' llm_rows.append( '
  • ' f'{x["rank"]:02d}' f'{E(x["name"])}{proposed}' f'{tag_html(x["tag"])}' '
  • ' ) llm = "".join(llm_rows) right = f'{n_common} diagnostic(s) commun(s) aux deux avis' return ( card_head("Étape 3", "Deux avis indépendants", "Chaque avis classe les maladies séparément. Les étiquettes comparent les codes ORPHA / OMIM, pas les noms.", right) + '
    ' '
    ' '
    ' '
    RAG, recherche hiérarchique HPO
    ' f'{N_DISEASES} fiches' '
    ' '

    Un symptôme rare et précis compte davantage (pondération par le contenu en information).

    ' f'
      {rag}
    ' '
    ' '
    ' '
    ' f'
    LLM, {E(LLM_NAME)}
    ' 'Réponses pré-calculées' '
    ' '

    10 propositions, reliées aux codes ORPHA / OMIM par embeddings.

    ' f'
      {llm}
    ' '
    ' '
    ' ) def source_badges(sources: list[str]) -> str: if len(sources) == 2: return 'RAG et LLM' if sources == ["RAG"]: return 'RAG seul' if sources == ["LLM"]: return 'LLM seul' return 'Hors top 10' def final_html(p: dict, reveal: bool) -> str: rows = "" max_score = max((x["score"] for x in p["final"]), default=0) or 1 for x in p["final"]: hit = reveal and x["is_answer"] shared = "".join(f'{E(s)}' for s in x["shared_symptoms"][:3]) status = ('Diagnostic de référence' if hit else f'' f'{x["score"]:.4f}') rows += ( f'' f'{x["rank"]}' f'{E(x["name"])}' f'{E(x["code"])}' f'{source_badges(x["sources"])}' f'{shared}' f'{status}' '' ) note = "" if reveal: a = p["answer"] if a["rank"] and a["rank"] <= 10: rank_label = f'rang {a["rank"]}' elif a["rank"]: rank_label = f'rang {a["rank"]} (hors du top 10)' else: rank_label = "non retrouvé par le système" note = ( '
    ' 'Diagnostic de référence du dossier' f'{E(a["name"] or "")}' f'{rank_label}' '
    ' ) return ( card_head("Étape 4", "Classement final par fusion RRF", "Fusion pondérée des deux classements (Reciprocal Rank Fusion). Les maladies proposées par les deux avis remontent en tête.", f'{E(p["formula"])}') + '
    ' '' '' '' '' '' f'{rows}
    RangMaladie candidateCodeSourceSymptômes communsStatut / score
    {note}' ) def agent_intro_html(p: dict) -> str: return card_head("Agent de clarification", "Questions complémentaires", "L'agent retient les signes et analyses qui séparent le mieux les maladies de tête " "(variance pondérée par le rang, bonus de 1,5 pour les analyses biologiques). " "Répondez par Oui, Non ou Je ne sais pas.") def agent_result_html(p: dict | None, u: dict | None) -> str: if not u: return ( '
    ' 'Aucune réponse enregistrée' '

    Répondez aux questions ci-dessus, puis cliquez sur « Réévaluer le classement ». ' 'Les réponses « Je ne sais pas » ne modifient pas le classement.

    ' '
    ' ) b, a = u["answer_rank_before"], u["answer_rank_after"] fmt = lambda r: f"#{r}" if r else "n.d." # noqa: E731 if a and b and a < b: delta, delta_cls = f"Gain de {b - a} rang(s)", "rd-delta-up" elif a and b and a > b: delta, delta_cls = f"Recul de {a - b} rang(s)", "rd-delta-down" else: delta, delta_cls = "Position inchangée", "rd-delta-eq" rows = "" for x in u["ranking"]: c = x["change"] if c is None: evo = 'Nouveau' elif c > 0: evo = f'+{c}' elif c < 0: evo = f'−{-c}' else: evo = '0' shared = "".join(f'{E(s)}' for s in x["shared_symptoms"][:3]) hit = 'Référence' if x["is_answer"] else "" rows += ( f'' f'{x["rank"]}' f'{E(x["name"])} {hit}' f'{evo}' f'{shared}' '' ) reasons = ("".join(f"
  • {E(r)}
  • " for r in u["reasons"]) or "
  • Aucune réponse « Oui » ou « Non » : le classement est inchangé.
  • ") return ( card_head("Résultat", "Classement après clarification", "Les signes confirmés sont ajoutés au patient. Chaque maladie est ensuite favorisée ou pénalisée " "selon la fréquence des signes confirmés ou absents.") + '
    ' '
    Rang du diagnostic de référence, avant' f'{fmt(b)}
    ' f'
    {delta}
    ' '
    Rang du diagnostic de référence, après' f'{fmt(a)}
    ' '
    ' + '
    ' '' '' '' '' f'{rows}
    RangMaladie candidateÉvolutionSymptômes communs
    ' + f'
    Détail des réajustements
    ' ) HEADER = f"""
    RareDx
    Aide au diagnostic des maladies rares

    RAG ontologique HPO, LLM et agent de questions, avec le médecin dans la boucle

    Ontologie HPO
    {E(HPO_VERSION)}
    Maladies indexées
    {N_DISEASES}
    Fusion
    RRF, c = {SYSTEM.settings.rrf_constant}
    Prototype de recherche. Cet outil repose sur le benchmark public RareBench (cas publics uniquement). Il n'est pas un dispositif médical et ne doit pas servir à la décision clinique.
    """ CSS = """ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap'); :root{ --navy-950:#0a1428; --navy-900:#0f1f3d; --navy-700:#1b3a6b; --ink:#13203a; --text:#1e293b; --muted:#5a6678; --faint:#8793a4; --line:#dbe1ea; --line-soft:#e8ecf2; --bg:#edf0f5; --surface:#ffffff; --tint:#f6f8fb; --accent:#1d4a8a; --accent-dark:#143868; --rag:#0f766e; --rag-bg:#e4f2f0; --rag-line:#b2d9d4; --llm:#5648a8; --llm-bg:#edebf8; --llm-line:#cbc5ea; --ok:#1b7248; --ok-bg:#e6f4ec; --ok-line:#a7d3b9; --bad:#a8281c; --shadow:0 1px 3px rgba(15,31,61,.06),0 12px 32px -14px rgba(15,31,61,.20); --shadow-lg:0 2px 6px rgba(15,31,61,.07),0 18px 40px -16px rgba(15,31,61,.28); } html,body{background:#fff!important;overflow-x:hidden!important;max-width:100%!important} .gradio-container,.gradio-container .main,.gradio-container .wrap,.app{ max-width:100%!important;width:100%!important; } .gradio-container{ background:#fff!important;overflow-x:hidden!important; font-family:'IBM Plex Sans',system-ui,-apple-system,'Segoe UI',sans-serif!important; margin:0!important;padding:0 clamp(20px,3vw,56px) 64px!important; color:var(--text)!important;font-size:14.5px; } .gradio-container code,.rd-formula,.rd-rank,.rd-score,.rd-metric-value,.rd-tile b,.rd-meta dd{ font-family:'IBM Plex Mono',ui-monospace,monospace!important; } footer{display:none!important} /* ---------- en-tête pleine largeur ---------- */ .rd-header{ margin:0 calc(-1 * clamp(20px,3vw,56px)) 26px;box-sizing:border-box; background:linear-gradient(120deg,var(--navy-950) 0%,var(--navy-900) 45%,var(--navy-700) 100%); color:#fff;border-bottom:1px solid #000; } .rd-header-main{display:flex;align-items:center;gap:40px;padding:22px clamp(20px,3vw,56px);flex-wrap:wrap} .rd-brand{display:flex;align-items:center;gap:16px} .rd-brand-mark{ width:6px;height:44px;border-radius:2px; background:linear-gradient(180deg,#5fd0c4,#7f8ff0); } .rd-brand-name{font-size:28px;font-weight:600;letter-spacing:-.02em;line-height:1.05;color:#fff} .rd-brand-desc{font-size:13.5px;color:#b8c6e0;margin-top:3px} .rd-brand-sub{margin:0;flex:1;min-width:260px;max-width:52ch;font-size:13px;line-height:1.55;color:#93a6c8;padding-left:32px;border-left:1px solid rgba(255,255,255,.14)} .rd-meta{display:flex;margin:0;margin-left:auto;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);border-radius:8px} .rd-meta div{padding:10px 24px;border-left:1px solid rgba(255,255,255,.12)} .rd-meta div:first-child{border-left:none} .rd-meta dt{font-size:11.5px;color:#93a6c8;margin:0} .rd-meta dd{font-size:15px;font-weight:500;color:#fff;margin:3px 0 0} .rd-disclaimer{ background:rgba(0,0,0,.28);border-top:1px solid rgba(255,255,255,.08); color:#e8d9a6;font-size:12.5px;padding:9px clamp(20px,3vw,56px); } .rd-disclaimer b{color:#f6e7ae} /* ---------- cartes ---------- */ .rd-card{ background:#fff!important;border:1px solid var(--line-soft)!important;border-radius:14px!important; padding:26px 30px!important;box-shadow:var(--shadow-lg)!important; } .rd-head{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--line-soft)} .rd-step{display:flex;align-items:center;gap:10px;font-size:12.5px;font-weight:500;color:var(--accent);margin-bottom:6px} .rd-step::before{content:"";width:22px;height:2px;background:var(--accent);border-radius:2px} .rd-title{margin:0!important;font-size:20px!important;font-weight:600!important;color:var(--ink)!important;letter-spacing:-.01em} .rd-subtitle{margin:6px 0 0!important;font-size:13.5px;color:var(--muted);line-height:1.55;max-width:90ch} .rd-head-right{flex-shrink:0;padding-top:20px} .rd-muted{color:var(--muted)} .rd-note{font-size:12.5px;color:var(--muted);margin:14px 0 0!important;line-height:1.5} /* ---------- phénotypes ---------- */ .rd-section-label{display:flex;justify-content:space-between;align-items:center;font-size:13.5px;font-weight:600;color:var(--text);margin:16px 0 12px} .rd-count{font-family:'IBM Plex Mono',monospace;font-size:12px;font-weight:500;color:var(--accent);background:#e8eef8;border:1px solid #c9d7ee;border-radius:999px;padding:1px 10px} .rd-chips{display:flex;flex-wrap:wrap;gap:8px} .rd-chip{display:inline-flex;align-items:center;gap:9px;padding:5px 11px;background:var(--tint);border:1px solid var(--line);border-radius:6px;font-size:13px;color:var(--text);transition:border-color .15s} .rd-chip:hover{border-color:#9fb0c7} .rd-chip-code{font-size:11px;color:var(--faint);background:none!important;padding:0!important} .rd-chip-meta{background:var(--rag-bg);border-color:var(--rag-line);color:#0b5a54;box-shadow:inset 3px 0 0 var(--rag)} .rd-chip-meta .rd-chip-code{color:#3f8d86} .rd-legend{display:flex;gap:22px;align-items:center;flex-wrap:wrap;margin-top:20px;padding-top:14px;border-top:1px solid var(--line-soft);font-size:12.5px;color:var(--muted)} .rd-legend-right{margin-left:auto;color:var(--faint)} .rd-swatch{display:inline-block;width:11px;height:11px;border-radius:3px;background:var(--tint);border:1px solid var(--line);margin-right:8px;vertical-align:-1px} .rd-swatch-meta{background:var(--rag-bg);border-color:var(--rag)} /* ---------- aiguillage ---------- */ .rd-panel{background:#fff;border:1px solid var(--line-soft);border-radius:12px;padding:20px 22px;box-shadow:var(--shadow-lg)} .rd-metric-row{display:flex;justify-content:space-between;align-items:flex-start;gap:12px} .rd-metric-title{font-size:14px;font-weight:600;color:var(--text)} .rd-metric-sub{font-size:12.5px;color:var(--muted);margin-top:3px} .rd-metric-value{font-size:38px;font-weight:500;color:var(--rag);line-height:1;letter-spacing:-.02em} .rd-meter{position:relative;height:10px;background:#dde4ed;border-radius:999px;margin:22px 0 40px} .rd-meter-fill{height:100%;background:linear-gradient(90deg,#2a6fb0,var(--rag));border-radius:999px} .rd-meter-pin{position:absolute;top:-6px;width:2px;height:22px;background:var(--bad)} .rd-meter-pin span{position:absolute;top:27px;left:-28px;font-family:'IBM Plex Mono',monospace;font-size:11px;color:#fff;background:var(--bad);padding:1px 7px;border-radius:3px;white-space:nowrap} .rd-kv{display:flex;justify-content:space-between;align-items:center;margin:0;padding-top:14px;border-top:1px solid var(--line);font-size:13.5px} .rd-kv dt{font-weight:500;color:var(--text)} .rd-kv dd{margin:0} /* ---------- pastilles et étiquettes ---------- */ .rd-pill{display:inline-block;padding:2px 10px;border-radius:999px;font-size:12px;font-weight:500;border:1px solid var(--line);background:var(--surface);color:var(--text);white-space:nowrap} .rd-pill-rag{background:var(--rag-bg);border-color:var(--rag-line);color:#0b5a54} .rd-pill-llm{background:var(--llm-bg);border-color:var(--llm-line);color:var(--llm)} .rd-summary-pill{display:inline-block;font-size:12.5px;font-weight:500;color:var(--ok);background:var(--ok-bg);border:1px solid var(--ok-line);border-radius:999px;padding:4px 14px} .rd-tag{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11.5px;font-weight:500;white-space:nowrap;border:1px solid transparent} .rd-tag-common,.rd-tag-both{background:var(--ok-bg);border-color:var(--ok-line);color:var(--ok)} .rd-tag-alone{background:var(--surface);border-color:var(--line);color:var(--muted)} .rd-tag-none{background:var(--tint);border-color:var(--line-soft);color:var(--faint)} .rd-tag-rag{background:var(--rag-bg);border-color:var(--rag-line);color:#0b5a54} .rd-tag-llm{background:var(--llm-bg);border-color:var(--llm-line);color:var(--llm)} /* ---------- deux avis ---------- */ .rd-two{display:grid;grid-template-columns:1fr 1fr;gap:24px} .rd-panel-rag{border-top:3px solid var(--rag)} .rd-panel-llm{border-top:3px solid var(--llm)} .rd-panel-head{display:flex;justify-content:space-between;align-items:center;gap:10px} .rd-panel-title{font-size:15px;font-weight:600;color:var(--ink)} .rd-panel-desc{font-size:13px;color:var(--muted);margin:5px 0 14px!important;line-height:1.5} .rd-cand-list{list-style:none;padding:0!important;margin:0!important;border:1px solid var(--line-soft);border-radius:10px;background:var(--surface);overflow:hidden;box-shadow:var(--shadow)} .rd-cand{display:flex;align-items:center;gap:14px;padding:0 14px 0 0;border-bottom:1px solid var(--line-soft);font-size:13.5px;margin:0!important;min-height:44px} .rd-cand:last-child{border-bottom:none} .rd-cand:hover{background:#fafbfd} .rd-rank{align-self:stretch;display:flex;align-items:center;justify-content:center;width:44px;flex-shrink:0;font-weight:500;font-size:12.5px;border-right:1px solid var(--line-soft);background:var(--tint)} .rd-c-rag{color:var(--rag)}.rd-c-llm{color:var(--llm)} .rd-cand-name{flex:1;min-width:0;color:var(--text);font-weight:500;padding:8px 0} .rd-cand-sub{display:block;font-size:12px;color:var(--faint);font-weight:400;margin-top:2px} /* ---------- tableaux ---------- */ .rd-formula{font-size:12px;color:var(--text);background:var(--tint);border:1px solid var(--line);border-radius:6px;padding:4px 11px} .rd-table-wrap{border:1px solid var(--line-soft);border-radius:12px;overflow:hidden;background:#fff;box-shadow:var(--shadow-lg)} .rd-table{width:100%;border-collapse:collapse!important;font-size:13.5px;margin:0!important} .rd-table th{background:var(--tint);color:var(--muted);font-size:12.5px;font-weight:600;text-align:left;padding:12px 16px;border:none!important;border-bottom:1px solid var(--line)!important} .rd-table td{padding:12px 16px;border:none!important;border-bottom:1px solid var(--line-soft)!important;vertical-align:middle;color:var(--text);background:var(--surface)} .rd-table tr:last-child td{border-bottom:none!important} .rd-table tbody tr:hover td{background:#f9fbfd} .rd-right{text-align:right!important} .rd-col-rank{font-family:'IBM Plex Mono',monospace;font-weight:600;color:var(--ink)} .rd-col-name{font-weight:500} .rd-code-badge{font-size:12px;color:var(--muted);background:none!important;padding:0!important} .rd-mini{display:inline-block;background:var(--tint);border:1px solid var(--line-soft);color:var(--muted);font-size:12px;padding:1px 8px;border-radius:999px;margin:2px 4px 2px 0} .rd-scorecell{display:inline-flex;align-items:center;gap:12px;justify-content:flex-end} .rd-scorebar{width:96px;height:6px;background:#e3e8ef;border-radius:999px;overflow:hidden} .rd-scorebar i{display:block;height:100%;background:linear-gradient(90deg,#2a6fb0,var(--rag));border-radius:999px} .rd-score{font-size:12.5px;color:var(--muted);min-width:54px;text-align:right} .rd-table tr.rd-row-hit td{background:var(--ok-bg)} .rd-table tr.rd-row-hit td:first-child{box-shadow:inset 4px 0 0 var(--ok)} .rd-hit-badge{display:inline-block;background:var(--ok);color:#fff;font-size:11.5px;font-weight:500;padding:3px 11px;border-radius:999px;white-space:nowrap} .rd-answer{display:flex;align-items:baseline;gap:16px;margin-top:18px;padding:14px 20px;background:var(--ok-bg);border:1px solid var(--ok-line);border-radius:12px;flex-wrap:wrap;box-shadow:var(--shadow)} .rd-answer-label{font-size:13px;color:var(--ok)} .rd-answer-value{font-size:15px;font-weight:600;color:#114d30} .rd-answer-rank{margin-left:auto;font-family:'IBM Plex Mono',monospace;font-size:13px;color:var(--ok)} /* ---------- agent ---------- */ .rd-empty{padding:28px;border:1px dashed #b9c4d3;border-radius:12px;background:var(--tint);color:var(--muted)} .rd-empty b{color:var(--text);font-size:14.5px} .rd-empty p{margin:6px 0 0;font-size:13.5px;line-height:1.55} .rd-compare{display:grid;grid-template-columns:1fr auto 1fr;gap:22px;align-items:center;margin-bottom:20px} .rd-tile{background:#fff;border:1px solid var(--line-soft);border-radius:12px;padding:20px 24px;box-shadow:var(--shadow-lg)} .rd-tile span{display:block;font-size:13px;color:var(--muted)} .rd-tile b{display:block;font-size:38px;font-weight:500;color:var(--ink);margin-top:6px;letter-spacing:-.02em} .rd-delta{font-size:13.5px;font-weight:600;padding:7px 16px;border-radius:999px;border:1px solid var(--line);white-space:nowrap} .rd-delta-up{color:var(--ok);background:var(--ok-bg);border-color:var(--ok-line)} .rd-delta-down{color:var(--bad);background:#fbeceb;border-color:#efc3bf} .rd-delta-eq{color:var(--muted);background:var(--tint)} .rd-evo{font-family:'IBM Plex Mono',monospace;font-size:13px;font-weight:500} .rd-evo-up{color:var(--ok)}.rd-evo-down{color:var(--bad)}.rd-evo-eq{color:var(--faint)}.rd-evo-new{color:var(--llm);font-family:'IBM Plex Sans',sans-serif} .rd-details{margin-top:18px;border:1px solid var(--line-soft);border-radius:12px;padding:14px 20px;background:#fff;box-shadow:var(--shadow)} .rd-details summary{cursor:pointer;font-size:14px;font-weight:600;color:var(--ink)} .rd-details ul{margin:12px 0 2px 18px;padding:0;font-size:13.5px;color:var(--muted);line-height:1.65} /* ---------- composants Gradio ---------- */ .rd-tabs{margin-top:0!important;overflow:visible!important} .rd-tabs *{scrollbar-width:none!important} .rd-tabs *::-webkit-scrollbar{display:none!important;width:0!important;height:0!important} .rd-tabs .tab-wrapper,.rd-tabs .tab-container,.rd-tabs [role=tablist]{overflow:visible!important} .rd-tabs .overflow-menu{display:none!important} *::-webkit-scrollbar:horizontal{display:none!important;height:0!important} .rd-tabs [role=tablist],.rd-tabs .tab-nav,.rd-tabs .tab-container{border-bottom:1px solid var(--line)!important;margin-bottom:18px!important} .rd-tabs button[role=tab]{font-family:'IBM Plex Sans',sans-serif!important;font-weight:500!important;font-size:14.5px!important;color:var(--muted)!important;padding:12px 24px!important;border-radius:0!important} .rd-tabs button[role=tab]:hover{color:var(--ink)!important} .rd-tabs button[role=tab][aria-selected=true]{color:var(--accent)!important;font-weight:600!important;border-bottom:3px solid var(--accent)!important;background:transparent!important} .rd-btn-primary{background:linear-gradient(180deg,#235aa5,var(--accent-dark))!important;color:#fff!important;border:1px solid var(--accent-dark)!important;border-radius:6px!important;font-weight:500!important;font-size:14px!important;box-shadow:0 1px 2px rgba(15,31,61,.25)!important} .rd-btn-primary:hover{filter:brightness(1.08)} .rd-btn-secondary{background:var(--surface)!important;color:var(--text)!important;border:1px solid #b6c0cd!important;border-radius:6px!important;font-weight:500!important;font-size:14px!important;box-shadow:0 1px 2px rgba(15,31,61,.08)!important} .rd-btn-secondary:hover{background:var(--tint)!important} .rd-q{border:none!important;border-bottom:1px solid var(--line-soft)!important;padding:14px 0!important;background:transparent!important;box-shadow:none!important} .rd-q span[data-testid=block-info]{font-size:14px!important;font-weight:500!important;color:var(--text)!important} .rd-q label{border-radius:6px!important;background:var(--surface)!important;border:1px solid var(--line)!important;padding:6px 16px!important;font-size:13.5px!important} .rd-q label:hover{border-color:#9fb0c7!important} .rd-q label.selected{background:var(--accent)!important;color:#fff!important;border-color:var(--accent)!important} .rd-q input[type=radio]{accent-color:var(--accent)} :focus-visible{outline:2px solid var(--accent);outline-offset:1px} @media(max-width:1000px){ .rd-two,.rd-compare{grid-template-columns:1fr} .rd-brand-sub{border-left:none;padding-left:0} .rd-meta{margin-left:0} } """ # ================================================================= événements def show_case(case_id: str): case = CASES[case_id] p = diagnosis_payload(SYSTEM, AGENT, case) qs = p["questions"][:N_QUESTIONS] radios = [] for i in range(N_QUESTIONS): if i < len(qs): q = qs[i] label = f'{i + 1}. {q["name"]} ?' + (" (analyse biologique)" if q["lab"] else "") radios.append(gr.update(label=label, value="Je ne sais pas", visible=True)) else: radios.append(gr.update(visible=False, value="Je ne sais pas")) return [p, False, chips_symptoms(p), routing_html(p), lists_html(p), final_html(p, False), agent_intro_html(p), agent_result_html(p, None), *radios] def toggle_reveal(p: dict, reveal: bool): reveal = not reveal return reveal, final_html(p, reveal), gr.update(value="Masquer la bonne réponse" if reveal else "Révéler la bonne réponse") def run_agent(case_id: str, p: dict, *answers): mapping = {"Oui": "oui", "Non": "non"} given = {q["code"]: mapping.get(a, "?") for q, a in zip(p["questions"][:N_QUESTIONS], answers)} u = update_payload(SYSTEM, AGENT, CASES[case_id], given) return agent_result_html(p, u) # ================================================================= mise en page with gr.Blocks(css=CSS, title="RareDx, aide au diagnostic des maladies rares", theme=gr.themes.Base()) as demo: payload, revealed = gr.State(), gr.State(False) gr.HTML(HEADER) with gr.Tabs(elem_classes="rd-tabs") as tabs: with gr.Tab("Diagnostic initial", id="diag"): with gr.Row(equal_height=True): with gr.Column(scale=7, elem_classes="rd-card"): gr.HTML(card_head("Étape 1", "Dossier patient et phénotypes", "Sélectionnez un cas clinique public et consultez ses phénotypes HPO.")) case_dd = gr.Dropdown(choices=CHOICES, value=CHOICES[0][1], label="Dossier clinique (RareBench)", interactive=True) symptoms = gr.HTML() with gr.Column(scale=5, elem_classes="rd-card"): routing = gr.HTML() with gr.Column(elem_classes="rd-card"): lists = gr.HTML() with gr.Column(elem_classes="rd-card"): final = gr.HTML() with gr.Row(): reveal_btn = gr.Button("Révéler la bonne réponse", elem_classes="rd-btn-secondary", scale=0, min_width=240) gr.HTML("") to_agent = gr.Button("Passer à l'agent de clarification", elem_classes="rd-btn-primary", scale=0, min_width=280) with gr.Tab("Agent de clarification", id="agent"): with gr.Column(elem_classes="rd-card"): agent_intro = gr.HTML() radios = [gr.Radio(ANSWERS, value="Je ne sais pas", label=f"Question {i + 1}", elem_classes="rd-q") for i in range(N_QUESTIONS)] update_btn = gr.Button("Réévaluer le classement", elem_classes="rd-btn-primary") gr.HTML('

    Aucun appel au LLM : le RAG est relancé ' 'et la fusion recalculée immédiatement.

    ') with gr.Column(elem_classes="rd-card"): agent_result = gr.HTML() outputs = [payload, revealed, symptoms, routing, lists, final, agent_intro, agent_result, *radios] case_dd.change(show_case, case_dd, outputs).then(lambda: gr.update(value="Révéler la bonne réponse"), None, reveal_btn) demo.load(show_case, case_dd, outputs) reveal_btn.click(toggle_reveal, [payload, revealed], [revealed, final, reveal_btn]) to_agent.click(lambda: gr.Tabs(selected="agent"), None, tabs) update_btn.click(run_agent, [case_dd, payload, *radios], agent_result) if __name__ == "__main__": on_space = bool(os.environ.get("SPACE_ID")) # Hugging Face Spaces demo.launch(server_name="0.0.0.0" if on_space else "127.0.0.1", server_port=7860 if on_space else None, ssr_mode=False)