Spaces:
Sleeping
Sleeping
File size: 9,008 Bytes
b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef f8ea354 b476fef |
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 229 230 231 232 233 234 235 236 237 238 239 240 241 |
import os
import gradio as gr
import pandas as pd
import numpy as np
from ai_chatbot import AIChatbot
from database_recommender import CourseRecommender
import warnings
import logging
# Suppress warnings
warnings.filterwarnings('ignore')
logging.getLogger('tensorflow').setLevel(logging.ERROR)
# Initialize components
try:
chatbot = AIChatbot()
print("β
Chatbot initialized successfully")
except Exception as e:
print(f"β οΈ Warning: Could not initialize chatbot: {e}")
chatbot = None
try:
recommender = CourseRecommender()
print("β
Recommender initialized successfully")
except Exception as e:
print(f"β οΈ Warning: Could not initialize recommender: {e}")
recommender = None
def chat_with_bot(message, history):
"""Handle chatbot interactions"""
if chatbot is None:
return "Sorry, the chatbot is not available at the moment. Please try again later."
if not message.strip():
return "Please enter a message to start the conversation."
# Get answer from chatbot
answer, confidence = chatbot.find_best_match(message)
# For general conversation, just return the answer
# For FAQ questions, include suggested questions
if confidence > 0.7: # High confidence FAQ match
suggested_questions = chatbot.get_suggested_questions(message)
if suggested_questions:
response = f"{answer}\n\n**Related Questions:**\n"
for i, q in enumerate(suggested_questions, 1):
response += f"{i}. {q}\n"
return response
# For general conversation or low confidence, just return the answer
return answer
def get_course_recommendations(stanine, gwa, strand, hobbies):
"""Get course recommendations"""
if recommender is None:
return "Sorry, the recommendation system is not available at the moment. Please try again later."
try:
# Validate and convert inputs
try:
stanine = int(stanine.strip()) if stanine else 0
except (ValueError, AttributeError):
return "β Stanine score must be a valid number between 1 and 9"
try:
gwa = float(gwa.strip()) if gwa else 0
except (ValueError, AttributeError):
return "β GWA must be a valid number between 75 and 100"
# Validate ranges
if not (1 <= stanine <= 9):
return "β Stanine score must be between 1 and 9"
if not (75 <= gwa <= 100):
return "β GWA must be between 75 and 100"
if not strand:
return "β Please select a strand"
if not hobbies or not hobbies.strip():
return "β Please enter your hobbies/interests"
# Get recommendations
recommendations = recommender.recommend_courses(
stanine=stanine,
gwa=gwa,
strand=strand,
hobbies=hobbies
)
if not recommendations:
return "No recommendations available at the moment."
# Format recommendations
response = f"## π― Course Recommendations for You\n\n"
response += f"**Profile:** Stanine {stanine}, GWA {gwa}, {strand} Strand\n"
response += f"**Interests:** {hobbies}\n\n"
for i, rec in enumerate(recommendations, 1):
response += f"### {i}. {rec['code']} - {rec['name']}\n"
response += f"**Match Score:** {rec.get('rating', rec.get('probability', 0)):.1f}%\n\n"
return response
except Exception as e:
return f"β Error getting recommendations: {str(e)}"
def get_faqs():
"""Get available FAQs"""
if chatbot and chatbot.faqs:
faq_text = "## π Frequently Asked Questions\n\n"
for i, faq in enumerate(chatbot.faqs, 1):
faq_text += f"**{i}. {faq['question']}**\n"
faq_text += f"{faq['answer']}\n\n"
return faq_text
return "No FAQs available at the moment."
def get_available_courses():
"""Get available courses"""
if recommender and recommender.courses:
course_text = "## π Available Courses\n\n"
for code, name in recommender.courses.items():
course_text += f"**{code}** - {name}\n"
return course_text
return "No courses available at the moment."
# Create Gradio interface
with gr.Blocks(title="PSAU AI Chatbot & Course Recommender", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# π€ PSAU AI Chatbot & Course Recommender
Welcome to the Pangasinan State University AI-powered admission assistant!
Get instant answers to your questions and receive personalized course recommendations.
"""
)
with gr.Tabs():
# Chatbot Tab
with gr.Tab("π€ AI Chatbot"):
gr.Markdown("""
**Chat with the PSAU AI Assistant!**
I can help you with:
β’ University admission questions
β’ Course information and guidance
β’ General conversation
β’ Academic support
Just type your message below and I'll respond naturally!
""")
chatbot_interface = gr.ChatInterface(
fn=chat_with_bot,
title="PSAU AI Assistant",
description="Chat with me about university admissions, courses, or just say hello!",
examples=[
"Hello!",
"What are the admission requirements?",
"How are you?",
"What courses are available?",
"Tell me about PSAU",
"What can you help me with?",
"Thank you",
"Goodbye"
],
cache_examples=True
)
# Course Recommender Tab
with gr.Tab("π― Course Recommender"):
gr.Markdown("""
Get personalized course recommendations based on your academic profile and interests!
**Input Guidelines:**
- **Stanine Score**: Enter a number between 1-9 (from your entrance exam)
- **GWA**: Enter your General Weighted Average (75-100)
- **Strand**: Select your senior high school strand
- **Hobbies**: Describe your interests and hobbies in detail
""")
with gr.Row():
with gr.Column():
stanine_input = gr.Textbox(
label="Stanine Score (1-9)",
placeholder="Enter your stanine score (1-9)",
info="Your stanine score from entrance examination",
value="7"
)
gwa_input = gr.Textbox(
label="GWA (75-100)",
placeholder="Enter your GWA (75-100)",
info="Your General Weighted Average",
value="85.0"
)
strand_input = gr.Dropdown(
choices=["STEM", "ABM", "HUMSS"],
value="STEM",
label="High School Strand",
info="Your senior high school strand"
)
hobbies_input = gr.Textbox(
label="Hobbies & Interests",
placeholder="e.g., programming, gaming, business, teaching, healthcare...",
info="Describe your interests and hobbies"
)
recommend_btn = gr.Button("Get Recommendations", variant="primary")
with gr.Column():
recommendations_output = gr.Markdown()
recommend_btn.click(
fn=get_course_recommendations,
inputs=[stanine_input, gwa_input, strand_input, hobbies_input],
outputs=recommendations_output
)
# Information Tab
with gr.Tab("π Information"):
with gr.Row():
with gr.Column():
gr.Markdown("### FAQ Section")
faq_btn = gr.Button("Show FAQs")
faq_output = gr.Markdown()
faq_btn.click(fn=get_faqs, outputs=faq_output)
with gr.Column():
gr.Markdown("### Available Courses")
courses_btn = gr.Button("Show Courses")
courses_output = gr.Markdown()
courses_btn.click(fn=get_available_courses, outputs=courses_output)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True
)
|