motsimaslam commited on
Commit
80ace65
·
verified ·
1 Parent(s): acf2539

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +376 -0
app.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from openai import OpenAI
3
+ from elevenlabs.client import ElevenLabs
4
+ from stability_sdk import client
5
+ import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
6
+ import pandas as pd
7
+ from datetime import datetime
8
+ from transformers import pipeline
9
+
10
+ # --- Configuration ---
11
+ st.set_page_config(
12
+ page_title="AfriLearn AI Tutor",
13
+ page_icon="🌍",
14
+ layout="wide"
15
+ )
16
+
17
+ # --- Load API Keys from secrets.toml ---
18
+ AIML_API_KEY = st.secrets["AIML_API_KEY"]
19
+ ELEVENLABS_API_KEY = st.secrets["ELEVENLABS_API_KEY"]
20
+ STABILITY_KEY = st.secrets["STABILITY_KEY"]
21
+ ADMIN_PASS = st.secrets["ADMIN_PASS"]
22
+
23
+ # --- Initialize APIs ---
24
+ @st.cache_resource
25
+ def initialize_apis():
26
+ base_url = "https://api.aimlapi.com/v1" # AIML API endpoint
27
+ api = OpenAI(api_key=AIML_API_KEY, base_url=base_url)
28
+ elevenlabs_client = ElevenLabs(api_key=ELEVENLABS_API_KEY)
29
+ stability_client = client.StabilityInference(
30
+ key=STABILITY_KEY,
31
+ engine="stable-diffusion-xl-1024-v1-0"
32
+ )
33
+ return api, elevenlabs_client, stability_client
34
+
35
+ api, elevenlabs_client, stability_client = initialize_apis()
36
+
37
+ # --- Language Setup ---
38
+ LANGUAGES = {
39
+ "English": "en",
40
+ "French": "fr",
41
+ "Swahili": "sw"
42
+ }
43
+
44
+ # --- Initialize Session State ---
45
+ if "language" not in st.session_state:
46
+ st.session_state.language = "English" # Default language
47
+
48
+ if "offline_mode" not in st.session_state:
49
+ st.session_state.offline_mode = False # Default offline mode
50
+
51
+ if "messages" not in st.session_state:
52
+ st.session_state.messages = []
53
+
54
+ # --- UI Translations ---
55
+ TRANSLATIONS = {
56
+ "English": {
57
+ "chat_header": "🤖 Chat with the AI Tutor",
58
+ "chat_placeholder": "Ask your question...",
59
+ "enable_voice": "Enable Voice",
60
+ "select_voice": "🎤 Select Voice",
61
+ },
62
+ "French": {
63
+ "chat_header": "🤖 Discutez avec le tuteur IA",
64
+ "chat_placeholder": "Posez votre question...",
65
+ "enable_voice": "Activer la voix",
66
+ "select_voice": "🎤 Sélectionnez une voix",
67
+ },
68
+ "Swahili": {
69
+ "chat_header": "🤖 Zungumza na Mwalimu wa AI",
70
+ "chat_placeholder": "Uliza swali lako...",
71
+ "enable_voice": "Washa Sauti",
72
+ "select_voice": "🎤 Chagua sauti",
73
+ }
74
+ }
75
+
76
+ # Get translations for the selected language
77
+ translations = TRANSLATIONS.get(st.session_state.language, TRANSLATIONS["English"])
78
+
79
+ # --- Language Selection ---
80
+ LANGUAGE = st.sidebar.selectbox(
81
+ "🌍 Choose Language / Choisir la langue / Chagua lugha",
82
+ list(LANGUAGES.keys()),
83
+ index=list(LANGUAGES.keys()).index(st.session_state.language) # Set default from session state
84
+ )
85
+
86
+ # Update session state when language changes
87
+ if LANGUAGE != st.session_state.language:
88
+ st.session_state.language = LANGUAGE
89
+ st.session_state.messages = [] # Clear chat history to reflect new language
90
+ st.rerun() # Rerun the app to apply language changes
91
+
92
+ # --- Voice Selection ---
93
+ VOICE_MAPPING = {
94
+ "English": ["George", "Alice"], # Voices for English
95
+ "French": ["Georges", "Alice"], # Voices for French
96
+ "Swahili": ["George", "Alice"] # Voices for Swahili
97
+ }
98
+
99
+ # Get voices for the selected language
100
+ voices = VOICE_MAPPING.get(st.session_state.language, ["Emily"]) # Default to English voices
101
+
102
+ # Add voice selection dropdown
103
+ selected_voice = st.sidebar.selectbox(
104
+ translations["select_voice"],
105
+ voices
106
+ )
107
+
108
+ # --- System Prompt for AI Tutor ---
109
+ SYSTEM_PROMPT = f"""
110
+ You are a friendly tutor for African students. Follow these rules:
111
+ 1. Respond in {st.session_state.language}
112
+ 2. Use examples from local culture (markets, farming, traditions)
113
+ 3. Keep answers under 3 sentences
114
+ 4. For math/science, use simple terms
115
+ """
116
+
117
+ # --- Main Navigation Tabs ---
118
+ tabs = ["Home", "About Me", "Tutoring Request", "Career Guidance"]
119
+ selected_tab = st.sidebar.radio("Go to / Aller à / Nenda kwa", tabs)
120
+
121
+ # --- Offline Mode Setup ---
122
+ @st.cache_resource
123
+ def load_offline_model():
124
+ # Load the castorini/afriberta_base model
125
+ return pipeline("text-generation", model="castorini/afriberta_base")
126
+
127
+ # --- Offline Mode Checkbox ---
128
+ st.session_state.offline_mode = st.sidebar.checkbox(
129
+ "Enable Offline Mode",
130
+ value=st.session_state.offline_mode # Preserve state
131
+ )
132
+
133
+ # --- Footer in Sidebar ---
134
+ st.sidebar.markdown("---")
135
+ st.sidebar.write("Developed with ❤️ by Motsim")
136
+ st.sidebar.write("Powered by **AI for Connectivity Hackathon II**")
137
+
138
+ # --- Home Tab ---
139
+ if selected_tab == "Home":
140
+ st.header(translations["chat_header"])
141
+
142
+ # Initialize chat history
143
+ if not st.session_state.messages:
144
+ st.session_state.messages = [{
145
+ "role": "assistant",
146
+ "content": {
147
+ "English": "Jambo! I'm your AI tutor. Ask me anything about school subjects!",
148
+ "French": "Bonjour! Je suis votre tuteur IA. Posez-moi des questions sur les sujets scolaires!",
149
+ "Swahili": "Habari! Mimi ni mwalimu wako wa AI. Niulize chochote kuhusu masomo!"
150
+ }.get(st.session_state.language, "Jambo! I'm your AI tutor. Ask me anything about school subjects!")
151
+ }]
152
+
153
+ # Display chat messages
154
+ for message in st.session_state.messages:
155
+ with st.chat_message(message["role"]):
156
+ st.write(message["content"])
157
+
158
+ # Chat input
159
+ if prompt := st.chat_input(translations["chat_placeholder"]):
160
+ st.session_state.messages.append({"role": "user", "content": prompt})
161
+
162
+ # Generate response using AIML API or offline model
163
+ if st.session_state.offline_mode:
164
+ # Use offline model
165
+ try:
166
+ offline_model = load_offline_model()
167
+ ai_response = offline_model(prompt, max_length=50)[0]['generated_text']
168
+ except Exception as e:
169
+ ai_response = f"⚠️ Error: {str(e)}"
170
+ else:
171
+ # Use AIML API
172
+ try:
173
+ completion = api.chat.completions.create(
174
+ model="mistralai/Mistral-7B-Instruct-v0.2", # Use the correct model name
175
+ messages=[
176
+ {"role": "system", "content": SYSTEM_PROMPT},
177
+ {"role": "user", "content": prompt},
178
+ ],
179
+ temperature=0.7,
180
+ max_tokens=256,
181
+ )
182
+ ai_response = completion.choices[0].message.content
183
+ except Exception as e:
184
+ ai_response = f"⚠️ Error: {str(e)}"
185
+
186
+ st.session_state.messages.append({"role": "assistant", "content": ai_response})
187
+ st.rerun()
188
+
189
+ # --- Text-to-Speech Feature with Language Support ---
190
+ if st.checkbox(translations["enable_voice"], key="voice_toggle"):
191
+ if st.session_state.messages[-1]["role"] == "assistant":
192
+ try:
193
+ # Generate audio for the text in the selected language
194
+ audio_generator = elevenlabs_client.generate(
195
+ text=st.session_state.messages[-1]["content"],
196
+ voice=selected_voice, # Use the selected voice
197
+ model="eleven_multilingual_v2" # Use the multilingual model
198
+ )
199
+
200
+ # Convert generator to bytes
201
+ audio_bytes = b"".join(audio_generator)
202
+
203
+ # Play audio
204
+ st.audio(audio_bytes, format="audio/mp3")
205
+ except Exception as e:
206
+ st.error(f"⚠️ Error generating audio: {str(e)}")
207
+
208
+ # --- About Me Tab ---
209
+ elif selected_tab == "About Us":
210
+ st.header("About Me 👨‍💻")
211
+ st.write("Meet the AfriLearn AI Team We are a diverse team of professionals and students specializing in AI, software engineering, pedagogy, cybersecurity, and machine learning. With expertise spanning data science, low-latency networks, education, and secure systems, we are committed to developing AfriLearn—an AI-powered tutoring platform designed to provide equitable, personalized education across Africa. Our platform integrates multilingual AI chatbots, culturally relevant visual lessons, and mentorship tracking to enhance learning experiences, even in low-connectivity regions. Together, we aim to bridge the digital divide and empower students through innovative, accessible education.")
212
+
213
+ # --- Tutoring Request Tab ---
214
+ elif selected_tab == "Tutoring Request":
215
+ st.header("📝 Tutoring Request Form")
216
+ st.write("Fill out the form below to request a tutor.")
217
+
218
+ MENTORSHIP_DB = "mentorship_requests.csv"
219
+
220
+ def load_requests():
221
+ try:
222
+ return pd.read_csv(MENTORSHIP_DB)
223
+ except FileNotFoundError:
224
+ return pd.DataFrame(columns=[
225
+ "timestamp", "name", "country", "interests",
226
+ "contact", "status", "notes"
227
+ ])
228
+
229
+ def save_request(request):
230
+ df = load_requests()
231
+ new_row = pd.DataFrame([request])
232
+ df = pd.concat([df, new_row], ignore_index=True)
233
+ df.to_csv(MENTORSHIP_DB, index=False)
234
+
235
+ with st.form("mentor_form"):
236
+ col1, col2 = st.columns(2)
237
+ with col1:
238
+ name = st.text_input("Full Name*", help="Required field")
239
+ country = st.selectbox("Country*", [
240
+ "Nigeria", "Kenya", "Ghana",
241
+ "South Africa", "Other"
242
+ ])
243
+ with col2:
244
+ contact = st.text_input("Email/Phone*",
245
+ placeholder="e.g. +2348123456789")
246
+ education_level = st.selectbox("Education Level", [
247
+ "Primary School", "Secondary School",
248
+ "University", "Graduate"
249
+ ])
250
+
251
+ interests = st.multiselect("Areas of Need*", [
252
+ "Math", "Science", "Coding",
253
+ "University Applications", "Career Advice"
254
+ ])
255
+
256
+ preferred_comms = st.radio("Preferred Communication", [
257
+ "WhatsApp", "SMS", "Email"
258
+ ], horizontal=True)
259
+
260
+ if st.form_submit_button("Submit Request"):
261
+ if not name or not contact or not interests:
262
+ st.error("Please fill required fields (*)")
263
+ else:
264
+ request = {
265
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
266
+ "name": name,
267
+ "country": country,
268
+ "contact": contact,
269
+ "interests": ", ".join(interests),
270
+ "education_level": education_level,
271
+ "preferred_comms": preferred_comms,
272
+ "status": "Pending",
273
+ "notes": ""
274
+ }
275
+ save_request(request)
276
+ st.success("Request submitted! Mentor will contact you within 48hrs.")
277
+
278
+ # Admin Panel
279
+ if st.sidebar.text_input("Admin Password", type="password") == ADMIN_PASS:
280
+ st.sidebar.success("Admin Mode")
281
+
282
+ st.header("🔒 Mentor Request Dashboard")
283
+ df = load_requests()
284
+
285
+ if not df.empty:
286
+ # Filtering
287
+ status_filter = st.multiselect("Filter Status",
288
+ options=df["status"].unique(), default=["Pending"])
289
+ filtered_df = df[df["status"].isin(status_filter)]
290
+
291
+ # Display table
292
+ st.dataframe(
293
+ filtered_df.sort_values("timestamp", ascending=False),
294
+ column_config={
295
+ "timestamp": "Date",
296
+ "contact": "Contact Info",
297
+ "preferred_comms": "Preferred Channel"
298
+ },
299
+ use_container_width=True
300
+ )
301
+
302
+ # Update status
303
+ selected_id = st.number_input("Enter Request ID to Update",
304
+ min_value=0, max_value=len(df)-1)
305
+ new_status = st.selectbox("New Status",
306
+ ["Pending", "Contacted", "Resolved"])
307
+ new_notes = st.text_area("Add Notes")
308
+
309
+ if st.button("Update Request"):
310
+ df.at[selected_id, "status"] = new_status
311
+ df.at[selected_id, "notes"] = new_notes
312
+ df.to_csv(MENTORSHIP_DB, index=False)
313
+ st.success("Request updated!")
314
+ else:
315
+ st.info("No mentorship requests yet")
316
+
317
+ # --- Career Guidance Tab ---
318
+ elif selected_tab == "Career Guidance":
319
+ st.header("🚀 Career Guidance")
320
+ st.write("Explore career options and connect with mentors.")
321
+
322
+ CAREER_DB = "career_requests.csv"
323
+
324
+ def load_career_requests():
325
+ try:
326
+ return pd.read_csv(CAREER_DB)
327
+ except FileNotFoundError:
328
+ return pd.DataFrame(columns=[
329
+ "timestamp", "name", "email", "career_interest"
330
+ ])
331
+
332
+ def save_career_request(request):
333
+ df = load_career_requests()
334
+ new_row = pd.DataFrame([request])
335
+ df = pd.concat([df, new_row], ignore_index=True)
336
+ df.to_csv(CAREER_DB, index=False)
337
+
338
+ with st.form("career_form"):
339
+ name = st.text_input("Your Name*")
340
+ email = st.text_input("Your Email*")
341
+ career_interest = st.selectbox("Career Interest", [
342
+ "Engineering", "Medicine", "Business", "Technology", "Arts"
343
+ ])
344
+
345
+ if st.form_submit_button("Submit"):
346
+ if not name or not email:
347
+ st.error("Please fill required fields (*)")
348
+ else:
349
+ request = {
350
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
351
+ "name": name,
352
+ "email": email,
353
+ "career_interest": career_interest
354
+ }
355
+ save_career_request(request)
356
+ st.success("Thank you! A mentor will contact you soon.")
357
+
358
+ # Admin Panel
359
+ if st.sidebar.text_input("Admin Password", type="password") == ADMIN_PASS:
360
+ st.sidebar.success("Admin Mode")
361
+
362
+ st.header("🔒 Career Guidance Dashboard")
363
+ df = load_career_requests()
364
+
365
+ if not df.empty:
366
+ st.dataframe(
367
+ df.sort_values("timestamp", ascending=False),
368
+ column_config={
369
+ "timestamp": "Date",
370
+ "email": "Email",
371
+ "career_interest": "Career Interest"
372
+ },
373
+ use_container_width=True
374
+ )
375
+ else:
376
+ st.info("No career guidance requests yet")