Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336import pandas as pdimport numpy as npfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.preprocessing import LabelEncoder, StandardScalerimport joblibimport jsonimport osimport requestsclass CourseRecommender:def __init__(self):self.model = Noneself.label_encoders = {}self.scaler = StandardScaler()self.courses = self.get_courses()self.training_data = self.get_training_data()self.train_model()def get_courses(self):"""Get static course data"""return {'BSCS': 'Bachelor of Science in Computer Science','BSIT': 'Bachelor of Science in Information Technology','BSBA': 'Bachelor of Science in Business Administration','BSED': 'Bachelor of Science in Education','BSN': 'Bachelor of Science in Nursing','BSArch': 'Bachelor of Science in Architecture','BSIE': 'Bachelor of Science in Industrial Engineering','BSHM': 'Bachelor of Science in Hospitality Management','BSA': 'Bachelor of Science in Accountancy','BSPsych': 'Bachelor of Science in Psychology','BSAgri': 'Bachelor of Science in Agriculture'}def save_student_data(self, stanine, gwa, strand, course, rating, hobbies=None):"""Save student feedback to in-memory storage (for demonstration purposes)"""try:# In a real implementation, you could save this to a file or external storageprint(f"Student feedback saved: Stanine={stanine}, GWA={gwa}, Strand={strand}, Course={course}, Rating={rating}, Hobbies={hobbies}")return Trueexcept Exception as e:print(f"Error saving student feedback: {e}")return Falsedef get_training_data(self):"""Get static training data for demonstration purposes"""# Sample training data to demonstrate the recommender systemtraining_data = [# STEM students(8, 95, 'STEM', 'BSCS', 5, 'programming, gaming, technology'),(7, 90, 'STEM', 'BSIT', 4, 'computers, software, coding'),(9, 98, 'STEM', 'BSCS', 5, 'programming, algorithms, math'),(6, 85, 'STEM', 'BSIT', 3, 'technology, computers'),(8, 92, 'STEM', 'BSArch', 4, 'design, drawing, creativity'),(7, 88, 'STEM', 'BSIE', 4, 'engineering, problem solving'),# ABM students(8, 90, 'ABM', 'BSBA', 5, 'business, management, leadership'),(7, 85, 'ABM', 'BSA', 4, 'accounting, numbers, finance'),(6, 82, 'ABM', 'BSBA', 3, 'business, marketing'),(9, 95, 'ABM', 'BSA', 5, 'accounting, finance, analysis'),# HUMSS students(8, 88, 'HUMSS', 'BSED', 5, 'teaching, helping, education'),(7, 85, 'HUMSS', 'BSPsych', 4, 'psychology, helping, people'),(6, 80, 'HUMSS', 'BSED', 3, 'teaching, children'),(9, 92, 'HUMSS', 'BSPsych', 5, 'psychology, counseling, people'),# General interests(7, 87, 'STEM', 'BSN', 4, 'helping, healthcare, caring'),(8, 89, 'ABM', 'BSHM', 4, 'hospitality, service, management'),(6, 83, 'HUMSS', 'BSAgri', 3, 'agriculture, environment, nature'),]return pd.DataFrame(training_data, columns=['stanine', 'gwa', 'strand', 'course', 'rating', 'hobbies'])def train_model(self):"""Train the recommendation model using the training data"""try:training_data = self.get_training_data()if training_data.empty:print("No training data available - using default recommendations")return# Prepare features (hobbies required)feature_columns = ['stanine', 'gwa', 'strand', 'hobbies']# Create feature matrixX = training_data[feature_columns].copy()y = training_data['course']# Handle categorical variablescategorical_columns = ['strand', 'hobbies']# Refit encoders every training to incorporate new categoriesfor col in categorical_columns:if col in X.columns:X[col] = X[col].fillna('unknown')self.label_encoders[col] = LabelEncoder()X[col] = self.label_encoders[col].fit_transform(X[col])# Scale numerical featuresnumerical_columns = ['stanine', 'gwa']if not X[numerical_columns].empty:X[numerical_columns] = self.scaler.fit_transform(X[numerical_columns])# Train KNN modelself.model = KNeighborsClassifier(n_neighbors=3, weights='distance')self.model.fit(X, y)print("Model trained successfully (hobbies required and encoded)")except Exception as e:print(f"Error training model: {e}")self.model = Nonedef get_default_recommendations(self, stanine, gwa, strand):"""Provide default recommendations based on basic rules when no training data is available"""courses = self.coursesrecommendations = []# Basic rules for recommendationsif strand == 'STEM':if stanine >= 8 and gwa >= 90:priority_courses = ['BSCS', 'BSIT']else:priority_courses = ['BSIT', 'BSCS']elif strand == 'ABM':priority_courses = ['BSBA']elif strand == 'HUMSS':priority_courses = ['BSED']else:priority_courses = list(courses.keys())# Add courses with default probabilitiesfor i, course in enumerate(priority_courses[:2]): # Only take top 2if course in courses:recommendations.append({'code': course,'name': courses[course],'probability': 1.0 - (i * 0.2) # Decreasing probability for each course})return recommendationsdef recommend_courses(self, stanine, gwa, strand, hobbies=None, top_n=5):"""Recommend courses based on student profile (hobbies required)"""try:if self.model is None:return self.get_default_recommendations(stanine, gwa, strand)# Prepare input featuresinput_data = pd.DataFrame([{'stanine': stanine,'gwa': gwa,'strand': strand,'hobbies': (hobbies or '').strip()}])# Validate hobbiesif not input_data['hobbies'].iloc[0]:raise ValueError('hobbies is required for recommendations')# Encode categorical variablesfor col in ['strand', 'hobbies']:if col in input_data.columns and col in self.label_encoders:value = input_data[col].iloc[0]if value not in self.label_encoders[col].classes_:# Extend encoder classes to include unseen value at inferenceself.label_encoders[col].classes_ = np.append(self.label_encoders[col].classes_, value)input_data[col] = self.label_encoders[col].transform(input_data[col])# Scale numerical featuresnumerical_columns = ['stanine', 'gwa']if not input_data[numerical_columns].empty:input_data[numerical_columns] = self.scaler.transform(input_data[numerical_columns])# Get predictionspredictions = self.model.predict_proba(input_data)courses = self.model.classes_# Get top recommendationstop_indices = np.argsort(predictions[0])[-top_n:][::-1]recommendations = []course_map = self.coursesfor idx in top_indices:code = courses[idx]confidence = predictions[0][idx]recommendations.append({'code': code,'name': course_map.get(code, code),'rating': round(confidence * 100, 1)})return recommendationsexcept Exception as e:print(f"Error recommending courses: {e}")return self.get_default_recommendations(stanine, gwa, strand)def _get_recommendation_reason(self, course, stanine, gwa, strand, hobbies, interests, personality_type, learning_style, career_goals):"""Generate personalized reason for recommendation"""reasons = []# Academic performance reasonsif stanine >= 8:reasons.append("Excellent academic performance")elif stanine >= 6:reasons.append("Good academic foundation")if gwa >= 85:reasons.append("High academic achievement")elif gwa >= 80:reasons.append("Strong academic record")# Strand alignmentif strand == "STEM" and course in ["BSCS", "BSIT", "BSArch", "BSIE", "BSN"]:reasons.append("Perfect match with your STEM background")elif strand == "ABM" and course in ["BSBA", "BSA"]:reasons.append("Excellent alignment with your ABM strand")elif strand == "HUMSS" and course in ["BSED", "BSPsych"]:reasons.append("Great fit with your HUMSS background")# Hobbies and interests alignmentif hobbies and any(hobby in hobbies.lower() for hobby in ["gaming", "programming", "technology", "computers"]):if course in ["BSCS", "BSIT"]:reasons.append("Matches your technology interests")if hobbies and any(hobby in hobbies.lower() for hobby in ["business", "leadership", "management"]):if course in ["BSBA", "BSA"]:reasons.append("Aligns with your business interests")if hobbies and any(hobby in hobbies.lower() for hobby in ["helping", "teaching", "caring"]):if course in ["BSED", "BSN", "BSPsych"]:reasons.append("Perfect for your helping nature")# Personality type alignmentif personality_type == "introvert" and course in ["BSCS", "BSA", "BSArch"]:reasons.append("Suits your introverted personality")elif personality_type == "extrovert" and course in ["BSBA", "BSED", "BSHM"]:reasons.append("Great for your outgoing personality")# Learning style alignmentif learning_style == "hands-on" and course in ["BSIT", "BSHM", "BSAgri"]:reasons.append("Matches your hands-on learning preference")elif learning_style == "visual" and course in ["BSArch", "BSCS"]:reasons.append("Perfect for your visual learning style")# Career goals alignmentif career_goals and any(goal in career_goals.lower() for goal in ["developer", "programmer", "software"]):if course in ["BSCS", "BSIT"]:reasons.append("Direct path to your career goals")if career_goals and any(goal in career_goals.lower() for goal in ["business", "entrepreneur", "manager"]):if course in ["BSBA", "BSA"]:reasons.append("Direct path to your business goals")# Default reason if no specific matchesif not reasons:reasons.append("Good academic and personal fit")return " β’ ".join(reasons[:3]) # Limit to top 3 reasonsdef save_model(self, model_path='course_recommender_model.joblib'):"""Save the trained model"""if self.model is None:raise Exception("No model to save!")model_data = {'model': self.model,'scaler': self.scaler,'label_encoders': self.label_encoders}joblib.dump(model_data, model_path)def load_model(self, model_path='course_recommender_model.joblib'):"""Load a trained model"""model_data = joblib.load(model_path)self.model = model_data['model']self.scaler = model_data['scaler']self.label_encoders = model_data['label_encoders']# ===== UI helper for Hugging Face integration =====def get_course_recommendations_ui(recommender: "CourseRecommender", stanine, gwa, strand, hobbies) -> str:if recommender is None:return "Sorry, the recommendation system is not available at the moment. Please try again later."try:try:stanine = int(stanine.strip()) if isinstance(stanine, str) else int(stanine)except (ValueError, TypeError, AttributeError):return "β Stanine score must be a valid number between 1 and 9"try:gwa = float(gwa.strip()) if isinstance(gwa, str) else float(gwa)except (ValueError, TypeError, AttributeError):return "β GWA must be a valid number between 75 and 100"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 str(hobbies).strip():return "β Please enter your hobbies/interests"recommendations = recommender.recommend_courses(stanine=stanine,gwa=gwa,strand=strand,hobbies=str(hobbies))if not recommendations:return "No recommendations available at the moment."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 responseexcept Exception as e:return f"β Error getting recommendations: {str(e)}"# Example usageif __name__ == "__main__":recommender = CourseRecommender()# Example recommendationrecommendations = recommender.recommend_courses(stanine=8,gwa=95,strand='STEM',hobbies='programming, gaming, technology')print("Recommended courses:", json.dumps(recommendations, indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247import gradio as grfrom chatbot import Chatbotimport json# Initialize chatbotchatbot = Chatbot()def chat_interface(message, history):"""Handle chat interface with Gradio"""if not message.strip():return "Please enter a message."# Get response from chatbotresponse = chatbot.get_response(message)# Format the response for display (removed confidence)if response['status'] == 'success':formatted_response = response['answer']else:formatted_response = response['answer']return formatted_responsedef get_system_info():"""Get system information"""faq_count = chatbot.get_qa_count()database_url = chatbot.database_url# Test database connectiontry:import requestsresponse = requests.get(f"{database_url}/faqs", params={'question': 'test'}, timeout=5)if response.status_code == 200:db_status = "Connected"else:db_status = f"Error ({response.status_code})"except:db_status = "Unavailable"return f"System Status: Active\nFAQ Pairs Loaded: {faq_count}\nDatabase: {db_status}\nCourse Recommender: Ready"def get_course_recommendations(stanine, gwa, strand, hobbies):"""Get course recommendations"""return chatbot.get_course_recommendations(stanine, gwa, strand, hobbies)# Create Gradio interfacewith gr.Blocks(title="AI Chatbot",theme=gr.themes.Soft(),css=""".gradio-container {max-width: 800px !important;margin: auto !important;}.chat-message {padding: 10px;margin: 5px 0;border-radius: 10px;}""") as demo:gr.Markdown("""# π€ AI Student AssistantGet answers to your questions and personalized course recommendations!**Features:**- FAQ Chat: Get instant answers from our knowledge base- Course Recommendations: Get personalized course suggestions based on your profile""")with gr.Tabs():with gr.TabItem("π¬ FAQ Chat"):with gr.Row():with gr.Column(scale=3):chatbot_interface = gr.Chatbot(label="FAQ Chat",height=400,show_label=True,container=True,bubble_full_width=False)with gr.Row():msg = gr.Textbox(placeholder="Type your question here...",show_label=False,scale=4,container=False)submit_btn = gr.Button("Send", variant="primary", scale=1)with gr.Column(scale=1):gr.Markdown("### System Info")system_info = gr.Textbox(value=get_system_info(),label="Status",interactive=False,lines=4)refresh_btn = gr.Button("Refresh Status", variant="secondary")gr.Markdown("### FAQ Instructions")gr.Markdown("""**How to use:**1. Type your question in the text box2. Click Send or press Enter3. Get AI-powered answers from FAQ database**Tips:**- Ask specific questions for better results- Try rephrasing if you don't get a good match""")with gr.TabItem("π― Course Recommendations"):with gr.Row():with gr.Column(scale=2):gr.Markdown("### π Student Profile")stanine_input = gr.Slider(minimum=1,maximum=9,step=1,value=5,label="Stanine Score (1-9)",info="Your stanine score from standardized tests")gwa_input = gr.Slider(minimum=75,maximum=100,step=0.1,value=85,label="GWA (75-100)",info="Your General Weighted Average")strand_input = gr.Dropdown(choices=["STEM", "ABM", "HUMSS"],label="Senior High School Strand",info="Select your SHS strand")hobbies_input = gr.Textbox(label="Hobbies & Interests",placeholder="e.g., programming, gaming, business, teaching...",lines=3,info="Describe your interests and hobbies")recommend_btn = gr.Button("Get Recommendations", variant="primary", size="lg")with gr.Column(scale=3):gr.Markdown("### π― Your Course Recommendations")recommendations_output = gr.Markdown(value="Enter your profile details and click 'Get Recommendations' to see personalized course suggestions.",label="Recommendations")gr.Markdown("### π Available Courses")gr.Markdown("""**STEM Courses:**- BSCS: Bachelor of Science in Computer Science- BSIT: Bachelor of Science in Information Technology- BSArch: Bachelor of Science in Architecture- BSIE: Bachelor of Science in Industrial Engineering- BSN: Bachelor of Science in Nursing**ABM Courses:**- BSBA: Bachelor of Science in Business Administration- BSA: Bachelor of Science in Accountancy**HUMSS Courses:**- BSED: Bachelor of Science in Education- BSPsych: Bachelor of Science in Psychology**Other Courses:**- BSHM: Bachelor of Science in Hospitality Management- BSAgri: Bachelor of Science in Agriculture""")# Event handlersdef user(user_message, history):return "", history + [[user_message, None]]def bot(history):user_message = history[-1][0]bot_message = chat_interface(user_message, history)history[-1][1] = bot_messagereturn historydef refresh_system_info():return get_system_info()# Connect FAQ Chat eventssubmit_btn.click(fn=user,inputs=[msg, chatbot_interface],outputs=[msg, chatbot_interface],queue=False).then(fn=bot,inputs=chatbot_interface,outputs=chatbot_interface,queue=True)msg.submit(fn=user,inputs=[msg, chatbot_interface],outputs=[msg, chatbot_interface],queue=False).then(fn=bot,inputs=chatbot_interface,outputs=chatbot_interface,queue=True)# Connect Course Recommendation eventsrecommend_btn.click(fn=get_course_recommendations,inputs=[stanine_input, gwa_input, strand_input, hobbies_input],outputs=recommendations_output)refresh_btn.click(fn=refresh_system_info,outputs=system_info)if __name__ == "__main__":demo.launch(server_name="0.0.0.0",server_port=7860,share=False,show_error=True,quiet=False)
app.py+235-324