Krsnapriya's picture
Upload folder using huggingface_hub
e8d92f9 verified
Raw History Blame Contribute Delete
10.2 kB
"""
CodeReviewEnv-RX β€” Interactive Research Dashboard
Streamlit-based UI for visualizing agent episodes, submitting actions
(open_file, inspect, trace, flag), and exploring multi-file grading results.
"""
import streamlit as st # pyre-ignore
import requests # pyre-ignore
import json
BASE = "http://localhost:8000"
st.set_page_config(
page_title="CodeReviewEnv-RX",
page_icon="🧠",
layout="wide",
initial_sidebar_state="expanded",
)
st.markdown("""
<style>
.stApp {
background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
color: #e0e0e0;
}
.metric-card {
background: rgba(255,255,255,0.05);
border-radius: 12px;
padding: 16px;
border: 1px solid rgba(255,255,255,0.1);
backdrop-filter: blur(10px);
}
.header-gradient {
background: linear-gradient(90deg, #667eea, #764ba2);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 2.5em;
font-weight: 800;
}
.file-tab {
font-family: monospace;
color: #a78bfa;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
st.markdown('<p class="header-gradient">🧠 CodeReviewEnv-RX</p>', unsafe_allow_html=True)
st.caption("Interactive Multi-File Code Review & Reasoning Benchmark")
# ── Sidebar ──────────────────────────────────────────
with st.sidebar:
st.header("βš™οΈ Environment")
try:
tasks_response = requests.get(f"{BASE}/tasks", timeout=2)
available_tasks = [t["level"] for t in tasks_response.json().get("tasks", [])]
except Exception:
available_tasks = ["easy", "medium", "hard", "security", "concurrency", "hard_rx"]
st.warning("Server unreachable. Ensure it's running on port 8000.")
task_level = st.selectbox("🎯 Task Level", available_tasks, index=available_tasks.index("hard_rx") if "hard_rx" in available_tasks else 0)
seed = st.number_input("🎲 Seed", value=42, min_value=0, max_value=9999)
if st.button("πŸ”„ Reset Environment", use_container_width=True):
try:
res = requests.post(f"{BASE}/reset?task_level={task_level}&seed={seed}")
if res.status_code == 200:
st.session_state["obs"] = res.json()
st.session_state["rewards"] = []
st.session_state["actions_log"] = []
st.session_state["episode_done"] = False
st.session_state["current_state"] = None
st.session_state["grade_result"] = None
st.success(f"Reset to **{task_level}**")
else:
st.error(f"Reset failed: {res.text}")
except Exception as e:
st.error(f"Connection error: {e}")
st.divider()
st.header("πŸ“Š Quick Stats")
col1, col2 = st.columns(2)
with col1:
if st.button("πŸ“ˆ State"):
try:
st.session_state["current_state"] = requests.get(f"{BASE}/state").json()
except Exception: pass
with col2:
if st.button("πŸ† Grade"):
try:
st.session_state["grade_result"] = requests.get(f"{BASE}/grader").json()
except Exception: pass
if "obs" not in st.session_state:
st.info("πŸ‘ˆ Select a task and click **Reset Environment** to begin.")
st.stop()
obs = st.session_state["obs"]
# ── Status Bar ───────────────────────────────────────
meta = obs.get("task_metadata", {})
prog, rem = obs.get("progress", 0), obs.get("remaining_issues", "?")
tleft, sleft = obs.get("time_left", 0), obs.get("steps_left", 0)
st.write(f"**Task**: {meta.get('task_name', '')} | **Issues**: {meta.get('total_required_issues', '?')}")
st.progress(prog, text=f"Progress: {prog:.0%} ({rem} issues left) | ⏱️ Time Budget: {tleft} | πŸ‘Ÿ Steps Left: {sleft}")
# ── Main Layout ──────────────────────────────────────
col_code, col_action = st.columns([3, 2])
with col_code:
st.subheader("πŸ“ Workspace")
available_files = obs.get("available_files", [])
current_file = obs.get("current_file")
visited = obs.get("visited_files", [])
st.write(f"**Available files**: {', '.join(available_files)}")
st.write(f"**Current active file**: <span class='file-tab'>{current_file or 'None (Open a file)'}</span>", unsafe_allow_html=True)
st.markdown("### πŸ” Visible Code")
visible_code = obs.get("visible_code", {})
if current_file and current_file in visible_code:
lines = visible_code[current_file]
if not lines:
st.code("# No lines inspected in this file yet.\n# Use 'inspect' action to reveal code.", language="python")
else:
sorted_lines = sorted([(int(k), v) for k, v in lines.items()])
code_str = ""
last_idx = -1
for ln, content in sorted_lines:
if last_idx != -1 and ln > last_idx + 1:
code_str += f"... (uninspected lines) ...\n"
code_str += f"{ln:3d} | {content}\n"
last_idx = ln
st.code(code_str, language="python")
elif current_file:
st.code("# No lines inspected in this file yet.\n# Use 'inspect' action to reveal code.", language="python")
else:
st.code("# Select `open_file` action to start analyzing.")
trace = obs.get("call_trace", [])
if trace:
st.info(f"**Last Call Trace**: {' β†’ '.join(trace)}")
with col_action:
st.subheader("🎯 Submit Action")
if st.session_state.get("episode_done", False):
st.success("βœ… Episode complete!")
else:
with st.form("action_form"):
action_type = st.selectbox("Action", ["open_file", "inspect", "trace", "flag"])
# Dynamic fields based on action_type
file_name = st.selectbox("File to Open", available_files) if available_files else ""
line_number = st.number_input("Line Number", min_value=1, value=1)
issue_type = st.selectbox("Issue Type", ["bug", "style", "optimization"])
suggestion = st.text_input("Suggestion (optional bonus)")
submitted = st.form_submit_button("πŸš€ Execute", use_container_width=True)
if submitted:
action = {"action_type": action_type}
if action_type == "open_file":
action["file_name"] = file_name
elif action_type in ["inspect", "trace"]:
action["line_number"] = int(line_number)
elif action_type == "flag":
action["line_number"] = int(line_number)
action["issue_type"] = issue_type
action["suggestion"] = suggestion
try:
res = requests.post(f"{BASE}/step", json=action)
if res.status_code == 200:
data = res.json()
st.session_state["obs"] = data["observation"]
reward_data = data["reward"]
rew = reward_data["reward"]
st.session_state.setdefault("rewards", []).append(rew)
log_entry = {**action, "reward": rew, "result": reward_data["info"].get("result", reward_data["info"].get("type", "unknown"))}
st.session_state.setdefault("actions_log", []).append(log_entry)
if reward_data["done"]:
st.session_state["episode_done"] = True
st.balloons()
st.rerun()
else:
st.error(f"Error: {res.text}")
except Exception as e:
st.error(f"Request failed: {e}")
# ── Results & Logs ───────────────────────────────────
st.divider()
col_metrics, col_chart, col_grade = st.columns(3)
with col_metrics:
st.subheader("πŸ“Š State Metrics")
state = st.session_state.get("current_state", {})
m1, m2, m3 = st.columns(3)
m1.metric("Correct", state.get("correct_flags", 0))
m2.metric("False +", state.get("false_flags", 0))
m3.metric("Root Causes", state.get("root_cause_found", 0))
m4, m5, m6 = st.columns(3)
m4.metric("Time Used", state.get("time_used", 0))
m5.metric("Files Visited", len(state.get("visited_files", [])))
m6.metric("Reasoning", f"{state.get('decision_quality', 0):.2f}")
with col_chart:
st.subheader("πŸ“ˆ Reward History")
rewards = st.session_state.get("rewards", [])
if rewards:
st.line_chart(rewards, use_container_width=True)
st.caption(f"Total reward accumulated: {sum(rewards):.3f}")
with col_grade:
st.subheader("πŸ† Final Grade")
grade = st.session_state.get("grade_result", {})
if grade:
st.metric("Final Score", f"{grade.get('score', 0):.4f}")
for comp, val in grade.get("breakdown", {}).items():
icon = "πŸ”»" if "penalty" in comp else "βœ…"
st.progress(min(val, 1.0), text=f"{icon} {comp.replace('_', ' ').title()}: {val:.2%}")
else:
st.caption("Click **Grade** in sidebar to calculate score")
if st.session_state.get("actions_log"):
st.divider()
st.subheader("πŸ“‹ Action Log")
for i, a in enumerate(st.session_state["actions_log"]):
res = a.get("result", "")
icon = "βœ…" if res=="correct" else "❌" if "false" in res or "penalty" in res or "invalid" in res or "error" in res or res=="trap" else "πŸ”"
detail = f"File: {a.get('file_name', 'current')} " if a['action_type'] == 'open_file' else f"Line {a.get('line_number')} "
if a['action_type'] == 'flag': detail += f"[{a.get('issue_type')}]"
st.text(f" {icon} Step {i+1}: {a['action_type'].upper()} | {detail} | Reward: {a['reward']:+.3f}")