bridget-20's picture
Update app.py
c8aeebb verified
Raw History Blame Contribute Delete
9.48 kB
import os
if os.environ.get("SPACES_ZERO_GPU") is not None:
import spaces
else:
class spaces:
@staticmethod
def GPU(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@spaces.GPU
def fake_gpu():
pass
from datetime import datetime, timedelta
import random
import gradio as gr
class EnhancedStudentPlatformBot:
def __init__(self):
self.student_data = {}
self.conversations = {}
self.custom_prompts = {}
self.conversation_history = {}
# Default FAQ responses
self.faq_responses = {
"attachment": "You can find available attachments under the 'Opportunities' tab. Navigate to the tab and click 'Apply' for positions that interest you.",
"submit_project": "To submit a project: 1. Go to 'My Projects' 2. Click 'New Submission' 3. Fill the form and upload your files 4. Click 'Submit'",
"portfolio": "To update your portfolio: 1. Go to 'My Profile' 2. Click 'Edit Portfolio' 3. Add your projects and skills 4. Save changes",
"register": "To register, go to the homepage, click on 'Sign Up', and fill in your details. Make sure to verify your email to complete the registration process."
}
# Conversation starters and follow-ups
self.conversation_starters = [
"How's your learning journey going today?",
"What's on your mind regarding your studies?",
"Need any help with your current projects?",
"How can I assist you with your learning goals today?"
]
self.follow_up_questions = {
"project_recommendation": [
"Would you like more details about any of these projects?",
"Shall I help you set up a project timeline?",
"Would you like to see learning resources for these projects?"
],
"progress_check": [
"Would you like specific tips to improve in any area?",
"Should we set some learning goals for the next week?",
"Would you like to see related project opportunities?"
]
}
def initialize_student(self, student_id, name, skills=None):
if student_id not in self.student_data:
self.student_data[student_id] = {
"name": name,
"skills": skills or [],
"projects": [],
"deadlines": [],
"progress": {
"web_development": 0,
"python": 0,
"data_science": 0
},
"last_interaction": datetime.now(),
"interaction_count": 0
}
self.conversation_history[student_id] = []
return self.generate_welcome_message(student_id)
def add_custom_prompt(self, keyword, response, follow_up=None):
self.custom_prompts[keyword.lower()] = {
"response": response,
"follow_up": follow_up
}
return f"Custom prompt added for keyword: {keyword}"
def generate_welcome_message(self, student_id):
student = self.student_data[student_id]
current_time = datetime.now()
time_diff = current_time - student["last_interaction"]
if time_diff.days == 0 and student["interaction_count"] > 0:
return f"Welcome back {student['name']}! Continuing from our previous conversation. How can I help you now?"
greeting = self._get_time_based_greeting()
return f"{greeting} {student['name']}! πŸ‘‹\n\n" \
f"I'm your learning assistant and I notice you're skilled in {', '.join(student['skills'])}. " \
f"I can help you with:\n\n" \
"🎯 Platform guidance and personalized recommendations\n" \
"πŸ“š Project suggestions and resources\n" \
"❓ Common questions and support\n" \
"⏰ Deadline management\n" \
"πŸ“Š Progress tracking\n\n" \
f"{random.choice(self.conversation_starters)}"
def _get_time_based_greeting(self):
hour = datetime.now().hour
if 5 <= hour < 12:
return "Good morning"
elif 12 <= hour < 17:
return "Good afternoon"
else:
return "Good evening"
def process_message(self, student_id, message):
if student_id not in self.student_data:
return "Please register first to use the chatbot."
self.student_data[student_id]["last_interaction"] = datetime.now()
self.student_data[student_id]["interaction_count"] += 1
self.conversation_history[student_id].append({
"timestamp": datetime.now(),
"message": message,
"type": "user"
})
response = self._generate_response(student_id, message)
self.conversation_history[student_id].append({
"timestamp": datetime.now(),
"message": response,
"type": "bot"
})
return response
def _generate_response(self, student_id, message):
message = message.lower()
for keyword, prompt_data in self.custom_prompts.items():
if keyword in message:
response = prompt_data["response"]
if prompt_data["follow_up"]:
response += f"\n\n{prompt_data['follow_up']}"
return response
if any(word in message for word in ["help", "guide", "how"]):
if "register" in message:
return self.faq_responses.get("register", "You can register by visiting the registration page.")
elif "project" in message and "submit" in message:
return self.faq_responses.get("submit_project", "")
elif any(word in message for word in ["recommend", "project", "idea"]):
response = self.recommend_projects(student_id)
return f"{response}\n\n{random.choice(self.follow_up_questions['project_recommendation'])}"
elif "deadline" in message:
return self.check_deadlines(student_id)
elif "progress" in message:
response = self.track_progress(student_id)
return f"{response}\n\n{random.choice(self.follow_up_questions['progress_check'])}"
elif any(keyword in message for keyword in self.faq_responses.keys()):
return self.handle_faq(message)
return self._generate_fallback_response(student_id)
def _generate_fallback_response(self, student_id):
student = self.student_data[student_id]
has_deadlines = len(student["deadlines"]) > 0
responses = [
f"I notice you're working on improving your {', '.join(student['skills'])}. Would you like some project recommendations in these areas?",
"I can help you track your progress or manage deadlines. What would you like to focus on?",
"Would you like to explore some learning resources or get project recommendations?"
]
if has_deadlines:
responses.append("I see you have some upcoming deadlines. Would you like to review them?")
return random.choice(responses)
def recommend_projects(self, student_id):
student = self.student_data[student_id]
skills = student['skills']
projects = [f"Build a {skill}-based project" for skill in skills]
return f"Here are some project ideas based on your skills: {', '.join(projects)}"
def check_deadlines(self, student_id):
student = self.student_data[student_id]
deadlines = student.get("deadlines", [])
if not deadlines:
return "You don't have any upcoming deadlines."
deadline_messages = [f"{d['task']} - Due by {d['date'].strftime('%Y-%m-%d')}" for d in deadlines]
return "Here are your upcoming deadlines:\n" + "\n".join(deadline_messages)
def track_progress(self, student_id):
student = self.student_data[student_id]
progress = student["progress"]
progress_report = [f"{skill}: {percent}% complete" for skill, percent in progress.items()]
return "Here's your current progress:\n" + "\n".join(progress_report)
def handle_faq(self, message):
for keyword, response in self.faq_responses.items():
if keyword in message:
return response
return "I couldn't find an answer to your query."
def chatbot_interface(user_input, history=[]):
student_id = "12345"
bot = EnhancedStudentPlatformBot()
if len(history) == 0:
bot.initialize_student(student_id=student_id, name="John", skills=["Python", "Web Development"])
bot_response = bot.process_message(student_id, user_input)
history.append((user_input, bot_response))
return history, history
with gr.Blocks() as chatbot_app:
gr.Markdown("<h1><center>Enhanced Student Platform Bot</center></h1>")
chatbot = gr.Chatbot(label="Chat with the bot")
message = gr.Textbox(placeholder="Type your message here...", label="Your Message")
message.submit(chatbot_interface, [message, chatbot], [message, chatbot])
if __name__ == "__main__":
chatbot_app.launch()