banao-tech's picture
Update app.py
0e658c0 verified
raw
history blame
16.9 kB
import streamlit as st
import json
from datetime import datetime
import time
import requests
import boto3
import uuid
import os
# Load configuration from environment variables (Hugging Face Spaces)
API_ENDPOINT = os.getenv("API_ENDPOINT", "https://oau6sljd4l.execute-api.ap-south-1.amazonaws.com/production/process")
# DynamoDB configuration for session tracking
DYNAMODB_REGION = os.getenv("DYNAMODB_REGION", "ap-south-1")
SESSION_TABLE = os.getenv("SESSION_TABLE", "SessionTracking")
# AWS Configuration
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "ap-south-1")
# Default values
DEFAULT_COURSE_ID = int(os.getenv("DEFAULT_COURSE_ID", "47"))
DEFAULT_USER_ID = int(os.getenv("DEFAULT_USER_ID", "30"))
DEFAULT_PERSONALIZATION_ID = int(os.getenv("DEFAULT_PERSONALIZATION_ID", "100"))
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "30"))
# Set page configuration
st.set_page_config(
page_title="Base Course Personalization",
layout="wide",
initial_sidebar_state="collapsed",
page_icon="πŸ“š",
menu_items={
'Get Help': None,
'Report a bug': None,
'About': None
}
)
# Custom CSS for dark theme styling
st.markdown("""
<style>
/* Dark theme colors */
:root {
--background-color: #1E1E1E;
--card-background: #2D2D2D;
--text-color: #E0E0E0;
--accent-color: #4F97FF;
--border-color: #444444;
--header-color: #4F97FF;
--subheader-color: #FFFFFF;
}
/* Main container styling */
.stApp {
background-color: var(--background-color);
color: var(--text-color);
}
/* Headers */
.main-header {
font-size: 2.5rem;
font-weight: 600;
color: var(--header-color);
margin-bottom: 1rem;
text-align: center;
}
.section-header {
font-size: 1.5rem;
font-weight: 500;
color: var(--subheader-color);
margin-top: 2rem;
margin-bottom: 1rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border-color);
}
/* Form container */
div[data-testid="stForm"] {
background-color: var(--card-background);
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.3);
}
/* Button styling */
.stButton>button {
background-color: var(--accent-color);
color: white;
border-radius: 4px;
padding: 0.5rem 2rem;
font-weight: 500;
border: none;
}
/* Input fields */
div[data-baseweb="select"] > div {
background-color: var(--background-color);
border-color: var(--border-color);
}
.stTextInput > div > div > input,
.stNumberInput > div > div > input,
.stTextArea > div > div > textarea {
background-color: var(--background-color);
color: var(--text-color);
border-color: var(--border-color);
}
/* Radio buttons - Fix visibility */
.stRadio > div {
background-color: transparent;
}
.stRadio > div > label > div {
color: var(--text-color) !important;
}
/* Select box labels */
.stSelectbox > label {
color: var(--text-color) !important;
}
/* All form labels */
div[data-testid="stForm"] label {
color: var(--text-color) !important;
}
/* Radio button text */
.stRadio label {
color: var(--text-color) !important;
}
/* Fix for all input labels */
.st-emotion-cache-1gulkj5,
.st-emotion-cache-1aumxhf,
.st-emotion-cache-16txtl3 {
color: var(--text-color) !important;
}
/* Spacing */
div.block-container {
padding-top: 2rem;
}
hr {
margin-top: 1rem;
margin-bottom: 1rem;
border-color: var(--border-color);
}
/* API Response Container */
.api-response {
background-color: #1A1A1A;
border-radius: 8px;
padding: 1rem;
border-left: 4px solid var(--accent-color);
}
.session-info {
background-color: var(--card-background);
padding: 1rem;
border-radius: 8px;
margin: 1rem 0;
border: 1px solid var(--border-color);
}
</style>
""", unsafe_allow_html=True)
# Initialize session state for topics and authentication
if 'topics_list' not in st.session_state:
st.session_state.topics_list = [{"topic_title": "What is Flask", "chapter_title": "Introduction to Flask"}]
if 'session_ids' not in st.session_state:
st.session_state.session_ids = []
if 'authenticated' not in st.session_state:
st.session_state.authenticated = False
# Hardcoded credentials (you can change these)
VALID_USERNAME = "admin"
VALID_PASSWORD = "techlearn2024"
# Authentication check
if not st.session_state.authenticated:
st.markdown('<h1 class="main-header">πŸ” Login to Course Personalization</h1>', unsafe_allow_html=True)
with st.form("login_form"):
st.markdown('<div class="section-header">πŸ”‘ Authentication Required</div>', unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
username = st.text_input("Username", placeholder="Enter username")
password = st.text_input("Password", placeholder="Enter password", type="password")
login_submitted = st.form_submit_button("πŸš€ Login", use_container_width=True)
if login_submitted:
if username == VALID_USERNAME and password == VALID_PASSWORD:
st.session_state.authenticated = True
st.success("Login successful! Redirecting...")
time.sleep(1)
st.rerun()
else:
st.error(" Invalid username or password")
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #888888;">
<small>Demo Credentials: admin / techlearn2024</small>
</div>
""", unsafe_allow_html=True)
st.stop()
# Main app (only shown after authentication)
# App Header
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.markdown('<h1 class="main-header">πŸ“š Base Course Personalization</h1>', unsafe_allow_html=True)
with col3:
if st.button(" Logout"):
st.session_state.authenticated = False
st.session_state.topics_list = [{"topic_title": "What is Flask", "chapter_title": "Introduction to Flask"}]
st.session_state.session_ids = []
st.rerun()
st.markdown("""
<div style="text-align: center; margin-bottom: 2rem;">
Complete this form to tailor your learning experience to your preferences.<br>
Your personalized course will be generated based on the information you provide below.
</div>
""", unsafe_allow_html=True)
# Main Form
with st.form("personalization_form", clear_on_submit=False):
# Topics Section
st.markdown('<div class="section-header">πŸ“‹ Topics Configuration</div>', unsafe_allow_html=True)
# Option to choose single or multiple topics
topic_mode = st.radio(
"Topic Mode",
["Single Topic", "Multiple Topics"],
horizontal=True,
help="Choose whether to process one topic or multiple topics"
)
if topic_mode == "Single Topic":
st.subheader("Single Topic Details")
single_topic_title = st.text_input("Topic Title", value="What is Flask", help="Enter the topic title")
else:
st.subheader("Multiple Topics")
# Display existing topics
for i, topic in enumerate(st.session_state.topics_list):
col1, col2 = st.columns([4, 1])
with col1:
topic_title = st.text_input(f"Topic {i+1}", value=topic["topic_title"], key=f"topic_{i}")
st.session_state.topics_list[i]["topic_title"] = topic_title
with col2:
if len(st.session_state.topics_list) > 1:
if st.button("πŸ—‘οΈ", key=f"remove_{i}", help="Remove topic"):
st.session_state.topics_list.pop(i)
st.rerun()
# Language & Voice Settings Section
st.markdown('<div class="section-header">πŸ—£οΈ Language & Voice Settings</div>', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
target_language = st.selectbox(
"Target Language",
["english", "hindi", "telugu", "tamil", "other"],
index=0,
format_func=lambda x: x.capitalize()
)
with col2:
tts_gender = st.selectbox(
"Voice Gender",
["male", "female"],
index=0,
format_func=lambda x: x.capitalize()
)
with col3:
tts_voice = st.selectbox(
"Voice Style",
["onyx", "echo", "soprano", "alto", "robotic"],
index=0, # Default to "onyx"
format_func=lambda x: x.capitalize()
)
# Technical Settings Section
st.markdown('<div class="section-header">πŸ’» Technical Settings</div>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
programming_language = st.selectbox(
"Programming Language",
["python", "java", "javascript", "c++", "go"],
index=0,
format_func=lambda x: x.capitalize()
)
with col2:
toggle_hinglish = st.toggle("Enable Hinglish", value=True, help="Mix of Hindi and English")
# Submit button
st.markdown("<br>", unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
submitted = st.form_submit_button("Generate Personalized Course", use_container_width=True)
# Add/Remove topic buttons outside the form (for multiple topics)
if topic_mode == "Multiple Topics":
col1, col2, col3 = st.columns([1, 1, 2])
with col1:
if st.button(" Add More Topic"):
st.session_state.topics_list.append({"topic_title": f"Topic {len(st.session_state.topics_list) + 1}"})
st.rerun()
with col2:
if st.button(" Reset Topics"):
st.session_state.topics_list = [{"topic_title": "What is Flask"}]
st.rerun()
# Handle submission
if submitted:
# Validate inputs
valid_topics = [topic for topic in st.session_state.topics_list if topic["topic_title"].strip() and topic["chapter_title"].strip()]
if not valid_topics:
st.error("Please enter at least one topic with both topic title and chapter title")
else:
# Show loading state
with st.spinner("Generating your personalized course..."):
time.sleep(1.5) # Simulating API call delay
# Hardcoded values
course_id = DEFAULT_COURSE_ID
user_id = DEFAULT_USER_ID
personalization_id = DEFAULT_PERSONALIZATION_ID
# Create user profile (hardcoded)
user_profile = {
"personalized": True,
"user_name": "System User",
"user_age": 25,
"user_gender": "male",
"user_tech_knowledge": "beginner",
"user_preferred_activity": "coding, learning, technology",
"user_food": "healthy food, vegetarian",
"user_physical_activities": "walking, yoga",
"learning_style": "visual",
"target_language": target_language,
"tts_gender": tts_gender,
"tts_voice": tts_voice,
"toggle_hinglish": toggle_hinglish,
"run_visualization": False,
"subtitle": "",
"age_group": "18-25"
}
# Create settings
settings = {
"target_language": target_language,
"tts_gender": tts_gender,
"tts_voice": tts_voice,
"toggle_hinglish": toggle_hinglish,
"run_visualization": False,
"subtitle": "",
"programming_language": programming_language,
"slide_colour": "blue",
"video_type": "base_video"
}
# Generate topics data with user input for titles and hardcoded values for others
topics_data = []
for i, topic in enumerate(valid_topics):
topics_data.append({
"topic_id": 10834 + i, # Hardcoded with increment
"topic_title": topic["topic_title"].strip(),
"chapter_id": 647, # Hardcoded
"chapter_title": topic["chapter_title"].strip(), # User input
"course_id": course_id,
"video_url": f"https://techlearn-dev.s3.ap-south-1.amazonaws.com/course_videos/47/647/172906{4365+i*50}.mp4", # Hardcoded with variation
"video_duration": 462 + i*20, # Hardcoded with variation
"sequence_number": i + 1,
})
# Create payload (always multiple topics structure)
payload = {
"personalization_id": personalization_id,
"user_id": user_id,
"course_id": course_id,
"total_videos": len(topics_data),
"created_at": datetime.utcnow().isoformat(),
"user_profile": user_profile,
"topics": topics_data,
"settings": settings
}
# Make API call
try:
headers = {
'Content-Type': 'application/json'
}
response = requests.post(API_ENDPOINT, json=payload, headers=headers, timeout=API_TIMEOUT)
if response.status_code == 200:
response_data = response.json()
session_ids = response_data.get("session_ids", [])
st.success(f"Course personalization started successfully!")
# Store session IDs in session state
st.session_state.session_ids.extend(session_ids)
# Display results in a clean format
st.markdown("### πŸŽ‰ Your personalized course generation has started!")
st.markdown(f"""
**Course ID**: {course_id}
**Programming Language**: {programming_language.capitalize()}
**Target Language**: {target_language.capitalize()}
**Voice**: {tts_voice.capitalize()} ({tts_gender.capitalize()})
**Topics**: {len(valid_topics)}
""")
# Display session IDs
if session_ids:
st.markdown("### πŸ” Session IDs for Tracking")
for i, session_id in enumerate(session_ids, 1):
st.markdown(f'<div class="session-info"><strong>Session {i}:</strong> <code>{session_id}</code></div>', unsafe_allow_html=True)
# Display API response
st.markdown('<div class="section-header">πŸ“Š API Response</div>', unsafe_allow_html=True)
st.markdown('<div class="api-response">', unsafe_allow_html=True)
st.json(response_data)
st.markdown('</div>', unsafe_allow_html=True)
# Information about tracking
st.info(f"""
πŸ’‘ **Tracking Information**
You can track the progress of your video generation using the session IDs above.
The processing status will be updated in DynamoDB table: `{SESSION_TABLE}`
Region: `{DYNAMODB_REGION}`
""")
else:
st.error(f"API Error: {response.status_code}")
if response.text:
st.error(f"Error Details: {response.text}")
except requests.exceptions.Timeout:
st.error("Request timed out. Please try again later.")
except requests.exceptions.ConnectionError:
st.error("Connection error. Please check your internet connection.")
except Exception as e:
st.error(f"API call failed: {str(e)}")
# Show payload for debugging
st.warning("Request payload for debugging:")
st.json(payload)