agente IA que enseña inglés. CONFIGURACIÓN INICIAL Carrusel imágenes: escenarios Selectbox: roles agente Selectbox: situaciones Botón "Start Conversation" CONVERSACIÓN (3 columnas, layout="wide") Izq (25%): Info escenario + gamificación (puntos, nivel, insignias, racha) Centro (50%): Chat con burbujas + input texto + botones (Send, Clear, New Topic) Der (25%): Correcciones tiempo real: errores (rojo), correcciones (verde), alternativas (azul) + retroalimentación español DASHBOARD KPIs: conversaciones, precisión%, palabras aprendidas, tiempo práctica Gráficos: progreso semanal, escenarios practicados, tipos errores Sistema insignias SIDEBAR: SESIONES Lista conversaciones guardadas (Ver, Continuar, Eliminar) Botones: New Conversation, Save Session GAMIFICACIÓN Puntos: +10 correcta, +20 vocabulario avanzado, +5 corrección Niveles: Beginner/Intermediate/Advanced/Expert Challenges diarios
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import random
import json
# Configure page
st.set_page_config(page_title="LinguaVerse - AI English Tutor", layout="wide", initial_sidebar_state="expanded")
# Initialize session state
if 'page' not in st.session_state:
st.session_state.page = 'setup'
if 'user_profile' not in st.session_state:
st.session_state.user_profile = {
'level': 'Beginner',
'points': 0,
'streak': 0,
'conversations': 0,
'accuracy': 0,
'words_learned': 0,
'practice_time': 0,
'badges': []
}
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'corrections' not in st.session_state:
st.session_state.corrections = []
if 'saved_sessions' not in st.session_state:
st.session_state.saved_sessions = []
if 'current_scenario' not in st.session_state:
st.session_state.current_scenario = None
if 'current_role' not in st.session_state:
st.session_state.current_role = None
if 'current_situation' not in st.session_state:
st.session_state.current_situation = None
# Sample data
scenarios = {
"Restaurant": {
"image": "🍽️",
"description": "Practice ordering food, asking about menu items, and restaurant conversations",
"roles": ["Customer", "Waiter", "Chef"],
"situations": ["Ordering dinner", "Complaining about food", "Making a reservation", "Asking for the bill"]
},
"Airport": {
"image": "✈️",
"description": "Learn travel vocabulary and airport procedures",
"roles": ["Passenger", "Check-in agent", "Security officer"],
"situations": ["Checking in", "Going through security", "Flight delay", "Lost luggage"]
},
"Office": {
"image": "💼",
"description": "Business English and workplace communication",
"roles": ["Employee", "Manager", "Client"],
"situations": ["Job interview", "Team meeting", "Presentation", "Negotiation"]
},
"Coffee Shop": {
"image": "☕",
"description": "Casual conversations and ordering drinks",
"roles": ["Customer", "Barista", "Friend"],
"situations": ["Ordering coffee", "Meeting a friend", "Working on laptop", "Small talk"]
}
}
def calculate_level(points):
if points < 100:
return "Beginner"
elif points < 500:
return "Intermediate"
elif points < 1000:
return "Advanced"
else:
return "Expert"
def get_badge_color(badge_type):
colors = {
"Conversation Master": "🥇",
"Grammar Guru": "📚",
"Vocabulary Champion": "💡",
"Streak Master": "🔥"
}
return colors.get(badge_type, "🏆")
# Sidebar
with st.sidebar:
st.title("LinguaVerse")
st.markdown("---")
# Navigation
if st.button("🏠 Home", use_container_width=True):
st.session_state.page = 'setup'
if st.button("💬 Conversation", use_container_width=True):
st.session_state.page = 'conversation'
if st.button("📊 Dashboard", use_container_width=True):
st.session_state.page = 'dashboard'
st.markdown("---")
# User Profile Summary
st.subheader("Your Progress")
st.metric("Level", st.session_state.user_profile['level'])
st.metric("Points", st.session_state.user_profile['points'])
st.metric("Streak", f"{st.session_state.user_profile['streak']} days")
# Saved Sessions
st.markdown("---")
st.subheader("Saved Sessions")
if st.session_state.saved_sessions:
for i, session in enumerate(st.session_state.saved_sessions):
with st.expander(f"Session {i+1} - {session['scenario']}"):
st.write(f"Role: {session['role']}")
st.write(f"Situation: {session['situation']}")
st.write(f"Messages: {len(session['messages'])}")
col1, col2 = st.columns(2)
with col1:
if st.button("Continue", key=f"continue_{i}"):
st.session_state.messages = session['messages']
st.session_state.current_scenario = session['scenario']
st.session_state.current_role = session['role']
st.session_state.current_situation = session['situation']
st.session_state.page = 'conversation'
st.rerun()
with col2:
if st.button("Delete", key=f"delete_{i}"):
st.session_state.saved_sessions.pop(i)
st.rerun()
else:
st.write("No saved sessions")
if st.button("New Conversation", use_container_width=True):
st.session_state.messages = []
st.session_state.corrections = []
st.session_state.page = 'setup'
st.rerun()
# Main content based on page
if st.session_state.page == 'setup':
st.title("🌟 Practice English with AI")
st.markdown("Choose a scenario, select your role, and start practicing your English conversation skills with our AI tutor!")
# Hero section
st.markdown("""
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem; border-radius: 10px; text-align: center; margin-bottom: 2rem;">
<h2 style="color: white; margin-bottom: 1rem;">🚀 Start Your English Journey</h2>
<p style="color: white; font-size: 1.1rem;">
Choose a scenario below, and our AI will guide you through realistic conversations
while providing real-time feedback and corrections.
</p>
</div>
""", unsafe_allow_html=True)
# Scenario selection with image carousel
st.subheader("📍 Choose a Scenario")
cols = st.columns(4)
selected_scenario = None
for i, (scenario_name, scenario_data) in enumerate(scenarios.items()):
with cols[i % 4]:
if st.button(f"{scenario_data['image']}\n\n**{scenario_name}**\n\n{scenario_data['description']}",
key=f"scenario_{scenario_name}", use_container_width=True,
type="primary" if st.session_state.current_scenario == scenario_name else "secondary"):
st.session_state.current_scenario = scenario_name
selected_scenario = scenario_name
if st.session_state.current_scenario:
selected_scenario = st.session_state.current_scenario
scenario_data = scenarios[selected_scenario]
st.success(f"✅ Selected scenario: **{selected_scenario}**")
col1, col2 = st.columns(2)
with col1:
st.subheader("🎭 Select Your Role")
selected_role = st.selectbox(
"Choose your role in this scenario:",
scenario_data['roles'],
key="role_select"
)
st.session_state.current_role = selected_role
with col2:
st.subheader("🎯 Select a Situation")
selected_situation = st.selectbox(
"What situation would you like to practice?",
scenario_data['situations'],
key="situation_select"
)
st.session_state.current_situation = selected_situation
# Start conversation button
st.markdown("<br>", unsafe_allow_html=True)
col1, col2, col3 = st.columns([1,1,1])
with col2:
if st.button("🚀 Start Conversation", type="primary", use_container_width=True):
st.session_state.page = 'conversation'
st.session_state.messages = []
st.session_state.corrections = []
# Add welcome message
welcome_msg = f"Hello! I'm your AI English tutor. You're a {selected_role} in a {selected_scenario.lower()}, and we're going to practice: {selected_situation}. Let's start! How can I help you today?"
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
st.rerun()
elif st.session_state.page == 'conversation':
if not st.session_state.current_scenario:
st.warning("Please select a scenario first!")
if st.button("Go to Setup"):
st.session_state.page = 'setup'
st.rerun()
else:
# Three column layout
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
# Scenario info and gamification
st.markdown(f"### {scenarios[st.session_state.current_scenario]['image']} {st.session_state.current_scenario}")
st.write(f"**Role:** {st.session_state.current_role}")
st.write(f"**Situation:** {st.session_state.current_situation}")
st.markdown("---")
st.markdown("### 🎮 Your Stats")
# Level progress
level = calculate_level(st.session_state.user_profile['points'])
st.session_state.user_profile['level'] = level
progress_value = (st.session_state.user_profile['points'] % 100) / 100
st.metric("Level", level)
st.progress(progress_value)
st.metric("Points", st.session_state.user_profile['points'])
st.metric("Streak", f"{st.session_state.user_profile['streak']} days")
# Badges
st.markdown("### 🏆 Badges")
if st.session_state.user_profile['badges']:
for badge in st.session_state.user_profile['badges']:
st.write(f"{get_badge_color(badge)} {badge}")
else:
st.write("No badges yet. Keep practicing!")
with col2:
# Chat interface
st.markdown("### 💬 Conversation")
# Chat messages
chat_container = st.container(height=400)
with chat_container:
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
col_input, col_send = st.columns([4, 1])
with col_input:
user_input = st.text_input("Type your message:", key="chat_input", placeholder="Type your message here...")
with col_send:
st.markdown("<br>", unsafe_allow_html=True)
send_clicked = st.button("Send", type="primary")
# Buttons row
col_clear, col_topic, col_save = st.columns(3)
with col_clear:
if st.button("Clear Chat"):
st.session_state.messages = []
st.session_state.corrections = []
st.rerun()
with col_topic:
if st.button("New Topic"):
new_topic_msg = f"Let's try a different situation in the {st.session_state.current_scenario.lower()}. What would you like to practice now?"
st.session_state.messages.append({"role": "assistant", "content": new_topic_msg})
st.rerun()
with col_save:
if st.button("Save Session"):
session = {
'scenario': st.session_state.current_scenario,
'role': st.session_state.current_role,
'situation': st.session_state.current_situation,
'messages': st.session_state.messages.copy(),
'date': datetime.now().strftime("%Y-%m-%d %H:%M")
}
st.session_state.saved_sessions.append(session)
st.success("Session saved!")
# Process user input
if send_clicked and user_input:
# Add user message
st.session_state.messages.append({"role": "user", "content": user_input})
# Simulate AI response with corrections
errors = []
corrections = []
alternatives = []
# Simple error detection (simulation)
if "dont" in user_input.lower():
errors.append("'dont' should be 'don't'")
if "i are" in user_input.lower():
errors.append("'I are' should be 'I am'")
if "good" in user_input.lower() and "well" not in user_input.lower():
alternatives.append("Instead of 'good', you could say 'well' or 'fine'")
# Add corrections to session state
if errors or corrections or alternatives:
correction_entry = {
"original": user_input,
"errors": errors,
"corrections": corrections,
"alternatives": alternatives
}
st.session_state.corrections.append(correction_entry)
# Award points
points_earned = 10
if len(user_input.split()) > 5:
points_earned += 5
if not errors:
points_earned += 10
st.session_state.user_profile['points'] += points_earned
st.session_state.user_profile['conversations'] += 1
# Generate AI response
ai_responses = [
f"That's great! I can see you're practicing well. {f'You earned {points_earned} points!' if points_earned > 10 else ''}",
"Excellent! Your English is improving. Can you tell me more about that?",
"Good job! I understand what you mean. Let's continue our conversation.",
"Very good! Your pronunciation of that phrase would be important to practice.",
"Nice! That's exactly how you would say it in this situation."
]
ai_response = random.choice(ai_responses)
st.session_state.messages.append({"role": "assistant", "content": ai_response})
st.rerun()
with col3:
# Real-time corrections
st.markdown("### ✏️ Real-time Feedback")
if st.session_state.corrections:
for i, correction in enumerate(st.session_state.corrections[-5:]): # Show last 5
with st.expander(f"Message {len(st.session_state.corrections) - 5 + i + 1}"):
st.write(f"**Original:** {correction['original']}")
if correction['errors']:
st.markdown("**🔴 Errors:**")
for error in correction['errors']:
st.write(f"• {error}")
if correction['corrections']:
st.markdown("**🟢 Corrections:**")
for corr in correction['corrections']:
st.write(f"• {corr}")
if correction['alternatives']:
st.markdown("**🔵 Alternatives:**")
for alt in correction['alternatives']:
st.write(f"• {alt}")
else:
st.write("Start chatting to get real-time feedback on your English!")
# Spanish feedback section
st.markdown("---")
st.markdown("### 🇪🇸 Retroalimentación en Español")
st.write("Tu pronunciación y gramática están mejorando. Sigue practicando para dominar estas situaciones cotidianas.")
elif st.session_state.page == 'dashboard':
st.title("📊 Learning Dashboard")
# KPIs
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Conversations", st.session_state.user_profile['conversations'])
with col2:
accuracy = random.randint(75, 95) # Simulated
st.metric("Accuracy", f"{accuracy}%")
with col3:
words = random.randint(50, 200) # Simulated
st.metric("Words Learned", words)
with col4:
time_practiced = random.randint(30, 180) # Simulated
st.metric("Practice Time", f"{time_practiced} min")
col1, col2 = st.columns(2)
with col1:
# Weekly progress chart
st.subheader("📈 Weekly Progress")
# Generate sample data
dates = pd.date_range(start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D')
progress_data = pd.DataFrame({
'Date': dates,
'Points': np.random.randint(0, 50, len(dates)),
'Conversations': np.random.randint(0, 5, len(dates))
})
fig = px.line(progress_data, x='Date', y=['Points', 'Conversations'],
title="Daily Learning Activity")
st.plotly_chart(fig, use_container_width=True)
# Error types chart
st.subheader("🎯 Common Error Types")
error_data = pd.DataFrame({
'Error Type': ['Grammar', 'Vocabulary', 'Pronunciation', 'Spelling'],
'Count': [15, 8, 12, 5]
})
fig = px.bar(error_data, x='Error Type', y='Count',
title="Areas for Improvement")
st.plotly_chart(fig, use_container_width=True)
with col2:
# Scenarios practiced
st.subheader("🎭 Scenarios Practiced")
scenario_data = pd.DataFrame({
'Scenario': list(scenarios.keys()),
'Practice Count': [random.randint(1, 10) for _ in scenarios.keys()]
})
fig = px.pie(scenario_data, values='Practice Count', names='Scenario',
title="Practice Distribution by Scenario")
st.plotly_chart(fig, use_container_width=True)
# Badges and achievements
st.subheader("🏆 Badge System")
all_badges = [
{"name": "First Conversation", "description": "Complete your first conversation", "earned": True},
{"name": "Grammar Master", "description": "Get 10 sentences correct in a row", "earned": False},
{"name": "Vocabulary Builder", "description": "Learn 50 new words", "earned": False},
{"name": "Streak Master", "description": "Practice for 7 days in a row", "earned": False},
{"name": "Conversation Expert", "description": "Complete 25 conversations", "earned": False}
]
for badge in all_badges:
status = "✅" if badge["earned"] else "⭕"
st.write(f"{status} **{badge['name']}**")
st.write(f" {badge['description']}")
st.markdown("---")
# Footer
st.markdown("---")
st.markdown(
"""
<div style="text-align: center; color: #666;">
<p>🌟 LinguaVerse - Your AI English Tutor | Practice makes perfect!</p>
</div>
""",
unsafe_allow_html=True
)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?