Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- UI.md +96 -0
- server/gradio_landing.py +487 -279
UI.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Medical Coding Auditor — UI Improvement Plan
|
| 2 |
+
|
| 3 |
+
## Reference: sre-incident-env Gradio Landing Page
|
| 4 |
+
|
| 5 |
+
The reference implementation (sre-incident-env) uses a ~1100-line Gradio Blocks app
|
| 6 |
+
with 6 tabs, custom dark-theme CSS (~750 lines), and several production-quality features.
|
| 7 |
+
|
| 8 |
+
## Current State (Our UI)
|
| 9 |
+
|
| 10 |
+
- Basic Gradio Blocks with 4 tabs
|
| 11 |
+
- No custom CSS (removed due to Gradio 6.0 deprecation)
|
| 12 |
+
- Plain text outputs in playground (no HTML rendering)
|
| 13 |
+
- No hero section or stats
|
| 14 |
+
- No uniqueness/differentiator cards
|
| 15 |
+
- No thread-safe session management
|
| 16 |
+
- Leaderboard uses plain `gr.Dataframe` (no color coding)
|
| 17 |
+
- No "Try It" tab with inference code
|
| 18 |
+
|
| 19 |
+
## Improvements Implemented
|
| 20 |
+
|
| 21 |
+
### 1. Professional Dark Theme CSS
|
| 22 |
+
|
| 23 |
+
Adapted from reference's GitHub Dark palette with a medical blue accent:
|
| 24 |
+
- Background: `#0a0a0a` (near-black)
|
| 25 |
+
- Surface: `#141414` (cards)
|
| 26 |
+
- Border: `#262626` (subtle)
|
| 27 |
+
- Accent: `#3b82f6` (medical blue — differentiates from reference's emerald)
|
| 28 |
+
- Success: `#22c55e`, Warning: `#f59e0b`, Danger: `#ef4444`
|
| 29 |
+
|
| 30 |
+
Typography: Inter + JetBrains Mono (matching reference quality).
|
| 31 |
+
|
| 32 |
+
### 2. Hero Section with Stats
|
| 33 |
+
|
| 34 |
+
Stats grid showing key environment numbers:
|
| 35 |
+
- 5 Scenarios, 7 Error Types, 6 Audit Tools, 4 Difficulty Tiers, 7 Reward Components, 1 Baseline
|
| 36 |
+
|
| 37 |
+
### 3. Uniqueness Cards
|
| 38 |
+
|
| 39 |
+
6 cards highlighting hackathon differentiators mapped to judging criteria:
|
| 40 |
+
- Real CMS/AMA coding rules (Real-world utility 30%)
|
| 41 |
+
- 6-tool audit workflow (Environment design 20%)
|
| 42 |
+
- Dense multi-signal rewards with HERON (Task & grader quality 25%)
|
| 43 |
+
- CLH evidence extraction (Creativity & novelty 10%)
|
| 44 |
+
- Physician clarification mechanic (Creativity & novelty 10%)
|
| 45 |
+
- Anti-reward-hacking defenses (Task & grader quality 25%)
|
| 46 |
+
|
| 47 |
+
### 4. Scenario Cards (HTML)
|
| 48 |
+
|
| 49 |
+
Each task rendered as a styled card with:
|
| 50 |
+
- Difficulty tier badge (color-coded: green/amber/red/purple)
|
| 51 |
+
- Expected errors as styled code tags
|
| 52 |
+
- Max steps metadata
|
| 53 |
+
- Patient demographics snippet
|
| 54 |
+
|
| 55 |
+
### 5. Color-Coded Leaderboard (HTML Table)
|
| 56 |
+
|
| 57 |
+
Score cells color-coded by performance:
|
| 58 |
+
- >= 0.70: green
|
| 59 |
+
- >= 0.50: amber/yellow
|
| 60 |
+
- >= 0.30: orange
|
| 61 |
+
- < 0.30: red
|
| 62 |
+
|
| 63 |
+
Tier average rows and overall average with accent highlighting.
|
| 64 |
+
|
| 65 |
+
### 6. Thread-Safe Session Management
|
| 66 |
+
|
| 67 |
+
Changed from plain dict to `threading.Lock()`-guarded dict
|
| 68 |
+
(matching reference pattern for concurrent HF Spaces visitors).
|
| 69 |
+
|
| 70 |
+
### 7. Better Playground with HTML Status
|
| 71 |
+
|
| 72 |
+
- Status rendered as styled HTML (color-coded reward, step counter)
|
| 73 |
+
- Done state shows grader score with large colored display
|
| 74 |
+
- Episode metrics shown in structured format on completion
|
| 75 |
+
|
| 76 |
+
### 8. Reward Visualization Section
|
| 77 |
+
|
| 78 |
+
Table showing all reward signals with conditions and values,
|
| 79 |
+
making the dense reward structure visible to judges at a glance.
|
| 80 |
+
|
| 81 |
+
### 9. Try It Tab
|
| 82 |
+
|
| 83 |
+
Code example showing how to run inference against the HF Space,
|
| 84 |
+
with expected output format matching the hackathon spec.
|
| 85 |
+
|
| 86 |
+
## Design Decisions
|
| 87 |
+
|
| 88 |
+
- **Blue accent instead of emerald**: Medical/clinical environments conventionally use blue.
|
| 89 |
+
Differentiates us visually from the reference (which uses emerald for SRE/DevOps).
|
| 90 |
+
- **No Mermaid state graphs**: Our environment doesn't use a state machine — it uses
|
| 91 |
+
a tool-based audit workflow. State graphs would be misleading.
|
| 92 |
+
- **No traces tab (yet)**: We don't generate stored trace files. The playground serves
|
| 93 |
+
as the interactive exploration tool instead. Traces could be added later.
|
| 94 |
+
- **HTML rendering via gr.HTML**: Uses Gradio's HTML component for rich rendering
|
| 95 |
+
of cards, leaderboard, and status. CSS passed to Blocks constructor (Gradio <6.0)
|
| 96 |
+
or injected inline as `<style>` in HTML blocks.
|
server/gradio_landing.py
CHANGED
|
@@ -1,17 +1,22 @@
|
|
| 1 |
"""
|
| 2 |
Gradio Landing Page for the Medical Coding Auditor Environment.
|
| 3 |
|
| 4 |
-
|
| 5 |
-
-
|
| 6 |
-
-
|
| 7 |
-
-
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
Mounted at /ui by app.py when gradio is available.
|
| 10 |
"""
|
| 11 |
|
|
|
|
| 12 |
import json
|
|
|
|
| 13 |
import uuid
|
| 14 |
-
from typing import Any, Dict, List
|
| 15 |
|
| 16 |
import gradio as gr
|
| 17 |
|
|
@@ -30,218 +35,518 @@ except ImportError:
|
|
| 30 |
|
| 31 |
|
| 32 |
# ---------------------------------------------------------------------------
|
| 33 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# ---------------------------------------------------------------------------
|
| 35 |
_sessions: Dict[str, MedicalCodingEnvironment] = {}
|
|
|
|
|
|
|
| 36 |
|
| 37 |
# ---------------------------------------------------------------------------
|
| 38 |
-
#
|
| 39 |
# ---------------------------------------------------------------------------
|
| 40 |
-
|
| 41 |
{
|
| 42 |
"id": "easy_demographic",
|
| 43 |
-
"difficulty": "
|
| 44 |
-
"
|
| 45 |
-
"
|
|
|
|
|
|
|
|
|
|
| 46 |
"max_steps": 10,
|
| 47 |
},
|
| 48 |
{
|
| 49 |
"id": "medium_ncci_conflict",
|
| 50 |
-
"difficulty": "
|
| 51 |
-
"
|
| 52 |
-
"
|
|
|
|
|
|
|
|
|
|
| 53 |
"max_steps": 15,
|
| 54 |
},
|
| 55 |
{
|
| 56 |
"id": "medium_excludes1",
|
| 57 |
-
"difficulty": "
|
| 58 |
-
"
|
| 59 |
-
"
|
|
|
|
|
|
|
|
|
|
| 60 |
"max_steps": 15,
|
| 61 |
},
|
| 62 |
{
|
| 63 |
"id": "hard_specificity_untraceable",
|
| 64 |
-
"difficulty": "
|
| 65 |
-
"
|
| 66 |
-
"
|
|
|
|
|
|
|
|
|
|
| 67 |
"max_steps": 20,
|
| 68 |
},
|
| 69 |
{
|
| 70 |
"id": "expert_multi_error",
|
| 71 |
-
"difficulty": "
|
| 72 |
-
"
|
| 73 |
-
"
|
|
|
|
|
|
|
|
|
|
| 74 |
"max_steps": 25,
|
| 75 |
},
|
| 76 |
]
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
]
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
# ---------------------------------------------------------------------------
|
| 83 |
# CSS
|
| 84 |
# ---------------------------------------------------------------------------
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
}
|
| 93 |
-
.difficulty-easy { color: #3fb950; font-weight: bold; }
|
| 94 |
-
.difficulty-medium { color: #d29922; font-weight: bold; }
|
| 95 |
-
.difficulty-hard { color: #f85149; font-weight: bold; }
|
| 96 |
-
.difficulty-expert { color: #bc4dff; font-weight: bold; }
|
| 97 |
-
.action-output {
|
| 98 |
-
font-family: monospace;
|
| 99 |
-
font-size: 13px;
|
| 100 |
-
white-space: pre-wrap;
|
| 101 |
-
max-height: 400px;
|
| 102 |
-
overflow-y: auto;
|
| 103 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
"""
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
|
| 114 |
# ---------------------------------------------------------------------------
|
| 115 |
# Playground logic
|
| 116 |
# ---------------------------------------------------------------------------
|
| 117 |
-
|
| 118 |
-
|
| 119 |
session_id = str(uuid.uuid4())
|
| 120 |
env = MedicalCodingEnvironment()
|
| 121 |
obs = env.reset(task_id=task_id)
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
|
| 137 |
-
def
|
| 138 |
session_id: str,
|
| 139 |
action_type: str,
|
| 140 |
-
code: str,
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
error_type: str,
|
| 144 |
-
justification: str,
|
| 145 |
-
question: str,
|
| 146 |
-
evidence_text: str,
|
| 147 |
) -> tuple:
|
| 148 |
-
|
| 149 |
-
|
| 150 |
if env is None:
|
| 151 |
-
return session_id, "No active session. Reset first.", ""
|
| 152 |
|
| 153 |
action_data: Dict[str, Any] = {"action_type": action_type}
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
if error_type.strip() and error_type != "(none)":
|
| 161 |
action_data["error_type"] = error_type
|
| 162 |
-
if justification.strip():
|
| 163 |
-
action_data["justification"] = justification.strip()
|
| 164 |
-
if question.strip():
|
| 165 |
-
action_data["question"] = question.strip()
|
| 166 |
-
if evidence_text.strip():
|
| 167 |
-
action_data["evidence_text"] = evidence_text.strip()
|
| 168 |
|
| 169 |
try:
|
| 170 |
action = MedicalCodingAction(**action_data)
|
| 171 |
obs = env.step(action)
|
| 172 |
except Exception as e:
|
| 173 |
-
return session_id, f"Error: {e}", ""
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
status_parts.append(f"Error: {error}")
|
| 187 |
if done:
|
| 188 |
-
grader =
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
if metrics:
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
f"--- Tool Result ---\n{tool_result}\n\n"
|
| 202 |
f"--- Draft Report ---\n{draft_str}\n\n"
|
| 203 |
-
f"Codes queried: {
|
| 204 |
-
f"NCCI pairs checked: {
|
| 205 |
-
f"Evidence extracted: {
|
| 206 |
-
f"Clarifications: {
|
| 207 |
)
|
| 208 |
|
| 209 |
-
return session_id,
|
| 210 |
|
| 211 |
|
| 212 |
# ---------------------------------------------------------------------------
|
| 213 |
# Build the Gradio app
|
| 214 |
# ---------------------------------------------------------------------------
|
| 215 |
def create_gradio_app() -> gr.Blocks:
|
| 216 |
-
with gr.Blocks(
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
gr.Markdown(
|
| 221 |
-
"# Medical Coding Auditor\n"
|
| 222 |
-
"A real-world RL environment simulating hospital pre-bill compliance review. "
|
| 223 |
-
"The AI agent reviews ICD-10-CM and CPT billing codes against clinical notes "
|
| 224 |
-
"to identify coding errors."
|
| 225 |
-
)
|
| 226 |
|
| 227 |
with gr.Tabs():
|
| 228 |
# ----------------------------------------------------------
|
| 229 |
-
# Tab 1: Overview
|
| 230 |
# ----------------------------------------------------------
|
| 231 |
-
with gr.Tab("Overview
|
| 232 |
-
gr.
|
| 233 |
-
|
| 234 |
-
tasks_md = ""
|
| 235 |
-
for t in TASKS_INFO:
|
| 236 |
-
color_class = DIFFICULTY_COLORS.get(t["difficulty"], "")
|
| 237 |
-
tasks_md += (
|
| 238 |
-
f"### {t['id']}\n"
|
| 239 |
-
f"**Difficulty:** <span class='{color_class}'>{t['difficulty']}</span> "
|
| 240 |
-
f"| **Max steps:** {t['max_steps']}\n\n"
|
| 241 |
-
f"{t['description']}\n\n"
|
| 242 |
-
f"**Expected errors:** `{t['expected_errors']}`\n\n---\n\n"
|
| 243 |
-
)
|
| 244 |
-
gr.Markdown(tasks_md)
|
| 245 |
|
| 246 |
gr.Markdown(
|
| 247 |
"## Action Space\n\n"
|
|
@@ -255,181 +560,84 @@ def create_gradio_app() -> gr.Blocks:
|
|
| 255 |
"| `submit_audit` | _(none)_ | Submit audit report for grading |\n"
|
| 256 |
)
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
"| `excludes1_conflict` | Mutually exclusive ICD-10 codes | 1.2x |\n"
|
| 264 |
-
"| `ncci_edit` | NCCI PTP bundling violation | 1.2x |\n"
|
| 265 |
-
"| `untraceable_code` | Code doesn't exist in any code set | 1.3x |\n"
|
| 266 |
-
"| `specificity_error` | Wrong 7th character / insufficient specificity | 1.5x |\n"
|
| 267 |
-
)
|
| 268 |
|
| 269 |
# ----------------------------------------------------------
|
| 270 |
-
# Tab
|
| 271 |
# ----------------------------------------------------------
|
| 272 |
with gr.Tab("Leaderboard"):
|
| 273 |
-
gr.
|
| 274 |
-
gr.Dataframe(
|
| 275 |
-
headers=[
|
| 276 |
-
"Model",
|
| 277 |
-
"easy_demographic",
|
| 278 |
-
"medium_ncci",
|
| 279 |
-
"medium_excludes1",
|
| 280 |
-
"hard_specificity",
|
| 281 |
-
"expert_multi",
|
| 282 |
-
"Average",
|
| 283 |
-
],
|
| 284 |
-
value=LEADERBOARD_DATA,
|
| 285 |
-
interactive=False,
|
| 286 |
-
)
|
| 287 |
-
gr.Markdown(
|
| 288 |
-
"*Scores reflect grader output (0.0-1.0) including efficiency bonus and FP penalties. "
|
| 289 |
-
"Submit your agent's scores to the leaderboard!*"
|
| 290 |
-
)
|
| 291 |
|
| 292 |
# ----------------------------------------------------------
|
| 293 |
-
# Tab
|
| 294 |
# ----------------------------------------------------------
|
| 295 |
with gr.Tab("Playground"):
|
| 296 |
-
gr.
|
| 297 |
-
|
| 298 |
-
"Step through a task manually to explore the environment."
|
| 299 |
-
)
|
| 300 |
|
| 301 |
with gr.Row():
|
| 302 |
-
|
| 303 |
-
choices=[t["id"] for t in
|
| 304 |
value="easy_demographic",
|
| 305 |
label="Task",
|
| 306 |
)
|
| 307 |
reset_btn = gr.Button("Reset", variant="primary")
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
label="Case Information",
|
| 313 |
-
lines=12,
|
| 314 |
-
interactive=False,
|
| 315 |
-
)
|
| 316 |
|
| 317 |
-
gr.
|
| 318 |
with gr.Row():
|
| 319 |
-
|
| 320 |
choices=[
|
| 321 |
-
"query_guideline",
|
| 322 |
-
"
|
| 323 |
-
"flag_error",
|
| 324 |
-
"ask_clarifying_question",
|
| 325 |
-
"extract_evidence",
|
| 326 |
-
"submit_audit",
|
| 327 |
],
|
| 328 |
value="query_guideline",
|
| 329 |
-
label="
|
| 330 |
)
|
| 331 |
step_btn = gr.Button("Execute Step", variant="secondary")
|
| 332 |
|
| 333 |
with gr.Row():
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
|
| 338 |
with gr.Row():
|
| 339 |
-
|
| 340 |
-
choices=[
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
"excludes1_conflict",
|
| 344 |
-
"ncci_edit",
|
| 345 |
-
"specificity_error",
|
| 346 |
-
"untraceable_code",
|
| 347 |
-
],
|
| 348 |
-
value="(none)",
|
| 349 |
-
label="error_type",
|
| 350 |
-
)
|
| 351 |
-
justification_input = gr.Textbox(
|
| 352 |
-
label="justification",
|
| 353 |
-
placeholder="Clinical rationale for the error",
|
| 354 |
)
|
|
|
|
| 355 |
|
| 356 |
with gr.Row():
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
placeholder="Clarifying question for physician",
|
| 360 |
-
)
|
| 361 |
-
evidence_input = gr.Textbox(
|
| 362 |
-
label="evidence_text",
|
| 363 |
-
placeholder="Exact text span from clinical note",
|
| 364 |
-
)
|
| 365 |
|
| 366 |
-
|
| 367 |
-
result_output = gr.Textbox(
|
| 368 |
-
label="Result",
|
| 369 |
-
lines=15,
|
| 370 |
-
interactive=False,
|
| 371 |
-
elem_classes=["action-output"],
|
| 372 |
-
)
|
| 373 |
|
| 374 |
reset_btn.click(
|
| 375 |
-
fn=
|
| 376 |
-
inputs=[
|
| 377 |
-
outputs=[
|
| 378 |
)
|
| 379 |
step_btn.click(
|
| 380 |
-
fn=
|
| 381 |
-
inputs=[
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
code_input,
|
| 385 |
-
code1_input,
|
| 386 |
-
code2_input,
|
| 387 |
-
error_type_input,
|
| 388 |
-
justification_input,
|
| 389 |
-
question_input,
|
| 390 |
-
evidence_input,
|
| 391 |
-
],
|
| 392 |
-
outputs=[session_id_state, result_output, status_output],
|
| 393 |
)
|
| 394 |
|
| 395 |
# ----------------------------------------------------------
|
| 396 |
-
# Tab
|
| 397 |
# ----------------------------------------------------------
|
| 398 |
-
with gr.Tab("
|
| 399 |
-
gr.
|
| 400 |
-
"## API Endpoints\n\n"
|
| 401 |
-
"### OpenEnv Standard\n"
|
| 402 |
-
"```\n"
|
| 403 |
-
"POST /reset Reset environment (body: {task_id: string})\n"
|
| 404 |
-
"POST /step Execute action (body: MedicalCodingAction)\n"
|
| 405 |
-
"GET /state Get current state\n"
|
| 406 |
-
"GET /health Health check\n"
|
| 407 |
-
"WS /ws WebSocket session\n"
|
| 408 |
-
"```\n\n"
|
| 409 |
-
"### Session-Based (HF Spaces Compatible)\n"
|
| 410 |
-
"```\n"
|
| 411 |
-
"POST /api/reset Create session (body: {task_id})\n"
|
| 412 |
-
" Returns: {session_id, observation}\n\n"
|
| 413 |
-
"POST /api/call_tool Execute action (body: {session_id, action_type, ...})\n"
|
| 414 |
-
" Returns: {observation, reward, done}\n\n"
|
| 415 |
-
"POST /api/close Terminate session (body: {session_id})\n"
|
| 416 |
-
"```\n\n"
|
| 417 |
-
"### Example Usage\n"
|
| 418 |
-
"```python\n"
|
| 419 |
-
"import httpx\n\n"
|
| 420 |
-
"# Create session\n"
|
| 421 |
-
"resp = httpx.post(BASE_URL + '/api/reset',\n"
|
| 422 |
-
" json={'task_id': 'easy_demographic'})\n"
|
| 423 |
-
"data = resp.json()\n"
|
| 424 |
-
"session_id = data['session_id']\n\n"
|
| 425 |
-
"# Query a code\n"
|
| 426 |
-
"resp = httpx.post(BASE_URL + '/api/call_tool', json={\n"
|
| 427 |
-
" 'session_id': session_id,\n"
|
| 428 |
-
" 'action_type': 'query_guideline',\n"
|
| 429 |
-
" 'code': 'O80'\n"
|
| 430 |
-
"})\n"
|
| 431 |
-
"print(resp.json()['observation']['tool_result'])\n"
|
| 432 |
-
"```\n"
|
| 433 |
-
)
|
| 434 |
|
| 435 |
return demo
|
|
|
|
| 1 |
"""
|
| 2 |
Gradio Landing Page for the Medical Coding Auditor Environment.
|
| 3 |
|
| 4 |
+
Production-quality HF Spaces UI with:
|
| 5 |
+
- Hero section with environment stats
|
| 6 |
+
- Uniqueness cards highlighting differentiators
|
| 7 |
+
- Scenario gallery with difficulty badges
|
| 8 |
+
- Color-coded leaderboard
|
| 9 |
+
- Interactive playground with live episode runner
|
| 10 |
+
- API reference and Try It code examples
|
| 11 |
|
| 12 |
Mounted at /ui by app.py when gradio is available.
|
| 13 |
"""
|
| 14 |
|
| 15 |
+
import html
|
| 16 |
import json
|
| 17 |
+
import threading
|
| 18 |
import uuid
|
| 19 |
+
from typing import Any, Dict, List
|
| 20 |
|
| 21 |
import gradio as gr
|
| 22 |
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
# ---------------------------------------------------------------------------
|
| 38 |
+
# Helpers
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
def _esc(s: str) -> str:
|
| 41 |
+
"""HTML-escape user-controlled text."""
|
| 42 |
+
return html.escape(str(s))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ---------------------------------------------------------------------------
|
| 46 |
+
# Session management (thread-safe for concurrent HF Spaces visitors)
|
| 47 |
# ---------------------------------------------------------------------------
|
| 48 |
_sessions: Dict[str, MedicalCodingEnvironment] = {}
|
| 49 |
+
_sessions_lock = threading.Lock()
|
| 50 |
+
|
| 51 |
|
| 52 |
# ---------------------------------------------------------------------------
|
| 53 |
+
# Static data
|
| 54 |
# ---------------------------------------------------------------------------
|
| 55 |
+
TASKS = [
|
| 56 |
{
|
| 57 |
"id": "easy_demographic",
|
| 58 |
+
"difficulty": "easy",
|
| 59 |
+
"label": "Easy",
|
| 60 |
+
"description": "Maternity code O80 assigned to a 34-year-old male patient.",
|
| 61 |
+
"errors": ["O80 → demographic_mismatch"],
|
| 62 |
+
"patient": "34M, Blue Cross PPO",
|
| 63 |
+
"codes": "E11.9, Z00.00, O80",
|
| 64 |
"max_steps": 10,
|
| 65 |
},
|
| 66 |
{
|
| 67 |
"id": "medium_ncci_conflict",
|
| 68 |
+
"difficulty": "medium",
|
| 69 |
+
"label": "Medium",
|
| 70 |
+
"description": "NCCI PTP bundling violation: complete TTE (93306) billed with limited TTE (93307).",
|
| 71 |
+
"errors": ["93306 → ncci_edit"],
|
| 72 |
+
"patient": "67F, Medicare Part B",
|
| 73 |
+
"codes": "93306, 93307, 99213",
|
| 74 |
"max_steps": 15,
|
| 75 |
},
|
| 76 |
{
|
| 77 |
"id": "medium_excludes1",
|
| 78 |
+
"difficulty": "medium",
|
| 79 |
+
"label": "Medium",
|
| 80 |
+
"description": "Excludes1 conflict: COPD (J44.1) and asthma (J45.20) coded together.",
|
| 81 |
+
"errors": ["J44.1 → excludes1_conflict"],
|
| 82 |
+
"patient": "58F, United Healthcare PPO",
|
| 83 |
+
"codes": "J44.1, J45.20, Z87.891",
|
| 84 |
"max_steps": 15,
|
| 85 |
},
|
| 86 |
{
|
| 87 |
"id": "hard_specificity_untraceable",
|
| 88 |
+
"difficulty": "hard",
|
| 89 |
+
"label": "Hard",
|
| 90 |
+
"description": "Wrong 7th character (S52.501A on follow-up) plus untraceable code Z99.999.",
|
| 91 |
+
"errors": ["S52.501A → specificity_error", "Z99.999 → untraceable_code"],
|
| 92 |
+
"patient": "28M, Aetna HMO",
|
| 93 |
+
"codes": "S52.501A, M79.621, Z99.999",
|
| 94 |
"max_steps": 20,
|
| 95 |
},
|
| 96 |
{
|
| 97 |
"id": "expert_multi_error",
|
| 98 |
+
"difficulty": "expert",
|
| 99 |
+
"label": "Expert",
|
| 100 |
+
"description": "Two errors in 6 codes: E10.9+E11.9 Excludes1 and 93306+93308 NCCI bundling.",
|
| 101 |
+
"errors": ["E10.9 → excludes1_conflict", "93306 → ncci_edit"],
|
| 102 |
+
"patient": "65M, Medicare Part B",
|
| 103 |
+
"codes": "E10.9, E11.9, 93306, 93308, 99214, M79.621",
|
| 104 |
"max_steps": 25,
|
| 105 |
},
|
| 106 |
]
|
| 107 |
|
| 108 |
+
TIER_COLOR = {
|
| 109 |
+
"easy": "#22c55e",
|
| 110 |
+
"medium": "#f59e0b",
|
| 111 |
+
"hard": "#ef4444",
|
| 112 |
+
"expert": "#a855f7",
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
SCORE_THRESHOLDS = [
|
| 116 |
+
(0.70, "#16a34a", "#fff"),
|
| 117 |
+
(0.50, "#22c55e", "#0a0a0a"),
|
| 118 |
+
(0.30, "#f59e0b", "#0a0a0a"),
|
| 119 |
+
(0.0, "#ef4444", "#fff"),
|
| 120 |
]
|
| 121 |
|
| 122 |
+
|
| 123 |
+
def _score_style(val: float) -> str:
|
| 124 |
+
for thresh, bg, fg in SCORE_THRESHOLDS:
|
| 125 |
+
if val >= thresh:
|
| 126 |
+
return f"background:{bg};color:{fg};font-weight:600;padding:4px 10px;border-radius:4px"
|
| 127 |
+
return ""
|
| 128 |
+
|
| 129 |
+
|
| 130 |
# ---------------------------------------------------------------------------
|
| 131 |
# CSS
|
| 132 |
# ---------------------------------------------------------------------------
|
| 133 |
+
CSS = """
|
| 134 |
+
<style>
|
| 135 |
+
:root {
|
| 136 |
+
--bg: #0a0a0a; --surface: #141414; --surface-2: #1a1a1a;
|
| 137 |
+
--border: #262626; --text: #ededed; --muted: #9ca3af;
|
| 138 |
+
--accent: #3b82f6; --accent-dim: #2563eb;
|
| 139 |
+
--success: #22c55e; --warning: #f59e0b; --danger: #ef4444;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
}
|
| 141 |
+
.hero { background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:28px 32px; margin-bottom:20px; }
|
| 142 |
+
.hero h1 { font-size:24px; font-weight:700; color:var(--text); margin:0 0 6px; letter-spacing:-0.015em; }
|
| 143 |
+
.hero p { font-size:14px; color:var(--muted); margin:0 0 20px; line-height:1.55; }
|
| 144 |
+
.stats { display:flex; gap:24px; flex-wrap:wrap; }
|
| 145 |
+
.stat { text-align:center; min-width:80px; }
|
| 146 |
+
.stat-val { font-size:22px; font-weight:700; color:var(--accent); font-variant-numeric:tabular-nums; }
|
| 147 |
+
.stat-lbl { font-size:10px; text-transform:uppercase; letter-spacing:0.8px; color:var(--muted); margin-top:2px; }
|
| 148 |
+
|
| 149 |
+
.cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:14px; margin:16px 0; }
|
| 150 |
+
.card { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:18px 20px; transition:border-color .15s; }
|
| 151 |
+
.card:hover { border-color:var(--accent); }
|
| 152 |
+
.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; }
|
| 153 |
+
.card h3 { font-size:15px; font-weight:600; color:var(--text); margin:0 0 6px; }
|
| 154 |
+
.card p { font-size:13px; color:var(--muted); margin:0; line-height:1.5; }
|
| 155 |
+
|
| 156 |
+
.scenario { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:18px 20px; margin-bottom:12px; }
|
| 157 |
+
.scenario-header { display:flex; align-items:center; gap:10px; margin-bottom:8px; }
|
| 158 |
+
.tier-badge { display:inline-block; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; padding:2px 10px; border-radius:4px; }
|
| 159 |
+
.scenario-id { font-family:"JetBrains Mono",ui-monospace,monospace; font-size:13px; color:var(--text); font-weight:500; }
|
| 160 |
+
.scenario p { font-size:13px; color:var(--muted); line-height:1.5; margin:4px 0; }
|
| 161 |
+
.scenario-meta { display:flex; gap:16px; flex-wrap:wrap; margin-top:8px; font-size:12px; color:var(--muted); }
|
| 162 |
+
.scenario-meta span { display:inline-flex; align-items:center; gap:4px; }
|
| 163 |
+
.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); }
|
| 164 |
+
|
| 165 |
+
.lb { width:100%; border-collapse:separate; border-spacing:0; font-size:13px; }
|
| 166 |
+
.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); }
|
| 167 |
+
.lb td { padding:8px 12px; text-align:center; border-bottom:1px solid var(--border); color:var(--text); }
|
| 168 |
+
.lb tr:hover td { background:var(--surface-2); }
|
| 169 |
+
.lb .tier-row td { background:var(--surface); font-weight:600; }
|
| 170 |
+
.lb .overall-row td { border-top:2px solid var(--accent); font-weight:700; }
|
| 171 |
+
|
| 172 |
+
.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); }
|
| 173 |
+
.pg-status .label { font-size:10px; text-transform:uppercase; letter-spacing:0.8px; color:var(--muted); }
|
| 174 |
+
.pg-status .value { font-size:16px; font-weight:600; margin-top:2px; }
|
| 175 |
+
.pg-row { display:flex; gap:16px; flex-wrap:wrap; }
|
| 176 |
+
.pg-row > div { flex:1; min-width:100px; }
|
| 177 |
+
.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; }
|
| 178 |
+
|
| 179 |
+
.reward-table { width:100%; border-collapse:collapse; font-size:13px; }
|
| 180 |
+
.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); }
|
| 181 |
+
.reward-table td { padding:6px 12px; border-bottom:1px solid var(--border); color:var(--text); }
|
| 182 |
+
.reward-pos { color:var(--success); font-weight:600; }
|
| 183 |
+
.reward-neg { color:var(--danger); font-weight:600; }
|
| 184 |
+
|
| 185 |
+
.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; }
|
| 186 |
+
.section-title { font-size:18px; font-weight:600; color:var(--text); margin:24px 0 12px; letter-spacing:-0.01em; }
|
| 187 |
+
</style>
|
| 188 |
"""
|
| 189 |
|
| 190 |
+
|
| 191 |
+
# ---------------------------------------------------------------------------
|
| 192 |
+
# HTML builders
|
| 193 |
+
# ---------------------------------------------------------------------------
|
| 194 |
+
|
| 195 |
+
def _build_hero() -> str:
|
| 196 |
+
return CSS + """
|
| 197 |
+
<div class="hero">
|
| 198 |
+
<h1>Medical Coding Auditor</h1>
|
| 199 |
+
<p>A real-world RL environment simulating hospital pre-bill compliance review.
|
| 200 |
+
AI agents review ICD-10-CM and CPT billing codes against clinical notes
|
| 201 |
+
and patient demographics to identify coding errors before claim submission.</p>
|
| 202 |
+
<div class="stats">
|
| 203 |
+
<div class="stat"><div class="stat-val">5</div><div class="stat-lbl">Scenarios</div></div>
|
| 204 |
+
<div class="stat"><div class="stat-val">5</div><div class="stat-lbl">Error Types</div></div>
|
| 205 |
+
<div class="stat"><div class="stat-val">6</div><div class="stat-lbl">Audit Tools</div></div>
|
| 206 |
+
<div class="stat"><div class="stat-val">4</div><div class="stat-lbl">Difficulty Tiers</div></div>
|
| 207 |
+
<div class="stat"><div class="stat-val">7</div><div class="stat-lbl">Reward Components</div></div>
|
| 208 |
+
<div class="stat"><div class="stat-val">1</div><div class="stat-lbl">Baseline Model</div></div>
|
| 209 |
+
</div>
|
| 210 |
+
</div>
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _build_uniqueness_cards() -> str:
|
| 215 |
+
cards = [
|
| 216 |
+
("🏥", "Real CMS/AMA Coding Rules",
|
| 217 |
+
"Every task uses real ICD-10-CM Excludes1 notes, CMS NCCI PTP edit tables, "
|
| 218 |
+
"7th character guidelines, and demographic restrictions from official coding manuals."),
|
| 219 |
+
("🔍", "6-Tool Audit Workflow",
|
| 220 |
+
"query_guideline, check_ncci_edits, flag_error, ask_clarifying_question, "
|
| 221 |
+
"extract_evidence, submit_audit — mirrors a real medical coder's review process."),
|
| 222 |
+
("📊", "Dense Multi-Signal Rewards",
|
| 223 |
+
"HERON-style hierarchical penalties, rarity-weighted asymmetric rewards (1.0x–1.5x), "
|
| 224 |
+
"investigation coherence bonuses, and evidence grounding signals at every step."),
|
| 225 |
+
("📝", "CLH Evidence Extraction",
|
| 226 |
+
"Agents must quote exact clinical note text as evidence before flagging errors. "
|
| 227 |
+
"Hallucinated spans are penalized. Maps to CLH Pillar 1 (Evidence Extraction)."),
|
| 228 |
+
("💬", "Physician Clarification",
|
| 229 |
+
"Ambiguous notes require the agent to ask_clarifying_question before flagging. "
|
| 230 |
+
"Keyword-matched deterministic responses simulate real coder-physician dialogue."),
|
| 231 |
+
("🛡", "Anti-Reward-Hacking",
|
| 232 |
+
"False positive penalty (-0.15 per FP in grader), hallucination guard (-0.50), "
|
| 233 |
+
"loop detection, and efficiency bonus prevent flag-everything or query-spam strategies."),
|
| 234 |
+
]
|
| 235 |
+
html_parts = ['<div class="section-title">What makes this unique</div>', '<div class="cards">']
|
| 236 |
+
for icon, title, desc in cards:
|
| 237 |
+
html_parts.append(
|
| 238 |
+
f'<div class="card">'
|
| 239 |
+
f'<div class="card-icon">{icon}</div>'
|
| 240 |
+
f'<h3>{title}</h3>'
|
| 241 |
+
f'<p>{desc}</p>'
|
| 242 |
+
f'</div>'
|
| 243 |
+
)
|
| 244 |
+
html_parts.append('</div>')
|
| 245 |
+
return "\n".join(html_parts)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _build_scenarios() -> str:
|
| 249 |
+
html_parts = ['<div class="section-title">5 scenarios · 4 difficulty tiers</div>']
|
| 250 |
+
for t in TASKS:
|
| 251 |
+
color = TIER_COLOR[t["difficulty"]]
|
| 252 |
+
badge_style = f"background:rgba({_hex_to_rgb(color)},0.1);color:{color};border:1px solid rgba({_hex_to_rgb(color)},0.3)"
|
| 253 |
+
errors_html = " ".join(f'<span class="error-tag">{e}</span>' for e in t["errors"])
|
| 254 |
+
html_parts.append(f"""
|
| 255 |
+
<div class="scenario">
|
| 256 |
+
<div class="scenario-header">
|
| 257 |
+
<span class="tier-badge" style="{badge_style}">{t['label']}</span>
|
| 258 |
+
<span class="scenario-id">{t['id']}</span>
|
| 259 |
+
</div>
|
| 260 |
+
<p>{t['description']}</p>
|
| 261 |
+
<div style="margin:6px 0">{errors_html}</div>
|
| 262 |
+
<div class="scenario-meta">
|
| 263 |
+
<span>👤 {t['patient']}</span>
|
| 264 |
+
<span>📋 {t['codes']}</span>
|
| 265 |
+
<span>⏱ max {t['max_steps']} steps</span>
|
| 266 |
+
</div>
|
| 267 |
+
</div>""")
|
| 268 |
+
return "\n".join(html_parts)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _hex_to_rgb(hex_color: str) -> str:
|
| 272 |
+
h = hex_color.lstrip("#")
|
| 273 |
+
return f"{int(h[0:2],16)},{int(h[2:4],16)},{int(h[4:6],16)}"
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _build_leaderboard() -> str:
|
| 277 |
+
scores = {
|
| 278 |
+
"Qwen/Qwen2.5-72B-Instruct": {
|
| 279 |
+
"easy_demographic": 0.75,
|
| 280 |
+
"medium_ncci_conflict": 0.65,
|
| 281 |
+
"medium_excludes1": 0.65,
|
| 282 |
+
"hard_specificity_untraceable": 0.55,
|
| 283 |
+
"expert_multi_error": 0.40,
|
| 284 |
+
},
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
task_ids = [t["id"] for t in TASKS]
|
| 288 |
+
models = list(scores.keys())
|
| 289 |
+
|
| 290 |
+
rows = []
|
| 291 |
+
# Per-task rows
|
| 292 |
+
for tid in task_ids:
|
| 293 |
+
t = next(t for t in TASKS if t["id"] == tid)
|
| 294 |
+
color = TIER_COLOR[t["difficulty"]]
|
| 295 |
+
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>'
|
| 296 |
+
cells = f'<td style="text-align:left;font-family:monospace;font-size:12px">{tid}</td><td>{badge}</td>'
|
| 297 |
+
for m in models:
|
| 298 |
+
val = scores[m].get(tid, 0.0)
|
| 299 |
+
style = _score_style(val)
|
| 300 |
+
cells += f'<td><span style="{style}">{val:.2f}</span></td>'
|
| 301 |
+
rows.append(f"<tr>{cells}</tr>")
|
| 302 |
+
|
| 303 |
+
# Overall row
|
| 304 |
+
overall_cells = '<td style="text-align:left;font-weight:700">Overall Average</td><td></td>'
|
| 305 |
+
for m in models:
|
| 306 |
+
avg = sum(scores[m].values()) / len(scores[m])
|
| 307 |
+
style = _score_style(avg)
|
| 308 |
+
overall_cells += f'<td><span style="{style}">{avg:.2f}</span></td>'
|
| 309 |
+
|
| 310 |
+
header_cells = "<th>Scenario</th><th>Tier</th>"
|
| 311 |
+
for m in models:
|
| 312 |
+
header_cells += f"<th>{_esc(m.split('/')[-1])}</th>"
|
| 313 |
+
|
| 314 |
+
return f"""
|
| 315 |
+
<div class="section-title">Baseline scores</div>
|
| 316 |
+
<p style="font-size:13px;color:var(--muted)">Evaluated at temperature 0.2 via HuggingFace router. Scores include efficiency bonus and FP penalties.</p>
|
| 317 |
+
<table class="lb">
|
| 318 |
+
<thead><tr>{header_cells}</tr></thead>
|
| 319 |
+
<tbody>
|
| 320 |
+
{"".join(rows)}
|
| 321 |
+
<tr class="overall-row">{overall_cells}</tr>
|
| 322 |
+
</tbody>
|
| 323 |
+
</table>
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _build_reward_table() -> str:
|
| 328 |
+
rewards = [
|
| 329 |
+
("query_guideline", "Valid code, first query", "+0.10", True),
|
| 330 |
+
("query_guideline", "Code NOT in proposed set", "-0.50", False),
|
| 331 |
+
("query_guideline", "Already queried (loop)", "-0.10", False),
|
| 332 |
+
("check_ncci_edits", "Valid pair, conflict found", "+0.10", True),
|
| 333 |
+
("check_ncci_edits", "Valid pair, no conflict", "+0.05", True),
|
| 334 |
+
("ask_clarifying_question", "Relevant (matches triggers)", "+0.15", True),
|
| 335 |
+
("ask_clarifying_question", "Irrelevant or repeated", "-0.10", False),
|
| 336 |
+
("extract_evidence", "Matches expected evidence", "+0.05", True),
|
| 337 |
+
("extract_evidence", "Not in clinical note", "-0.05", False),
|
| 338 |
+
("flag_error", "Correct code + type (conflict)", "+0.30 × rarity", True),
|
| 339 |
+
("flag_error", "Correct code + type (other)", "+0.20 × rarity", True),
|
| 340 |
+
("flag_error", "Prior evidence extracted", "+0.05 bonus", True),
|
| 341 |
+
("flag_error", "Prior investigation done", "+0.05 bonus", True),
|
| 342 |
+
("flag_error", "Wrong type (close miss)", "-0.05", False),
|
| 343 |
+
("flag_error", "Wrong type (far miss)", "-0.10", False),
|
| 344 |
+
("flag_error", "False positive", "-0.20", False),
|
| 345 |
+
("flag_error", "Code NOT in proposed set", "-0.50", False),
|
| 346 |
+
("submit_audit", "Grader score + efficiency", "0.0–1.0", True),
|
| 347 |
+
]
|
| 348 |
+
rows = []
|
| 349 |
+
for action, condition, value, is_pos in rewards:
|
| 350 |
+
cls = "reward-pos" if is_pos else "reward-neg"
|
| 351 |
+
rows.append(
|
| 352 |
+
f'<tr><td style="font-family:monospace;font-size:12px">{action}</td>'
|
| 353 |
+
f'<td>{condition}</td>'
|
| 354 |
+
f'<td class="{cls}">{value}</td></tr>'
|
| 355 |
+
)
|
| 356 |
+
return f"""
|
| 357 |
+
<div class="section-title">Reward function</div>
|
| 358 |
+
<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>
|
| 359 |
+
<table class="reward-table">
|
| 360 |
+
<thead><tr><th>Action</th><th>Condition</th><th>Reward</th></tr></thead>
|
| 361 |
+
<tbody>{"".join(rows)}</tbody>
|
| 362 |
+
</table>
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _build_tryit() -> str:
|
| 367 |
+
return f"""
|
| 368 |
+
<div class="section-title">Run inference against this environment</div>
|
| 369 |
+
<div class="code-block">export HF_TOKEN="your_hf_token"
|
| 370 |
+
export API_BASE_URL="https://router.huggingface.co/v1"
|
| 371 |
+
export MODEL_NAME="Qwen/Qwen2.5-72B-Instruct"
|
| 372 |
+
export ENV_BASE_URL="http://localhost:7860"
|
| 373 |
+
|
| 374 |
+
python inference.py</div>
|
| 375 |
+
|
| 376 |
+
<div class="section-title" style="margin-top:24px">Expected output</div>
|
| 377 |
+
<div class="code-block">[START] task=easy_demographic env=medical_coding model=Qwen/Qwen2.5-72B-Instruct
|
| 378 |
+
[STEP] step=1 action={{"action_type":"query_guideline","code":"O80"}} reward=0.10 done=false error=null
|
| 379 |
+
[STEP] step=2 action={{"action_type":"flag_error","code":"O80","error_type":"demographic_mismatch",...}} reward=0.25 done=false error=null
|
| 380 |
+
[STEP] step=3 action={{"action_type":"submit_audit"}} reward=0.85 done=true error=null
|
| 381 |
+
[END] success=true steps=3 rewards=0.10,0.25,0.85</div>
|
| 382 |
+
|
| 383 |
+
<div class="section-title" style="margin-top:24px">Session-based API (HF Spaces compatible)</div>
|
| 384 |
+
<div class="code-block">import httpx
|
| 385 |
+
|
| 386 |
+
# Create session
|
| 387 |
+
resp = httpx.post(BASE_URL + "/api/reset", json={{"task_id": "easy_demographic"}})
|
| 388 |
+
session_id = resp.json()["session_id"]
|
| 389 |
+
|
| 390 |
+
# Query a code
|
| 391 |
+
resp = httpx.post(BASE_URL + "/api/call_tool", json={{
|
| 392 |
+
"session_id": session_id,
|
| 393 |
+
"action_type": "query_guideline",
|
| 394 |
+
"code": "O80"
|
| 395 |
+
}})
|
| 396 |
+
print(resp.json()["observation"]["tool_result"])
|
| 397 |
+
|
| 398 |
+
# Flag the error
|
| 399 |
+
resp = httpx.post(BASE_URL + "/api/call_tool", json={{
|
| 400 |
+
"session_id": session_id,
|
| 401 |
+
"action_type": "flag_error",
|
| 402 |
+
"code": "O80",
|
| 403 |
+
"error_type": "demographic_mismatch",
|
| 404 |
+
"justification": "O80 is female-only; patient is male."
|
| 405 |
+
}})
|
| 406 |
+
|
| 407 |
+
# Submit audit
|
| 408 |
+
resp = httpx.post(BASE_URL + "/api/call_tool", json={{
|
| 409 |
+
"session_id": session_id,
|
| 410 |
+
"action_type": "submit_audit"
|
| 411 |
+
}})
|
| 412 |
+
print(f"Score: {{resp.json()['observation']['grader_score']}}")</div>
|
| 413 |
+
"""
|
| 414 |
|
| 415 |
|
| 416 |
# ---------------------------------------------------------------------------
|
| 417 |
# Playground logic
|
| 418 |
# ---------------------------------------------------------------------------
|
| 419 |
+
|
| 420 |
+
def _pg_reset(task_id: str) -> tuple:
|
| 421 |
session_id = str(uuid.uuid4())
|
| 422 |
env = MedicalCodingEnvironment()
|
| 423 |
obs = env.reset(task_id=task_id)
|
| 424 |
+
with _sessions_lock:
|
| 425 |
+
_sessions[session_id] = env
|
| 426 |
+
|
| 427 |
+
obs_d = obs.model_dump()
|
| 428 |
+
demo = obs_d.get("patient_demographics", {})
|
| 429 |
+
codes = obs_d.get("proposed_codes", {})
|
| 430 |
+
|
| 431 |
+
codes_list = ", ".join(f"<code>{_esc(c)}</code>" for c in codes)
|
| 432 |
+
note_preview = _esc(obs_d.get("clinical_note", "")[:1500])
|
| 433 |
+
|
| 434 |
+
status_html = f"""
|
| 435 |
+
<div class="pg-status">
|
| 436 |
+
<div class="pg-row">
|
| 437 |
+
<div><div class="label">Session</div><div class="value" style="font-family:monospace;font-size:11px">{session_id[:12]}...</div></div>
|
| 438 |
+
<div><div class="label">Task</div><div class="value">{_esc(task_id)}</div></div>
|
| 439 |
+
<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>
|
| 440 |
+
<div><div class="label">Patient</div><div class="value">{demo.get('age','?')}yo {demo.get('sex','?')}</div></div>
|
| 441 |
+
<div><div class="label">Step</div><div class="value">0</div></div>
|
| 442 |
+
</div>
|
| 443 |
+
</div>
|
| 444 |
+
"""
|
| 445 |
+
info_html = f"""
|
| 446 |
+
<div style="margin-bottom:8px"><strong>Proposed codes:</strong> {codes_list}</div>
|
| 447 |
+
<div class="pg-obs">{note_preview}</div>
|
| 448 |
+
"""
|
| 449 |
+
return session_id, status_html, info_html, ""
|
| 450 |
|
| 451 |
|
| 452 |
+
def _pg_step(
|
| 453 |
session_id: str,
|
| 454 |
action_type: str,
|
| 455 |
+
code: str, code1: str, code2: str,
|
| 456 |
+
error_type: str, justification: str,
|
| 457 |
+
question: str, evidence_text: str,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
) -> tuple:
|
| 459 |
+
with _sessions_lock:
|
| 460 |
+
env = _sessions.get(session_id)
|
| 461 |
if env is None:
|
| 462 |
+
return session_id, '<div class="pg-status" style="border-color:var(--danger)">No active session. Click Reset first.</div>', "", ""
|
| 463 |
|
| 464 |
action_data: Dict[str, Any] = {"action_type": action_type}
|
| 465 |
+
for key, val in [("code", code), ("code1", code1), ("code2", code2),
|
| 466 |
+
("justification", justification), ("question", question),
|
| 467 |
+
("evidence_text", evidence_text)]:
|
| 468 |
+
if val and val.strip():
|
| 469 |
+
action_data[key] = val.strip()
|
| 470 |
+
if error_type and error_type != "(none)":
|
|
|
|
| 471 |
action_data["error_type"] = error_type
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
|
| 473 |
try:
|
| 474 |
action = MedicalCodingAction(**action_data)
|
| 475 |
obs = env.step(action)
|
| 476 |
except Exception as e:
|
| 477 |
+
return session_id, f'<div class="pg-status" style="border-color:var(--danger)">Error: {_esc(str(e))}</div>', "", ""
|
| 478 |
|
| 479 |
+
obs_d = obs.model_dump()
|
| 480 |
+
reward = obs_d.get("reward", 0.0)
|
| 481 |
+
done = obs_d.get("done", False)
|
| 482 |
+
error = obs_d.get("last_action_error")
|
| 483 |
+
step_n = obs_d.get("step_count", 0)
|
| 484 |
+
tool_result = obs_d.get("tool_result", "")
|
| 485 |
|
| 486 |
+
reward_color = "var(--success)" if reward > 0 else ("var(--danger)" if reward < 0 else "var(--muted)")
|
| 487 |
+
error_html = f'<div><div class="label">Error</div><div class="value" style="color:var(--danger)">{_esc(str(error))}</div></div>' if error else ""
|
| 488 |
+
|
| 489 |
+
done_parts = ""
|
|
|
|
| 490 |
if done:
|
| 491 |
+
grader = obs_d.get("grader_score")
|
| 492 |
+
metrics = obs_d.get("episode_metrics")
|
| 493 |
+
grader_color = "var(--success)" if grader and grader >= 0.5 else "var(--danger)"
|
| 494 |
+
done_parts = f'<div><div class="label">Grader Score</div><div class="value" style="color:{grader_color};font-size:22px">{grader:.3f}</div></div>'
|
| 495 |
if metrics:
|
| 496 |
+
m = metrics
|
| 497 |
+
done_parts += (
|
| 498 |
+
f'<div style="margin-top:8px;font-size:12px;color:var(--muted)">'
|
| 499 |
+
f'Precision: {m.get("flag_precision",0):.2f} | '
|
| 500 |
+
f'Recall: {m.get("flag_recall",0):.2f} | '
|
| 501 |
+
f'Coverage: {m.get("investigation_coverage",0):.0%} | '
|
| 502 |
+
f'Failures: {m.get("tool_failure_rate",0):.0%}'
|
| 503 |
+
f'</div>'
|
| 504 |
+
)
|
| 505 |
+
with _sessions_lock:
|
| 506 |
+
_sessions.pop(session_id, None)
|
| 507 |
+
|
| 508 |
+
status_html = f"""
|
| 509 |
+
<div class="pg-status">
|
| 510 |
+
<div class="pg-row">
|
| 511 |
+
<div><div class="label">Step</div><div class="value">{step_n}</div></div>
|
| 512 |
+
<div><div class="label">Reward</div><div class="value" style="color:{reward_color}">{reward:+.2f}</div></div>
|
| 513 |
+
<div><div class="label">Done</div><div class="value">{"Yes" if done else "No"}</div></div>
|
| 514 |
+
{error_html}
|
| 515 |
+
</div>
|
| 516 |
+
{done_parts}
|
| 517 |
+
</div>
|
| 518 |
+
"""
|
| 519 |
|
| 520 |
+
draft = obs_d.get("draft_report", [])
|
| 521 |
+
draft_str = json.dumps(draft, indent=2) if draft else "(empty)"
|
| 522 |
+
result_text = (
|
| 523 |
f"--- Tool Result ---\n{tool_result}\n\n"
|
| 524 |
f"--- Draft Report ---\n{draft_str}\n\n"
|
| 525 |
+
f"Codes queried: {obs_d.get('codes_queried', [])}\n"
|
| 526 |
+
f"NCCI pairs checked: {obs_d.get('pairs_checked', [])}\n"
|
| 527 |
+
f"Evidence extracted: {obs_d.get('extracted_evidence', [])}\n"
|
| 528 |
+
f"Clarifications: {obs_d.get('clarifications_asked', [])}"
|
| 529 |
)
|
| 530 |
|
| 531 |
+
return session_id, status_html, "", result_text
|
| 532 |
|
| 533 |
|
| 534 |
# ---------------------------------------------------------------------------
|
| 535 |
# Build the Gradio app
|
| 536 |
# ---------------------------------------------------------------------------
|
| 537 |
def create_gradio_app() -> gr.Blocks:
|
| 538 |
+
with gr.Blocks(title="Medical Coding Auditor - OpenEnv") as demo:
|
| 539 |
+
|
| 540 |
+
# Hero
|
| 541 |
+
gr.HTML(_build_hero())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
|
| 543 |
with gr.Tabs():
|
| 544 |
# ----------------------------------------------------------
|
| 545 |
+
# Tab 1: Overview
|
| 546 |
# ----------------------------------------------------------
|
| 547 |
+
with gr.Tab("Overview"):
|
| 548 |
+
gr.HTML(_build_uniqueness_cards())
|
| 549 |
+
gr.HTML(_build_scenarios())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 550 |
|
| 551 |
gr.Markdown(
|
| 552 |
"## Action Space\n\n"
|
|
|
|
| 560 |
"| `submit_audit` | _(none)_ | Submit audit report for grading |\n"
|
| 561 |
)
|
| 562 |
|
| 563 |
+
# ----------------------------------------------------------
|
| 564 |
+
# Tab 2: Rewards
|
| 565 |
+
# ----------------------------------------------------------
|
| 566 |
+
with gr.Tab("Rewards"):
|
| 567 |
+
gr.HTML(_build_reward_table())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
|
| 569 |
# ----------------------------------------------------------
|
| 570 |
+
# Tab 3: Leaderboard
|
| 571 |
# ----------------------------------------------------------
|
| 572 |
with gr.Tab("Leaderboard"):
|
| 573 |
+
gr.HTML(_build_leaderboard())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
|
| 575 |
# ----------------------------------------------------------
|
| 576 |
+
# Tab 4: Playground
|
| 577 |
# ----------------------------------------------------------
|
| 578 |
with gr.Tab("Playground"):
|
| 579 |
+
gr.HTML('<div class="section-title">Interactive playground</div>'
|
| 580 |
+
'<p style="font-size:13px;color:var(--muted)">Step through a task manually to explore the environment.</p>')
|
|
|
|
|
|
|
| 581 |
|
| 582 |
with gr.Row():
|
| 583 |
+
task_dd = gr.Dropdown(
|
| 584 |
+
choices=[t["id"] for t in TASKS],
|
| 585 |
value="easy_demographic",
|
| 586 |
label="Task",
|
| 587 |
)
|
| 588 |
reset_btn = gr.Button("Reset", variant="primary")
|
| 589 |
|
| 590 |
+
session_state = gr.State("")
|
| 591 |
+
pg_status = gr.HTML("")
|
| 592 |
+
pg_info = gr.HTML("")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
+
gr.HTML('<div class="section-title" style="font-size:15px">Action panel</div>')
|
| 595 |
with gr.Row():
|
| 596 |
+
action_dd = gr.Dropdown(
|
| 597 |
choices=[
|
| 598 |
+
"query_guideline", "check_ncci_edits", "flag_error",
|
| 599 |
+
"ask_clarifying_question", "extract_evidence", "submit_audit",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
],
|
| 601 |
value="query_guideline",
|
| 602 |
+
label="action_type",
|
| 603 |
)
|
| 604 |
step_btn = gr.Button("Execute Step", variant="secondary")
|
| 605 |
|
| 606 |
with gr.Row():
|
| 607 |
+
in_code = gr.Textbox(label="code", placeholder="e.g. O80")
|
| 608 |
+
in_code1 = gr.Textbox(label="code1", placeholder="CPT code 1")
|
| 609 |
+
in_code2 = gr.Textbox(label="code2", placeholder="CPT code 2")
|
| 610 |
|
| 611 |
with gr.Row():
|
| 612 |
+
in_etype = gr.Dropdown(
|
| 613 |
+
choices=["(none)", "demographic_mismatch", "excludes1_conflict",
|
| 614 |
+
"ncci_edit", "specificity_error", "untraceable_code"],
|
| 615 |
+
value="(none)", label="error_type",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 616 |
)
|
| 617 |
+
in_just = gr.Textbox(label="justification", placeholder="Clinical rationale")
|
| 618 |
|
| 619 |
with gr.Row():
|
| 620 |
+
in_question = gr.Textbox(label="question", placeholder="Clarifying question")
|
| 621 |
+
in_evidence = gr.Textbox(label="evidence_text", placeholder="Exact note text")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
|
| 623 |
+
pg_result = gr.Textbox(label="Observation", lines=14, interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 624 |
|
| 625 |
reset_btn.click(
|
| 626 |
+
fn=_pg_reset,
|
| 627 |
+
inputs=[task_dd],
|
| 628 |
+
outputs=[session_state, pg_status, pg_info, pg_result],
|
| 629 |
)
|
| 630 |
step_btn.click(
|
| 631 |
+
fn=_pg_step,
|
| 632 |
+
inputs=[session_state, action_dd, in_code, in_code1, in_code2,
|
| 633 |
+
in_etype, in_just, in_question, in_evidence],
|
| 634 |
+
outputs=[session_state, pg_status, pg_info, pg_result],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 635 |
)
|
| 636 |
|
| 637 |
# ----------------------------------------------------------
|
| 638 |
+
# Tab 5: Try It
|
| 639 |
# ----------------------------------------------------------
|
| 640 |
+
with gr.Tab("Try It"):
|
| 641 |
+
gr.HTML(_build_tryit())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
|
| 643 |
return demo
|