# app.py import streamlit as st import os import json import datetime import pandas as pd from dotenv import load_dotenv import openai import autogen from autogen import AssistantAgent, UserProxyAgent, config_list_from_json import uuid # Load environment variables load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") # Set Streamlit page configuration for better visuals st.set_page_config( page_title="FiTA Ugadi Event Registration", page_icon="🪔", layout="wide", initial_sidebar_state="expanded", ) # Custom styling for a more appealing visual experience st.markdown(""" """, unsafe_allow_html=True) # Initialize session state variables if not already done if 'conversations' not in st.session_state: st.session_state.conversations = {} if 'registrations' not in st.session_state: st.session_state.registrations = [] if 'current_user_id' not in st.session_state: st.session_state.current_user_id = str(uuid.uuid4()) if 'dashboard_view' not in st.session_state: st.session_state.dashboard_view = False if 'logged_in' not in st.session_state: st.session_state.logged_in = False if 'admin_view' not in st.session_state: st.session_state.admin_view = False if 'edit_mode' not in st.session_state: st.session_state.edit_mode = False if 'current_user_data' not in st.session_state: st.session_state.current_user_data = {} if 'selected_rows' not in st.session_state: st.session_state.selected_rows = [] # Load registrations from file if exists try: with open('registrations.json', 'r') as f: st.session_state.registrations = json.load(f) except FileNotFoundError: pass # Configure AutoGen def get_config_list(): return [{ "model": "gpt-4", # or any model you prefer "api_key": os.getenv("OPENAI_API_KEY"), }] # Initialize AutoGen agents assistant = AssistantAgent( name="registration_assistant", llm_config={"config_list": get_config_list()}, system_message=""" You are an event registration assistant for FiTA (Finland Telugu Association). Your job is to help users register for the Ugadi event happening on March 30th. Collect the following information in a conversational manner: - Full name - Email - Phone number - Number of attendees (accept text like "2 adults and 1 kid") - Preference for vegetarian or non-vegetarian food - Interest in cultural performances (yes/no) - Contribution to fund (options: €5/€10/€20; if the user doesn't specify, leave it blank) Be friendly, helpful, and respond in English or Telugu based on the user's preference. Avoid asking for all information at once - have a natural conversation. Keep track of information already collected and don't ask for it again. For each piece of information collected, make sure to acknowledge receipt and store it. If the user provides an email that is already registered, inform them with: "This email address is already registered. A new registration with this email is not allowed. Please use a different email or update your existing registration by logging in with your current email." Wait for their response before proceeding. If the user does not provide a contribution amount, do not assume a default value—leave it blank. Once all information is collected and the email is unique or an update is confirmed, confirm the registration details with the user in this format: "I've collected all the required information for your registration: - Name: [user's name] - Email: [user's email] - Phone: [user's phone] - Number of Attendees: [text input, e.g., '2 adults and 1 kid'] - Food Preference: [preference] - Cultural Performance Interest: [yes/no] - Fund Contribution: [amount or leave blank if not specified] Is this information correct? Your registration will be complete once you confirm." Once confirmed, let the user know they can now access their personalized dashboard. """ ) user_proxy = UserProxyAgent( name="user_proxy", human_input_mode="NEVER", code_execution_config=False, ) # Function to save registrations to file def save_registrations(): with open('registrations.json', 'w') as f: json.dump(st.session_state.registrations, f) # Function to check if email exists def is_email_registered(email): return any(reg.get('email') == email for reg in st.session_state.registrations) # Function to remove duplicate entries based on email (keep latest) def clear_duplicates(): if not st.session_state.registrations: return unique_registrations = {} for reg in sorted(st.session_state.registrations, key=lambda x: x.get('timestamp', ''), reverse=True): email = reg.get('email') if email and email not in unique_registrations: unique_registrations[email] = reg st.session_state.registrations = list(unique_registrations.values()) save_registrations() st.success("Duplicate entries cleared! Only the latest registration per email is retained.") # Function to delete a specific registration def delete_registration(index): if 0 <= index < len(st.session_state.registrations): del st.session_state.registrations[index] save_registrations() st.success("Registration deleted successfully!") st.rerun() # Function to delete selected registrations def delete_selected_registrations(): if st.session_state.selected_rows: # Sort in reverse to avoid index shifting issues for index in sorted(st.session_state.selected_rows, reverse=True): if 0 <= index < len(st.session_state.registrations): del st.session_state.registrations[index] st.session_state.selected_rows = [] save_registrations() st.success("Selected registrations deleted successfully!") st.rerun() # Function to process message with OpenAI def process_message(message, user_id): if user_id not in st.session_state.conversations: st.session_state.conversations[user_id] = [] # Add user message to conversation history st.session_state.conversations[user_id].append({"role": "user", "content": message}) # Find existing registration data for this user if any existing_data = {} for reg in st.session_state.registrations: if reg.get('user_id') == user_id: existing_data = reg break # Use OpenAI directly for more control over parsing response conversation_history = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.conversations[user_id]]) system_prompt = assistant.system_message if existing_data: system_prompt += f"\n\nUser already has the following information registered:\n" for key, value in existing_data.items(): if key not in ['user_id', 'timestamp'] and value: system_prompt += f"- {key}: {value}\n" response = openai.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Conversation history:\n{conversation_history}\nUser's latest message: {message}\n\nRespond to the user and extract any registration information. If the user provides an email that matches an existing registration and this is a new registration (not an update), include: 'This email address is already registered. A new registration with this email is not allowed. Please use a different email or update your existing registration by logging in with your current email.' and wait for their response. If all required information is collected and the email is unique or an update is confirmed, summarize it in a JSON format at the end of your message wrapped in tags. Make sure to include all fields: name, email, phone, attendees, food_preference, cultural_interest, contribution. If the contribution is not specified, set it to null in the JSON."} ] ) bot_response = response.choices[0].message.content # Extract registration data if present registration_data = None if '' in bot_response and '' in bot_response: try: data_start = bot_response.find('') + len('') data_end = bot_response.find('') registration_json = bot_response[data_start:data_end].strip() registration_data = json.loads(registration_json) # Check for existing email before saving if registration_data.get('email') and is_email_registered(registration_data['email']): if not existing_data: # New registration attempt with existing email bot_response += "\n\nNote: This email is already registered. A new registration with this email is not allowed. Please use a different email or update your existing registration." registration_data = None # Prevent saving until email issue is resolved else: # Update existing registration existing_data.update(registration_data) existing_data['updated_at'] = datetime.datetime.now().isoformat() else: # Add or update registration if existing_data: existing_data.update(registration_data) existing_data['updated_at'] = datetime.datetime.now().isoformat() else: registration_data['user_id'] = user_id registration_data['timestamp'] = datetime.datetime.now().isoformat() st.session_state.registrations.append(registration_data) save_registrations() # Set current user data for dashboard for reg in st.session_state.registrations: if reg.get('user_id') == user_id: st.session_state.current_user_data = reg break except Exception as e: st.error(f"Error processing registration data: {e}") # Add bot response to conversation history st.session_state.conversations[user_id].append({"role": "assistant", "content": bot_response}) return bot_response, registration_data # Update existing registration with edited data def update_registration(user_id, updated_data): for i, reg in enumerate(st.session_state.registrations): if reg.get('user_id') == user_id: # Ensure volunteer_roles is a list if 'volunteer_roles' in updated_data and updated_data['volunteer_roles'] is not None: if not isinstance(updated_data['volunteer_roles'], list): updated_data['volunteer_roles'] = [updated_data['volunteer_roles']] if updated_data['volunteer_roles'] else [] elif 'volunteer_roles' not in reg or reg['volunteer_roles'] is None: reg['volunteer_roles'] = [] st.session_state.registrations[i].update(updated_data) st.session_state.registrations[i]['updated_at'] = datetime.datetime.now().isoformat() st.session_state.current_user_data = st.session_state.registrations[i] save_registrations() return True return False # UI Components st.title("🪔 FiTA Ugadi Event Registration") # Sidebar with options with st.sidebar: st.image("https://via.placeholder.com/150x150.png?text=FiTA", width=150) sidebar_option = st.radio("Choose Option", ["ChatBot Registration", "User Dashboard", "Admin Panel"]) if sidebar_option == "ChatBot Registration": st.session_state.dashboard_view = False st.session_state.admin_view = False col1, col2 = st.columns([2, 1]) with col1: st.subheader("AI Registration Assistant") st.write("Chat with our AI assistant to register for the Ugadi event on March 30th") user_id = st.session_state.current_user_id if user_id in st.session_state.conversations: for message in st.session_state.conversations[user_id]: if message["role"] == "user": st.chat_message("user").write(message["content"]) else: st.chat_message("assistant").write(message["content"]) if prompt := st.chat_input("Type your message here..."): st.chat_message("user").write(prompt) response, registration_data = process_message(prompt, user_id) st.chat_message("assistant").write(response) if registration_data: st.success("Registration completed successfully! You can now access your personalized dashboard.") st.session_state.logged_in = True with col2: st.subheader("Event Highlights") st.markdown(""" 🗓️ **Date**: March 30, 2025 🕔 **Time**: 5:00 PM - 10:00 PM 📍 **Venue**: Community Hall, Helsinki ✨ **Activities**: * Traditional Telugu Cultural Performances * Authentic Telugu Cuisine * Community Networking * Kids Activities Register today to secure your spot! """) elif sidebar_option == "User Dashboard" and st.session_state.logged_in: st.session_state.dashboard_view = True st.session_state.admin_view = False user_id = st.session_state.current_user_id user_registrations = [r for r in st.session_state.registrations if r.get('user_id') == user_id] if user_registrations: user_data = user_registrations[-1] st.session_state.current_user_data = user_data st.header(f"Welcome, {user_data.get('name', 'User')}!") tabs = st.tabs(["Event Details", "My Registration", "Tasks", "Contributions"]) with tabs[0]: st.subheader("Ugadi Event Details") col1, col2 = st.columns(2) with col1: st.write("**Date:** March 30, 2025") st.write("**Time:** 5:00 PM - 10:00 PM") st.write("**Location:** Community Hall, Helsinki") st.write("**Theme:** Traditional Telugu New Year Celebration") with col2: event_date = datetime.datetime(2025, 3, 30) today = datetime.datetime.now() days_left = (event_date - today).days st.info(f"🗓️ {days_left} days left until the event!") st.write("**Event Program:**") st.write("5:00 PM - Registration & Welcome Drinks") st.write("6:00 PM - Cultural Performances") st.write("7:30 PM - Traditional Dinner") st.write("9:00 PM - Community Awards & Recognition") st.subheader("About Ugadi") st.write(""" Ugadi marks the beginning of the New Year for Telugu people. The festival is celebrated with great enthusiasm, including the preparation of special dishes, cultural performances, and community gatherings. Join us in keeping our traditions alive in Finland! """) with tabs[1]: st.subheader("My Registration Details") if not st.session_state.edit_mode: edit_col1, edit_col2 = st.columns([3, 1]) with edit_col2: if st.button("Edit Registration"): st.session_state.edit_mode = True if st.session_state.edit_mode: with st.form("edit_registration_form"): name = st.text_input("Name", value=user_data.get('name', '')) email = st.text_input("Email", value=user_data.get('email', '')) phone = st.text_input("Phone", value=user_data.get('phone', '')) attendees = st.text_input("Number of Attendees", value=user_data.get('attendees', '')) food_preference = st.selectbox("Food Preference", ["Vegetarian", "Non-vegetarian"], index=0 if user_data.get('food_preference', '') == "Vegetarian" else 1) cultural_interest = st.selectbox("Interest in Cultural Performances", ["yes", "no"], index=0 if user_data.get('cultural_interest', '') == "yes" else 1) contribution = st.selectbox("Fund Contribution", ["", "€5", "€10", "€20"], index=0 if not user_data.get('contribution') else 1 if user_data.get('contribution', '') == "€5" else 2 if user_data.get('contribution', '') == "€10" else 3) col1, col2 = st.columns(2) with col1: submit = st.form_submit_button("Save Changes") with col2: cancel = st.form_submit_button("Cancel") if submit: updated_data = { 'name': name, 'email': email, 'phone': phone, 'attendees': attendees, 'food_preference': food_preference, 'cultural_interest': cultural_interest, 'contribution': contribution if contribution else None } if update_registration(user_id, updated_data): st.success("Registration updated successfully!") st.session_state.edit_mode = False else: st.error("Failed to update registration. Please try again.") if cancel: st.session_state.edit_mode = False else: col1, col2 = st.columns(2) with col1: st.write(f"**Name:** {user_data.get('name', 'N/A')}") st.write(f"**Email:** {user_data.get('email', 'N/A')}") st.write(f"**Phone:** {user_data.get('phone', 'N/A')}") st.write(f"**Number of Attendees:** {user_data.get('attendees', 'N/A')}") with col2: st.write(f"**Food Preference:** {user_data.get('food_preference', 'N/A')}") st.write(f"**Cultural Performance Interest:** {user_data.get('cultural_interest', 'N/A')}") contribution_display = user_data.get('contribution', None) st.write(f"**Fund Contribution:** {contribution_display if contribution_display else 'N/A'}") payment_status = user_data.get('payment_status', 'pending') if payment_status == 'completed': st.success("Payment Status: Completed") else: st.warning("Payment Status: Pending") with tabs[2]: st.subheader("Your Tasks") tasks_completed = 0 total_tasks = 0 total_tasks += 1 if user_data.get('payment_status', '') != 'completed': st.warning("⚠️ Task 1: Complete your fund contribution payment") if st.button("Complete Payment"): contribution = user_data.get('contribution', None) if contribution: st.success(f"Payment of {contribution} completed successfully!") user_data['payment_status'] = 'completed' update_registration(user_id, {'payment_status': 'completed'}) else: st.warning("No contribution amount specified. Please update your contribution in the 'My Registration' tab.") else: st.success("✅ Task 1: Payment completed") tasks_completed += 1 if user_data.get('cultural_interest') == 'yes': total_tasks += 1 if not user_data.get('song_choice'): st.warning("⚠️ Task 2: Submit your song choice for the cultural performance by March 15th!") song_choice = st.text_input("Enter your song choice:") if st.button("Submit Song Choice"): if song_choice: st.success("Song choice submitted successfully!") update_registration(user_id, {'song_choice': song_choice}) tasks_completed += 1 else: st.success(f"✅ Task 2: Song choice submitted ({user_data.get('song_choice')})") tasks_completed += 1 total_tasks += 1 if not user_data.get('food_contribution'): st.warning("⚠️ Task 3: Consider contributing a food item to the event") else: st.success(f"✅ Task 3: Food contribution confirmed ({user_data.get('food_contribution')})") tasks_completed += 1 if user_data.get('attendees') and user_data.get('attendees') != '1': total_tasks += 1 if not user_data.get('family_members'): st.warning(f"⚠️ Task 4: Register the names of your additional family members") family_members = st.text_area("Enter names of family members attending with you:") if st.button("Submit Family Members"): if family_members: # Join multiple lines with semicolon family_members_list = [name.strip() for name in family_members.split('\n') if name.strip()] updated_family_members = '; '.join(family_members_list) st.success("Family members registered successfully!") update_registration(user_id, {'family_members': updated_family_members}) tasks_completed += 1 else: st.success(f"✅ Task 4: Family members registered") tasks_completed += 1 st.subheader("Registration Completion") progress = tasks_completed / total_tasks if total_tasks > 0 else 0 st.progress(progress) st.write(f"Completed {tasks_completed} of {total_tasks} tasks ({int(progress*100)}%)") with tabs[3]: st.subheader("Event Contributions") col1, col2 = st.columns(2) with col1: st.write("Would you like to contribute a dish to the event?") food_options = ["Sweets", "Snacks", "Main Course", "Dessert", "None"] selected_index = 4 if user_data.get('food_contribution') in food_options: selected_index = food_options.index(user_data.get('food_contribution')) food_contribution = st.selectbox("Select food item to contribute:", food_options, index=selected_index) if food_contribution != "None" and food_contribution != user_data.get('food_contribution'): if st.button("Confirm Food Contribution"): st.success(f"Thank you for offering to bring {food_contribution}!") update_registration(user_id, {'food_contribution': food_contribution}) st.rerun() with col2: st.write("Volunteer Opportunities:") current_roles = user_data.get('volunteer_roles', []) if isinstance(current_roles, str): current_roles = current_roles.split('; ') if current_roles else [] volunteer_options = st.multiselect( "Select areas where you'd like to help:", ["Setup (3:00-5:00 PM)", "Registration Desk", "Food Service", "Clean-up", "Photography", "Technical Support"], default=current_roles ) if volunteer_options != current_roles: if st.button("Update Volunteer Roles"): st.success("Thank you for volunteering! The organizing team will contact you soon.") update_registration(user_id, {'volunteer_roles': volunteer_options}) st.rerun() else: st.warning("Please register using the chatbot first to access your dashboard.") st.session_state.dashboard_view = False elif sidebar_option == "User Dashboard" and not st.session_state.logged_in: st.warning("Please register using the chatbot first to access your dashboard.") if st.button("Go to Registration"): st.session_state.dashboard_view = False st.rerun() elif sidebar_option == "Admin Panel": st.session_state.dashboard_view = False st.session_state.admin_view = True admin_password = st.sidebar.text_input("Admin Password:", type="password", help="Default: admin123") if admin_password == "admin123": st.header("Admin Dashboard") admin_tabs = st.tabs(["Registrations", "Analytics", "Export Data"]) with admin_tabs[0]: st.subheader("Event Registrations") if st.session_state.registrations: # Create DataFrame with core columns that are always present core_columns = ['name', 'email', 'phone', 'attendees', 'food_preference', 'cultural_interest', 'contribution'] df = pd.DataFrame(st.session_state.registrations)[core_columns] # Add optional columns if they exist, filling missing values with None and ensuring volunteer_roles is a list optional_columns = ['food_contribution', 'payment_status', 'song_choice', 'family_members', 'volunteer_roles'] for col in optional_columns: if any(col in reg for reg in st.session_state.registrations): if col == 'volunteer_roles': df[col] = [reg.get(col, []) for reg in st.session_state.registrations] # Ensure list else: df[col] = [reg.get(col, '') for reg in st.session_state.registrations] # Add checkbox column for selection df_with_checkbox = df.copy() df_with_checkbox.insert(0, 'Select', False) # Display DataFrame with checkboxes edited_df = st.data_editor(df_with_checkbox, hide_index=True, use_container_width=True) # Update selected rows st.session_state.selected_rows = [i for i, row in edited_df.iterrows() if row['Select']] if 'user_id' in df.columns: df = df.drop(columns=['user_id', 'timestamp', 'updated_at'], errors='ignore') st.dataframe(df) # Display clean DataFrame without checkboxes st.info(f"Total Registrations: {len(st.session_state.registrations)}") # Check for duplicates email_counts = df['email'].value_counts() duplicate_emails = email_counts[email_counts > 1].index.tolist() if duplicate_emails: st.warning(f"Duplicate emails found: {', '.join(duplicate_emails)}") for email in duplicate_emails: duplicates = df[df['email'] == email].index.tolist() for idx in duplicates[1:]: # Skip the first (latest) entry if st.button(f"Delete Duplicate Entry for {email} at Index {idx}"): delete_registration(idx) # Clear duplicates button if st.button("Clear Duplicates"): clear_duplicates() st.rerun() # Delete selected button if st.button("Delete Selected"): delete_selected_registrations() search_term = st.text_input("Search by name or email:") if search_term: filtered_df = df[df['name'].str.contains(search_term, case=False, na=False) | df['email'].str.contains(search_term, case=False, na=False)] st.subheader("Search Results") st.dataframe(filtered_df) else: st.info("No registrations available.") with admin_tabs[1]: st.subheader("Registration Analytics") if st.session_state.registrations: df = pd.DataFrame(st.session_state.registrations) col1, col2 = st.columns(2) with col1: st.write("**Food Preference Distribution:**") food_prefs = df['food_preference'].value_counts() st.bar_chart(food_prefs) st.write("**Cultural Performance Interest:**") cultural = df['cultural_interest'].value_counts() st.bar_chart(cultural) with col2: st.write("**Fund Contribution Distribution:**") contributions = df['contribution'].value_counts() st.bar_chart(contributions) st.write("**Food Contributions:**") food_contributions = df['food_contribution'].value_counts() st.bar_chart(food_contributions) st.subheader("Summary Statistics") col1, col2, col3 = st.columns(3) with col1: st.metric("Total Registrations", len(st.session_state.registrations)) with col2: total_contribution = sum(int(r.get('contribution', '0').replace('€', '')) for r in st.session_state.registrations if r.get('contribution')) st.metric("Total Fund Collection", f"€{total_contribution}") with col3: cultural_performances = sum(1 for r in st.session_state.registrations if r.get('cultural_interest') == 'yes') st.metric("Cultural Performances", cultural_performances) else: st.info("No data available for analytics yet.") with admin_tabs[2]: st.subheader("Export Registration Data") if st.session_state.registrations: # Create DataFrame with core and optional columns core_columns = ['name', 'email', 'phone', 'attendees', 'food_preference', 'cultural_interest', 'contribution'] df = pd.DataFrame(st.session_state.registrations)[core_columns] optional_columns = ['food_contribution', 'payment_status', 'song_choice', 'family_members', 'volunteer_roles'] for col in optional_columns: if any(col in reg for reg in st.session_state.registrations): if col == 'volunteer_roles': df[col] = [reg.get(col, []) for reg in st.session_state.registrations] # Ensure list else: df[col] = [reg.get(col, '') for reg in st.session_state.registrations] df = df.drop(columns=['user_id', 'timestamp', 'updated_at'], errors='ignore') csv = df.to_csv(index=False) st.download_button( label="Download Registrations as CSV", data=csv, file_name=f"ugadi_registrations_{datetime.datetime.now().strftime('%Y%m%d_%H%M')}.csv", mime="text/csv" ) st.subheader("Attendee List") attendee_list = "" for i, reg in enumerate(st.session_state.registrations, 1): attendee_list += f"{i}. {reg.get('name', 'Unknown')} - {reg.get('attendees', 'N/A')} attendees\n" st.text_area("Attendee List (Copy & Paste)", attendee_list, height=300) st.subheader("Email List") email_list = "\n".join([reg.get('email', '') for reg in st.session_state.registrations if reg.get('email')]) st.text_area("Email List (Copy & Paste)", email_list, height=150) else: st.info("No registrations to export yet.") else: st.warning("Please enter the admin password to access the admin panel.") # Footer st.markdown("---") st.markdown("© 2025 Finland Telugu Association (FiTA) | Created by Goutham Ippili | Powered by AI")