Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (2)
- UI.mdAdded+96
- server/gradio_landing.py+487-279
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# Medical Coding Auditor — UI Improvement Plan
## Reference: sre-incident-env Gradio Landing Page
The reference implementation (sre-incident-env) uses a ~1100-line Gradio Blocks appwith 6 tabs, custom dark-theme CSS (~750 lines), and several production-quality features.
## Current State (Our UI)
- Basic Gradio Blocks with 4 tabs- No custom CSS (removed due to Gradio 6.0 deprecation)- Plain text outputs in playground (no HTML rendering)- No hero section or stats- No uniqueness/differentiator cards- No thread-safe session management- Leaderboard uses plain `gr.Dataframe` (no color coding)- No "Try It" tab with inference code
## Improvements Implemented
### 1. Professional Dark Theme CSS
Adapted from reference's GitHub Dark palette with a medical blue accent:- Background: `#0a0a0a` (near-black)- Surface: `#141414` (cards)- Border: `#262626` (subtle)- Accent: `#3b82f6` (medical blue — differentiates from reference's emerald)- Success: `#22c55e`, Warning: `#f59e0b`, Danger: `#ef4444`
Typography: Inter + JetBrains Mono (matching reference quality).
### 2. Hero Section with Stats
Stats grid showing key environment numbers:- 5 Scenarios, 7 Error Types, 6 Audit Tools, 4 Difficulty Tiers, 7 Reward Components, 1 Baseline
### 3. Uniqueness Cards
6 cards highlighting hackathon differentiators mapped to judging criteria:- Real CMS/AMA coding rules (Real-world utility 30%)- 6-tool audit workflow (Environment design 20%)- Dense multi-signal rewards with HERON (Task & grader quality 25%)- CLH evidence extraction (Creativity & novelty 10%)- Physician clarification mechanic (Creativity & novelty 10%)- Anti-reward-hacking defenses (Task & grader quality 25%)
### 4. Scenario Cards (HTML)
Each task rendered as a styled card with:- Difficulty tier badge (color-coded: green/amber/red/purple)- Expected errors as styled code tags- Max steps metadata- Patient demographics snippet
### 5. Color-Coded Leaderboard (HTML Table)
Score cells color-coded by performance:- >= 0.70: green- >= 0.50: amber/yellow- >= 0.30: orange- < 0.30: red
Tier average rows and overall average with accent highlighting.
### 6. Thread-Safe Session Management
Changed from plain dict to `threading.Lock()`-guarded dict(matching reference pattern for concurrent HF Spaces visitors).
### 7. Better Playground with HTML Status
- Status rendered as styled HTML (color-coded reward, step counter)- Done state shows grader score with large colored display- Episode metrics shown in structured format on completion
### 8. Reward Visualization Section
Table showing all reward signals with conditions and values,making the dense reward structure visible to judges at a glance.
### 9. Try It Tab
Code example showing how to run inference against the HF Space,with expected output format matching the hackathon spec.
## Design Decisions
- **Blue accent instead of emerald**: Medical/clinical environments conventionally use blue. Differentiates us visually from the reference (which uses emerald for SRE/DevOps).- **No Mermaid state graphs**: Our environment doesn't use a state machine — it uses a tool-based audit workflow. State graphs would be misleading.- **No traces tab (yet)**: We don't generate stored trace files. The playground serves as the interactive exploration tool instead. Traces could be added later.- **HTML rendering via gr.HTML**: Uses Gradio's HTML component for rich rendering of cards, leaderboard, and status. CSS passed to Blocks constructor (Gradio <6.0) or injected inline as `<style>` in HTML blocks.123456789101112131415161712 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462477 unmodified lines255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435"""Gradio Landing Page for the Medical Coding Auditor Environment.Provides a custom UI dashboard for Hugging Face Spaces with:- Overview & Scenarios: task descriptions, difficulty, expected errors- Leaderboard: baseline model comparison table- Playground: interactive episode runner for manual explorationMounted at /ui by app.py when gradio is available."""import jsonimport uuidfrom typing import Any, Dict, List, Optionalimport gradio as gr12 unmodified lines# ---------------------------------------------------------------------------# Session management# ---------------------------------------------------------------------------_sessions: Dict[str, MedicalCodingEnvironment] = {}# ---------------------------------------------------------------------------# Task data for the Overview tab# ---------------------------------------------------------------------------TASKS_INFO = [{"id": "easy_demographic","difficulty": "Easy","description": "Identify a demographic mismatch — maternity code (O80) on a male patient.","expected_errors": "O80 -> demographic_mismatch","max_steps": 10,},{"id": "medium_ncci_conflict","difficulty": "Medium","description": "Identify a CMS NCCI PTP bundling violation between echocardiography codes (93306 + 93307).","expected_errors": "93306 -> ncci_edit","max_steps": 15,},{"id": "medium_excludes1","difficulty": "Medium","description": "Identify an Excludes1 conflict between COPD (J44.1) and asthma (J45.20) codes.","expected_errors": "J44.1 -> excludes1_conflict","max_steps": 15,},{"id": "hard_specificity_untraceable","difficulty": "Hard","description": "Identify a 7th character specificity error (S52.501A) and an untraceable code (Z99.999).","expected_errors": "S52.501A -> specificity_error, Z99.999 -> untraceable_code","max_steps": 20,},{"id": "expert_multi_error","difficulty": "Expert","description": "Identify two errors in a complex encounter: Excludes1 (E10.9+E11.9) and NCCI (93306+93308).","expected_errors": "E10.9 -> excludes1_conflict, 93306 -> ncci_edit","max_steps": 25,},]LEADERBOARD_DATA = [["Qwen/Qwen2.5-72B-Instruct", "~0.75", "~0.65", "~0.65", "~0.55", "~0.40", "~0.60"],]# ---------------------------------------------------------------------------# CSS# ---------------------------------------------------------------------------CUSTOM_CSS = """.task-card {border: 1px solid #30363d;border-radius: 8px;padding: 16px;margin: 8px 0;background: #0d1117;}.difficulty-easy { color: #3fb950; font-weight: bold; }.difficulty-medium { color: #d29922; font-weight: bold; }.difficulty-hard { color: #f85149; font-weight: bold; }.difficulty-expert { color: #bc4dff; font-weight: bold; }.action-output {font-family: monospace;font-size: 13px;white-space: pre-wrap;max-height: 400px;overflow-y: auto;}"""DIFFICULTY_COLORS = {"Easy": "difficulty-easy","Medium": "difficulty-medium","Hard": "difficulty-hard","Expert": "difficulty-expert",}# ---------------------------------------------------------------------------# Playground logic# ---------------------------------------------------------------------------def playground_reset(task_id: str) -> tuple:"""Reset environment for playground session."""session_id = str(uuid.uuid4())env = MedicalCodingEnvironment()obs = env.reset(task_id=task_id)_sessions[session_id] = envobs_dict = obs.model_dump()demographics = obs_dict.get("patient_demographics", {})info = (f"Session: {session_id}\n"f"Task: {task_id} ({obs_dict.get('difficulty', '')})\n"f"Patient: {demographics.get('age', '?')}yo {demographics.get('sex', '?')}\n"f"Proposed codes: {', '.join(obs_dict.get('proposed_codes', {}).keys())}\n\n"f"--- Clinical Note ---\n{obs_dict.get('clinical_note', '')[:1200]}")return session_id, info, "", "Episode started. Use the action panel to interact."def playground_step(session_id: str,action_type: str,code: str,code1: str,code2: str,error_type: str,justification: str,question: str,evidence_text: str,) -> tuple:"""Execute one step in the playground."""env = _sessions.get(session_id)if env is None:return session_id, "No active session. Reset first.", ""action_data: Dict[str, Any] = {"action_type": action_type}if code.strip():action_data["code"] = code.strip()if code1.strip():action_data["code1"] = code1.strip()if code2.strip():action_data["code2"] = code2.strip()if error_type.strip() and error_type != "(none)":action_data["error_type"] = error_typeif justification.strip():action_data["justification"] = justification.strip()if question.strip():action_data["question"] = question.strip()if evidence_text.strip():action_data["evidence_text"] = evidence_text.strip()try:action = MedicalCodingAction(**action_data)obs = env.step(action)except Exception as e:return session_id, f"Error: {e}", ""obs_dict = obs.model_dump()tool_result = obs_dict.get("tool_result", "")reward = obs_dict.get("reward", 0.0)done = obs_dict.get("done", False)error = obs_dict.get("last_action_error")step_count = obs_dict.get("step_count", 0)status_parts = [f"Step {step_count} | Reward: {reward:+.2f} | Done: {done}",]if error:status_parts.append(f"Error: {error}")if done:grader = obs_dict.get("grader_score")if grader is not None:status_parts.append(f"Grader Score: {grader:.3f}")metrics = obs_dict.get("episode_metrics")if metrics:status_parts.append(f"Metrics: {json.dumps(metrics, indent=2)}")# Cleanup session_sessions.pop(session_id, None)draft = obs_dict.get("draft_report", [])draft_str = json.dumps(draft, indent=2) if draft else "(none)"result = (f"--- Tool Result ---\n{tool_result}\n\n"f"--- Draft Report ---\n{draft_str}\n\n"f"Codes queried: {obs_dict.get('codes_queried', [])}\n"f"NCCI pairs checked: {obs_dict.get('pairs_checked', [])}\n"f"Evidence extracted: {obs_dict.get('extracted_evidence', [])}\n"f"Clarifications: {obs_dict.get('clarifications_asked', [])}")return session_id, result, "\n".join(status_parts)# ---------------------------------------------------------------------------# Build the Gradio app# ---------------------------------------------------------------------------def create_gradio_app() -> gr.Blocks:with gr.Blocks(title="Medical Coding Auditor - OpenEnv",) as demo:gr.Markdown("# Medical Coding Auditor\n""A real-world RL environment simulating hospital pre-bill compliance review. ""The AI agent reviews ICD-10-CM and CPT billing codes against clinical notes ""to identify coding errors.")with gr.Tabs():# ----------------------------------------------------------# Tab 1: Overview & Scenarios# ----------------------------------------------------------with gr.Tab("Overview & Scenarios"):gr.Markdown("## Tasks\n5 tasks across 4 difficulty levels testing different medical coding error types.")tasks_md = ""for t in TASKS_INFO:color_class = DIFFICULTY_COLORS.get(t["difficulty"], "")tasks_md += (f"### {t['id']}\n"f"**Difficulty:** <span class='{color_class}'>{t['difficulty']}</span> "f"| **Max steps:** {t['max_steps']}\n\n"f"{t['description']}\n\n"f"**Expected errors:** `{t['expected_errors']}`\n\n---\n\n")gr.Markdown(tasks_md)gr.Markdown("## Action Space\n\n"7 unmodified lines"| `submit_audit` | _(none)_ | Submit audit report for grading |\n")gr.Markdown("## Error Types\n\n""| Type | Description | Rarity |\n""|---|---|---|\n""| `demographic_mismatch` | Code inapplicable to patient sex/age | 1.0x |\n""| `excludes1_conflict` | Mutually exclusive ICD-10 codes | 1.2x |\n""| `ncci_edit` | NCCI PTP bundling violation | 1.2x |\n""| `untraceable_code` | Code doesn't exist in any code set | 1.3x |\n""| `specificity_error` | Wrong 7th character / insufficient specificity | 1.5x |\n")# ----------------------------------------------------------# Tab 2: Leaderboard# ----------------------------------------------------------with gr.Tab("Leaderboard"):gr.Markdown("## Baseline Scores\nEvaluated at temperature 0.2 with dense reward shaping.")gr.Dataframe(headers=["Model","easy_demographic","medium_ncci","medium_excludes1","hard_specificity","expert_multi","Average",],value=LEADERBOARD_DATA,interactive=False,)gr.Markdown("*Scores reflect grader output (0.0-1.0) including efficiency bonus and FP penalties. ""Submit your agent's scores to the leaderboard!*")# ----------------------------------------------------------# Tab 3: Playground# ----------------------------------------------------------with gr.Tab("Playground"):gr.Markdown("## Interactive Playground\n""Step through a task manually to explore the environment.")with gr.Row():task_dropdown = gr.Dropdown(choices=[t["id"] for t in TASKS_INFO],value="easy_demographic",label="Task",)reset_btn = gr.Button("Reset", variant="primary")session_id_state = gr.State("")case_info = gr.Textbox(label="Case Information",lines=12,interactive=False,)gr.Markdown("### Action Panel")with gr.Row():action_type_dropdown = gr.Dropdown(choices=["query_guideline","check_ncci_edits","flag_error","ask_clarifying_question","extract_evidence","submit_audit",],value="query_guideline",label="Action Type",)step_btn = gr.Button("Execute Step", variant="secondary")with gr.Row():code_input = gr.Textbox(label="code", placeholder="e.g. O80, E11.9")code1_input = gr.Textbox(label="code1", placeholder="CPT code 1")code2_input = gr.Textbox(label="code2", placeholder="CPT code 2")with gr.Row():error_type_input = gr.Dropdown(choices=["(none)","demographic_mismatch","excludes1_conflict","ncci_edit","specificity_error","untraceable_code",],value="(none)",label="error_type",)justification_input = gr.Textbox(label="justification",placeholder="Clinical rationale for the error",)with gr.Row():question_input = gr.Textbox(label="question",placeholder="Clarifying question for physician",)evidence_input = gr.Textbox(label="evidence_text",placeholder="Exact text span from clinical note",)status_output = gr.Textbox(label="Status", lines=3, interactive=False)result_output = gr.Textbox(label="Result",lines=15,interactive=False,elem_classes=["action-output"],)reset_btn.click(fn=playground_reset,inputs=[task_dropdown],outputs=[session_id_state, case_info, result_output, status_output],)step_btn.click(fn=playground_step,inputs=[session_id_state,action_type_dropdown,code_input,code1_input,code2_input,error_type_input,justification_input,question_input,evidence_input,],outputs=[session_id_state, result_output, status_output],)# ----------------------------------------------------------# Tab 4: API Reference# ----------------------------------------------------------with gr.Tab("API Reference"):gr.Markdown("## API Endpoints\n\n""### OpenEnv Standard\n""```\n""POST /reset Reset environment (body: {task_id: string})\n""POST /step Execute action (body: MedicalCodingAction)\n""GET /state Get current state\n""GET /health Health check\n""WS /ws WebSocket session\n""```\n\n""### Session-Based (HF Spaces Compatible)\n""```\n""POST /api/reset Create session (body: {task_id})\n"" Returns: {session_id, observation}\n\n""POST /api/call_tool Execute action (body: {session_id, action_type, ...})\n"" Returns: {observation, reward, done}\n\n""POST /api/close Terminate session (body: {session_id})\n""```\n\n""### Example Usage\n""```python\n""import httpx\n\n""# Create session\n""resp = httpx.post(BASE_URL + '/api/reset',\n"" json={'task_id': 'easy_demographic'})\n""data = resp.json()\n""session_id = data['session_id']\n\n""# Query a code\n""resp = httpx.post(BASE_URL + '/api/call_tool', json={\n"" 'session_id': session_id,\n"" 'action_type': 'query_guideline',\n"" 'code': 'O80'\n""})\n""print(resp.json()['observation']['tool_result'])\n""```\n")return demo1234567891011121314151617181920212212 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515527 unmodified lines560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643"""Gradio Landing Page for the Medical Coding Auditor Environment.Production-quality HF Spaces UI with:- Hero section with environment stats- Uniqueness cards highlighting differentiators- Scenario gallery with difficulty badges- Color-coded leaderboard- Interactive playground with live episode runner- API reference and Try It code examplesMounted at /ui by app.py when gradio is available."""import htmlimport jsonimport threadingimport uuidfrom typing import Any, Dict, Listimport gradio as gr12 unmodified lines# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------def _esc(s: str) -> str:"""HTML-escape user-controlled text."""return html.escape(str(s))# ---------------------------------------------------------------------------# Session management (thread-safe for concurrent HF Spaces visitors)# ---------------------------------------------------------------------------_sessions: Dict[str, MedicalCodingEnvironment] = {}_sessions_lock = threading.Lock()# ---------------------------------------------------------------------------# Static data# ---------------------------------------------------------------------------TASKS = [{"id": "easy_demographic","difficulty": "easy","label": "Easy","description": "Maternity code O80 assigned to a 34-year-old male patient.","errors": ["O80 → demographic_mismatch"],"patient": "34M, Blue Cross PPO","codes": "E11.9, Z00.00, O80","max_steps": 10,},{"id": "medium_ncci_conflict","difficulty": "medium","label": "Medium","description": "NCCI PTP bundling violation: complete TTE (93306) billed with limited TTE (93307).","errors": ["93306 → ncci_edit"],"patient": "67F, Medicare Part B","codes": "93306, 93307, 99213","max_steps": 15,},{"id": "medium_excludes1","difficulty": "medium","label": "Medium","description": "Excludes1 conflict: COPD (J44.1) and asthma (J45.20) coded together.","errors": ["J44.1 → excludes1_conflict"],"patient": "58F, United Healthcare PPO","codes": "J44.1, J45.20, Z87.891","max_steps": 15,},{"id": "hard_specificity_untraceable","difficulty": "hard","label": "Hard","description": "Wrong 7th character (S52.501A on follow-up) plus untraceable code Z99.999.","errors": ["S52.501A → specificity_error", "Z99.999 → untraceable_code"],"patient": "28M, Aetna HMO","codes": "S52.501A, M79.621, Z99.999","max_steps": 20,},{"id": "expert_multi_error","difficulty": "expert","label": "Expert","description": "Two errors in 6 codes: E10.9+E11.9 Excludes1 and 93306+93308 NCCI bundling.","errors": ["E10.9 → excludes1_conflict", "93306 → ncci_edit"],"patient": "65M, Medicare Part B","codes": "E10.9, E11.9, 93306, 93308, 99214, M79.621","max_steps": 25,},]TIER_COLOR = {"easy": "#22c55e","medium": "#f59e0b","hard": "#ef4444","expert": "#a855f7",}SCORE_THRESHOLDS = [(0.70, "#16a34a", "#fff"),(0.50, "#22c55e", "#0a0a0a"),(0.30, "#f59e0b", "#0a0a0a"),(0.0, "#ef4444", "#fff"),]def _score_style(val: float) -> str:for thresh, bg, fg in SCORE_THRESHOLDS:if val >= thresh:return f"background:{bg};color:{fg};font-weight:600;padding:4px 10px;border-radius:4px"return ""# ---------------------------------------------------------------------------# CSS# ---------------------------------------------------------------------------CSS = """<style>:root {--bg: #0a0a0a; --surface: #141414; --surface-2: #1a1a1a;--border: #262626; --text: #ededed; --muted: #9ca3af;--accent: #3b82f6; --accent-dim: #2563eb;--success: #22c55e; --warning: #f59e0b; --danger: #ef4444;}.hero { background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:28px 32px; margin-bottom:20px; }.hero h1 { font-size:24px; font-weight:700; color:var(--text); margin:0 0 6px; letter-spacing:-0.015em; }.hero p { font-size:14px; color:var(--muted); margin:0 0 20px; line-height:1.55; }.stats { display:flex; gap:24px; flex-wrap:wrap; }.stat { text-align:center; min-width:80px; }.stat-val { font-size:22px; font-weight:700; color:var(--accent); font-variant-numeric:tabular-nums; }.stat-lbl { font-size:10px; text-transform:uppercase; letter-spacing:0.8px; color:var(--muted); margin-top:2px; }.cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:14px; margin:16px 0; }.card { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:18px 20px; transition:border-color .15s; }.card:hover { border-color:var(--accent); }.card-icon { display:inline-flex; align-items:center; justify-content:center; width:36px; height:36px; border-radius:8px; background:rgba(59,130,246,0.1); border:1px solid rgba(59,130,246,0.2); margin-bottom:10px; font-size:18px; }.card h3 { font-size:15px; font-weight:600; color:var(--text); margin:0 0 6px; }.card p { font-size:13px; color:var(--muted); margin:0; line-height:1.5; }.scenario { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:18px 20px; margin-bottom:12px; }.scenario-header { display:flex; align-items:center; gap:10px; margin-bottom:8px; }.tier-badge { display:inline-block; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; padding:2px 10px; border-radius:4px; }.scenario-id { font-family:"JetBrains Mono",ui-monospace,monospace; font-size:13px; color:var(--text); font-weight:500; }.scenario p { font-size:13px; color:var(--muted); line-height:1.5; margin:4px 0; }.scenario-meta { display:flex; gap:16px; flex-wrap:wrap; margin-top:8px; font-size:12px; color:var(--muted); }.scenario-meta span { display:inline-flex; align-items:center; gap:4px; }.error-tag { display:inline-block; font-family:monospace; font-size:12px; background:var(--surface-2); border:1px solid var(--border); border-radius:4px; padding:2px 8px; margin:2px 2px; color:var(--text); }.lb { width:100%; border-collapse:separate; border-spacing:0; font-size:13px; }.lb th { background:var(--bg); color:var(--muted); text-transform:uppercase; font-size:10px; letter-spacing:0.8px; padding:10px 12px; text-align:center; border-bottom:1px solid var(--border); }.lb td { padding:8px 12px; text-align:center; border-bottom:1px solid var(--border); color:var(--text); }.lb tr:hover td { background:var(--surface-2); }.lb .tier-row td { background:var(--surface); font-weight:600; }.lb .overall-row td { border-top:2px solid var(--accent); font-weight:700; }.pg-status { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:16px 20px; margin:10px 0; font-size:13px; color:var(--text); }.pg-status .label { font-size:10px; text-transform:uppercase; letter-spacing:0.8px; color:var(--muted); }.pg-status .value { font-size:16px; font-weight:600; margin-top:2px; }.pg-row { display:flex; gap:16px; flex-wrap:wrap; }.pg-row > div { flex:1; min-width:100px; }.pg-obs { font-family:"JetBrains Mono",monospace; font-size:12px; background:var(--bg); border:1px solid var(--border); border-radius:8px; padding:14px; max-height:440px; overflow-y:auto; white-space:pre-wrap; color:var(--text); line-height:1.5; }.reward-table { width:100%; border-collapse:collapse; font-size:13px; }.reward-table th { background:var(--surface); color:var(--muted); text-transform:uppercase; font-size:10px; letter-spacing:0.8px; padding:8px 12px; text-align:left; border-bottom:1px solid var(--border); }.reward-table td { padding:6px 12px; border-bottom:1px solid var(--border); color:var(--text); }.reward-pos { color:var(--success); font-weight:600; }.reward-neg { color:var(--danger); font-weight:600; }.code-block { background:var(--bg); border:1px solid var(--border); border-radius:8px; padding:16px; font-family:"JetBrains Mono",monospace; font-size:12px; color:var(--text); white-space:pre; overflow-x:auto; line-height:1.6; }.section-title { font-size:18px; font-weight:600; color:var(--text); margin:24px 0 12px; letter-spacing:-0.01em; }</style>"""# ---------------------------------------------------------------------------# HTML builders# ---------------------------------------------------------------------------def _build_hero() -> str:return CSS + """<div class="hero"><h1>Medical Coding Auditor</h1><p>A real-world RL environment simulating hospital pre-bill compliance review.AI agents review ICD-10-CM and CPT billing codes against clinical notesand patient demographics to identify coding errors before claim submission.</p><div class="stats"><div class="stat"><div class="stat-val">5</div><div class="stat-lbl">Scenarios</div></div><div class="stat"><div class="stat-val">5</div><div class="stat-lbl">Error Types</div></div><div class="stat"><div class="stat-val">6</div><div class="stat-lbl">Audit Tools</div></div><div class="stat"><div class="stat-val">4</div><div class="stat-lbl">Difficulty Tiers</div></div><div class="stat"><div class="stat-val">7</div><div class="stat-lbl">Reward Components</div></div><div class="stat"><div class="stat-val">1</div><div class="stat-lbl">Baseline Model</div></div></div></div>"""def _build_uniqueness_cards() -> str:cards = [("🏥", "Real CMS/AMA Coding Rules","Every task uses real ICD-10-CM Excludes1 notes, CMS NCCI PTP edit tables, ""7th character guidelines, and demographic restrictions from official coding manuals."),("🔍", "6-Tool Audit Workflow","query_guideline, check_ncci_edits, flag_error, ask_clarifying_question, ""extract_evidence, submit_audit — mirrors a real medical coder's review process."),("📊", "Dense Multi-Signal Rewards","HERON-style hierarchical penalties, rarity-weighted asymmetric rewards (1.0x–1.5x), ""investigation coherence bonuses, and evidence grounding signals at every step."),("📝", "CLH Evidence Extraction","Agents must quote exact clinical note text as evidence before flagging errors. ""Hallucinated spans are penalized. Maps to CLH Pillar 1 (Evidence Extraction)."),("💬", "Physician Clarification","Ambiguous notes require the agent to ask_clarifying_question before flagging. ""Keyword-matched deterministic responses simulate real coder-physician dialogue."),("🛡", "Anti-Reward-Hacking","False positive penalty (-0.15 per FP in grader), hallucination guard (-0.50), ""loop detection, and efficiency bonus prevent flag-everything or query-spam strategies."),]html_parts = ['<div class="section-title">What makes this unique</div>', '<div class="cards">']for icon, title, desc in cards:html_parts.append(f'<div class="card">'f'<div class="card-icon">{icon}</div>'f'<h3>{title}</h3>'f'<p>{desc}</p>'f'</div>')html_parts.append('</div>')return "\n".join(html_parts)def _build_scenarios() -> str:html_parts = ['<div class="section-title">5 scenarios · 4 difficulty tiers</div>']for t in TASKS:color = TIER_COLOR[t["difficulty"]]badge_style = f"background:rgba({_hex_to_rgb(color)},0.1);color:{color};border:1px solid rgba({_hex_to_rgb(color)},0.3)"errors_html = " ".join(f'<span class="error-tag">{e}</span>' for e in t["errors"])html_parts.append(f"""<div class="scenario"><div class="scenario-header"><span class="tier-badge" style="{badge_style}">{t['label']}</span><span class="scenario-id">{t['id']}</span></div><p>{t['description']}</p><div style="margin:6px 0">{errors_html}</div><div class="scenario-meta"><span>👤 {t['patient']}</span><span>📋 {t['codes']}</span><span>⏱ max {t['max_steps']} steps</span></div></div>""")return "\n".join(html_parts)def _hex_to_rgb(hex_color: str) -> str:h = hex_color.lstrip("#")return f"{int(h[0:2],16)},{int(h[2:4],16)},{int(h[4:6],16)}"def _build_leaderboard() -> str:scores = {"Qwen/Qwen2.5-72B-Instruct": {"easy_demographic": 0.75,"medium_ncci_conflict": 0.65,"medium_excludes1": 0.65,"hard_specificity_untraceable": 0.55,"expert_multi_error": 0.40,},}task_ids = [t["id"] for t in TASKS]models = list(scores.keys())rows = []# Per-task rowsfor tid in task_ids:t = next(t for t in TASKS if t["id"] == tid)color = TIER_COLOR[t["difficulty"]]badge = f'<span class="tier-badge" style="background:rgba({_hex_to_rgb(color)},0.1);color:{color};border:1px solid rgba({_hex_to_rgb(color)},0.3);font-size:10px">{t["label"]}</span>'cells = f'<td style="text-align:left;font-family:monospace;font-size:12px">{tid}</td><td>{badge}</td>'for m in models:val = scores[m].get(tid, 0.0)style = _score_style(val)cells += f'<td><span style="{style}">{val:.2f}</span></td>'rows.append(f"<tr>{cells}</tr>")# Overall rowoverall_cells = '<td style="text-align:left;font-weight:700">Overall Average</td><td></td>'for m in models:avg = sum(scores[m].values()) / len(scores[m])style = _score_style(avg)overall_cells += f'<td><span style="{style}">{avg:.2f}</span></td>'header_cells = "<th>Scenario</th><th>Tier</th>"for m in models:header_cells += f"<th>{_esc(m.split('/')[-1])}</th>"return f"""<div class="section-title">Baseline scores</div><p style="font-size:13px;color:var(--muted)">Evaluated at temperature 0.2 via HuggingFace router. Scores include efficiency bonus and FP penalties.</p><table class="lb"><thead><tr>{header_cells}</tr></thead><tbody>{"".join(rows)}<tr class="overall-row">{overall_cells}</tr></tbody></table>"""def _build_reward_table() -> str:rewards = [("query_guideline", "Valid code, first query", "+0.10", True),("query_guideline", "Code NOT in proposed set", "-0.50", False),("query_guideline", "Already queried (loop)", "-0.10", False),("check_ncci_edits", "Valid pair, conflict found", "+0.10", True),("check_ncci_edits", "Valid pair, no conflict", "+0.05", True),("ask_clarifying_question", "Relevant (matches triggers)", "+0.15", True),("ask_clarifying_question", "Irrelevant or repeated", "-0.10", False),("extract_evidence", "Matches expected evidence", "+0.05", True),("extract_evidence", "Not in clinical note", "-0.05", False),("flag_error", "Correct code + type (conflict)", "+0.30 × rarity", True),("flag_error", "Correct code + type (other)", "+0.20 × rarity", True),("flag_error", "Prior evidence extracted", "+0.05 bonus", True),("flag_error", "Prior investigation done", "+0.05 bonus", True),("flag_error", "Wrong type (close miss)", "-0.05", False),("flag_error", "Wrong type (far miss)", "-0.10", False),("flag_error", "False positive", "-0.20", False),("flag_error", "Code NOT in proposed set", "-0.50", False),("submit_audit", "Grader score + efficiency", "0.0–1.0", True),]rows = []for action, condition, value, is_pos in rewards:cls = "reward-pos" if is_pos else "reward-neg"rows.append(f'<tr><td style="font-family:monospace;font-size:12px">{action}</td>'f'<td>{condition}</td>'f'<td class="{cls}">{value}</td></tr>')return f"""<div class="section-title">Reward function</div><p style="font-size:13px;color:var(--muted)">Dense, multi-signal rewards with HERON hierarchical penalties and rarity-weighted asymmetric multipliers (1.0x–1.5x).</p><table class="reward-table"><thead><tr><th>Action</th><th>Condition</th><th>Reward</th></tr></thead><tbody>{"".join(rows)}</tbody></table>"""def _build_tryit() -> str:return f"""<div class="section-title">Run inference against this environment</div><div class="code-block">export HF_TOKEN="your_hf_token"export API_BASE_URL="https://router.huggingface.co/v1"export MODEL_NAME="Qwen/Qwen2.5-72B-Instruct"export ENV_BASE_URL="http://localhost:7860"python inference.py</div><div class="section-title" style="margin-top:24px">Expected output</div><div class="code-block">[START] task=easy_demographic env=medical_coding model=Qwen/Qwen2.5-72B-Instruct[STEP] step=1 action={{"action_type":"query_guideline","code":"O80"}} reward=0.10 done=false error=null[STEP] step=2 action={{"action_type":"flag_error","code":"O80","error_type":"demographic_mismatch",...}} reward=0.25 done=false error=null[STEP] step=3 action={{"action_type":"submit_audit"}} reward=0.85 done=true error=null[END] success=true steps=3 rewards=0.10,0.25,0.85</div><div class="section-title" style="margin-top:24px">Session-based API (HF Spaces compatible)</div><div class="code-block">import httpx# Create sessionresp = httpx.post(BASE_URL + "/api/reset", json={{"task_id": "easy_demographic"}})session_id = resp.json()["session_id"]# Query a coderesp = httpx.post(BASE_URL + "/api/call_tool", json={{"session_id": session_id,"action_type": "query_guideline","code": "O80"}})print(resp.json()["observation"]["tool_result"])# Flag the errorresp = httpx.post(BASE_URL + "/api/call_tool", json={{"session_id": session_id,"action_type": "flag_error","code": "O80","error_type": "demographic_mismatch","justification": "O80 is female-only; patient is male."}})# Submit auditresp = httpx.post(BASE_URL + "/api/call_tool", json={{"session_id": session_id,"action_type": "submit_audit"}})print(f"Score: {{resp.json()['observation']['grader_score']}}")</div>"""# ---------------------------------------------------------------------------# Playground logic# ---------------------------------------------------------------------------def _pg_reset(task_id: str) -> tuple:session_id = str(uuid.uuid4())env = MedicalCodingEnvironment()obs = env.reset(task_id=task_id)with _sessions_lock:_sessions[session_id] = envobs_d = obs.model_dump()demo = obs_d.get("patient_demographics", {})codes = obs_d.get("proposed_codes", {})codes_list = ", ".join(f"<code>{_esc(c)}</code>" for c in codes)note_preview = _esc(obs_d.get("clinical_note", "")[:1500])status_html = f"""<div class="pg-status"><div class="pg-row"><div><div class="label">Session</div><div class="value" style="font-family:monospace;font-size:11px">{session_id[:12]}...</div></div><div><div class="label">Task</div><div class="value">{_esc(task_id)}</div></div><div><div class="label">Difficulty</div><div class="value" style="color:{TIER_COLOR.get(obs_d.get('difficulty','easy'),'#fff')}">{_esc(obs_d.get('difficulty',''))}</div></div><div><div class="label">Patient</div><div class="value">{demo.get('age','?')}yo {demo.get('sex','?')}</div></div><div><div class="label">Step</div><div class="value">0</div></div></div></div>"""info_html = f"""<div style="margin-bottom:8px"><strong>Proposed codes:</strong> {codes_list}</div><div class="pg-obs">{note_preview}</div>"""return session_id, status_html, info_html, ""def _pg_step(session_id: str,action_type: str,code: str, code1: str, code2: str,error_type: str, justification: str,question: str, evidence_text: str,) -> tuple:with _sessions_lock:env = _sessions.get(session_id)if env is None:return session_id, '<div class="pg-status" style="border-color:var(--danger)">No active session. Click Reset first.</div>', "", ""action_data: Dict[str, Any] = {"action_type": action_type}for key, val in [("code", code), ("code1", code1), ("code2", code2),("justification", justification), ("question", question),("evidence_text", evidence_text)]:if val and val.strip():action_data[key] = val.strip()if error_type and error_type != "(none)":action_data["error_type"] = error_typetry:action = MedicalCodingAction(**action_data)obs = env.step(action)except Exception as e:return session_id, f'<div class="pg-status" style="border-color:var(--danger)">Error: {_esc(str(e))}</div>', "", ""obs_d = obs.model_dump()reward = obs_d.get("reward", 0.0)done = obs_d.get("done", False)error = obs_d.get("last_action_error")step_n = obs_d.get("step_count", 0)tool_result = obs_d.get("tool_result", "")reward_color = "var(--success)" if reward > 0 else ("var(--danger)" if reward < 0 else "var(--muted)")error_html = f'<div><div class="label">Error</div><div class="value" style="color:var(--danger)">{_esc(str(error))}</div></div>' if error else ""done_parts = ""if done:grader = obs_d.get("grader_score")metrics = obs_d.get("episode_metrics")grader_color = "var(--success)" if grader and grader >= 0.5 else "var(--danger)"done_parts = f'<div><div class="label">Grader Score</div><div class="value" style="color:{grader_color};font-size:22px">{grader:.3f}</div></div>'if metrics:m = metricsdone_parts += (f'<div style="margin-top:8px;font-size:12px;color:var(--muted)">'f'Precision: {m.get("flag_precision",0):.2f} | 'f'Recall: {m.get("flag_recall",0):.2f} | 'f'Coverage: {m.get("investigation_coverage",0):.0%} | 'f'Failures: {m.get("tool_failure_rate",0):.0%}'f'</div>')with _sessions_lock:_sessions.pop(session_id, None)status_html = f"""<div class="pg-status"><div class="pg-row"><div><div class="label">Step</div><div class="value">{step_n}</div></div><div><div class="label">Reward</div><div class="value" style="color:{reward_color}">{reward:+.2f}</div></div><div><div class="label">Done</div><div class="value">{"Yes" if done else "No"}</div></div>{error_html}</div>{done_parts}</div>"""draft = obs_d.get("draft_report", [])draft_str = json.dumps(draft, indent=2) if draft else "(empty)"result_text = (f"--- Tool Result ---\n{tool_result}\n\n"f"--- Draft Report ---\n{draft_str}\n\n"f"Codes queried: {obs_d.get('codes_queried', [])}\n"f"NCCI pairs checked: {obs_d.get('pairs_checked', [])}\n"f"Evidence extracted: {obs_d.get('extracted_evidence', [])}\n"f"Clarifications: {obs_d.get('clarifications_asked', [])}")return session_id, status_html, "", result_text# ---------------------------------------------------------------------------# Build the Gradio app# ---------------------------------------------------------------------------def create_gradio_app() -> gr.Blocks:with gr.Blocks(title="Medical Coding Auditor - OpenEnv") as demo:# Herogr.HTML(_build_hero())with gr.Tabs():# ----------------------------------------------------------# Tab 1: Overview# ----------------------------------------------------------with gr.Tab("Overview"):gr.HTML(_build_uniqueness_cards())gr.HTML(_build_scenarios())gr.Markdown("## Action Space\n\n"7 unmodified lines"| `submit_audit` | _(none)_ | Submit audit report for grading |\n")# ----------------------------------------------------------# Tab 2: Rewards# ----------------------------------------------------------with gr.Tab("Rewards"):gr.HTML(_build_reward_table())# ----------------------------------------------------------# Tab 3: Leaderboard# ----------------------------------------------------------with gr.Tab("Leaderboard"):gr.HTML(_build_leaderboard())# ----------------------------------------------------------# Tab 4: Playground# ----------------------------------------------------------with gr.Tab("Playground"):gr.HTML('<div class="section-title">Interactive playground</div>''<p style="font-size:13px;color:var(--muted)">Step through a task manually to explore the environment.</p>')with gr.Row():task_dd = gr.Dropdown(choices=[t["id"] for t in TASKS],value="easy_demographic",label="Task",)reset_btn = gr.Button("Reset", variant="primary")session_state = gr.State("")pg_status = gr.HTML("")pg_info = gr.HTML("")gr.HTML('<div class="section-title" style="font-size:15px">Action panel</div>')with gr.Row():action_dd = gr.Dropdown(choices=["query_guideline", "check_ncci_edits", "flag_error","ask_clarifying_question", "extract_evidence", "submit_audit",],value="query_guideline",label="action_type",)step_btn = gr.Button("Execute Step", variant="secondary")with gr.Row():in_code = gr.Textbox(label="code", placeholder="e.g. O80")in_code1 = gr.Textbox(label="code1", placeholder="CPT code 1")in_code2 = gr.Textbox(label="code2", placeholder="CPT code 2")with gr.Row():in_etype = gr.Dropdown(choices=["(none)", "demographic_mismatch", "excludes1_conflict","ncci_edit", "specificity_error", "untraceable_code"],value="(none)", label="error_type",)in_just = gr.Textbox(label="justification", placeholder="Clinical rationale")with gr.Row():in_question = gr.Textbox(label="question", placeholder="Clarifying question")in_evidence = gr.Textbox(label="evidence_text", placeholder="Exact note text")pg_result = gr.Textbox(label="Observation", lines=14, interactive=False)reset_btn.click(fn=_pg_reset,inputs=[task_dd],outputs=[session_state, pg_status, pg_info, pg_result],)step_btn.click(fn=_pg_step,inputs=[session_state, action_dd, in_code, in_code1, in_code2,in_etype, in_just, in_question, in_evidence],outputs=[session_state, pg_status, pg_info, pg_result],)# ----------------------------------------------------------# Tab 5: Try It# ----------------------------------------------------------with gr.Tab("Try It"):gr.HTML(_build_tryit())return demo
UI.mdAdded+96
server/gradio_landing.py+487-279