Spaces:
Sleeping
Sleeping
Update app.py
Browse files1223345678956101112131415161718192021222324252627288929303132333411353613143738391617181920404142434445464748492223242526275051525354315556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261273435363738394041424344454647484912812913052131132545556575813313413513613713863646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169108170171172173174175176177178179180181182110111112113114115116117183184185186119187188189121122190123124125126191192128193194195130196197198133134199200201136202203139140204205206207144208209146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225210211212213214215216217218219220221222223224225226227228229230231232233234235236237238232233234239240import osimport gradio as grfrom chatbot import Chatbotimport jsonimport pandas as pdimport numpy as npfrom ai_chatbot import AIChatbotfrom database_recommender import CourseRecommenderimport warningsimport logging
# Initialize chatbotchatbot = Chatbot()# Suppress warningswarnings.filterwarnings('ignore')logging.getLogger('tensorflow').setLevel(logging.ERROR)
# Initialize componentstry: 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_interface(message, history): """Handle chat interface with Gradio"""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." return "Please enter a message to start the conversation." # Get response from chatbot response = chatbot.get_response(message) # Get answer from chatbot answer, confidence = chatbot.find_best_match(message) # Format the response for display (removed confidence) if response['status'] == 'success': formatted_response = response['answer'] else: formatted_response = response['answer'] # 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 return formatted_response
def get_system_info(): """Get system information""" faq_count = chatbot.get_qa_count() return f"System Status: β
Active\nFAQ Pairs Loaded: {faq_count}\nCourse Recommender: β
Ready" # For general conversation or low confidence, just return the answer return answer
def get_course_recommendations(stanine, gwa, strand, hobbies): """Get course recommendations""" return chatbot.get_course_recommendations(stanine, gwa, strand, hobbies) 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 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: with gr.Blocks(title="PSAU AI Chatbot & Course Recommender", theme=gr.themes.Soft()) as demo: gr.Markdown( """ # π€ AI Student Assistant # π€ PSAU AI Chatbot & Course Recommender Get 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 Welcome to the Pangasinan State University AI-powered admission assistant! Get instant answers to your questions and receive personalized course recommendations. """ ) 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 box 2. Click Send or press Enter 3. Get AI-powered answers from FAQ database **Tips:** - Ask specific questions for better results - Try rephrasing if you don't get a good match """ ) # 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 ) with gr.TabItem("π― Course Recommendations"): # 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(scale=2): gr.Markdown("### π Student Profile") stanine_input = gr.Slider( minimum=1, maximum=9, step=1, value=5, with gr.Column(): stanine_input = gr.Textbox( label="Stanine Score (1-9)", placeholder="Enter your stanine score (1-9)", info="Your stanine score from standardized tests" info="Your stanine score from entrance examination", value="7" ) gwa_input = gr.Slider( gwa_input = gr.Textbox( minimum=75, maximum=100, step=0.1, value=85, label="GWA (75-100)", placeholder="Enter your GWA (75-100)", info="Your General Weighted Average" info="Your General Weighted Average", value="85.0" ) strand_input = gr.Dropdown( choices=["STEM", "ABM", "HUMSS"], value="STEM", label="Senior High School Strand", info="Select your SHS strand" label="High School Strand", info="Your senior high school strand" ) hobbies_input = gr.Textbox( label="Hobbies & Interests", placeholder="e.g., programming, gaming, business, teaching...", lines=3, placeholder="e.g., programming, gaming, business, teaching, healthcare...", info="Describe your interests and hobbies" ) recommend_btn = gr.Button("Get Recommendations", variant="primary", size="lg") recommend_btn = gr.Button("Get Recommendations", variant="primary") 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 handlers def 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_message return history def refresh_system_info(): return get_system_info() # Connect FAQ Chat events submit_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 events recommend_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 ) 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, quiet=False ) show_error=True )app.py+200-194