"""
streamlit_app.py — Vidya V3 Real-Time AI Tutor — Streamlit UI
Run: streamlit run streamlit_app.py
Features:
- Full chat interface with Vidya V3
- Live signal scorecard with bar charts
- Mastery level tracker
- Phase history timeline
- ICP + session config panel
- Conversation history viewer
- Session logs browser
"""
import streamlit as st
import json
import sys
import os
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
# ── Page config ───────────────────────────────────────────────────────────────
st.set_page_config(
page_title="Vidya V3 — AI Tutor",
page_icon="🎓",
layout="wide",
initial_sidebar_state="expanded",
)
# ── Custom CSS ────────────────────────────────────────────────────────────────
st.markdown("""
""", unsafe_allow_html=True)
# ── Helpers ───────────────────────────────────────────────────────────────────
def signal_color(score: float) -> str:
if score >= 65: return "#FF5C5C" if score >= 80 else "#F5A623"
if score <= 35: return "#3DD68C"
return "#6B6B85"
def phase_color(phase: str) -> str:
return {"MODEL": "#4EADFF", "COACH": "#3DD68C",
"SCAFFOLD": "#F5A623", "FADE": "#B57BFF"}.get(phase, "#6B6B85")
def phase_emoji(phase: str) -> str:
return {"MODEL": "📖", "COACH": "💬", "SCAFFOLD": "🧩", "FADE": "🚀"}.get(phase, "🎓")
def render_signal_bar(label: str, score: float):
color = signal_color(score)
pct = score
st.markdown(f"""
""", unsafe_allow_html=True)
def render_mastery_bar(mastery: float):
pct = mastery * 100
st.markdown(f"""
""", unsafe_allow_html=True)
# ── Session state init ────────────────────────────────────────────────────────
def init_state():
defaults = {
"session": None,
"messages": [], # [{role, content, phase, mastery, signals, suggestion}]
"phase_history": [], # [(turn, phase)]
"mastery_history":[], # [(turn, mastery)]
"configured": False,
"turn_count": 0,
}
for k, v in defaults.items():
if k not in st.session_state:
st.session_state[k] = v
init_state()
# ── Sidebar — Session Config ──────────────────────────────────────────────────
with st.sidebar:
st.markdown("""
VIDYA V3
Real-Time AI Tutor
""", unsafe_allow_html=True)
st.markdown("---")
st.markdown('', unsafe_allow_html=True)
skill_topic = st.text_input(
"Skill Topic",
value="Python functions",
placeholder="e.g. Python functions",
disabled=st.session_state.configured,
)
mastery_input = st.slider(
"Starting Mastery Level",
0.0, 1.0, 0.2, 0.05,
disabled=st.session_state.configured,
)
icp_type = st.selectbox(
"ICP Type",
["low_wage", "high_wage"],
format_func=lambda x: {
"low_wage": "🌱 Low Wage — Early career / reskilling",
"high_wage": "🚀 High Wage — Professional / aspirational",
}[x],
disabled=st.session_state.configured,
)
language = st.selectbox(
"Language",
["en", "hi", "mixed"],
format_func=lambda x: {"en": "🇬🇧 English", "hi": "🇮🇳 Hindi/Hinglish", "mixed": "🔀 Mixed"}[x],
disabled=st.session_state.configured,
)
if not st.session_state.configured:
if st.button("🚀 Start Session", use_container_width=True):
try:
from src.schemas import SessionConfig
from src.icp_profiles import mastery_to_phase
from src.tutor_session import TutorSession
auto_phase = mastery_to_phase(mastery_input, icp_type)
config = SessionConfig(
skill_topic=skill_topic,
mastery_level=mastery_input,
icp_type=icp_type,
ca_phase=auto_phase,
language_preference=language,
)
st.session_state.session = TutorSession(config)
st.session_state.configured = True
st.session_state.phase_history = [(0, auto_phase)]
st.session_state.mastery_history= [(0, mastery_input)]
st.rerun()
except Exception as e:
st.error(f"Setup failed: {e}")
else:
if st.button("🔄 New Session", use_container_width=True):
for k in ["session","messages","phase_history","mastery_history","configured","turn_count"]:
del st.session_state[k]
st.rerun()
st.markdown("---")
# Live signal scorecard
if st.session_state.configured and st.session_state.session:
sess = st.session_state.session
st.markdown('', unsafe_allow_html=True)
scores = sess.scorecard.to_dict()
for sig in ["confidence", "effort", "confusion", "frustration", "answer_seeking", "off_topic"]:
render_signal_bar(sig, scores.get(sig, 50))
st.markdown("---")
st.markdown('', unsafe_allow_html=True)
mastery = sess.mastery_level
render_mastery_bar(mastery)
col1, col2 = st.columns(2)
with col1:
st.markdown(f"""
""", unsafe_allow_html=True)
with col2:
phase = sess.current_phase
st.markdown(f"""
""", unsafe_allow_html=True)
# Phase timeline
if st.session_state.phase_history:
st.markdown("---")
st.markdown('', unsafe_allow_html=True)
for turn, phase in st.session_state.phase_history[-8:]:
st.markdown(f"""
T{turn}
{phase_emoji(phase)} {phase}
""", unsafe_allow_html=True)
# Judge stats
if hasattr(sess.scorecard, 'stats'):
st.markdown("---")
st.caption(f"🔍 {sess.scorecard.stats()}")
# ── Main area ─────────────────────────────────────────────────────────────────
if not st.session_state.configured:
# Welcome screen
st.markdown("""
🎓
VIDYA V3
Real-Time AI Tutor · Cognitive Apprenticeship · Signal-Driven Adaptation
""", unsafe_allow_html=True)
c1, c2, c3 = st.columns(3)
for col, icon, title, desc in [
(c1, "📊", "Signal Scoring", "6 signals tracked as rolling 0–100 scores across turns"),
(c2, "🎯", "ICP Adaptation", "low_wage vs high_wage — different tone, pace, and phase thresholds"),
(c3, "🔄", "Phase Control", "Mastery level drives phase. Gemini cannot jump ahead of what's earned"),
]:
with col:
st.markdown(f"""
""", unsafe_allow_html=True)
st.markdown("""
Configure your session in the sidebar and click Start Session
""", unsafe_allow_html=True)
else:
sess = st.session_state.session
# Header row
col_h1, col_h2, col_h3, col_h4 = st.columns([3,1,1,1])
with col_h1:
st.markdown(f"""
{sess.config.skill_topic.upper()}
{sess.config.icp_type} · {sess.config.language_preference}
""", unsafe_allow_html=True)
with col_h2:
st.markdown(f"""
{st.session_state.turn_count}
Turns
""", unsafe_allow_html=True)
with col_h3:
st.markdown(f"""
{sess.mastery_level:.2f}
Mastery
""", unsafe_allow_html=True)
with col_h4:
phase = sess.current_phase
st.markdown(f"""
{phase_emoji(phase)} {phase}
Phase
""", unsafe_allow_html=True)
st.markdown("", unsafe_allow_html=True)
# ── Chat area ─────────────────────────────────────────────────────────────
chat_container = st.container()
with chat_container:
st.markdown('', unsafe_allow_html=True)
st.markdown("", unsafe_allow_html=True)
# ── Input area ────────────────────────────────────────────────────────────
with st.form("chat_form", clear_on_submit=True):
col_inp, col_btn = st.columns([5, 1])
with col_inp:
user_input = st.text_input(
"Message",
placeholder="Type your message here...",
label_visibility="collapsed",
)
with col_btn:
submitted = st.form_submit_button("Send →", use_container_width=True)
if submitted and user_input.strip():
with st.spinner("Vidya is thinking..."):
try:
output = sess.process_turn(user_input.strip())
st.session_state.turn_count += 1
turn = st.session_state.turn_count
# Save messages
st.session_state.messages.append({
"role": "user", "content": user_input.strip()
})
st.session_state.messages.append({
"role": "assistant",
"content": output["tutor_response"],
"phase": output["updated_ca_phase"],
"mastery": sess.mastery_level,
"suggestion": output.get("suggested_next_action", ""),
"signals": output["_debug"]["signal_scores"],
})
# Track history
st.session_state.phase_history.append((turn, output["updated_ca_phase"]))
st.session_state.mastery_history.append((turn, sess.mastery_level))
# Show off-topic warning
if not output.get("on_topic_flag", True):
st.warning("⚠️ Off-topic detected — Vidya redirected to the skill topic.")
st.rerun()
except Exception as e:
st.error(f"Error: {e}")
# ── Bottom tabs ───────────────────────────────────────────────────────────
st.markdown("---")
tab1, tab2, tab3 = st.tabs(["📈 Mastery Chart", "🔍 Debug Output", "📋 Session Log"])
with tab1:
if st.session_state.mastery_history:
import pandas as pd
df = pd.DataFrame(st.session_state.mastery_history, columns=["Turn", "Mastery"])
# Add phase boundaries
st.line_chart(df.set_index("Turn"), color="#7C6FF7", height=200)
# ICP threshold reference
icp = sess.config.icp_type
from src.icp_profiles import get_icp
profile = get_icp(icp)
thresholds = profile["phase_thresholds"]
st.markdown(f"""
{''.join(f'{p}: {lo:.2f}–{hi:.2f}'
for p, (lo, hi) in thresholds.items())}
""", unsafe_allow_html=True)
else:
st.caption("Start chatting to see mastery chart.")
with tab2:
if st.session_state.messages:
last_tutor = next(
(m for m in reversed(st.session_state.messages) if m["role"] == "assistant"), None
)
if last_tutor and "signals" in last_tutor:
st.markdown('', unsafe_allow_html=True)
sigs = last_tutor["signals"]
cols = st.columns(3)
for i, (sig, val) in enumerate(sigs.items()):
with cols[i % 3]:
color = signal_color(val)
st.markdown(f"""
""", unsafe_allow_html=True)
else:
st.caption("Debug info appears after first message.")
with tab3:
if st.session_state.messages:
log_data = {
"config": sess.config.model_dump(),
"final_phase": sess.current_phase,
"final_mastery": round(sess.mastery_level, 3),
"turns": st.session_state.turn_count,
"signal_scorecard": sess.scorecard.to_dict(),
"conversation": [
{"role": m["role"], "content": m["content"]}
for m in st.session_state.messages
],
}
st.json(log_data)
if st.button("💾 Save Session Log"):
try:
sess.save_log()
st.success("Saved to logs/conversations.json")
except Exception as e:
st.error(f"Save failed: {e}")
else:
st.caption("Session log appears after first message.")