Spaces:
Running
Running
File size: 37,424 Bytes
3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 6ce9877 4968617 d0e3fb3 4968617 d0e3fb3 6ce9877 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 f8de84c 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 3a62c95 4968617 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 |
import gradio as gr
import os
import json
import uuid
from datetime import datetime
from groq import Groq
# Set up Groq API key
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("GROQ_API_KEY environment variable not set.")
client = Groq(api_key=GROQ_API_KEY)
# Default system prompt
SYSTEM_PROMPT = (
"You are an intelligent, friendly, and highly adaptable Teaching Assistant Chatbot. "
"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. "
"You explain concepts clearly using real-world analogies, examples, and interactive exercises. "
"You ask questions to assess the learner's level, adapt accordingly, and provide learning paths tailored to their pace and goals. "
"Your responses are structured, engaging, and supportive. "
"You can explain code snippets, generate exercises and quizzes, and recommend projects. "
"You never overwhelm users with jargon. Instead, you scaffold complex concepts in simple, digestible steps."
)
# Define learning paths with format options for different learning styles
LEARNING_PATHS = {
"python_beginner": {
"title": "Python Fundamentals",
"description": "Learn Python basics from variables to functions",
"modules": [
"Variables & Data Types",
"Control Flow",
"Functions",
"Data Structures",
"File I/O"
],
"resources": {
"Visual": ["Interactive Python visualizers", "Flowcharts for algorithms", "Concept maps"],
"Reading/Writing": ["Comprehensive Python documentation", "Written tutorials", "Practice exercises with solutions"],
"Hands-on Projects": ["Mini-projects for each concept", "Code challenges", "GitHub repositories with starter code"],
"Video Tutorials": ["Python beginner video series", "Live coding sessions", "Animated explanations"],
"Interactive Exercises": ["Interactive coding environments", "Quizzes after each topic", "Peer programming exercises"],
"Combination": ["Mix of videos, reading materials and hands-on practice"]
}
},
"python_intermediate": {
"title": "Intermediate Python",
"description": "Advance your Python skills with OOP and more",
"modules": [
"Object-Oriented Programming",
"Modules & Packages",
"Error Handling",
"List Comprehensions",
"Decorators & Generators"
],
"resources": {
"Visual": ["OOP visualizers", "Package dependency graphs", "Error handling flowcharts"],
"Reading/Writing": ["In-depth Python guides", "Advanced documentation", "Design pattern examples"],
"Hands-on Projects": ["Medium-sized applications", "Library contributions", "Optimization challenges"],
"Video Tutorials": ["Advanced Python concept videos", "Live implementation sessions", "Code reviews"],
"Interactive Exercises": ["Advanced coding challenges", "Refactoring exercises", "Implementation quizzes"],
"Combination": ["Mix of videos, reading materials and advanced projects"]
}
},
"data_science_beginner": {
"title": "Data Science Foundations",
"description": "Begin your data science journey",
"modules": [
"Numpy Basics",
"Pandas Fundamentals",
"Data Visualization",
"Basic Statistics",
"Intro to Machine Learning"
],
"resources": {
"Visual": ["Data visualization galleries", "Statistical concept diagrams", "Algorithm flowcharts"],
"Reading/Writing": ["Data science textbooks", "Research papers", "Case studies"],
"Hands-on Projects": ["Dataset analysis projects", "Visualization portfolios", "Simple ML implementations"],
"Video Tutorials": ["Data science fundamentals series", "Tool-specific tutorials", "Statistical concept videos"],
"Interactive Exercises": ["Data analysis notebooks", "Interactive statistics demos", "ML model building exercises"],
"Combination": ["Mix of data analysis, visualization practice and statistical theory"]
}
},
"data_science_advanced": {
"title": "Advanced Data Science",
"description": "Master complex data science concepts",
"modules": [
"Advanced ML Algorithms",
"Feature Engineering",
"Time Series Analysis",
"Natural Language Processing",
"Deep Learning Basics"
],
"resources": {
"Visual": ["Complex algorithm visualizations", "Neural network architecture diagrams", "Feature importance plots"],
"Reading/Writing": ["Academic papers", "Advanced statistics guides", "Mathematical foundations"],
"Hands-on Projects": ["Kaggle competitions", "Research implementations", "Production-level ML systems"],
"Video Tutorials": ["Expert talks", "Research paper walkthroughs", "Implementation guides"],
"Interactive Exercises": ["Advanced model tuning", "Algorithm implementation", "Real-world data challenges"],
"Combination": ["Mix of theoretical study, research implementation and real-world applications"]
}
},
"ai_specialization": {
"title": "AI Specialization",
"description": "Focus on artificial intelligence concepts",
"modules": [
"Neural Networks",
"Computer Vision",
"Advanced NLP",
"Reinforcement Learning",
"AI Ethics"
],
"resources": {
"Visual": ["Neural network visualizers", "Computer vision demonstrations", "AI system diagrams"],
"Reading/Writing": ["Research papers", "AI textbooks", "Ethics case studies"],
"Hands-on Projects": ["Model implementations", "AI application development", "Research reproductions"],
"Video Tutorials": ["Research paper explanations", "Implementation walkthroughs", "Expert interviews"],
"Interactive Exercises": ["Model training exercises", "Hyperparameter tuning", "AI debugging workshops"],
"Combination": ["Mix of theoretical study, practical implementation and ethical discussions"]
}
}
}
# Learning resources expanded for different learning styles
LEARNING_RESOURCES = {
"python": {
"Visual": [
{"title": "Python Tutor - Code Visualization", "url": "http://pythontutor.com/"},
{"title": "Real Python - Visual Guides", "url": "https://realpython.com/"},
{"title": "Visualize Python - Concept Maps", "url": "https://pythonvisualization.example.org/"}
],
"Reading/Writing": [
{"title": "Python Documentation", "url": "https://docs.python.org/3/"},
{"title": "Real Python", "url": "https://realpython.com/"},
{"title": "Python for Everybody Book", "url": "https://www.py4e.com/"},
{"title": "Automate the Boring Stuff with Python", "url": "https://automatetheboringstuff.com/"}
],
"Hands-on Projects": [
{"title": "Exercism Python Track", "url": "https://exercism.org/tracks/python"},
{"title": "Project Euler", "url": "https://projecteuler.net/"},
{"title": "Python Projects on GitHub", "url": "https://github.com/topics/python-projects"},
],
"Video Tutorials": [
{"title": "YouTube - Python Programming Tutorials", "url": "https://www.youtube.com/results?search_query=python+programming+tutorials"},
{"title": "Coursera - Python Courses", "url": "https://www.coursera.org/courses?query=python"},
{"title": "edX - Learn Python", "url": "https://www.edx.org/learn/python"},
{"title": "Udemy - Python Video Courses", "url": "https://www.udemy.com/topic/python/"},
{"title": "Khan Academy - Computer Programming", "url": "https://www.khanacademy.org/computing/computer-programming"}
],
"Interactive Exercises": [
{"title": "CheckiO Python Challenges", "url": "https://py.checkio.org/"},
{"title": "HackerRank Python", "url": "https://www.hackerrank.com/domains/python"},
{"title": "Codewars Python", "url": "https://www.codewars.com/?language=python"},
{"title": "LeetCode Python", "url": "https://leetcode.com/problemset/all/?difficulty=Easy&topicSlugs=python"}
],
"Video Tutorials": [
{"title": "YouTube - Data Science Tutorials", "url": "https://www.youtube.com/results?search_query=data+science+tutorials"},
{"title": "Coursera - Data Science Courses", "url": "https://www.coursera.org/browse/data-science"},
{"title": "edX - Learn Data Science", "url": "https://www.edx.org/learn/data-science"},
{"title": "Udacity - Data Science Programs", "url": "https://www.udacity.com/school-of-data-science"},
{"title": "Udemy - Data Science Video Courses", "url": "https://www.udemy.com/topic/data-science/"}
]
},
"data_science": {
"Visual": [
{"title": "Seeing Theory - Visual Statistics", "url": "https://seeing-theory.brown.edu/"},
{"title": "Data Visualization Catalogue", "url": "https://datavizcatalogue.com/"},
{"title": "Visualizing Machine Learning", "url": "https://www.r2d3.us/visual-intro-to-machine-learning-part-1/"}
],
"Reading/Writing": [
{"title": "Towards Data Science", "url": "https://towardsdatascience.com/"},
{"title": "Machine Learning Mastery", "url": "https://machinelearningmastery.com/"},
{"title": "Data Science Handbook", "url": "https://jakevdp.github.io/PythonDataScienceHandbook/"},
{"title": "Statistical Learning Book", "url": "https://www.statlearning.com/"}
],
"Hands-on Projects": [
{"title": "Kaggle Competitions", "url": "https://www.kaggle.com/competitions"},
{"title": "Data Science Projects on GitHub", "url": "https://github.com/topics/data-science-projects"},
{"title": "Real-world Data Science Tasks", "url": "https://www.drivendata.org/"},
{"title": "UCI Machine Learning Repository", "url": "https://archive.ics.uci.edu/ml/index.php"}
],
"Video Tutorials": [
{"title": "StatQuest with Josh Starmer", "url": "https://www.youtube.com/c/joshstarmer"},
{"title": "Data School", "url": "https://www.youtube.com/c/dataschool"},
{"title": "3Blue1Brown Statistics", "url": "https://www.youtube.com/c/3blue1brown"},
{"title": "Krish Naik Data Science", "url": "https://www.youtube.com/user/krishnaik06"}
],
"Interactive Exercises": [
{"title": "Kaggle Learn", "url": "https://www.kaggle.com/learn"},
{"title": "DataQuest Interactive Lessons", "url": "https://www.dataquest.io/"},
{"title": "Mode Analytics SQL Tutorial", "url": "https://mode.com/sql-tutorial/"},
{"title": "IBM Data Science Exercise", "url": "https://cognitiveclass.ai/"}
],
"Combination": [
{"title": "DataCamp", "url": "https://www.datacamp.com/"},
{"title": "Coursera Data Science Specialization", "url": "https://www.coursera.org/specializations/jhu-data-science"},
{"title": "edX Data Science MicroMasters", "url": "https://www.edx.org/micromasters/mitx-statistics-and-data-science"},
{"title": "Fast.ai Practical Data Science", "url": "https://www.fast.ai/"}
]
},
"ai": {
"Visual": [
{"title": "TensorFlow Playground", "url": "https://playground.tensorflow.org/"},
{"title": "Distill.pub Visualizations", "url": "https://distill.pub/"},
{"title": "AI Visuals & Explainers", "url": "https://pair.withgoogle.com/explorables/"}
],
"Reading/Writing": [
{"title": "arXiv AI Papers", "url": "https://arxiv.org/list/cs.AI/recent"},
{"title": "AI Textbook", "url": "http://aima.cs.berkeley.edu/"},
{"title": "Deep Learning Book", "url": "https://www.deeplearningbook.org/"},
{"title": "Papers with Code", "url": "https://paperswithcode.com/"}
],
"Hands-on Projects": [
{"title": "AI Projects on GitHub", "url": "https://github.com/topics/artificial-intelligence"},
{"title": "Hugging Face Model Hub", "url": "https://huggingface.co/models"},
{"title": "TensorFlow Model Garden", "url": "https://github.com/tensorflow/models"},
{"title": "PyTorch Examples", "url": "https://github.com/pytorch/examples"}
],
"Video Tutorials": [
{"title": "DeepMind YouTube", "url": "https://www.youtube.com/c/DeepMind"},
{"title": "Yannic Kilcher AI Papers", "url": "https://www.youtube.com/c/YannicKilcher"},
{"title": "MIT Deep Learning Lectures", "url": "https://www.youtube.com/playlist?list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI"},
{"title": "Stanford CS231n Videos", "url": "https://www.youtube.com/playlist?list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv"}
],
"Interactive Exercises": [
{"title": "Google AI Experiments", "url": "https://experiments.withgoogle.com/collection/ai"},
{"title": "OpenAI Gym", "url": "https://gym.openai.com/"},
{"title": "ML Playground", "url": "https://ml-playground.com/"},
{"title": "Colab Research AI Projects", "url": "https://colab.research.google.com/"}
],
"Combination": [
{"title": "Fast.ai", "url": "https://www.fast.ai/"},
{"title": "DeepLearning.AI", "url": "https://www.deeplearning.ai/"},
{"title": "Coursera Machine Learning", "url": "https://www.coursera.org/learn/machine-learning"},
{"title": "edX AI Courses", "url": "https://www.edx.org/learn/artificial-intelligence"}
]
}
}
# Practice project ideas
PROJECT_IDEAS = {
"python_beginner": [
"To-Do List Application",
"Simple Calculator",
"Password Generator",
"Hangman Game",
"Basic File Organizer"
],
"python_intermediate": [
"Weather App with API",
"Personal Blog with Flask",
"Web Scraper for News Articles",
"Data Visualization Dashboard",
"Task Automation Scripts"
],
"data_science": [
"Housing Price Prediction",
"Customer Segmentation Analysis",
"Sentiment Analysis of Reviews",
"Stock Price Forecasting",
"A/B Test Analysis Dashboard"
],
"ai": [
"Image Classification System",
"Chatbot with NLP",
"Recommendation Engine",
"Text Summarization Tool",
"Object Detection Application"
]
}
# User session data store
SESSION_DATA = {}
def save_session(session_id, data):
"""Save session data to SESSION_DATA global dictionary"""
if session_id in SESSION_DATA:
SESSION_DATA[session_id].update(data)
else:
SESSION_DATA[session_id] = data
# Add timestamp for session tracking
SESSION_DATA[session_id]["last_activity"] = datetime.now().isoformat()
def load_session(session_id):
"""Load session data from SESSION_DATA global dictionary"""
return SESSION_DATA.get(session_id, {})
def recommend_learning_path(age, goals, knowledge_level, interests):
"""Recommend personalized learning paths based on user profile"""
paths = []
# Simple recommendation logic based on profile
if "beginner" in knowledge_level.lower():
if any(topic in interests.lower() for topic in ["python", "programming", "coding"]):
paths.append("python_beginner")
if any(topic in interests.lower() for topic in ["data", "analysis", "statistics"]):
paths.append("data_science_beginner")
elif "intermediate" in knowledge_level.lower() or "advanced" in knowledge_level.lower():
if any(topic in interests.lower() for topic in ["python", "programming", "coding"]):
paths.append("python_intermediate")
if any(topic in interests.lower() for topic in ["data", "analysis", "statistics"]):
paths.append("data_science_advanced")
if any(topic in interests.lower() for topic in ["ai", "machine learning", "deep learning"]):
paths.append("ai_specialization")
# Default path if no matches
if not paths:
paths = ["python_beginner"]
return [LEARNING_PATHS[path] for path in paths if path in LEARNING_PATHS]
def get_recommended_resources(interests):
"""Get recommended learning resources based on interests"""
resources = []
if any(topic in interests.lower() for topic in ["python", "programming", "coding"]):
resources.extend(LEARNING_RESOURCES["python"])
if any(topic in interests.lower() for topic in ["data", "analysis", "statistics"]):
resources.extend(LEARNING_RESOURCES["data_science"])
if any(topic in interests.lower() for topic in ["ai", "machine learning", "deep learning"]):
resources.extend(LEARNING_RESOURCES["ai"])
# If no specific interests match, provide general resources
if not resources:
for category in LEARNING_RESOURCES:
resources.extend(LEARNING_RESOURCES[category][:1]) # Add first resource from each category
return resources
def get_project_ideas(learning_paths):
"""Get project ideas based on recommended learning paths"""
ideas = []
for path in learning_paths:
path_id = next((k for k, v in LEARNING_PATHS.items() if v["title"] == path["title"]), None)
if path_id:
if path_id.startswith("python"):
category = "python_beginner" if "beginner" in path_id else "python_intermediate"
ideas.extend(PROJECT_IDEAS[category])
elif path_id.startswith("data_science"):
ideas.extend(PROJECT_IDEAS["data_science"])
elif path_id.startswith("ai"):
ideas.extend(PROJECT_IDEAS["ai"])
# If no specific paths match, provide some general project ideas
if not ideas:
ideas = PROJECT_IDEAS["python_beginner"][:2] + PROJECT_IDEAS["data_science"][:2]
return ideas[:5] # Return up to 5 project ideas
def generate_quiz(topic, difficulty):
"""Generate a quiz based on the topic and difficulty"""
# In a real application, you might use the LLM to generate quizzes
# Here we're using a template approach for simplicity
quiz_prompt = f"""
Generate a {difficulty} level quiz on {topic} with 3 multiple-choice questions.
For each question, provide 4 options and indicate the correct answer.
Format the quiz nicely with clear question numbering and option lettering.
"""
# Use Groq to generate the quiz
quiz_messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": quiz_prompt}
]
quiz_response = client.chat.completions.create(
messages=quiz_messages,
model="llama-3.3-70b-versatile",
stream=False
)
return quiz_response.choices[0].message.content
def create_study_plan(topic, time_available, goals):
"""Create a personalized study plan"""
plan_prompt = f"""
Create a structured study plan for learning {topic} with {time_available} hours per week available for study.
The learner's goal is: {goals}
Include:
1. Weekly breakdown of topics
2. Time allocation for theory vs practice
3. Recommended resources for each week
4. Milestone projects or assessments
5. Tips for effective learning
"""
# Use Groq to generate the study plan
plan_messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": plan_prompt}
]
plan_response = client.chat.completions.create(
messages=plan_messages,
model="llama-3.3-70b-versatile",
stream=False
)
return plan_response.choices[0].message.content
def chat_with_groq(user_input, session_id):
"""Chat with Groq LLM using session context"""
user_data = load_session(session_id)
# Build context from session data if available
context = ""
if user_data:
context = f"""
User Profile:
- Age: {user_data.get('age', 'Unknown')}
- Knowledge Level: {user_data.get('knowledge_level', 'Unknown')}
- Learning Goals: {user_data.get('goals', 'Unknown')}
- Interests: {user_data.get('interests', 'Unknown')}
- Available Study Time: {user_data.get('study_time', 'Unknown')} hours per week
- Preferred Learning Style: {user_data.get('learning_style', 'Unknown')}
Based on this profile, tailor your response appropriately.
"""
# Add chat history context if available
chat_history = user_data.get('chat_history', [])
if chat_history:
context += "\n\nRecent conversation context (most recent first):\n"
# Include up to 3 most recent exchanges
for i, (q, a) in enumerate(reversed(chat_history[-3:])):
context += f"User: {q}\nYou: {a}\n\n"
# Combine everything for the LLM
full_prompt = f"{context}\n\nUser's current question: {user_input}"
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": full_prompt}
]
chat_completion = client.chat.completions.create(
messages=messages,
model="llama-3.3-70b-versatile",
stream=False
)
response = chat_completion.choices[0].message.content
# Update chat history
if 'chat_history' not in user_data:
user_data['chat_history'] = []
user_data['chat_history'].append((user_input, response))
save_session(session_id, user_data)
return response
def format_learning_paths(paths):
"""Format learning paths for display"""
if not paths:
return "No specific learning paths recommended yet. Please complete your profile."
result = "### Recommended Learning Paths\n\n"
for i, path in enumerate(paths, 1):
result += f"**{i}. {path['title']}**\n"
result += f"{path['description']}\n\n"
result += "**Modules:**\n"
for module in path['modules']:
result += f"- {module}\n"
result += "\n"
return result
def format_resources(resources):
"""Format resources for display"""
if not resources:
return "No resources recommended yet. Please complete your profile."
result = "### Recommended Learning Resources\n\n"
for i, resource in enumerate(resources, 1):
result += f"{i}. [{resource['title']}]({resource['url']})\n"
return result
def format_project_ideas(ideas):
"""Format project ideas for display"""
if not ideas:
return "No project ideas recommended yet. Please complete your profile."
result = "### Recommended Practice Projects\n\n"
for i, idea in enumerate(ideas, 1):
result += f"{i}. {idea}\n"
return result
def user_onboarding(session_id, age, goals, knowledge_level, interests, study_time, learning_style):
"""Process user profile and provide initial recommendations"""
# Save user profile data
user_data = {
'age': age,
'goals': goals,
'knowledge_level': knowledge_level,
'interests': interests,
'study_time': study_time,
'learning_style': learning_style
}
save_session(session_id, user_data)
# Generate recommendations
learning_paths = recommend_learning_path(age, goals, knowledge_level, interests)
resources = get_recommended_resources(interests)
project_ideas = get_project_ideas(learning_paths)
# Save recommendations to session
user_data.update({
'recommended_paths': learning_paths,
'recommended_resources': resources,
'recommended_projects': project_ideas
})
save_session(session_id, user_data)
# Format welcome message with personalized recommendations
welcome_message = f"""
# Welcome to Your Personalized Learning Journey!
Thank you for providing your profile. Based on your information, I've prepared some tailored recommendations to start your learning journey.
## Your Profile Summary:
- **Age:** {age}
- **Knowledge Level:** {knowledge_level}
- **Learning Goals:** {goals}
- **Interests:** {interests}
- **Available Study Time:** {study_time} hours per week
- **Preferred Learning Style:** {learning_style}
{format_learning_paths(learning_paths)}
{format_resources(resources)}
{format_project_ideas(project_ideas)}
## Next Steps:
1. Browse through the recommended learning paths and resources
2. Ask me any questions about the topics you're interested in
3. Request exercises, explanations, or code samples
4. Try one of the project ideas to apply your knowledge
I'm here to help you every step of the way! What would you like to explore first?
"""
return welcome_message
def chatbot_interface(session_id, user_message):
"""Main chatbot interface function"""
user_data = load_session(session_id)
if not user_data or not user_data.get('age'):
return "Please complete your profile first by going to the Profile tab."
response = chat_with_groq(user_message, session_id)
return response
def generate_recommendations(session_id):
"""Generate or refresh recommendations based on current profile"""
user_data = load_session(session_id)
if not user_data or not user_data.get('age'):
return "Please complete your profile first by going to the Profile tab."
# Generate fresh recommendations
learning_paths = recommend_learning_path(
user_data.get('age', ''),
user_data.get('goals', ''),
user_data.get('knowledge_level', ''),
user_data.get('interests', '')
)
resources = get_recommended_resources(user_data.get('interests', ''))
project_ideas = get_project_ideas(learning_paths)
# Save recommendations to session
user_data.update({
'recommended_paths': learning_paths,
'recommended_resources': resources,
'recommended_projects': project_ideas
})
save_session(session_id, user_data)
# Format recommendations
recommendations = f"""
# Your Personalized Learning Recommendations
{format_learning_paths(learning_paths)}
{format_resources(resources)}
{format_project_ideas(project_ideas)}
"""
return recommendations
def handle_quiz_request(session_id, topic, difficulty):
"""Handle quiz generation request"""
user_data = load_session(session_id)
if not user_data or not user_data.get('age'):
return "Please complete your profile first by going to the Profile tab."
quiz = generate_quiz(topic, difficulty)
return quiz
def handle_study_plan_request(session_id, topic, time_available):
"""Handle study plan generation request"""
user_data = load_session(session_id)
if not user_data or not user_data.get('age'):
return "Please complete your profile first by going to the Profile tab."
goals = user_data.get('goals', 'improving skills')
study_plan = create_study_plan(topic, time_available, goals)
return study_plan
def create_chatbot():
"""Create the Gradio interface for the chatbot"""
# Generate a random session ID for the user
session_id = str(uuid.uuid4())
# Define theme colors and styling
primary_color = "#4a6fa5"
secondary_color = "#6c757d"
success_color = "#28a745"
light_color = "#f8f9fa"
dark_color = "#343a40"
custom_css = f"""
:root {{
--primary-color: {primary_color};
--secondary-color: {secondary_color};
--success-color: {success_color};
--light-color: {light_color};
--dark-color: {dark_color};
}}
.gradio-container {{
background-color: var(--light-color);
font-family: 'Inter', 'Segoe UI', sans-serif;
}}
#title {{
font-size: 32px;
font-weight: bold;
text-align: center;
padding-top: 20px;
color: var(--primary-color);
margin-bottom: 0;
}}
#subtitle {{
font-size: 18px;
text-align: center;
margin-bottom: 20px;
color: var(--secondary-color);
}}
.card {{
background-color: white;
padding: 20px;
border-radius: 12px;
box-shadow: 0 4px 10px rgba(0,0,0,0.08);
margin-bottom: 20px;
}}
.tabs {{
margin-top: 20px;
}}
.gr-button-primary {{
background-color: var(--primary-color) !important;
}}
.gr-button-secondary {{
background-color: var(--secondary-color) !important;
}}
.gr-button-success {{
background-color: var(--success-color) !important;
}}
.footer {{
text-align: center;
margin-top: 30px;
padding: 10px;
font-size: 14px;
color: var(--secondary-color);
}}
.progress-module {{
padding: 10px;
margin: 5px 0;
border-radius: 5px;
background-color: #e9ecef;
}}
.progress-module.completed {{
background-color: #d4edda;
}}
"""
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="blue")) as demo:
gr.HTML("<div id='title'>🎓 AI Teaching Assistant</div>")
gr.HTML("<div id='subtitle'>Your personalized learning companion for Python, Data Science & AI</div>")
# Tabs for different sections
with gr.Tabs(elem_classes=["tabs"]) as tabs:
# Profile Tab
with gr.Tab("Profile & Goals"):
with gr.Column(elem_classes=["card"]):
gr.HTML("<h3>Complete Your Learning Profile</h3>")
with gr.Row():
with gr.Column(scale=1):
age_input = gr.Textbox(
label="Age",
placeholder="e.g. 20",
lines=1
)
with gr.Column(scale=2):
knowledge_level_input = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced", "Expert"],
label="Knowledge Level",
value="Beginner"
)
goals_input = gr.Textbox(
label="Learning Goals",
placeholder="e.g. I want to become a data scientist and work with machine learning models",
lines=2
)
interests_input = gr.Textbox(
label="Specific Interests",
placeholder="e.g. Python, data visualization, neural networks",
lines=2
)
with gr.Row():
with gr.Column(scale=1):
study_time_input = gr.Dropdown(
choices=["1-3", "4-6", "7-10", "10+"],
label="Hours Available Weekly",
value="4-6"
)
with gr.Column(scale=2):
learning_style_input = gr.Dropdown(
choices=["Visual", "Reading/Writing", "Hands-on Projects", "Video Tutorials", "Interactive Exercises", "Combination"],
label="Preferred Learning Style",
value="Combination"
)
profile_submit_btn = gr.Button("Save Profile & Generate Recommendations", variant="primary")
profile_output = gr.Markdown(label="Personalized Recommendations")
# Chat Tab
with gr.Tab("Learning Assistant"):
with gr.Row():
with gr.Column(elem_classes=["card"]):
chat_input = gr.Textbox(
label="Ask a Question",
placeholder="Ask anything about Python, Data Science, AI...",
lines=3
)
with gr.Row():
chat_submit_btn = gr.Button("Send Message", variant="primary")
chat_clear_btn = gr.Button("Clear Chat", variant="secondary")
chat_output = gr.Markdown(label="Assistant Response")
# Resources Tab
with gr.Tab("Resources & Recommendations"):
with gr.Column(elem_classes=["card"]):
gr.HTML("<h3>Your Learning Resources</h3>")
refresh_recommendations_btn = gr.Button("Refresh Recommendations", variant="primary")
recommendations_output = gr.Markdown(label="Personalized Recommendations")
# Practice Tab
with gr.Tab("Practice & Assessment"):
with gr.Column(elem_classes=["card"]):
gr.HTML("<h3>Generate a Quiz</h3>")
with gr.Row():
quiz_topic_input = gr.Textbox(
label="Quiz Topic",
placeholder="e.g. Python Lists",
lines=1
)
quiz_difficulty_input = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
label="Difficulty Level",
value="Beginner"
)
generate_quiz_btn = gr.Button("Generate Quiz", variant="primary")
quiz_output = gr.Markdown(label="Quiz")
# Study Plan Tab
with gr.Tab("Study Plan"):
with gr.Column(elem_classes=["card"]):
gr.HTML("<h3>Generate a Personalized Study Plan</h3>")
with gr.Row():
plan_topic_input = gr.Textbox(
label="Study Topic",
placeholder="e.g. Data Science",
lines=1
)
plan_time_input = gr.Dropdown(
choices=["1-3", "4-6", "7-10", "10+"],
label="Hours Available Weekly",
value="4-6"
)
generate_plan_btn = gr.Button("Generate Study Plan", variant="primary")
plan_output = gr.Markdown(label="Personalized Study Plan")
gr.HTML("""<div class="footer">
AI Teaching Assistant Pro | Version 2.0 | © 2025 | Powered by Groq AI
</div>""")
# Event handlers
profile_submit_btn.click(
user_onboarding,
inputs=[
gr.State(session_id),
age_input,
goals_input,
knowledge_level_input,
interests_input,
study_time_input,
learning_style_input
],
outputs=profile_output
)
chat_submit_btn.click(
chatbot_interface,
inputs=[gr.State(session_id), chat_input],
outputs=chat_output
)
chat_clear_btn.click(
lambda: "",
inputs=[],
outputs=[chat_output, chat_input]
)
refresh_recommendations_btn.click(
generate_recommendations,
inputs=[gr.State(session_id)],
outputs=recommendations_output
)
generate_quiz_btn.click(
handle_quiz_request,
inputs=[gr.State(session_id), quiz_topic_input, quiz_difficulty_input],
outputs=quiz_output
)
generate_plan_btn.click(
handle_study_plan_request,
inputs=[gr.State(session_id), plan_topic_input, plan_time_input],
outputs=plan_output
)
return demo
# Run the chatbot
if __name__ == "__main__":
app = create_chatbot()
app.launch() |