bridget-20 commited on
Commit
936e1d7
Β·
verified Β·
1 Parent(s): 4b178aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -0
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta
2
+ import random
3
+ import gradio as gr
4
+
5
+ class EnhancedStudentPlatformBot:
6
+ def __init__(self):
7
+ self.student_data = {}
8
+ self.conversations = {}
9
+ self.custom_prompts = {}
10
+ self.conversation_history = {}
11
+
12
+ # Default FAQ responses
13
+ self.faq_responses = {
14
+ "attachment": "You can find available attachments under the 'Opportunities' tab. Navigate to the tab and click 'Apply' for positions that interest you.",
15
+ "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'",
16
+ "portfolio": "To update your portfolio: 1. Go to 'My Profile' 2. Click 'Edit Portfolio' 3. Add your projects and skills 4. Save changes",
17
+ "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."
18
+ }
19
+
20
+ # Conversation starters and follow-ups
21
+ self.conversation_starters = [
22
+ "How's your learning journey going today?",
23
+ "What's on your mind regarding your studies?",
24
+ "Need any help with your current projects?",
25
+ "How can I assist you with your learning goals today?"
26
+ ]
27
+
28
+ self.follow_up_questions = {
29
+ "project_recommendation": [
30
+ "Would you like more details about any of these projects?",
31
+ "Shall I help you set up a project timeline?",
32
+ "Would you like to see learning resources for these projects?"
33
+ ],
34
+ "progress_check": [
35
+ "Would you like specific tips to improve in any area?",
36
+ "Should we set some learning goals for the next week?",
37
+ "Would you like to see related project opportunities?"
38
+ ]
39
+ }
40
+
41
+ def initialize_student(self, student_id, name, skills=None):
42
+ if student_id not in self.student_data:
43
+ self.student_data[student_id] = {
44
+ "name": name,
45
+ "skills": skills or [],
46
+ "projects": [],
47
+ "deadlines": [],
48
+ "progress": {
49
+ "web_development": 0,
50
+ "python": 0,
51
+ "data_science": 0
52
+ },
53
+ "last_interaction": datetime.now(),
54
+ "interaction_count": 0
55
+ }
56
+ self.conversation_history[student_id] = []
57
+ return self.generate_welcome_message(student_id)
58
+
59
+ def add_custom_prompt(self, keyword, response, follow_up=None):
60
+ self.custom_prompts[keyword.lower()] = {
61
+ "response": response,
62
+ "follow_up": follow_up
63
+ }
64
+ return f"Custom prompt added for keyword: {keyword}"
65
+
66
+ def generate_welcome_message(self, student_id):
67
+ student = self.student_data[student_id]
68
+ current_time = datetime.now()
69
+ time_diff = current_time - student["last_interaction"]
70
+
71
+ if time_diff.days == 0 and student["interaction_count"] > 0:
72
+ return f"Welcome back {student['name']}! Continuing from our previous conversation. How can I help you now?"
73
+
74
+ greeting = self._get_time_based_greeting()
75
+ return f"{greeting} {student['name']}! πŸ‘‹\n\n" \
76
+ f"I'm your learning assistant and I notice you're skilled in {', '.join(student['skills'])}. " \
77
+ f"I can help you with:\n\n" \
78
+ "🎯 Platform guidance and personalized recommendations\n" \
79
+ "πŸ“š Project suggestions and resources\n" \
80
+ "❓ Common questions and support\n" \
81
+ "⏰ Deadline management\n" \
82
+ "πŸ“Š Progress tracking\n\n" \
83
+ f"{random.choice(self.conversation_starters)}"
84
+
85
+ def _get_time_based_greeting(self):
86
+ hour = datetime.now().hour
87
+ if 5 <= hour < 12:
88
+ return "Good morning"
89
+ elif 12 <= hour < 17:
90
+ return "Good afternoon"
91
+ else:
92
+ return "Good evening"
93
+
94
+ def process_message(self, student_id, message):
95
+ if student_id not in self.student_data:
96
+ return "Please register first to use the chatbot."
97
+
98
+ self.student_data[student_id]["last_interaction"] = datetime.now()
99
+ self.student_data[student_id]["interaction_count"] += 1
100
+
101
+ self.conversation_history[student_id].append({
102
+ "timestamp": datetime.now(),
103
+ "message": message,
104
+ "type": "user"
105
+ })
106
+
107
+ response = self._generate_response(student_id, message)
108
+
109
+ self.conversation_history[student_id].append({
110
+ "timestamp": datetime.now(),
111
+ "message": response,
112
+ "type": "bot"
113
+ })
114
+
115
+ return response
116
+
117
+ def _generate_response(self, student_id, message):
118
+ message = message.lower()
119
+
120
+ for keyword, prompt_data in self.custom_prompts.items():
121
+ if keyword in message:
122
+ response = prompt_data["response"]
123
+ if prompt_data["follow_up"]:
124
+ response += f"\n\n{prompt_data['follow_up']}"
125
+ return response
126
+
127
+ if any(word in message for word in ["help", "guide", "how"]):
128
+ if "register" in message:
129
+ return self.faq_responses.get("register", "You can register by visiting the registration page.")
130
+ elif "project" in message and "submit" in message:
131
+ return self.faq_responses.get("submit_project", "")
132
+
133
+ elif any(word in message for word in ["recommend", "project", "idea"]):
134
+ response = self.recommend_projects(student_id)
135
+ return f"{response}\n\n{random.choice(self.follow_up_questions['project_recommendation'])}"
136
+
137
+ elif "deadline" in message:
138
+ return self.check_deadlines(student_id)
139
+
140
+ elif "progress" in message:
141
+ response = self.track_progress(student_id)
142
+ return f"{response}\n\n{random.choice(self.follow_up_questions['progress_check'])}"
143
+
144
+ elif any(keyword in message for keyword in self.faq_responses.keys()):
145
+ return self.handle_faq(message)
146
+
147
+ return self._generate_fallback_response(student_id)
148
+
149
+ def _generate_fallback_response(self, student_id):
150
+ student = self.student_data[student_id]
151
+ has_deadlines = len(student["deadlines"]) > 0
152
+
153
+ responses = [
154
+ f"I notice you're working on improving your {', '.join(student['skills'])}. Would you like some project recommendations in these areas?",
155
+ "I can help you track your progress or manage deadlines. What would you like to focus on?",
156
+ "Would you like to explore some learning resources or get project recommendations?"
157
+ ]
158
+
159
+ if has_deadlines:
160
+ responses.append("I see you have some upcoming deadlines. Would you like to review them?")
161
+
162
+ return random.choice(responses)
163
+
164
+ def recommend_projects(self, student_id):
165
+ student = self.student_data[student_id]
166
+ skills = student['skills']
167
+ projects = [f"Build a {skill}-based project" for skill in skills]
168
+ return f"Here are some project ideas based on your skills: {', '.join(projects)}"
169
+
170
+ def check_deadlines(self, student_id):
171
+ student = self.student_data[student_id]
172
+ deadlines = student.get("deadlines", [])
173
+
174
+ if not deadlines:
175
+ return "You don't have any upcoming deadlines."
176
+
177
+ deadline_messages = [f"{d['task']} - Due by {d['date'].strftime('%Y-%m-%d')}" for d in deadlines]
178
+ return "Here are your upcoming deadlines:\n" + "\n".join(deadline_messages)
179
+
180
+ def track_progress(self, student_id):
181
+ student = self.student_data[student_id]
182
+ progress = student["progress"]
183
+ progress_report = [f"{skill}: {percent}% complete" for skill, percent in progress.items()]
184
+ return "Here's your current progress:\n" + "\n".join(progress_report)
185
+
186
+ def handle_faq(self, message):
187
+ for keyword, response in self.faq_responses.items():
188
+ if keyword in message:
189
+ return response
190
+ return "I couldn't find an answer to your query."
191
+
192
+
193
+ def chatbot_interface(user_input, history=[]):
194
+ student_id = "12345"
195
+
196
+ bot = EnhancedStudentPlatformBot()
197
+ if len(history) == 0:
198
+ bot.initialize_student(student_id=student_id, name="John", skills=["Python", "Web Development"])
199
+
200
+ bot_response = bot.process_message(student_id, user_input)
201
+ history.append((user_input, bot_response))
202
+
203
+ return history, history
204
+
205
+
206
+ with gr.Blocks() as chatbot_app:
207
+ gr.Markdown("<h1><center>Enhanced Student Platform Bot</center></h1>")
208
+ chatbot = gr.Chatbot(label="Chat with the bot")
209
+ message = gr.Textbox(placeholder="Type your message here...", label="Your Message")
210
+ message.submit(chatbot_interface, [message, chatbot], [message, chatbot])
211
+
212
+ if __name__ == "__main__":
213
+ chatbot_app.launch(share=True)