File size: 9,476 Bytes
c8aeebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
936e1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f9a5f4
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
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()