maria355 commited on
Commit
4968617
·
verified ·
1 Parent(s): d551f50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +685 -70
app.py CHANGED
@@ -1,5 +1,8 @@
1
  import gradio as gr
2
  import os
 
 
 
3
  from groq import Groq
4
 
5
  # Set up Groq API key
@@ -9,107 +12,719 @@ if not GROQ_API_KEY:
9
 
10
  client = Groq(api_key=GROQ_API_KEY)
11
 
12
- # System prompt
13
  SYSTEM_PROMPT = (
14
  "You are an intelligent, friendly, and highly adaptable Teaching Assistant Chatbot. "
15
  "Your mission is to help users of all ages and skill levels—from complete beginners to seasoned professionals—learn Python, Data Science, and Artificial Intelligence. "
16
  "You explain concepts clearly using real-world analogies, examples, and interactive exercises. "
17
- "You ask questions to assess the learners level, adapt accordingly, and provide learning paths tailored to their pace and goals. "
18
  "Your responses are structured, engaging, and supportive. "
19
  "You can explain code snippets, generate exercises and quizzes, and recommend projects. "
20
  "You never overwhelm users with jargon. Instead, you scaffold complex concepts in simple, digestible steps."
21
  )
22
 
23
- def chat_with_groq(user_input, user_data):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  messages = [
25
  {"role": "system", "content": SYSTEM_PROMPT},
26
- {"role": "user", "content": user_input}
27
  ]
 
28
  chat_completion = client.chat.completions.create(
29
  messages=messages,
30
  model="llama-3.3-70b-versatile",
31
  stream=False
32
  )
33
- return chat_completion.choices[0].message.content
 
 
 
 
 
 
 
 
 
34
 
35
- def user_onboarding(age, goals, knowledge_level):
36
- return (
37
- "Welcome! Based on your goals and knowledge level, we will tailor the learning experience for you.\n"
38
- "Let's start learning Python, Data Science, or AI!"
39
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- def chatbot_interface(age, goals, knowledge_level, user_message):
42
- if not age or not goals or not knowledge_level:
43
- return user_onboarding(age, goals, knowledge_level)
 
 
 
 
 
 
 
 
 
 
 
44
  user_data = {
45
- "age": age,
46
- "goals": goals,
47
- "knowledge_level": knowledge_level
 
 
 
48
  }
49
- return chat_with_groq(user_message, user_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  def create_chatbot():
52
- with gr.Blocks(css="""
53
- .gradio-container { background-color: #f0f4f8; font-family: 'Segoe UI', sans-serif; }
54
- #title { font-size: 32px; font-weight: bold; text-align: center; padding-top: 20px; color: #2c3e50; }
55
- #subtitle { font-size: 18px; text-align: center; margin-bottom: 20px; color: #34495e; }
56
- .input-card, .output-card {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  background-color: white;
58
  padding: 20px;
59
  border-radius: 12px;
60
- box-shadow: 0 4px 10px rgba(0,0,0,0.05);
61
  margin-bottom: 20px;
62
- }
63
- .gr-button { font-size: 16px !important; padding: 10px 20px !important; }
64
- """) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- gr.HTML("<div id='title'>🎓 AI Teaching Assistant Chatbot</div>")
67
- gr.HTML("<div id='subtitle'>Helping you learn Python, Data Science & AI at your pace!</div>")
68
-
69
- with gr.Row():
70
- with gr.Column(elem_classes=["input-card"]):
71
- age_input = gr.Textbox(label="Age", placeholder="e.g. 20", interactive=True)
72
- goals_input = gr.Textbox(label="Learning Goals", placeholder="e.g. I want to become a data analyst", interactive=True)
73
- knowledge_level_input = gr.Dropdown(
74
- choices=["Beginner", "Intermediate", "Advanced"],
75
- label="Knowledge Level",
76
- interactive=True
77
- )
78
-
79
- with gr.Column(elem_classes=["input-card"]):
80
- user_message_input = gr.Textbox(
81
- label="Your Question or Message",
82
- placeholder="Ask anything about Python, Data Science, AI...",
83
- lines=5,
84
- interactive=True
85
- )
86
-
87
- with gr.Column(elem_classes=["output-card"]):
88
- chatbot_output = gr.Textbox(
89
- label="Chatbot Response",
90
- placeholder="Chatbot response will appear here.",
91
- lines=12,
92
- max_lines=30,
93
- interactive=False
94
- )
95
-
96
- with gr.Row():
97
- submit_button = gr.Button("Submit", variant="primary")
98
- clear_button = gr.Button("Clear", variant="secondary")
99
-
100
- submit_button.click(
101
  chatbot_interface,
102
- inputs=[age_input, goals_input, knowledge_level_input, user_message_input],
103
- outputs=chatbot_output
104
  )
105
-
106
- clear_button.click(
107
- fn=lambda: ("", "", "", "", ""),
108
  inputs=[],
109
- outputs=[age_input, goals_input, knowledge_level_input, user_message_input, chatbot_output]
110
  )
111
-
112
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  # Run the chatbot
115
- create_chatbot()
 
 
 
1
  import gradio as gr
2
  import os
3
+ import json
4
+ import uuid
5
+ from datetime import datetime
6
  from groq import Groq
7
 
8
  # Set up Groq API key
 
12
 
13
  client = Groq(api_key=GROQ_API_KEY)
14
 
15
+ # Default system prompt
16
  SYSTEM_PROMPT = (
17
  "You are an intelligent, friendly, and highly adaptable Teaching Assistant Chatbot. "
18
  "Your mission is to help users of all ages and skill levels—from complete beginners to seasoned professionals—learn Python, Data Science, and Artificial Intelligence. "
19
  "You explain concepts clearly using real-world analogies, examples, and interactive exercises. "
20
+ "You ask questions to assess the learner's level, adapt accordingly, and provide learning paths tailored to their pace and goals. "
21
  "Your responses are structured, engaging, and supportive. "
22
  "You can explain code snippets, generate exercises and quizzes, and recommend projects. "
23
  "You never overwhelm users with jargon. Instead, you scaffold complex concepts in simple, digestible steps."
24
  )
25
 
26
+ # Define learning paths
27
+ LEARNING_PATHS = {
28
+ "python_beginner": {
29
+ "title": "Python Fundamentals",
30
+ "description": "Learn Python basics from variables to functions",
31
+ "modules": [
32
+ "Variables & Data Types",
33
+ "Control Flow",
34
+ "Functions",
35
+ "Data Structures",
36
+ "File I/O"
37
+ ]
38
+ },
39
+ "python_intermediate": {
40
+ "title": "Intermediate Python",
41
+ "description": "Advance your Python skills with OOP and more",
42
+ "modules": [
43
+ "Object-Oriented Programming",
44
+ "Modules & Packages",
45
+ "Error Handling",
46
+ "List Comprehensions",
47
+ "Decorators & Generators"
48
+ ]
49
+ },
50
+ "data_science_beginner": {
51
+ "title": "Data Science Foundations",
52
+ "description": "Begin your data science journey",
53
+ "modules": [
54
+ "Numpy Basics",
55
+ "Pandas Fundamentals",
56
+ "Data Visualization",
57
+ "Basic Statistics",
58
+ "Intro to Machine Learning"
59
+ ]
60
+ },
61
+ "data_science_advanced": {
62
+ "title": "Advanced Data Science",
63
+ "description": "Master complex data science concepts",
64
+ "modules": [
65
+ "Advanced ML Algorithms",
66
+ "Feature Engineering",
67
+ "Time Series Analysis",
68
+ "Natural Language Processing",
69
+ "Deep Learning Basics"
70
+ ]
71
+ },
72
+ "ai_specialization": {
73
+ "title": "AI Specialization",
74
+ "description": "Focus on artificial intelligence concepts",
75
+ "modules": [
76
+ "Neural Networks",
77
+ "Computer Vision",
78
+ "Advanced NLP",
79
+ "Reinforcement Learning",
80
+ "AI Ethics"
81
+ ]
82
+ }
83
+ }
84
+
85
+ # Learning resources
86
+ LEARNING_RESOURCES = {
87
+ "python": [
88
+ {"title": "Python Documentation", "url": "https://docs.python.org/3/"},
89
+ {"title": "Real Python", "url": "https://realpython.com/"},
90
+ {"title": "Python for Everybody", "url": "https://www.py4e.com/"},
91
+ {"title": "Automate the Boring Stuff with Python", "url": "https://automatetheboringstuff.com/"}
92
+ ],
93
+ "data_science": [
94
+ {"title": "Kaggle Learn", "url": "https://www.kaggle.com/learn"},
95
+ {"title": "Towards Data Science", "url": "https://towardsdatascience.com/"},
96
+ {"title": "DataCamp", "url": "https://www.datacamp.com/"},
97
+ {"title": "Machine Learning Mastery", "url": "https://machinelearningmastery.com/"}
98
+ ],
99
+ "ai": [
100
+ {"title": "Fast.ai", "url": "https://www.fast.ai/"},
101
+ {"title": "DeepLearning.AI", "url": "https://www.deeplearning.ai/"},
102
+ {"title": "TensorFlow Tutorials", "url": "https://www.tensorflow.org/tutorials"},
103
+ {"title": "PyTorch Tutorials", "url": "https://pytorch.org/tutorials/"}
104
+ ]
105
+ }
106
+
107
+ # Practice project ideas
108
+ PROJECT_IDEAS = {
109
+ "python_beginner": [
110
+ "To-Do List Application",
111
+ "Simple Calculator",
112
+ "Password Generator",
113
+ "Hangman Game",
114
+ "Basic File Organizer"
115
+ ],
116
+ "python_intermediate": [
117
+ "Weather App with API",
118
+ "Personal Blog with Flask",
119
+ "Web Scraper for News Articles",
120
+ "Data Visualization Dashboard",
121
+ "Task Automation Scripts"
122
+ ],
123
+ "data_science": [
124
+ "Housing Price Prediction",
125
+ "Customer Segmentation Analysis",
126
+ "Sentiment Analysis of Reviews",
127
+ "Stock Price Forecasting",
128
+ "A/B Test Analysis Dashboard"
129
+ ],
130
+ "ai": [
131
+ "Image Classification System",
132
+ "Chatbot with NLP",
133
+ "Recommendation Engine",
134
+ "Text Summarization Tool",
135
+ "Object Detection Application"
136
+ ]
137
+ }
138
+
139
+ # User session data store
140
+ SESSION_DATA = {}
141
+
142
+ def save_session(session_id, data):
143
+ """Save session data to SESSION_DATA global dictionary"""
144
+ if session_id in SESSION_DATA:
145
+ SESSION_DATA[session_id].update(data)
146
+ else:
147
+ SESSION_DATA[session_id] = data
148
+
149
+ # Add timestamp for session tracking
150
+ SESSION_DATA[session_id]["last_activity"] = datetime.now().isoformat()
151
+
152
+ def load_session(session_id):
153
+ """Load session data from SESSION_DATA global dictionary"""
154
+ return SESSION_DATA.get(session_id, {})
155
+
156
+ def recommend_learning_path(age, goals, knowledge_level, interests):
157
+ """Recommend personalized learning paths based on user profile"""
158
+ paths = []
159
+
160
+ # Simple recommendation logic based on profile
161
+ if "beginner" in knowledge_level.lower():
162
+ if any(topic in interests.lower() for topic in ["python", "programming", "coding"]):
163
+ paths.append("python_beginner")
164
+ if any(topic in interests.lower() for topic in ["data", "analysis", "statistics"]):
165
+ paths.append("data_science_beginner")
166
+ elif "intermediate" in knowledge_level.lower() or "advanced" in knowledge_level.lower():
167
+ if any(topic in interests.lower() for topic in ["python", "programming", "coding"]):
168
+ paths.append("python_intermediate")
169
+ if any(topic in interests.lower() for topic in ["data", "analysis", "statistics"]):
170
+ paths.append("data_science_advanced")
171
+ if any(topic in interests.lower() for topic in ["ai", "machine learning", "deep learning"]):
172
+ paths.append("ai_specialization")
173
+
174
+ # Default path if no matches
175
+ if not paths:
176
+ paths = ["python_beginner"]
177
+
178
+ return [LEARNING_PATHS[path] for path in paths if path in LEARNING_PATHS]
179
+
180
+ def get_recommended_resources(interests):
181
+ """Get recommended learning resources based on interests"""
182
+ resources = []
183
+ if any(topic in interests.lower() for topic in ["python", "programming", "coding"]):
184
+ resources.extend(LEARNING_RESOURCES["python"])
185
+ if any(topic in interests.lower() for topic in ["data", "analysis", "statistics"]):
186
+ resources.extend(LEARNING_RESOURCES["data_science"])
187
+ if any(topic in interests.lower() for topic in ["ai", "machine learning", "deep learning"]):
188
+ resources.extend(LEARNING_RESOURCES["ai"])
189
+
190
+ # If no specific interests match, provide general resources
191
+ if not resources:
192
+ for category in LEARNING_RESOURCES:
193
+ resources.extend(LEARNING_RESOURCES[category][:1]) # Add first resource from each category
194
+
195
+ return resources
196
+
197
+ def get_project_ideas(learning_paths):
198
+ """Get project ideas based on recommended learning paths"""
199
+ ideas = []
200
+ for path in learning_paths:
201
+ path_id = next((k for k, v in LEARNING_PATHS.items() if v["title"] == path["title"]), None)
202
+ if path_id:
203
+ if path_id.startswith("python"):
204
+ category = "python_beginner" if "beginner" in path_id else "python_intermediate"
205
+ ideas.extend(PROJECT_IDEAS[category])
206
+ elif path_id.startswith("data_science"):
207
+ ideas.extend(PROJECT_IDEAS["data_science"])
208
+ elif path_id.startswith("ai"):
209
+ ideas.extend(PROJECT_IDEAS["ai"])
210
+
211
+ # If no specific paths match, provide some general project ideas
212
+ if not ideas:
213
+ ideas = PROJECT_IDEAS["python_beginner"][:2] + PROJECT_IDEAS["data_science"][:2]
214
+
215
+ return ideas[:5] # Return up to 5 project ideas
216
+
217
+ def generate_quiz(topic, difficulty):
218
+ """Generate a quiz based on the topic and difficulty"""
219
+ # In a real application, you might use the LLM to generate quizzes
220
+ # Here we're using a template approach for simplicity
221
+ quiz_prompt = f"""
222
+ Generate a {difficulty} level quiz on {topic} with 3 multiple-choice questions.
223
+ For each question, provide 4 options and indicate the correct answer.
224
+ Format the quiz nicely with clear question numbering and option lettering.
225
+ """
226
+
227
+ # Use Groq to generate the quiz
228
+ quiz_messages = [
229
+ {"role": "system", "content": SYSTEM_PROMPT},
230
+ {"role": "user", "content": quiz_prompt}
231
+ ]
232
+
233
+ quiz_response = client.chat.completions.create(
234
+ messages=quiz_messages,
235
+ model="llama-3.3-70b-versatile",
236
+ stream=False
237
+ )
238
+
239
+ return quiz_response.choices[0].message.content
240
+
241
+ def create_study_plan(topic, time_available, goals):
242
+ """Create a personalized study plan"""
243
+ plan_prompt = f"""
244
+ Create a structured study plan for learning {topic} with {time_available} hours per week available for study.
245
+ The learner's goal is: {goals}
246
+
247
+ Include:
248
+ 1. Weekly breakdown of topics
249
+ 2. Time allocation for theory vs practice
250
+ 3. Recommended resources for each week
251
+ 4. Milestone projects or assessments
252
+ 5. Tips for effective learning
253
+ """
254
+
255
+ # Use Groq to generate the study plan
256
+ plan_messages = [
257
+ {"role": "system", "content": SYSTEM_PROMPT},
258
+ {"role": "user", "content": plan_prompt}
259
+ ]
260
+
261
+ plan_response = client.chat.completions.create(
262
+ messages=plan_messages,
263
+ model="llama-3.3-70b-versatile",
264
+ stream=False
265
+ )
266
+
267
+ return plan_response.choices[0].message.content
268
+
269
+ def chat_with_groq(user_input, session_id):
270
+ """Chat with Groq LLM using session context"""
271
+ user_data = load_session(session_id)
272
+
273
+ # Build context from session data if available
274
+ context = ""
275
+ if user_data:
276
+ context = f"""
277
+ User Profile:
278
+ - Age: {user_data.get('age', 'Unknown')}
279
+ - Knowledge Level: {user_data.get('knowledge_level', 'Unknown')}
280
+ - Learning Goals: {user_data.get('goals', 'Unknown')}
281
+ - Interests: {user_data.get('interests', 'Unknown')}
282
+ - Available Study Time: {user_data.get('study_time', 'Unknown')} hours per week
283
+ - Preferred Learning Style: {user_data.get('learning_style', 'Unknown')}
284
+
285
+ Based on this profile, tailor your response appropriately.
286
+ """
287
+
288
+ # Add chat history context if available
289
+ chat_history = user_data.get('chat_history', [])
290
+ if chat_history:
291
+ context += "\n\nRecent conversation context (most recent first):\n"
292
+ # Include up to 3 most recent exchanges
293
+ for i, (q, a) in enumerate(reversed(chat_history[-3:])):
294
+ context += f"User: {q}\nYou: {a}\n\n"
295
+
296
+ # Combine everything for the LLM
297
+ full_prompt = f"{context}\n\nUser's current question: {user_input}"
298
+
299
  messages = [
300
  {"role": "system", "content": SYSTEM_PROMPT},
301
+ {"role": "user", "content": full_prompt}
302
  ]
303
+
304
  chat_completion = client.chat.completions.create(
305
  messages=messages,
306
  model="llama-3.3-70b-versatile",
307
  stream=False
308
  )
309
+
310
+ response = chat_completion.choices[0].message.content
311
+
312
+ # Update chat history
313
+ if 'chat_history' not in user_data:
314
+ user_data['chat_history'] = []
315
+ user_data['chat_history'].append((user_input, response))
316
+ save_session(session_id, user_data)
317
+
318
+ return response
319
 
320
+ def format_learning_paths(paths):
321
+ """Format learning paths for display"""
322
+ if not paths:
323
+ return "No specific learning paths recommended yet. Please complete your profile."
324
+
325
+ result = "### Recommended Learning Paths\n\n"
326
+ for i, path in enumerate(paths, 1):
327
+ result += f"**{i}. {path['title']}**\n"
328
+ result += f"{path['description']}\n\n"
329
+ result += "**Modules:**\n"
330
+ for module in path['modules']:
331
+ result += f"- {module}\n"
332
+ result += "\n"
333
+
334
+ return result
335
+
336
+ def format_resources(resources):
337
+ """Format resources for display"""
338
+ if not resources:
339
+ return "No resources recommended yet. Please complete your profile."
340
+
341
+ result = "### Recommended Learning Resources\n\n"
342
+ for i, resource in enumerate(resources, 1):
343
+ result += f"{i}. [{resource['title']}]({resource['url']})\n"
344
+
345
+ return result
346
 
347
+ def format_project_ideas(ideas):
348
+ """Format project ideas for display"""
349
+ if not ideas:
350
+ return "No project ideas recommended yet. Please complete your profile."
351
+
352
+ result = "### Recommended Practice Projects\n\n"
353
+ for i, idea in enumerate(ideas, 1):
354
+ result += f"{i}. {idea}\n"
355
+
356
+ return result
357
+
358
+ def user_onboarding(session_id, age, goals, knowledge_level, interests, study_time, learning_style):
359
+ """Process user profile and provide initial recommendations"""
360
+ # Save user profile data
361
  user_data = {
362
+ 'age': age,
363
+ 'goals': goals,
364
+ 'knowledge_level': knowledge_level,
365
+ 'interests': interests,
366
+ 'study_time': study_time,
367
+ 'learning_style': learning_style
368
  }
369
+ save_session(session_id, user_data)
370
+
371
+ # Generate recommendations
372
+ learning_paths = recommend_learning_path(age, goals, knowledge_level, interests)
373
+ resources = get_recommended_resources(interests)
374
+ project_ideas = get_project_ideas(learning_paths)
375
+
376
+ # Save recommendations to session
377
+ user_data.update({
378
+ 'recommended_paths': learning_paths,
379
+ 'recommended_resources': resources,
380
+ 'recommended_projects': project_ideas
381
+ })
382
+ save_session(session_id, user_data)
383
+
384
+ # Format welcome message with personalized recommendations
385
+ welcome_message = f"""
386
+ # Welcome to Your Personalized Learning Journey!
387
+
388
+ Thank you for providing your profile. Based on your information, I've prepared some tailored recommendations to start your learning journey.
389
+
390
+ ## Your Profile Summary:
391
+ - **Age:** {age}
392
+ - **Knowledge Level:** {knowledge_level}
393
+ - **Learning Goals:** {goals}
394
+ - **Interests:** {interests}
395
+ - **Available Study Time:** {study_time} hours per week
396
+ - **Preferred Learning Style:** {learning_style}
397
+
398
+ {format_learning_paths(learning_paths)}
399
+
400
+ {format_resources(resources)}
401
+
402
+ {format_project_ideas(project_ideas)}
403
+
404
+ ## Next Steps:
405
+ 1. Browse through the recommended learning paths and resources
406
+ 2. Ask me any questions about the topics you're interested in
407
+ 3. Request exercises, explanations, or code samples
408
+ 4. Try one of the project ideas to apply your knowledge
409
+
410
+ I'm here to help you every step of the way! What would you like to explore first?
411
+ """
412
+
413
+ return welcome_message
414
+
415
+ def chatbot_interface(session_id, user_message):
416
+ """Main chatbot interface function"""
417
+ user_data = load_session(session_id)
418
+
419
+ if not user_data or not user_data.get('age'):
420
+ return "Please complete your profile first by going to the Profile tab."
421
+
422
+ response = chat_with_groq(user_message, session_id)
423
+ return response
424
+
425
+ def generate_recommendations(session_id):
426
+ """Generate or refresh recommendations based on current profile"""
427
+ user_data = load_session(session_id)
428
+
429
+ if not user_data or not user_data.get('age'):
430
+ return "Please complete your profile first by going to the Profile tab."
431
+
432
+ # Generate fresh recommendations
433
+ learning_paths = recommend_learning_path(
434
+ user_data.get('age', ''),
435
+ user_data.get('goals', ''),
436
+ user_data.get('knowledge_level', ''),
437
+ user_data.get('interests', '')
438
+ )
439
+ resources = get_recommended_resources(user_data.get('interests', ''))
440
+ project_ideas = get_project_ideas(learning_paths)
441
+
442
+ # Save recommendations to session
443
+ user_data.update({
444
+ 'recommended_paths': learning_paths,
445
+ 'recommended_resources': resources,
446
+ 'recommended_projects': project_ideas
447
+ })
448
+ save_session(session_id, user_data)
449
+
450
+ # Format recommendations
451
+ recommendations = f"""
452
+ # Your Personalized Learning Recommendations
453
+
454
+ {format_learning_paths(learning_paths)}
455
+
456
+ {format_resources(resources)}
457
+
458
+ {format_project_ideas(project_ideas)}
459
+ """
460
+
461
+ return recommendations
462
+
463
+ def handle_quiz_request(session_id, topic, difficulty):
464
+ """Handle quiz generation request"""
465
+ user_data = load_session(session_id)
466
+
467
+ if not user_data or not user_data.get('age'):
468
+ return "Please complete your profile first by going to the Profile tab."
469
+
470
+ quiz = generate_quiz(topic, difficulty)
471
+ return quiz
472
+
473
+ def handle_study_plan_request(session_id, topic, time_available):
474
+ """Handle study plan generation request"""
475
+ user_data = load_session(session_id)
476
+
477
+ if not user_data or not user_data.get('age'):
478
+ return "Please complete your profile first by going to the Profile tab."
479
+
480
+ goals = user_data.get('goals', 'improving skills')
481
+ study_plan = create_study_plan(topic, time_available, goals)
482
+ return study_plan
483
 
484
  def create_chatbot():
485
+ """Create the Gradio interface for the chatbot"""
486
+ # Generate a random session ID for the user
487
+ session_id = str(uuid.uuid4())
488
+
489
+ # Define theme colors and styling
490
+ primary_color = "#4a6fa5"
491
+ secondary_color = "#6c757d"
492
+ success_color = "#28a745"
493
+ light_color = "#f8f9fa"
494
+ dark_color = "#343a40"
495
+
496
+ custom_css = f"""
497
+ :root {{
498
+ --primary-color: {primary_color};
499
+ --secondary-color: {secondary_color};
500
+ --success-color: {success_color};
501
+ --light-color: {light_color};
502
+ --dark-color: {dark_color};
503
+ }}
504
+ .gradio-container {{
505
+ background-color: var(--light-color);
506
+ font-family: 'Inter', 'Segoe UI', sans-serif;
507
+ }}
508
+ #title {{
509
+ font-size: 32px;
510
+ font-weight: bold;
511
+ text-align: center;
512
+ padding-top: 20px;
513
+ color: var(--primary-color);
514
+ margin-bottom: 0;
515
+ }}
516
+ #subtitle {{
517
+ font-size: 18px;
518
+ text-align: center;
519
+ margin-bottom: 20px;
520
+ color: var(--secondary-color);
521
+ }}
522
+ .card {{
523
  background-color: white;
524
  padding: 20px;
525
  border-radius: 12px;
526
+ box-shadow: 0 4px 10px rgba(0,0,0,0.08);
527
  margin-bottom: 20px;
528
+ }}
529
+ .tabs {{
530
+ margin-top: 20px;
531
+ }}
532
+ .gr-button-primary {{
533
+ background-color: var(--primary-color) !important;
534
+ }}
535
+ .gr-button-secondary {{
536
+ background-color: var(--secondary-color) !important;
537
+ }}
538
+ .gr-button-success {{
539
+ background-color: var(--success-color) !important;
540
+ }}
541
+ .footer {{
542
+ text-align: center;
543
+ margin-top: 30px;
544
+ padding: 10px;
545
+ font-size: 14px;
546
+ color: var(--secondary-color);
547
+ }}
548
+ .progress-module {{
549
+ padding: 10px;
550
+ margin: 5px 0;
551
+ border-radius: 5px;
552
+ background-color: #e9ecef;
553
+ }}
554
+ .progress-module.completed {{
555
+ background-color: #d4edda;
556
+ }}
557
+ """
558
+
559
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="blue")) as demo:
560
+ gr.HTML("<div id='title'>🎓 AI Teaching Assistant Pro</div>")
561
+ gr.HTML("<div id='subtitle'>Your personalized learning companion for Python, Data Science & AI</div>")
562
+
563
+ # Tabs for different sections
564
+ with gr.Tabs(elem_classes=["tabs"]) as tabs:
565
+ # Profile Tab
566
+ with gr.Tab("Profile & Goals"):
567
+ with gr.Column(elem_classes=["card"]):
568
+ gr.HTML("<h3>Complete Your Learning Profile</h3>")
569
+
570
+ with gr.Row():
571
+ with gr.Column(scale=1):
572
+ age_input = gr.Textbox(
573
+ label="Age",
574
+ placeholder="e.g. 20",
575
+ lines=1
576
+ )
577
+ with gr.Column(scale=2):
578
+ knowledge_level_input = gr.Dropdown(
579
+ choices=["Beginner", "Intermediate", "Advanced", "Expert"],
580
+ label="Knowledge Level",
581
+ value="Beginner"
582
+ )
583
+
584
+ goals_input = gr.Textbox(
585
+ label="Learning Goals",
586
+ placeholder="e.g. I want to become a data scientist and work with machine learning models",
587
+ lines=2
588
+ )
589
+
590
+ interests_input = gr.Textbox(
591
+ label="Specific Interests",
592
+ placeholder="e.g. Python, data visualization, neural networks",
593
+ lines=2
594
+ )
595
+
596
+ with gr.Row():
597
+ with gr.Column(scale=1):
598
+ study_time_input = gr.Dropdown(
599
+ choices=["1-3", "4-6", "7-10", "10+"],
600
+ label="Hours Available Weekly",
601
+ value="4-6"
602
+ )
603
+ with gr.Column(scale=2):
604
+ learning_style_input = gr.Dropdown(
605
+ choices=["Visual", "Reading/Writing", "Hands-on Projects", "Video Tutorials", "Interactive Exercises", "Combination"],
606
+ label="Preferred Learning Style",
607
+ value="Combination"
608
+ )
609
+
610
+ profile_submit_btn = gr.Button("Save Profile & Generate Recommendations", variant="primary")
611
+ profile_output = gr.Markdown(label="Personalized Recommendations")
612
+
613
+ # Chat Tab
614
+ with gr.Tab("Learning Assistant"):
615
+ with gr.Row():
616
+ with gr.Column(elem_classes=["card"]):
617
+ chat_input = gr.Textbox(
618
+ label="Ask a Question",
619
+ placeholder="Ask anything about Python, Data Science, AI...",
620
+ lines=3
621
+ )
622
+
623
+ with gr.Row():
624
+ chat_submit_btn = gr.Button("Send Message", variant="primary")
625
+ chat_clear_btn = gr.Button("Clear Chat", variant="secondary")
626
+
627
+ chat_output = gr.Markdown(label="Assistant Response")
628
+
629
+ # Resources Tab
630
+ with gr.Tab("Resources & Recommendations"):
631
+ with gr.Column(elem_classes=["card"]):
632
+ gr.HTML("<h3>Your Learning Resources</h3>")
633
+ refresh_recommendations_btn = gr.Button("Refresh Recommendations", variant="primary")
634
+ recommendations_output = gr.Markdown(label="Personalized Recommendations")
635
+
636
+ # Practice Tab
637
+ with gr.Tab("Practice & Assessment"):
638
+ with gr.Column(elem_classes=["card"]):
639
+ gr.HTML("<h3>Generate a Quiz</h3>")
640
+
641
+ with gr.Row():
642
+ quiz_topic_input = gr.Textbox(
643
+ label="Quiz Topic",
644
+ placeholder="e.g. Python Lists",
645
+ lines=1
646
+ )
647
+ quiz_difficulty_input = gr.Dropdown(
648
+ choices=["Beginner", "Intermediate", "Advanced"],
649
+ label="Difficulty Level",
650
+ value="Beginner"
651
+ )
652
+
653
+ generate_quiz_btn = gr.Button("Generate Quiz", variant="primary")
654
+ quiz_output = gr.Markdown(label="Quiz")
655
+
656
+ # Study Plan Tab
657
+ with gr.Tab("Study Plan"):
658
+ with gr.Column(elem_classes=["card"]):
659
+ gr.HTML("<h3>Generate a Personalized Study Plan</h3>")
660
+
661
+ with gr.Row():
662
+ plan_topic_input = gr.Textbox(
663
+ label="Study Topic",
664
+ placeholder="e.g. Data Science",
665
+ lines=1
666
+ )
667
+ plan_time_input = gr.Dropdown(
668
+ choices=["1-3", "4-6", "7-10", "10+"],
669
+ label="Hours Available Weekly",
670
+ value="4-6"
671
+ )
672
+
673
+ generate_plan_btn = gr.Button("Generate Study Plan", variant="primary")
674
+ plan_output = gr.Markdown(label="Personalized Study Plan")
675
+
676
+ gr.HTML("""<div class="footer">
677
+ AI Teaching Assistant Pro | Version 2.0 | © 2025 | Powered by Groq AI
678
+ </div>""")
679
 
680
+ # Event handlers
681
+ profile_submit_btn.click(
682
+ user_onboarding,
683
+ inputs=[
684
+ gr.State(session_id),
685
+ age_input,
686
+ goals_input,
687
+ knowledge_level_input,
688
+ interests_input,
689
+ study_time_input,
690
+ learning_style_input
691
+ ],
692
+ outputs=profile_output
693
+ )
694
+
695
+ chat_submit_btn.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
696
  chatbot_interface,
697
+ inputs=[gr.State(session_id), chat_input],
698
+ outputs=chat_output
699
  )
700
+
701
+ chat_clear_btn.click(
702
+ lambda: "",
703
  inputs=[],
704
+ outputs=[chat_output, chat_input]
705
  )
706
+
707
+ refresh_recommendations_btn.click(
708
+ generate_recommendations,
709
+ inputs=[gr.State(session_id)],
710
+ outputs=recommendations_output
711
+ )
712
+
713
+ generate_quiz_btn.click(
714
+ handle_quiz_request,
715
+ inputs=[gr.State(session_id), quiz_topic_input, quiz_difficulty_input],
716
+ outputs=quiz_output
717
+ )
718
+
719
+ generate_plan_btn.click(
720
+ handle_study_plan_request,
721
+ inputs=[gr.State(session_id), plan_topic_input, plan_time_input],
722
+ outputs=plan_output
723
+ )
724
+
725
+ return demo
726
 
727
  # Run the chatbot
728
+ if __name__ == "__main__":
729
+ app = create_chatbot()
730
+ app.launch()