Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322import gradio as grimport pandas as pdimport numpy as npfrom course_recommender import CourseRecommenderfrom database_connection import DatabaseConnectionimport os# Initialize the recommender systemrecommender = CourseRecommender()db_connection = DatabaseConnection()# Global variables to store current recommendationscurrent_recommendations = []current_user_input = {}def get_course_recommendations(stanine, gwa, strand, hobbies):"""Get course recommendations based on user input"""global current_recommendations, current_user_input# Validate inputsif not stanine or not gwa or not strand or not hobbies:return "Please fill in all fields", "", "", "", "", ""try:stanine = int(stanine)gwa = float(gwa)if stanine < 1 or stanine > 9:return "Stanine must be between 1-9", "", "", "", "", ""if gwa < 75 or gwa > 100:return "GWA must be between 75-100", "", "", "", "", ""# Normalize strand to uppercase for case-insensitive matchingstrand = strand.upper()if strand not in ["STEM", "ABM", "HUMSS", "GAS", "TVL"]:return "Strand must be one of: STEM, ABM, HUMSS, GAS, TVL", "", "", "", "", ""# Store current user inputcurrent_user_input = {'stanine': stanine,'gwa': gwa,'strand': strand,'hobbies': hobbies}# Get recommendationsrecommendations = recommender.predict_course(stanine, gwa, strand, hobbies)current_recommendations = recommendations# Format top 3 recommendationsif len(recommendations) >= 3:course1 = f"{recommendations[0][0]} (Confidence: {recommendations[0][1]*100:.1f}%)"course2 = f"{recommendations[1][0]} (Confidence: {recommendations[1][1]*100:.1f}%)"course3 = f"{recommendations[2][0]} (Confidence: {recommendations[2][1]*100:.1f}%)"elif len(recommendations) == 2:course1 = f"{recommendations[0][0]} (Confidence: {recommendations[0][1]*100:.1f}%)"course2 = f"{recommendations[1][0]} (Confidence: {recommendations[1][1]*100:.1f}%)"course3 = "No third recommendation available"elif len(recommendations) == 1:course1 = f"{recommendations[0][0]} (Confidence: {recommendations[0][1]*100:.1f}%)"course2 = "No second recommendation available"course3 = "No third recommendation available"else:course1 = "No recommendations available"course2 = ""course3 = ""return course1, course2, course3, None, None, Noneexcept ValueError as e:return f"Invalid input: {str(e)}", "", "", None, None, Noneexcept Exception as e:return f"Error getting recommendations: {str(e)}", "", "", None, None, Nonedef submit_all_ratings(course1_rating, course2_rating, course3_rating):"""Submit ratings for all three recommendations"""global current_recommendations, current_user_inputif not current_recommendations or not current_user_input:return "No recommendations to rate. Please get recommendations first."try:results = []ratings_submitted = 0# Rate first recommendationif course1_rating and len(current_recommendations) >= 1:rating_value = "like" if course1_rating == "๐ Like" else "dislike"course = current_recommendations[0][0]success = recommender.add_feedback_with_learning(course=course,stanine=current_user_input['stanine'],gwa=current_user_input['gwa'],strand=current_user_input['strand'],rating=rating_value,hobbies=current_user_input['hobbies'])if success:results.append(f"โ Rating for '{course}' recorded")ratings_submitted += 1else:results.append(f"โ Failed to record rating for '{course}'")# Rate second recommendationif course2_rating and len(current_recommendations) >= 2:rating_value = "like" if course2_rating == "๐ Like" else "dislike"course = current_recommendations[1][0]success = recommender.add_feedback_with_learning(course=course,stanine=current_user_input['stanine'],gwa=current_user_input['gwa'],strand=current_user_input['strand'],rating=rating_value,hobbies=current_user_input['hobbies'])if success:results.append(f"โ Rating for '{course}' recorded")ratings_submitted += 1else:results.append(f"โ Failed to record rating for '{course}'")# Rate third recommendationif course3_rating and len(current_recommendations) >= 3:rating_value = "like" if course3_rating == "๐ Like" else "dislike"course = current_recommendations[2][0]success = recommender.add_feedback_with_learning(course=course,stanine=current_user_input['stanine'],gwa=current_user_input['gwa'],strand=current_user_input['strand'],rating=rating_value,hobbies=current_user_input['hobbies'])if success:results.append(f"โ Rating for '{course}' recorded")ratings_submitted += 1else:results.append(f"โ Failed to record rating for '{course}'")if ratings_submitted > 0:return f"Thank you! {ratings_submitted} rating(s) submitted successfully.\n\n" + "\n".join(results)else:return "Please select at least one rating before submitting."except Exception as e:return f"Error recording feedback: {str(e)}"def train_model():"""Train the model with current data"""try:accuracy = recommender.train_model(use_database=True)return f"โ Model trained successfully! Accuracy: {accuracy:.3f}"except Exception as e:return f"โ Error training model: {str(e)}"def get_available_courses_info():"""Get information about available courses from database"""try:courses = db_connection.get_available_courses()if courses:return f"๐ Available courses in database: {len(courses)}\n\n" + "\n".join([f"โข {course}" for course in courses[:10]]) + (f"\n... and {len(courses)-10} more" if len(courses) > 10 else "")else:return "๐ No courses found in database. Please check the /courses endpoint."except Exception as e:return f"โ Error fetching courses: {str(e)}"# Create Gradio interfacedef create_interface():with gr.Blocks(title="Course AI Recommender", theme=gr.themes.Soft()) as demo:gr.Markdown("""# ๐ Course AI Machine Learning RecommenderGet personalized course recommendations based on your academic profile and interests!""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### ๐ Your Profile")stanine_input = gr.Textbox(label="Stanine Score (1-9)",placeholder="Enter your stanine score (1-9)",info="Your stanine score from standardized tests")gwa_input = gr.Textbox(label="GWA (75-100)",placeholder="Enter your GWA (75-100)",info="Your Grade Weighted Average")strand_input = gr.Dropdown(choices=["STEM", "ABM", "HUMSS", "GAS", "TVL"],value="STEM",label="Academic Strand",info="Your current academic strand")hobbies_input = gr.Textbox(label="Hobbies & Interests",placeholder="e.g., Programming, Reading, Sports, Music",info="List your hobbies and interests (comma-separated)")get_recommendations_btn = gr.Button("๐ฏ Get Recommendations", variant="primary")train_model_btn = gr.Button("๐ค Train Model", variant="secondary")show_courses_btn = gr.Button("๐ Show Available Courses", variant="secondary")with gr.Column(scale=1):gr.Markdown("### ๐ Top 3 Course Recommendations")# Display top 3 recommendationscourse1_output = gr.Textbox(label="1st Recommendation",interactive=False)course1_rating = gr.Radio(choices=["๐ Like", "๐ Dislike"],label="Rate 1st Recommendation",interactive=True)course2_output = gr.Textbox(label="2nd Recommendation",interactive=False)course2_rating = gr.Radio(choices=["๐ Like", "๐ Dislike"],label="Rate 2nd Recommendation",interactive=True)course3_output = gr.Textbox(label="3rd Recommendation",interactive=False)course3_rating = gr.Radio(choices=["๐ Like", "๐ Dislike"],label="Rate 3rd Recommendation",interactive=True)submit_ratings_btn = gr.Button("Submit All Ratings", variant="primary")rating_feedback = gr.Textbox(label="Rating Feedback",interactive=False)courses_info = gr.Textbox(label="Available Courses",lines=8,interactive=False)# Event handlersget_recommendations_btn.click(fn=get_course_recommendations,inputs=[stanine_input, gwa_input, strand_input, hobbies_input],outputs=[course1_output, course2_output, course3_output, course1_rating, course2_rating, course3_rating])submit_ratings_btn.click(fn=submit_all_ratings,inputs=[course1_rating, course2_rating, course3_rating],outputs=[rating_feedback])train_model_btn.click(fn=train_model,outputs=[gr.Textbox(label="Training Status", interactive=False)])show_courses_btn.click(fn=get_available_courses_info,outputs=[courses_info])# Add some example inputsgr.Markdown("""### ๐ก Example Inputs**For STEM students:**- Stanine: 7-9, GWA: 85-95, Strand: STEM, Hobbies: Programming, Mathematics, Science**For ABM students:**- Stanine: 6-8, GWA: 80-90, Strand: ABM, Hobbies: Business, Leadership, Economics**For HUMSS students:**- Stanine: 5-8, GWA: 78-88, Strand: HUMSS, Hobbies: Literature, History, Writing""")return demo# Initialize the interfaceif __name__ == "__main__":# Try to load existing modeltry:recommender.load_model()print("โ Loaded existing model")except:print("โ ๏ธ No existing model found. Training with basic data...")try:recommender.train_model(use_database=False)print("โ Model trained with basic data")except Exception as e:print(f"โ Error training model: {e}")# Create and launch interfacedemo = create_interface()demo.launch(server_name="0.0.0.0",server_port=7860,share=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import pandas as pdimport numpy as npfrom database_connection import DatabaseConnectiondef create_basic_training_data():"""Create basic training data for the course recommender - DEPRECATED"""print("WARNING: Basic training data is deprecated. Use student feedback data instead.")raise ValueError("Basic training data is no longer used. Please use student feedback data from /student_feedback_counts endpoint.")# Define strandsstrands = ["STEM", "ABM", "HUMSS", "GAS", "TVL"]# Define common hobbieshobbies_list = ["Programming", "Reading", "Sports", "Music", "Art", "Gaming","Photography", "Writing", "Dancing", "Cooking", "Traveling","Mathematics", "Science", "History", "Literature", "Technology"]# Generate synthetic datanp.random.seed(42) # For reproducible resultsn_samples = 1000data = []for _ in range(n_samples):# Generate random but realistic datastanine = np.random.randint(1, 10)gwa = np.random.uniform(75, 100) # GWA between 75-100strand = np.random.choice(strands)course = np.random.choice(courses)hobbies = np.random.choice(hobbies_list, size=np.random.randint(1, 4), replace=False)hobbies_str = ", ".join(hobbies)# Generate rating based on some logicif stanine >= 7 and gwa >= 85:rating = np.random.choice([4, 5], p=[0.3, 0.7])elif stanine >= 5 and gwa >= 80:rating = np.random.choice([3, 4, 5], p=[0.2, 0.5, 0.3])else:rating = np.random.choice([1, 2, 3, 4], p=[0.1, 0.3, 0.4, 0.2])count = np.random.randint(1, 10)data.append({'course': course,'stanine': stanine,'gwa': gwa,'strand': strand,'rating': rating,'hobbies': hobbies_str,'count': count})return pd.DataFrame(data)def save_basic_data():"""Save basic training data to CSV"""df = create_basic_training_data()df.to_csv('basic_training_data.csv', index=False)print(f"Basic training data saved with {len(df)} samples")return dfif __name__ == "__main__":save_basic_data()
app.py+49-307