markobinario commited on
Commit
196d9d1
Β·
verified Β·
1 Parent(s): 529ba47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +214 -239
app.py CHANGED
@@ -1,261 +1,236 @@
1
  import gradio as gr
2
- from chatbot import Chatbot
3
- import json
 
 
 
4
 
5
- # Initialize chatbot
6
- chatbot = Chatbot()
 
7
 
8
- def chat_interface(message, history):
9
- """Handle chat interface with Gradio"""
10
- if not message.strip():
11
- return "Please enter a message."
12
-
13
- # Get response from chatbot
14
- response = chatbot.get_response(message)
15
 
16
- # Format the response for display (removed confidence)
17
- if response['status'] == 'success':
18
- formatted_response = response['answer']
19
- else:
20
- formatted_response = response['answer']
21
 
22
- return formatted_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
- def get_system_info():
25
- """Get system information"""
26
- faq_count = chatbot.get_qa_count()
27
- database_url = chatbot.database_url
 
 
28
 
29
- # Test database connection
30
  try:
31
- import requests
32
- response = requests.get(f"{database_url}/faqs", params={'question': 'test'}, timeout=5)
33
- if response.status_code == 200:
34
- db_status = "Connected"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  else:
36
- db_status = f"Error ({response.status_code})"
37
- except:
38
- db_status = "Unavailable"
39
-
40
- return f"System Status: Active\nFAQ Pairs Loaded: {faq_count}\nDatabase: {db_status}\nCourse Recommender: Ready"
41
 
42
- def get_course_recommendations(stanine, gwa, strand, hobbies):
43
- """Get course recommendations"""
44
- return chatbot.get_course_recommendations(stanine, gwa, strand, hobbies)
 
 
 
 
45
 
46
  # Create Gradio interface
47
- with gr.Blocks(
48
- title="AI Chatbot",
49
- theme=gr.themes.Soft(),
50
- css="""
51
- .gradio-container {
52
- max-width: 800px !important;
53
- margin: auto !important;
54
- }
55
- .chat-message {
56
- padding: 10px;
57
- margin: 5px 0;
58
- border-radius: 10px;
59
- }
60
- """
61
- ) as demo:
62
-
63
- gr.Markdown(
64
- """
65
- # πŸ€– AI Student Assistant
66
 
67
- Get answers to your questions and personalized course recommendations!
 
68
 
69
- **Features:**
70
- - FAQ Chat: Get instant answers from our knowledge base
71
- - Course Recommendations: Get personalized course suggestions based on your profile
72
- """
73
- )
74
-
75
- with gr.Tabs():
76
- with gr.TabItem("πŸ’¬ FAQ Chat"):
77
- with gr.Row():
78
- with gr.Column(scale=3):
79
- chatbot_interface = gr.Chatbot(
80
- label="FAQ Chat",
81
- height=400,
82
- show_label=True,
83
- container=True,
84
- bubble_full_width=False
85
- )
86
-
87
- with gr.Row():
88
- msg = gr.Textbox(
89
- placeholder="Type your question here...",
90
- show_label=False,
91
- scale=4,
92
- container=False
93
- )
94
- submit_btn = gr.Button("Send", variant="primary", scale=1)
95
 
96
- with gr.Column(scale=1):
97
- gr.Markdown("### System Info")
98
- system_info = gr.Textbox(
99
- value=get_system_info(),
100
- label="Status",
101
- interactive=False,
102
- lines=4
103
- )
104
-
105
- refresh_btn = gr.Button("Refresh Status", variant="secondary")
106
-
107
- gr.Markdown("### FAQ Instructions")
108
- gr.Markdown(
109
- """
110
- **How to use:**
111
- 1. Type your question in the text box
112
- 2. Click Send or press Enter
113
- 3. Get AI-powered answers from FAQ database
114
-
115
- **Tips:**
116
- - Ask specific questions for better results
117
- - Try rephrasing if you don't get a good match
118
- """
119
- )
120
-
121
- with gr.TabItem("🎯 Course Recommendations"):
122
- with gr.Row():
123
- with gr.Column(scale=2):
124
- gr.Markdown("### πŸ“ Student Profile")
125
-
126
- stanine_input = gr.Textbox(
127
- value="5",
128
- label="Stanine (1-9)",
129
- placeholder="Enter a number between 1 and 9",
130
- info="Your stanine score from standardized tests"
131
- )
132
-
133
- gwa_input = gr.Textbox(
134
- value="85",
135
- label="GWA (75-100)",
136
- placeholder="Enter a number between 75 and 100",
137
- info="Your General Weighted Average"
138
- )
139
-
140
- strand_input = gr.Dropdown(
141
- choices=["STEM", "ABM", "HUMSS", "GAS", "TVL"],
142
- label="Senior High School Strand",
143
- info="Select your SHS strand (TVL uses hobbies to infer track)"
144
- )
145
-
146
- hobbies_input = gr.Textbox(
147
- label="Hobbies & Interests",
148
- placeholder="e.g., programming, gaming, business, teaching...",
149
- lines=3,
150
- info="Describe your interests and hobbies"
151
- )
152
-
153
- recommend_btn = gr.Button("Get Recommendations", variant="primary", size="lg")
154
 
155
- with gr.Column(scale=3):
156
- gr.Markdown("### 🎯 Your Course Recommendations")
157
- recommendations_output = gr.Markdown(
158
- value="Enter your profile details and click 'Get Recommendations' to see personalized course suggestions.",
159
- label="Recommendations"
160
- )
161
-
162
- gr.Markdown("### πŸ“š Available Courses")
163
- gr.Markdown(
164
- """
165
- **CASTECH**
166
- - BSA: Bachelor of Science in Agriculture
167
- - BSFish: Bachelor of Science in Fisheries
168
- - BSFoodTech: Bachelor of Science in Food Technology
169
-
170
- **CFA**
171
- - BSFo: Bachelor of Science in Forestry
172
- - BSAgFo: Bachelor of Science in Agroforestry
173
-
174
- **CBEE**
175
- - BSHM: Bachelor of Science in Hospitality Management
176
- - BSEntrep: Bachelor of Science in Entrepreneurship
177
- - BSAgribus: Bachelor of Science in Agriculture Business
178
- - BSAgEcon: Bachelor of Science in Agricultural Economics
179
-
180
- **CAS**
181
- - BSBio: Bachelor of Science in Biology
182
- - BSMath: Bachelor of Science in Mathematics
183
- - BAELS: Bachelor of Arts in English Language Studies
184
- - BSDevComm: Bachelor of Science in Development Communication
185
-
186
- **COECS**
187
- - BSABE: Agricultural and Biosystems Engineering
188
- - BSGE: Geodetic Engineering
189
- - BSCE: Civil Engineering
190
- - BSCpE: Computer Engineering
191
- - BSIT: Information Technology
192
-
193
- **COED**
194
- - BTLEd: Technology and Livelihood Education
195
- - BSED: Secondary Education
196
- - BEED: Elementary Education
197
- - BPE: Physical Education
198
-
199
- **CVM**
200
- - DVM: Doctor of Veterinary Medicine
201
- """
202
- )
203
-
204
- # Event handlers
205
- def user(user_message, history):
206
- return "", history + [[user_message, None]]
207
-
208
- def bot(history):
209
- user_message = history[-1][0]
210
- bot_message = chat_interface(user_message, history)
211
- history[-1][1] = bot_message
212
- return history
213
-
214
- def refresh_system_info():
215
- return get_system_info()
216
-
217
- # Connect FAQ Chat events
218
- submit_btn.click(
219
- fn=user,
220
- inputs=[msg, chatbot_interface],
221
- outputs=[msg, chatbot_interface],
222
- queue=False
223
- ).then(
224
- fn=bot,
225
- inputs=chatbot_interface,
226
- outputs=chatbot_interface,
227
- queue=True
228
- )
229
-
230
- msg.submit(
231
- fn=user,
232
- inputs=[msg, chatbot_interface],
233
- outputs=[msg, chatbot_interface],
234
- queue=False
235
- ).then(
236
- fn=bot,
237
- inputs=chatbot_interface,
238
- outputs=chatbot_interface,
239
- queue=True
240
- )
241
-
242
- # Connect Course Recommendation events
243
- recommend_btn.click(
244
- fn=get_course_recommendations,
245
- inputs=[stanine_input, gwa_input, strand_input, hobbies_input],
246
- outputs=recommendations_output
247
- )
248
 
249
- refresh_btn.click(
250
- fn=refresh_system_info,
251
- outputs=system_info
252
- )
253
 
 
254
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  demo.launch(
256
  server_name="0.0.0.0",
257
  server_port=7860,
258
- share=False,
259
- show_error=True,
260
- quiet=False
261
- )
 
1
  import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ from course_recommender import CourseRecommender
5
+ from database_connection import DatabaseConnection
6
+ import os
7
 
8
+ # Initialize the recommender system
9
+ recommender = CourseRecommender()
10
+ db_connection = DatabaseConnection()
11
 
12
+ # Global variables to store current recommendations
13
+ current_recommendations = []
14
+ current_user_input = {}
15
+
16
+ def get_course_recommendations(stanine, gwa, strand, hobbies):
17
+ """Get course recommendations based on user input"""
18
+ global current_recommendations, current_user_input
19
 
20
+ # Validate inputs
21
+ if not stanine or not gwa or not strand or not hobbies:
22
+ return "Please fill in all fields", "", ""
 
 
23
 
24
+ try:
25
+ stanine = int(stanine)
26
+ gwa = float(gwa)
27
+
28
+ if stanine < 1 or stanine > 9:
29
+ return "Stanine must be between 1-9", "", ""
30
+
31
+ if gwa < 75 or gwa > 100:
32
+ return "GWA must be between 75-100", "", ""
33
+
34
+ if strand not in ["STEM", "ABM", "HUMSS", "GAS", "TVL"]:
35
+ return "Strand must be one of: STEM, ABM, HUMSS, GAS, TVL", "", ""
36
+
37
+ # Store current user input
38
+ current_user_input = {
39
+ 'stanine': stanine,
40
+ 'gwa': gwa,
41
+ 'strand': strand,
42
+ 'hobbies': hobbies
43
+ }
44
+
45
+ # Get recommendations
46
+ recommendations = recommender.predict_course(stanine, gwa, strand, hobbies)
47
+ current_recommendations = recommendations
48
+
49
+ # Format recommendations
50
+ result_text = "πŸŽ“ Course Recommendations:\n\n"
51
+ for i, (course, confidence) in enumerate(recommendations, 1):
52
+ confidence_percent = confidence * 100
53
+ result_text += f"{i}. {course} (Confidence: {confidence_percent:.1f}%)\n"
54
+
55
+ # Show top recommendation
56
+ top_course = recommendations[0][0] if recommendations else "No recommendations"
57
+ confidence = recommendations[0][1] * 100 if recommendations else 0
58
+
59
+ return result_text, top_course, f"{confidence:.1f}%"
60
+
61
+ except ValueError as e:
62
+ return f"Invalid input: {str(e)}", "", ""
63
+ except Exception as e:
64
+ return f"Error getting recommendations: {str(e)}", "", ""
65
 
66
+ def rate_recommendation(rating):
67
+ """Rate the current recommendation (like/dislike)"""
68
+ global current_recommendations, current_user_input
69
+
70
+ if not current_recommendations or not current_user_input:
71
+ return "No recommendations to rate. Please get recommendations first."
72
 
 
73
  try:
74
+ # Convert rating to numeric
75
+ rating_value = 1 if rating == "πŸ‘ Like" else 0
76
+
77
+ # Get the top recommendation
78
+ top_course = current_recommendations[0][0]
79
+
80
+ # Add feedback to database
81
+ success = recommender.add_feedback(
82
+ course=top_course,
83
+ stanine=current_user_input['stanine'],
84
+ gwa=current_user_input['gwa'],
85
+ strand=current_user_input['strand'],
86
+ rating=rating_value,
87
+ hobbies=current_user_input['hobbies']
88
+ )
89
+
90
+ if success:
91
+ return f"βœ… Thank you for your feedback! Your rating for '{top_course}' has been recorded."
92
  else:
93
+ return "❌ Failed to record feedback. Please try again."
94
+
95
+ except Exception as e:
96
+ return f"Error recording feedback: {str(e)}"
 
97
 
98
+ def train_model():
99
+ """Train the model with current data"""
100
+ try:
101
+ accuracy = recommender.train_model(use_database=True)
102
+ return f"βœ… Model trained successfully! Accuracy: {accuracy:.3f}"
103
+ except Exception as e:
104
+ return f"❌ Error training model: {str(e)}"
105
 
106
  # Create Gradio interface
107
+ def create_interface():
108
+ with gr.Blocks(title="Course AI Recommender", theme=gr.themes.Soft()) as demo:
109
+ gr.Markdown("""
110
+ # πŸŽ“ Course AI Machine Learning Recommender
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ Get personalized course recommendations based on your academic profile and interests!
113
+ """)
114
 
115
+ with gr.Row():
116
+ with gr.Column(scale=1):
117
+ gr.Markdown("### πŸ“ Your Profile")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
+ stanine_input = gr.Slider(
120
+ minimum=1, maximum=9, step=1, value=5,
121
+ label="Stanine Score (1-9)",
122
+ info="Your stanine score from standardized tests"
123
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
+ gwa_input = gr.Slider(
126
+ minimum=75, maximum=100, step=0.1, value=85,
127
+ label="GWA (75-100)",
128
+ info="Your Grade Weighted Average"
129
+ )
130
+
131
+ strand_input = gr.Dropdown(
132
+ choices=["STEM", "ABM", "HUMSS", "GAS", "TVL"],
133
+ value="STEM",
134
+ label="Academic Strand",
135
+ info="Your current academic strand"
136
+ )
137
+
138
+ hobbies_input = gr.Textbox(
139
+ label="Hobbies & Interests",
140
+ placeholder="e.g., Programming, Reading, Sports, Music",
141
+ info="List your hobbies and interests (comma-separated)"
142
+ )
143
+
144
+ get_recommendations_btn = gr.Button("🎯 Get Recommendations", variant="primary")
145
+
146
+ train_model_btn = gr.Button("πŸ€– Train Model", variant="secondary")
147
+
148
+ with gr.Column(scale=1):
149
+ gr.Markdown("### πŸŽ“ Recommendations")
150
+
151
+ recommendations_output = gr.Textbox(
152
+ label="Course Recommendations",
153
+ lines=8,
154
+ interactive=False
155
+ )
156
+
157
+ top_course_output = gr.Textbox(
158
+ label="Top Recommendation",
159
+ interactive=False
160
+ )
161
+
162
+ confidence_output = gr.Textbox(
163
+ label="Confidence Score",
164
+ interactive=False
165
+ )
166
+
167
+ gr.Markdown("### πŸ‘ Rate Your Recommendation")
168
+
169
+ rating_buttons = gr.Radio(
170
+ choices=["πŸ‘ Like", "πŸ‘Ž Dislike"],
171
+ label="How do you rate this recommendation?",
172
+ interactive=True
173
+ )
174
+
175
+ rate_btn = gr.Button("Submit Rating", variant="secondary")
176
+
177
+ rating_feedback = gr.Textbox(
178
+ label="Rating Feedback",
179
+ interactive=False
180
+ )
181
+
182
+ # Event handlers
183
+ get_recommendations_btn.click(
184
+ fn=get_course_recommendations,
185
+ inputs=[stanine_input, gwa_input, strand_input, hobbies_input],
186
+ outputs=[recommendations_output, top_course_output, confidence_output]
187
+ )
188
+
189
+ rate_btn.click(
190
+ fn=rate_recommendation,
191
+ inputs=[rating_buttons],
192
+ outputs=[rating_feedback]
193
+ )
194
+
195
+ train_model_btn.click(
196
+ fn=train_model,
197
+ outputs=[gr.Textbox(label="Training Status", interactive=False)]
198
+ )
199
+
200
+ # Add some example inputs
201
+ gr.Markdown("""
202
+ ### πŸ’‘ Example Inputs
203
+
204
+ **For STEM students:**
205
+ - Stanine: 7-9, GWA: 85-95, Strand: STEM, Hobbies: Programming, Mathematics, Science
206
+
207
+ **For ABM students:**
208
+ - Stanine: 6-8, GWA: 80-90, Strand: ABM, Hobbies: Business, Leadership, Economics
209
+
210
+ **For HUMSS students:**
211
+ - Stanine: 5-8, GWA: 78-88, Strand: HUMSS, Hobbies: Literature, History, Writing
212
+ """)
 
 
 
 
 
213
 
214
+ return demo
 
 
 
215
 
216
+ # Initialize the interface
217
  if __name__ == "__main__":
218
+ # Try to load existing model
219
+ try:
220
+ recommender.load_model()
221
+ print("βœ… Loaded existing model")
222
+ except:
223
+ print("⚠️ No existing model found. Training with basic data...")
224
+ try:
225
+ recommender.train_model(use_database=False)
226
+ print("βœ… Model trained with basic data")
227
+ except Exception as e:
228
+ print(f"❌ Error training model: {e}")
229
+
230
+ # Create and launch interface
231
+ demo = create_interface()
232
  demo.launch(
233
  server_name="0.0.0.0",
234
  server_port=7860,
235
+ share=True
236
+ )