markobinario commited on
Commit
8483ca0
Β·
verified Β·
1 Parent(s): d1aea16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -127
app.py CHANGED
@@ -1,164 +1,234 @@
1
- import os
2
  import gradio as gr
3
- import pandas as pd
4
- import numpy as np
5
- from ai_chatbot import AIChatbot, chat_with_bot_via_gateway, get_faqs_via_gateway
6
- from database_recommender import CourseRecommender, get_course_recommendations_ui
7
- import warnings
8
- import logging
9
- import requests
10
 
11
- # Suppress warnings
12
- warnings.filterwarnings('ignore')
13
- logging.getLogger('tensorflow').setLevel(logging.ERROR)
14
 
15
- # Initialize components
16
- try:
17
- chatbot = AIChatbot()
18
- print("βœ… Chatbot initialized successfully")
19
- except Exception as e:
20
- print(f"⚠️ Warning: Could not initialize chatbot: {e}")
21
- chatbot = None
22
-
23
- try:
24
- recommender = CourseRecommender()
25
- print("βœ… Recommender initialized successfully")
26
- except Exception as e:
27
- print(f"⚠️ Warning: Could not initialize recommender: {e}")
28
- recommender = None
29
-
30
- GATEWAY_BASE_URL = os.environ.get('GATEWAY_BASE_URL', 'https://database-46m3.onrender.com')
31
 
32
- def chat_with_bot(message, history):
33
- """Handle chatbot interactions via gateway-aware helper"""
34
- return chat_with_bot_via_gateway(chatbot, message, history, gateway_base_url=GATEWAY_BASE_URL)
 
35
 
36
  def get_course_recommendations(stanine, gwa, strand, hobbies):
37
- return get_course_recommendations_ui(recommender, stanine, gwa, strand, hobbies)
38
-
39
- def get_faqs():
40
- return get_faqs_via_gateway(gateway_base_url=GATEWAY_BASE_URL)
41
-
42
- def get_available_courses():
43
- """Get available courses"""
44
- if recommender and recommender.courses:
45
- course_text = "## πŸŽ“ Available Courses\n\n"
46
- for code, name in recommender.courses.items():
47
- course_text += f"**{code}** - {name}\n"
48
- return course_text
49
- return "No courses available at the moment."
50
 
51
  # Create Gradio interface
52
- with gr.Blocks(title="PSAU AI Chatbot & Course Recommender", theme=gr.themes.Soft()) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  gr.Markdown(
54
  """
55
- # πŸ€– PSAU AI Chatbot & Course Recommender
56
 
57
- Welcome to the Pangasinan State University AI-powered admission assistant!
58
- Get instant answers to your questions and receive personalized course recommendations.
 
 
 
59
  """
60
  )
61
 
62
  with gr.Tabs():
63
- # Chatbot Tab
64
- with gr.Tab("πŸ€– AI Chatbot"):
65
- gr.Markdown("""
66
- **Chat with the PSAU AI Assistant!**
67
-
68
- I can help you with:
69
- β€’ University admission questions
70
- β€’ Course information and guidance
71
- β€’ General conversation
72
- β€’ Academic support
73
-
74
- Just type your message below and I'll respond naturally!
75
- """)
76
-
77
- chatbot_interface = gr.ChatInterface(
78
- fn=chat_with_bot,
79
- title="PSAU AI Assistant",
80
- description="Chat with me about university admissions, courses, or just say hello!",
81
- examples=[
82
- "Hello!",
83
- "What are the admission requirements?",
84
- "How are you?",
85
- "What courses are available?",
86
- "Tell me about PSAU",
87
- "What can you help me with?",
88
- "Thank you",
89
- "Goodbye"
90
- ],
91
- cache_examples=True
92
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- # Course Recommender Tab
95
- with gr.Tab("🎯 Course Recommender"):
96
- gr.Markdown("""
97
- Get personalized course recommendations based on your academic profile and interests!
98
-
99
- **Input Guidelines:**
100
- - **Stanine Score**: Enter a number between 1-9 (from your entrance exam)
101
- - **GWA**: Enter your General Weighted Average (75-100)
102
- - **Strand**: Select your senior high school strand
103
- - **Hobbies**: Describe your interests and hobbies in detail
104
- """)
105
-
106
  with gr.Row():
107
- with gr.Column():
108
- stanine_input = gr.Textbox(
 
 
 
 
 
 
109
  label="Stanine Score (1-9)",
110
- placeholder="Enter your stanine score (1-9)",
111
- info="Your stanine score from entrance examination",
112
- value="7"
113
  )
114
- gwa_input = gr.Textbox(
 
 
 
 
 
115
  label="GWA (75-100)",
116
- placeholder="Enter your GWA (75-100)",
117
- info="Your General Weighted Average",
118
- value="85.0"
119
  )
 
120
  strand_input = gr.Dropdown(
121
  choices=["STEM", "ABM", "HUMSS"],
122
- value="STEM",
123
- label="High School Strand",
124
- info="Your senior high school strand"
125
  )
 
126
  hobbies_input = gr.Textbox(
127
  label="Hobbies & Interests",
128
- placeholder="e.g., programming, gaming, business, teaching, healthcare...",
 
129
  info="Describe your interests and hobbies"
130
  )
131
 
132
- recommend_btn = gr.Button("Get Recommendations", variant="primary")
133
-
134
- with gr.Column():
135
- recommendations_output = gr.Markdown()
136
-
137
- recommend_btn.click(
138
- fn=get_course_recommendations,
139
- inputs=[stanine_input, gwa_input, strand_input, hobbies_input],
140
- outputs=recommendations_output
141
- )
142
-
143
- # Information Tab
144
- with gr.Tab("πŸ“š Information"):
145
- with gr.Row():
146
- with gr.Column():
147
- gr.Markdown("### FAQ Section")
148
- faq_btn = gr.Button("Show FAQs")
149
- faq_output = gr.Markdown()
150
- faq_btn.click(fn=get_faqs, outputs=faq_output)
151
 
152
- with gr.Column():
153
- gr.Markdown("### Available Courses")
154
- courses_btn = gr.Button("Show Courses")
155
- courses_output = gr.Markdown()
156
- courses_btn.click(fn=get_available_courses, outputs=courses_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  if __name__ == "__main__":
159
  demo.launch(
160
  server_name="0.0.0.0",
161
  server_port=7860,
162
  share=False,
163
- show_error=True
 
164
  )
 
 
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
+ return f"System Status: βœ… Active\nFAQ Pairs Loaded: {faq_count}\nCourse Recommender: βœ… Ready"
28
 
29
  def get_course_recommendations(stanine, gwa, strand, hobbies):
30
+ """Get course recommendations"""
31
+ return chatbot.get_course_recommendations(stanine, gwa, strand, hobbies)
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # Create Gradio interface
34
+ with gr.Blocks(
35
+ title="AI Chatbot",
36
+ theme=gr.themes.Soft(),
37
+ css="""
38
+ .gradio-container {
39
+ max-width: 800px !important;
40
+ margin: auto !important;
41
+ }
42
+ .chat-message {
43
+ padding: 10px;
44
+ margin: 5px 0;
45
+ border-radius: 10px;
46
+ }
47
+ """
48
+ ) as demo:
49
+
50
  gr.Markdown(
51
  """
52
+ # πŸ€– AI Student Assistant
53
 
54
+ Get answers to your questions and personalized course recommendations!
55
+
56
+ **Features:**
57
+ - FAQ Chat: Get instant answers from our knowledge base
58
+ - Course Recommendations: Get personalized course suggestions based on your profile
59
  """
60
  )
61
 
62
  with gr.Tabs():
63
+ with gr.TabItem("πŸ’¬ FAQ Chat"):
64
+ with gr.Row():
65
+ with gr.Column(scale=3):
66
+ chatbot_interface = gr.Chatbot(
67
+ label="FAQ Chat",
68
+ height=400,
69
+ show_label=True,
70
+ container=True,
71
+ bubble_full_width=False
72
+ )
73
+
74
+ with gr.Row():
75
+ msg = gr.Textbox(
76
+ placeholder="Type your question here...",
77
+ show_label=False,
78
+ scale=4,
79
+ container=False
80
+ )
81
+ submit_btn = gr.Button("Send", variant="primary", scale=1)
82
+
83
+ with gr.Column(scale=1):
84
+ gr.Markdown("### System Info")
85
+ system_info = gr.Textbox(
86
+ value=get_system_info(),
87
+ label="Status",
88
+ interactive=False,
89
+ lines=4
90
+ )
91
+
92
+ refresh_btn = gr.Button("Refresh Status", variant="secondary")
93
+
94
+ gr.Markdown("### FAQ Instructions")
95
+ gr.Markdown(
96
+ """
97
+ **How to use:**
98
+ 1. Type your question in the text box
99
+ 2. Click Send or press Enter
100
+ 3. Get AI-powered answers from FAQ database
101
+
102
+ **Tips:**
103
+ - Ask specific questions for better results
104
+ - Try rephrasing if you don't get a good match
105
+ """
106
+ )
107
 
108
+ with gr.TabItem("🎯 Course Recommendations"):
 
 
 
 
 
 
 
 
 
 
 
109
  with gr.Row():
110
+ with gr.Column(scale=2):
111
+ gr.Markdown("### πŸ“ Student Profile")
112
+
113
+ stanine_input = gr.Slider(
114
+ minimum=1,
115
+ maximum=9,
116
+ step=1,
117
+ value=5,
118
  label="Stanine Score (1-9)",
119
+ info="Your stanine score from standardized tests"
 
 
120
  )
121
+
122
+ gwa_input = gr.Slider(
123
+ minimum=75,
124
+ maximum=100,
125
+ step=0.1,
126
+ value=85,
127
  label="GWA (75-100)",
128
+ info="Your General Weighted Average"
 
 
129
  )
130
+
131
  strand_input = gr.Dropdown(
132
  choices=["STEM", "ABM", "HUMSS"],
133
+ label="Senior High School Strand",
134
+ info="Select your SHS strand"
 
135
  )
136
+
137
  hobbies_input = gr.Textbox(
138
  label="Hobbies & Interests",
139
+ placeholder="e.g., programming, gaming, business, teaching...",
140
+ lines=3,
141
  info="Describe your interests and hobbies"
142
  )
143
 
144
+ recommend_btn = gr.Button("Get Recommendations", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
+ with gr.Column(scale=3):
147
+ gr.Markdown("### 🎯 Your Course Recommendations")
148
+ recommendations_output = gr.Markdown(
149
+ value="Enter your profile details and click 'Get Recommendations' to see personalized course suggestions.",
150
+ label="Recommendations"
151
+ )
152
+
153
+ gr.Markdown("### πŸ“š Available Courses")
154
+ gr.Markdown(
155
+ """
156
+ **STEM Courses:**
157
+ - BSCS: Bachelor of Science in Computer Science
158
+ - BSIT: Bachelor of Science in Information Technology
159
+ - BSArch: Bachelor of Science in Architecture
160
+ - BSIE: Bachelor of Science in Industrial Engineering
161
+ - BSN: Bachelor of Science in Nursing
162
+
163
+ **ABM Courses:**
164
+ - BSBA: Bachelor of Science in Business Administration
165
+ - BSA: Bachelor of Science in Accountancy
166
+
167
+ **HUMSS Courses:**
168
+ - BSED: Bachelor of Science in Education
169
+ - BSPsych: Bachelor of Science in Psychology
170
+
171
+ **Other Courses:**
172
+ - BSHM: Bachelor of Science in Hospitality Management
173
+ - BSAgri: Bachelor of Science in Agriculture
174
+ """
175
+ )
176
+
177
+ # Event handlers
178
+ def user(user_message, history):
179
+ return "", history + [[user_message, None]]
180
+
181
+ def bot(history):
182
+ user_message = history[-1][0]
183
+ bot_message = chat_interface(user_message, history)
184
+ history[-1][1] = bot_message
185
+ return history
186
+
187
+ def refresh_system_info():
188
+ return get_system_info()
189
+
190
+ # Connect FAQ Chat events
191
+ submit_btn.click(
192
+ fn=user,
193
+ inputs=[msg, chatbot_interface],
194
+ outputs=[msg, chatbot_interface],
195
+ queue=False
196
+ ).then(
197
+ fn=bot,
198
+ inputs=chatbot_interface,
199
+ outputs=chatbot_interface,
200
+ queue=True
201
+ )
202
+
203
+ msg.submit(
204
+ fn=user,
205
+ inputs=[msg, chatbot_interface],
206
+ outputs=[msg, chatbot_interface],
207
+ queue=False
208
+ ).then(
209
+ fn=bot,
210
+ inputs=chatbot_interface,
211
+ outputs=chatbot_interface,
212
+ queue=True
213
+ )
214
+
215
+ # Connect Course Recommendation events
216
+ recommend_btn.click(
217
+ fn=get_course_recommendations,
218
+ inputs=[stanine_input, gwa_input, strand_input, hobbies_input],
219
+ outputs=recommendations_output
220
+ )
221
+
222
+ refresh_btn.click(
223
+ fn=refresh_system_info,
224
+ outputs=system_info
225
+ )
226
 
227
  if __name__ == "__main__":
228
  demo.launch(
229
  server_name="0.0.0.0",
230
  server_port=7860,
231
  share=False,
232
+ show_error=True,
233
+ quiet=False
234
  )