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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import streamlit as st
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import datetime
|
6 |
+
import pandas as pd
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
import openai
|
9 |
+
import autogen
|
10 |
+
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
|
11 |
+
import uuid
|
12 |
+
|
13 |
+
# Load environment variables
|
14 |
+
load_dotenv()
|
15 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
16 |
+
|
17 |
+
# Set Streamlit page configuration for better visuals
|
18 |
+
st.set_page_config(
|
19 |
+
page_title="FiTA Ugadi Event Registration",
|
20 |
+
page_icon="🪔",
|
21 |
+
layout="wide",
|
22 |
+
initial_sidebar_state="expanded",
|
23 |
+
)
|
24 |
+
|
25 |
+
# Custom styling for a more appealing visual experience
|
26 |
+
st.markdown("""
|
27 |
+
<style>
|
28 |
+
/* Main background and text colors */
|
29 |
+
.stApp {
|
30 |
+
background-color: #f8f9fa;
|
31 |
+
color: #333333;
|
32 |
+
}
|
33 |
+
|
34 |
+
/* Header styling */
|
35 |
+
h1, h2, h3 {
|
36 |
+
color: #5c3566;
|
37 |
+
}
|
38 |
+
|
39 |
+
/* Button styling */
|
40 |
+
.stButton button {
|
41 |
+
background-color: #5c3566;
|
42 |
+
color: white;
|
43 |
+
border-radius: 5px;
|
44 |
+
}
|
45 |
+
|
46 |
+
.stButton button:hover {
|
47 |
+
background-color: #7d4a8d;
|
48 |
+
}
|
49 |
+
|
50 |
+
/* Sidebar styling */
|
51 |
+
.css-1d391kg {
|
52 |
+
background-color: #f0e6f5;
|
53 |
+
}
|
54 |
+
|
55 |
+
/* Card-like elements */
|
56 |
+
.css-1r6slb0, .css-12w0qpk {
|
57 |
+
background-color: white;
|
58 |
+
border-radius: 10px;
|
59 |
+
padding: 20px;
|
60 |
+
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
61 |
+
margin-bottom: 20px;
|
62 |
+
}
|
63 |
+
|
64 |
+
/* Chat message styling */
|
65 |
+
.stChatMessage {
|
66 |
+
background-color: #f5f5f5;
|
67 |
+
border-radius: 15px;
|
68 |
+
padding: 10px;
|
69 |
+
margin-bottom: 10px;
|
70 |
+
}
|
71 |
+
|
72 |
+
/* Tabs styling */
|
73 |
+
.stTabs [data-baseweb="tab-list"] {
|
74 |
+
gap: 8px;
|
75 |
+
}
|
76 |
+
|
77 |
+
.stTabs [data-baseweb="tab"] {
|
78 |
+
background-color: #f0e6f5;
|
79 |
+
border-radius: 4px 4px 0px 0px;
|
80 |
+
padding: 10px 20px;
|
81 |
+
color: #5c3566;
|
82 |
+
}
|
83 |
+
|
84 |
+
.stTabs [aria-selected="true"] {
|
85 |
+
background-color: #5c3566;
|
86 |
+
color: white;
|
87 |
+
}
|
88 |
+
</style>
|
89 |
+
""", unsafe_allow_html=True)
|
90 |
+
|
91 |
+
# Initialize session state variables if not already done
|
92 |
+
if 'conversations' not in st.session_state:
|
93 |
+
st.session_state.conversations = {}
|
94 |
+
if 'registrations' not in st.session_state:
|
95 |
+
st.session_state.registrations = []
|
96 |
+
if 'current_user_id' not in st.session_state:
|
97 |
+
st.session_state.current_user_id = str(uuid.uuid4())
|
98 |
+
if 'dashboard_view' not in st.session_state:
|
99 |
+
st.session_state.dashboard_view = False
|
100 |
+
if 'logged_in' not in st.session_state:
|
101 |
+
st.session_state.logged_in = False
|
102 |
+
if 'admin_view' not in st.session_state:
|
103 |
+
st.session_state.admin_view = False
|
104 |
+
if 'edit_mode' not in st.session_state:
|
105 |
+
st.session_state.edit_mode = False
|
106 |
+
if 'current_user_data' not in st.session_state:
|
107 |
+
st.session_state.current_user_data = {}
|
108 |
+
if 'selected_rows' not in st.session_state:
|
109 |
+
st.session_state.selected_rows = []
|
110 |
+
|
111 |
+
# Load registrations from file if exists
|
112 |
+
try:
|
113 |
+
with open('registrations.json', 'r') as f:
|
114 |
+
st.session_state.registrations = json.load(f)
|
115 |
+
except FileNotFoundError:
|
116 |
+
pass
|
117 |
+
|
118 |
+
# Configure AutoGen
|
119 |
+
def get_config_list():
|
120 |
+
return [{
|
121 |
+
"model": "gpt-4", # or any model you prefer
|
122 |
+
"api_key": os.getenv("OPENAI_API_KEY"),
|
123 |
+
}]
|
124 |
+
|
125 |
+
# Initialize AutoGen agents
|
126 |
+
assistant = AssistantAgent(
|
127 |
+
name="registration_assistant",
|
128 |
+
llm_config={"config_list": get_config_list()},
|
129 |
+
system_message="""
|
130 |
+
You are an event registration assistant for FiTA (Finland Telugu Association).
|
131 |
+
Your job is to help users register for the Ugadi event happening on March 30th.
|
132 |
+
Collect the following information in a conversational manner:
|
133 |
+
- Full name
|
134 |
+
- Email
|
135 |
+
- Phone number
|
136 |
+
- Number of attendees (accept text like "2 adults and 1 kid")
|
137 |
+
- Preference for vegetarian or non-vegetarian food
|
138 |
+
- Interest in cultural performances (yes/no)
|
139 |
+
- Contribution to fund (options: €5/€10/€20; if the user doesn't specify, leave it blank)
|
140 |
+
|
141 |
+
Be friendly, helpful, and respond in English or Telugu based on the user's preference.
|
142 |
+
Avoid asking for all information at once - have a natural conversation.
|
143 |
+
Keep track of information already collected and don't ask for it again.
|
144 |
+
|
145 |
+
For each piece of information collected, make sure to acknowledge receipt and store it.
|
146 |
+
If the user provides an email that is already registered, inform them with:
|
147 |
+
"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."
|
148 |
+
Wait for their response before proceeding.
|
149 |
+
If the user does not provide a contribution amount, do not assume a default value—leave it blank.
|
150 |
+
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:
|
151 |
+
|
152 |
+
"I've collected all the required information for your registration:
|
153 |
+
- Name: [user's name]
|
154 |
+
- Email: [user's email]
|
155 |
+
- Phone: [user's phone]
|
156 |
+
- Number of Attendees: [text input, e.g., '2 adults and 1 kid']
|
157 |
+
- Food Preference: [preference]
|
158 |
+
- Cultural Performance Interest: [yes/no]
|
159 |
+
- Fund Contribution: [amount or leave blank if not specified]
|
160 |
+
|
161 |
+
Is this information correct? Your registration will be complete once you confirm."
|
162 |
+
|
163 |
+
Once confirmed, let the user know they can now access their personalized dashboard.
|
164 |
+
"""
|
165 |
+
)
|
166 |
+
|
167 |
+
user_proxy = UserProxyAgent(
|
168 |
+
name="user_proxy",
|
169 |
+
human_input_mode="NEVER",
|
170 |
+
code_execution_config=False,
|
171 |
+
)
|
172 |
+
|
173 |
+
# Function to save registrations to file
|
174 |
+
def save_registrations():
|
175 |
+
with open('registrations.json', 'w') as f:
|
176 |
+
json.dump(st.session_state.registrations, f)
|
177 |
+
|
178 |
+
# Function to check if email exists
|
179 |
+
def is_email_registered(email):
|
180 |
+
return any(reg.get('email') == email for reg in st.session_state.registrations)
|
181 |
+
|
182 |
+
# Function to remove duplicate entries based on email (keep latest)
|
183 |
+
def clear_duplicates():
|
184 |
+
if not st.session_state.registrations:
|
185 |
+
return
|
186 |
+
unique_registrations = {}
|
187 |
+
for reg in sorted(st.session_state.registrations, key=lambda x: x.get('timestamp', ''), reverse=True):
|
188 |
+
email = reg.get('email')
|
189 |
+
if email and email not in unique_registrations:
|
190 |
+
unique_registrations[email] = reg
|
191 |
+
st.session_state.registrations = list(unique_registrations.values())
|
192 |
+
save_registrations()
|
193 |
+
st.success("Duplicate entries cleared! Only the latest registration per email is retained.")
|
194 |
+
|
195 |
+
# Function to delete a specific registration
|
196 |
+
def delete_registration(index):
|
197 |
+
if 0 <= index < len(st.session_state.registrations):
|
198 |
+
del st.session_state.registrations[index]
|
199 |
+
save_registrations()
|
200 |
+
st.success("Registration deleted successfully!")
|
201 |
+
st.rerun()
|
202 |
+
|
203 |
+
# Function to delete selected registrations
|
204 |
+
def delete_selected_registrations():
|
205 |
+
if st.session_state.selected_rows:
|
206 |
+
# Sort in reverse to avoid index shifting issues
|
207 |
+
for index in sorted(st.session_state.selected_rows, reverse=True):
|
208 |
+
if 0 <= index < len(st.session_state.registrations):
|
209 |
+
del st.session_state.registrations[index]
|
210 |
+
st.session_state.selected_rows = []
|
211 |
+
save_registrations()
|
212 |
+
st.success("Selected registrations deleted successfully!")
|
213 |
+
st.rerun()
|
214 |
+
|
215 |
+
# Function to process message with OpenAI
|
216 |
+
def process_message(message, user_id):
|
217 |
+
if user_id not in st.session_state.conversations:
|
218 |
+
st.session_state.conversations[user_id] = []
|
219 |
+
|
220 |
+
# Add user message to conversation history
|
221 |
+
st.session_state.conversations[user_id].append({"role": "user", "content": message})
|
222 |
+
|
223 |
+
# Find existing registration data for this user if any
|
224 |
+
existing_data = {}
|
225 |
+
for reg in st.session_state.registrations:
|
226 |
+
if reg.get('user_id') == user_id:
|
227 |
+
existing_data = reg
|
228 |
+
break
|
229 |
+
|
230 |
+
# Use OpenAI directly for more control over parsing response
|
231 |
+
conversation_history = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.conversations[user_id]])
|
232 |
+
|
233 |
+
system_prompt = assistant.system_message
|
234 |
+
if existing_data:
|
235 |
+
system_prompt += f"\n\nUser already has the following information registered:\n"
|
236 |
+
for key, value in existing_data.items():
|
237 |
+
if key not in ['user_id', 'timestamp'] and value:
|
238 |
+
system_prompt += f"- {key}: {value}\n"
|
239 |
+
|
240 |
+
response = openai.chat.completions.create(
|
241 |
+
model="gpt-4",
|
242 |
+
messages=[
|
243 |
+
{"role": "system", "content": system_prompt},
|
244 |
+
{"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 <registration_data> 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."}
|
245 |
+
]
|
246 |
+
)
|
247 |
+
|
248 |
+
bot_response = response.choices[0].message.content
|
249 |
+
|
250 |
+
# Extract registration data if present
|
251 |
+
registration_data = None
|
252 |
+
if '<registration_data>' in bot_response and '</registration_data>' in bot_response:
|
253 |
+
try:
|
254 |
+
data_start = bot_response.find('<registration_data>') + len('<registration_data>')
|
255 |
+
data_end = bot_response.find('</registration_data>')
|
256 |
+
registration_json = bot_response[data_start:data_end].strip()
|
257 |
+
registration_data = json.loads(registration_json)
|
258 |
+
|
259 |
+
# Check for existing email before saving
|
260 |
+
if registration_data.get('email') and is_email_registered(registration_data['email']):
|
261 |
+
if not existing_data: # New registration attempt with existing email
|
262 |
+
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."
|
263 |
+
registration_data = None # Prevent saving until email issue is resolved
|
264 |
+
else:
|
265 |
+
# Update existing registration
|
266 |
+
existing_data.update(registration_data)
|
267 |
+
existing_data['updated_at'] = datetime.datetime.now().isoformat()
|
268 |
+
else:
|
269 |
+
# Add or update registration
|
270 |
+
if existing_data:
|
271 |
+
existing_data.update(registration_data)
|
272 |
+
existing_data['updated_at'] = datetime.datetime.now().isoformat()
|
273 |
+
else:
|
274 |
+
registration_data['user_id'] = user_id
|
275 |
+
registration_data['timestamp'] = datetime.datetime.now().isoformat()
|
276 |
+
st.session_state.registrations.append(registration_data)
|
277 |
+
|
278 |
+
save_registrations()
|
279 |
+
|
280 |
+
# Set current user data for dashboard
|
281 |
+
for reg in st.session_state.registrations:
|
282 |
+
if reg.get('user_id') == user_id:
|
283 |
+
st.session_state.current_user_data = reg
|
284 |
+
break
|
285 |
+
except Exception as e:
|
286 |
+
st.error(f"Error processing registration data: {e}")
|
287 |
+
|
288 |
+
# Add bot response to conversation history
|
289 |
+
st.session_state.conversations[user_id].append({"role": "assistant", "content": bot_response})
|
290 |
+
|
291 |
+
return bot_response, registration_data
|
292 |
+
|
293 |
+
# Update existing registration with edited data
|
294 |
+
def update_registration(user_id, updated_data):
|
295 |
+
for i, reg in enumerate(st.session_state.registrations):
|
296 |
+
if reg.get('user_id') == user_id:
|
297 |
+
# Ensure volunteer_roles is a list
|
298 |
+
if 'volunteer_roles' in updated_data and updated_data['volunteer_roles'] is not None:
|
299 |
+
if not isinstance(updated_data['volunteer_roles'], list):
|
300 |
+
updated_data['volunteer_roles'] = [updated_data['volunteer_roles']] if updated_data['volunteer_roles'] else []
|
301 |
+
elif 'volunteer_roles' not in reg or reg['volunteer_roles'] is None:
|
302 |
+
reg['volunteer_roles'] = []
|
303 |
+
|
304 |
+
st.session_state.registrations[i].update(updated_data)
|
305 |
+
st.session_state.registrations[i]['updated_at'] = datetime.datetime.now().isoformat()
|
306 |
+
st.session_state.current_user_data = st.session_state.registrations[i]
|
307 |
+
save_registrations()
|
308 |
+
return True
|
309 |
+
return False
|
310 |
+
|
311 |
+
# UI Components
|
312 |
+
st.title("🪔 FiTA Ugadi Event Registration")
|
313 |
+
|
314 |
+
# Sidebar with options
|
315 |
+
with st.sidebar:
|
316 |
+
st.image("https://via.placeholder.com/150x150.png?text=FiTA", width=150)
|
317 |
+
sidebar_option = st.radio("Choose Option", ["ChatBot Registration", "User Dashboard", "Admin Panel"])
|
318 |
+
|
319 |
+
if sidebar_option == "ChatBot Registration":
|
320 |
+
st.session_state.dashboard_view = False
|
321 |
+
st.session_state.admin_view = False
|
322 |
+
|
323 |
+
col1, col2 = st.columns([2, 1])
|
324 |
+
|
325 |
+
with col1:
|
326 |
+
st.subheader("AI Registration Assistant")
|
327 |
+
st.write("Chat with our AI assistant to register for the Ugadi event on March 30th")
|
328 |
+
|
329 |
+
user_id = st.session_state.current_user_id
|
330 |
+
if user_id in st.session_state.conversations:
|
331 |
+
for message in st.session_state.conversations[user_id]:
|
332 |
+
if message["role"] == "user":
|
333 |
+
st.chat_message("user").write(message["content"])
|
334 |
+
else:
|
335 |
+
st.chat_message("assistant").write(message["content"])
|
336 |
+
|
337 |
+
if prompt := st.chat_input("Type your message here..."):
|
338 |
+
st.chat_message("user").write(prompt)
|
339 |
+
response, registration_data = process_message(prompt, user_id)
|
340 |
+
st.chat_message("assistant").write(response)
|
341 |
+
|
342 |
+
if registration_data:
|
343 |
+
st.success("Registration completed successfully! You can now access your personalized dashboard.")
|
344 |
+
st.session_state.logged_in = True
|
345 |
+
|
346 |
+
with col2:
|
347 |
+
st.subheader("Event Highlights")
|
348 |
+
st.markdown("""
|
349 |
+
🗓️ **Date**: March 30, 2025
|
350 |
+
|
351 |
+
🕔 **Time**: 5:00 PM - 10:00 PM
|
352 |
+
|
353 |
+
📍 **Venue**: Community Hall, Helsinki
|
354 |
+
|
355 |
+
✨ **Activities**:
|
356 |
+
* Traditional Telugu Cultural Performances
|
357 |
+
* Authentic Telugu Cuisine
|
358 |
+
* Community Networking
|
359 |
+
* Kids Activities
|
360 |
+
|
361 |
+
Register today to secure your spot!
|
362 |
+
""")
|
363 |
+
|
364 |
+
elif sidebar_option == "User Dashboard" and st.session_state.logged_in:
|
365 |
+
st.session_state.dashboard_view = True
|
366 |
+
st.session_state.admin_view = False
|
367 |
+
|
368 |
+
user_id = st.session_state.current_user_id
|
369 |
+
user_registrations = [r for r in st.session_state.registrations if r.get('user_id') == user_id]
|
370 |
+
|
371 |
+
if user_registrations:
|
372 |
+
user_data = user_registrations[-1]
|
373 |
+
st.session_state.current_user_data = user_data
|
374 |
+
|
375 |
+
st.header(f"Welcome, {user_data.get('name', 'User')}!")
|
376 |
+
|
377 |
+
tabs = st.tabs(["Event Details", "My Registration", "Tasks", "Contributions"])
|
378 |
+
|
379 |
+
with tabs[0]:
|
380 |
+
st.subheader("Ugadi Event Details")
|
381 |
+
col1, col2 = st.columns(2)
|
382 |
+
with col1:
|
383 |
+
st.write("**Date:** March 30, 2025")
|
384 |
+
st.write("**Time:** 5:00 PM - 10:00 PM")
|
385 |
+
st.write("**Location:** Community Hall, Helsinki")
|
386 |
+
st.write("**Theme:** Traditional Telugu New Year Celebration")
|
387 |
+
with col2:
|
388 |
+
event_date = datetime.datetime(2025, 3, 30)
|
389 |
+
today = datetime.datetime.now()
|
390 |
+
days_left = (event_date - today).days
|
391 |
+
st.info(f"🗓️ {days_left} days left until the event!")
|
392 |
+
st.write("**Event Program:**")
|
393 |
+
st.write("5:00 PM - Registration & Welcome Drinks")
|
394 |
+
st.write("6:00 PM - Cultural Performances")
|
395 |
+
st.write("7:30 PM - Traditional Dinner")
|
396 |
+
st.write("9:00 PM - Community Awards & Recognition")
|
397 |
+
st.subheader("About Ugadi")
|
398 |
+
st.write("""
|
399 |
+
Ugadi marks the beginning of the New Year for Telugu people. The festival is celebrated with great enthusiasm,
|
400 |
+
including the preparation of special dishes, cultural performances, and community gatherings. Join us in keeping
|
401 |
+
our traditions alive in Finland!
|
402 |
+
""")
|
403 |
+
|
404 |
+
with tabs[1]:
|
405 |
+
st.subheader("My Registration Details")
|
406 |
+
if not st.session_state.edit_mode:
|
407 |
+
edit_col1, edit_col2 = st.columns([3, 1])
|
408 |
+
with edit_col2:
|
409 |
+
if st.button("Edit Registration"):
|
410 |
+
st.session_state.edit_mode = True
|
411 |
+
if st.session_state.edit_mode:
|
412 |
+
with st.form("edit_registration_form"):
|
413 |
+
name = st.text_input("Name", value=user_data.get('name', ''))
|
414 |
+
email = st.text_input("Email", value=user_data.get('email', ''))
|
415 |
+
phone = st.text_input("Phone", value=user_data.get('phone', ''))
|
416 |
+
attendees = st.text_input("Number of Attendees", value=user_data.get('attendees', ''))
|
417 |
+
food_preference = st.selectbox("Food Preference",
|
418 |
+
["Vegetarian", "Non-vegetarian"],
|
419 |
+
index=0 if user_data.get('food_preference', '') == "Vegetarian" else 1)
|
420 |
+
cultural_interest = st.selectbox("Interest in Cultural Performances",
|
421 |
+
["yes", "no"],
|
422 |
+
index=0 if user_data.get('cultural_interest', '') == "yes" else 1)
|
423 |
+
contribution = st.selectbox("Fund Contribution",
|
424 |
+
["", "€5", "€10", "€20"],
|
425 |
+
index=0 if not user_data.get('contribution') else
|
426 |
+
1 if user_data.get('contribution', '') == "€5" else
|
427 |
+
2 if user_data.get('contribution', '') == "€10" else 3)
|
428 |
+
col1, col2 = st.columns(2)
|
429 |
+
with col1:
|
430 |
+
submit = st.form_submit_button("Save Changes")
|
431 |
+
with col2:
|
432 |
+
cancel = st.form_submit_button("Cancel")
|
433 |
+
if submit:
|
434 |
+
updated_data = {
|
435 |
+
'name': name,
|
436 |
+
'email': email,
|
437 |
+
'phone': phone,
|
438 |
+
'attendees': attendees,
|
439 |
+
'food_preference': food_preference,
|
440 |
+
'cultural_interest': cultural_interest,
|
441 |
+
'contribution': contribution if contribution else None
|
442 |
+
}
|
443 |
+
if update_registration(user_id, updated_data):
|
444 |
+
st.success("Registration updated successfully!")
|
445 |
+
st.session_state.edit_mode = False
|
446 |
+
else:
|
447 |
+
st.error("Failed to update registration. Please try again.")
|
448 |
+
if cancel:
|
449 |
+
st.session_state.edit_mode = False
|
450 |
+
else:
|
451 |
+
col1, col2 = st.columns(2)
|
452 |
+
with col1:
|
453 |
+
st.write(f"**Name:** {user_data.get('name', 'N/A')}")
|
454 |
+
st.write(f"**Email:** {user_data.get('email', 'N/A')}")
|
455 |
+
st.write(f"**Phone:** {user_data.get('phone', 'N/A')}")
|
456 |
+
st.write(f"**Number of Attendees:** {user_data.get('attendees', 'N/A')}")
|
457 |
+
with col2:
|
458 |
+
st.write(f"**Food Preference:** {user_data.get('food_preference', 'N/A')}")
|
459 |
+
st.write(f"**Cultural Performance Interest:** {user_data.get('cultural_interest', 'N/A')}")
|
460 |
+
contribution_display = user_data.get('contribution', None)
|
461 |
+
st.write(f"**Fund Contribution:** {contribution_display if contribution_display else 'N/A'}")
|
462 |
+
payment_status = user_data.get('payment_status', 'pending')
|
463 |
+
if payment_status == 'completed':
|
464 |
+
st.success("Payment Status: Completed")
|
465 |
+
else:
|
466 |
+
st.warning("Payment Status: Pending")
|
467 |
+
|
468 |
+
with tabs[2]:
|
469 |
+
st.subheader("Your Tasks")
|
470 |
+
tasks_completed = 0
|
471 |
+
total_tasks = 0
|
472 |
+
total_tasks += 1
|
473 |
+
if user_data.get('payment_status', '') != 'completed':
|
474 |
+
st.warning("⚠️ Task 1: Complete your fund contribution payment")
|
475 |
+
if st.button("Complete Payment"):
|
476 |
+
contribution = user_data.get('contribution', None)
|
477 |
+
if contribution:
|
478 |
+
st.success(f"Payment of {contribution} completed successfully!")
|
479 |
+
user_data['payment_status'] = 'completed'
|
480 |
+
update_registration(user_id, {'payment_status': 'completed'})
|
481 |
+
else:
|
482 |
+
st.warning("No contribution amount specified. Please update your contribution in the 'My Registration' tab.")
|
483 |
+
else:
|
484 |
+
st.success("✅ Task 1: Payment completed")
|
485 |
+
tasks_completed += 1
|
486 |
+
if user_data.get('cultural_interest') == 'yes':
|
487 |
+
total_tasks += 1
|
488 |
+
if not user_data.get('song_choice'):
|
489 |
+
st.warning("⚠️ Task 2: Submit your song choice for the cultural performance by March 15th!")
|
490 |
+
song_choice = st.text_input("Enter your song choice:")
|
491 |
+
if st.button("Submit Song Choice"):
|
492 |
+
if song_choice:
|
493 |
+
st.success("Song choice submitted successfully!")
|
494 |
+
update_registration(user_id, {'song_choice': song_choice})
|
495 |
+
tasks_completed += 1
|
496 |
+
else:
|
497 |
+
st.success(f"✅ Task 2: Song choice submitted ({user_data.get('song_choice')})")
|
498 |
+
tasks_completed += 1
|
499 |
+
total_tasks += 1
|
500 |
+
if not user_data.get('food_contribution'):
|
501 |
+
st.warning("⚠️ Task 3: Consider contributing a food item to the event")
|
502 |
+
else:
|
503 |
+
st.success(f"✅ Task 3: Food contribution confirmed ({user_data.get('food_contribution')})")
|
504 |
+
tasks_completed += 1
|
505 |
+
if user_data.get('attendees') and user_data.get('attendees') != '1':
|
506 |
+
total_tasks += 1
|
507 |
+
if not user_data.get('family_members'):
|
508 |
+
st.warning(f"⚠️ Task 4: Register the names of your additional family members")
|
509 |
+
family_members = st.text_area("Enter names of family members attending with you:")
|
510 |
+
if st.button("Submit Family Members"):
|
511 |
+
if family_members:
|
512 |
+
# Join multiple lines with semicolon
|
513 |
+
family_members_list = [name.strip() for name in family_members.split('\n') if name.strip()]
|
514 |
+
updated_family_members = '; '.join(family_members_list)
|
515 |
+
st.success("Family members registered successfully!")
|
516 |
+
update_registration(user_id, {'family_members': updated_family_members})
|
517 |
+
tasks_completed += 1
|
518 |
+
else:
|
519 |
+
st.success(f"✅ Task 4: Family members registered")
|
520 |
+
tasks_completed += 1
|
521 |
+
st.subheader("Registration Completion")
|
522 |
+
progress = tasks_completed / total_tasks if total_tasks > 0 else 0
|
523 |
+
st.progress(progress)
|
524 |
+
st.write(f"Completed {tasks_completed} of {total_tasks} tasks ({int(progress*100)}%)")
|
525 |
+
|
526 |
+
with tabs[3]:
|
527 |
+
st.subheader("Event Contributions")
|
528 |
+
col1, col2 = st.columns(2)
|
529 |
+
with col1:
|
530 |
+
st.write("Would you like to contribute a dish to the event?")
|
531 |
+
food_options = ["Sweets", "Snacks", "Main Course", "Dessert", "None"]
|
532 |
+
selected_index = 4
|
533 |
+
if user_data.get('food_contribution') in food_options:
|
534 |
+
selected_index = food_options.index(user_data.get('food_contribution'))
|
535 |
+
food_contribution = st.selectbox("Select food item to contribute:", food_options, index=selected_index)
|
536 |
+
if food_contribution != "None" and food_contribution != user_data.get('food_contribution'):
|
537 |
+
if st.button("Confirm Food Contribution"):
|
538 |
+
st.success(f"Thank you for offering to bring {food_contribution}!")
|
539 |
+
update_registration(user_id, {'food_contribution': food_contribution})
|
540 |
+
st.rerun()
|
541 |
+
with col2:
|
542 |
+
st.write("Volunteer Opportunities:")
|
543 |
+
current_roles = user_data.get('volunteer_roles', [])
|
544 |
+
if isinstance(current_roles, str):
|
545 |
+
current_roles = current_roles.split('; ') if current_roles else []
|
546 |
+
volunteer_options = st.multiselect(
|
547 |
+
"Select areas where you'd like to help:",
|
548 |
+
["Setup (3:00-5:00 PM)", "Registration Desk", "Food Service", "Clean-up", "Photography", "Technical Support"],
|
549 |
+
default=current_roles
|
550 |
+
)
|
551 |
+
if volunteer_options != current_roles:
|
552 |
+
if st.button("Update Volunteer Roles"):
|
553 |
+
st.success("Thank you for volunteering! The organizing team will contact you soon.")
|
554 |
+
update_registration(user_id, {'volunteer_roles': volunteer_options})
|
555 |
+
st.rerun()
|
556 |
+
else:
|
557 |
+
st.warning("Please register using the chatbot first to access your dashboard.")
|
558 |
+
st.session_state.dashboard_view = False
|
559 |
+
|
560 |
+
elif sidebar_option == "User Dashboard" and not st.session_state.logged_in:
|
561 |
+
st.warning("Please register using the chatbot first to access your dashboard.")
|
562 |
+
if st.button("Go to Registration"):
|
563 |
+
st.session_state.dashboard_view = False
|
564 |
+
st.rerun()
|
565 |
+
|
566 |
+
elif sidebar_option == "Admin Panel":
|
567 |
+
st.session_state.dashboard_view = False
|
568 |
+
st.session_state.admin_view = True
|
569 |
+
|
570 |
+
admin_password = st.sidebar.text_input("Admin Password:", type="password", help="Default: admin123")
|
571 |
+
if admin_password == "admin123":
|
572 |
+
st.header("Admin Dashboard")
|
573 |
+
|
574 |
+
admin_tabs = st.tabs(["Registrations", "Analytics", "Export Data"])
|
575 |
+
|
576 |
+
with admin_tabs[0]:
|
577 |
+
st.subheader("Event Registrations")
|
578 |
+
if st.session_state.registrations:
|
579 |
+
# Create DataFrame with core columns that are always present
|
580 |
+
core_columns = ['name', 'email', 'phone', 'attendees', 'food_preference', 'cultural_interest', 'contribution']
|
581 |
+
df = pd.DataFrame(st.session_state.registrations)[core_columns]
|
582 |
+
# Add optional columns if they exist, filling missing values with None and ensuring volunteer_roles is a list
|
583 |
+
optional_columns = ['food_contribution', 'payment_status', 'song_choice', 'family_members', 'volunteer_roles']
|
584 |
+
for col in optional_columns:
|
585 |
+
if any(col in reg for reg in st.session_state.registrations):
|
586 |
+
if col == 'volunteer_roles':
|
587 |
+
df[col] = [reg.get(col, []) for reg in st.session_state.registrations] # Ensure list
|
588 |
+
else:
|
589 |
+
df[col] = [reg.get(col, '') for reg in st.session_state.registrations]
|
590 |
+
|
591 |
+
# Add checkbox column for selection
|
592 |
+
df_with_checkbox = df.copy()
|
593 |
+
df_with_checkbox.insert(0, 'Select', False)
|
594 |
+
|
595 |
+
# Display DataFrame with checkboxes
|
596 |
+
edited_df = st.data_editor(df_with_checkbox, hide_index=True, use_container_width=True)
|
597 |
+
|
598 |
+
# Update selected rows
|
599 |
+
st.session_state.selected_rows = [i for i, row in edited_df.iterrows() if row['Select']]
|
600 |
+
|
601 |
+
if 'user_id' in df.columns:
|
602 |
+
df = df.drop(columns=['user_id', 'timestamp', 'updated_at'], errors='ignore')
|
603 |
+
st.dataframe(df) # Display clean DataFrame without checkboxes
|
604 |
+
|
605 |
+
st.info(f"Total Registrations: {len(st.session_state.registrations)}")
|
606 |
+
|
607 |
+
# Check for duplicates
|
608 |
+
email_counts = df['email'].value_counts()
|
609 |
+
duplicate_emails = email_counts[email_counts > 1].index.tolist()
|
610 |
+
if duplicate_emails:
|
611 |
+
st.warning(f"Duplicate emails found: {', '.join(duplicate_emails)}")
|
612 |
+
for email in duplicate_emails:
|
613 |
+
duplicates = df[df['email'] == email].index.tolist()
|
614 |
+
for idx in duplicates[1:]: # Skip the first (latest) entry
|
615 |
+
if st.button(f"Delete Duplicate Entry for {email} at Index {idx}"):
|
616 |
+
delete_registration(idx)
|
617 |
+
|
618 |
+
# Clear duplicates button
|
619 |
+
if st.button("Clear Duplicates"):
|
620 |
+
clear_duplicates()
|
621 |
+
st.rerun()
|
622 |
+
|
623 |
+
# Delete selected button
|
624 |
+
if st.button("Delete Selected"):
|
625 |
+
delete_selected_registrations()
|
626 |
+
|
627 |
+
search_term = st.text_input("Search by name or email:")
|
628 |
+
if search_term:
|
629 |
+
filtered_df = df[df['name'].str.contains(search_term, case=False, na=False) |
|
630 |
+
df['email'].str.contains(search_term, case=False, na=False)]
|
631 |
+
st.subheader("Search Results")
|
632 |
+
st.dataframe(filtered_df)
|
633 |
+
else:
|
634 |
+
st.info("No registrations available.")
|
635 |
+
|
636 |
+
with admin_tabs[1]:
|
637 |
+
st.subheader("Registration Analytics")
|
638 |
+
if st.session_state.registrations:
|
639 |
+
df = pd.DataFrame(st.session_state.registrations)
|
640 |
+
col1, col2 = st.columns(2)
|
641 |
+
with col1:
|
642 |
+
st.write("**Food Preference Distribution:**")
|
643 |
+
food_prefs = df['food_preference'].value_counts()
|
644 |
+
st.bar_chart(food_prefs)
|
645 |
+
st.write("**Cultural Performance Interest:**")
|
646 |
+
cultural = df['cultural_interest'].value_counts()
|
647 |
+
st.bar_chart(cultural)
|
648 |
+
with col2:
|
649 |
+
st.write("**Fund Contribution Distribution:**")
|
650 |
+
contributions = df['contribution'].value_counts()
|
651 |
+
st.bar_chart(contributions)
|
652 |
+
st.write("**Food Contributions:**")
|
653 |
+
food_contributions = df['food_contribution'].value_counts()
|
654 |
+
st.bar_chart(food_contributions)
|
655 |
+
st.subheader("Summary Statistics")
|
656 |
+
col1, col2, col3 = st.columns(3)
|
657 |
+
with col1:
|
658 |
+
st.metric("Total Registrations", len(st.session_state.registrations))
|
659 |
+
with col2:
|
660 |
+
total_contribution = sum(int(r.get('contribution', '0').replace('€', '')) for r in st.session_state.registrations if r.get('contribution'))
|
661 |
+
st.metric("Total Fund Collection", f"€{total_contribution}")
|
662 |
+
with col3:
|
663 |
+
cultural_performances = sum(1 for r in st.session_state.registrations if r.get('cultural_interest') == 'yes')
|
664 |
+
st.metric("Cultural Performances", cultural_performances)
|
665 |
+
else:
|
666 |
+
st.info("No data available for analytics yet.")
|
667 |
+
|
668 |
+
with admin_tabs[2]:
|
669 |
+
st.subheader("Export Registration Data")
|
670 |
+
if st.session_state.registrations:
|
671 |
+
# Create DataFrame with core and optional columns
|
672 |
+
core_columns = ['name', 'email', 'phone', 'attendees', 'food_preference', 'cultural_interest', 'contribution']
|
673 |
+
df = pd.DataFrame(st.session_state.registrations)[core_columns]
|
674 |
+
optional_columns = ['food_contribution', 'payment_status', 'song_choice', 'family_members', 'volunteer_roles']
|
675 |
+
for col in optional_columns:
|
676 |
+
if any(col in reg for reg in st.session_state.registrations):
|
677 |
+
if col == 'volunteer_roles':
|
678 |
+
df[col] = [reg.get(col, []) for reg in st.session_state.registrations] # Ensure list
|
679 |
+
else:
|
680 |
+
df[col] = [reg.get(col, '') for reg in st.session_state.registrations]
|
681 |
+
df = df.drop(columns=['user_id', 'timestamp', 'updated_at'], errors='ignore')
|
682 |
+
csv = df.to_csv(index=False)
|
683 |
+
st.download_button(
|
684 |
+
label="Download Registrations as CSV",
|
685 |
+
data=csv,
|
686 |
+
file_name=f"ugadi_registrations_{datetime.datetime.now().strftime('%Y%m%d_%H%M')}.csv",
|
687 |
+
mime="text/csv"
|
688 |
+
)
|
689 |
+
st.subheader("Attendee List")
|
690 |
+
attendee_list = ""
|
691 |
+
for i, reg in enumerate(st.session_state.registrations, 1):
|
692 |
+
attendee_list += f"{i}. {reg.get('name', 'Unknown')} - {reg.get('attendees', 'N/A')} attendees\n"
|
693 |
+
st.text_area("Attendee List (Copy & Paste)", attendee_list, height=300)
|
694 |
+
st.subheader("Email List")
|
695 |
+
email_list = "\n".join([reg.get('email', '') for reg in st.session_state.registrations if reg.get('email')])
|
696 |
+
st.text_area("Email List (Copy & Paste)", email_list, height=150)
|
697 |
+
else:
|
698 |
+
st.info("No registrations to export yet.")
|
699 |
+
else:
|
700 |
+
st.warning("Please enter the admin password to access the admin panel.")
|
701 |
+
|
702 |
+
# Footer
|
703 |
+
st.markdown("---")
|
704 |
+
st.markdown("© 2025 Finland Telugu Association (FiTA) | Created by Goutham Ippili | Powered by AI")
|