Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# app.pyimport gradio as grdef chatbot_response(message, history):"""Process user input and return chatbot response"""user_input = message.lower()if "hello" in user_input:return "Hello there! How can I help you today?"elif "bye" in user_input:return "Goodbye! π"else:return f"You said: {message}. I'm still learning!"# Create Gradio interfacewith gr.Blocks(title="AI Chatbot", theme=gr.themes.Soft()) as demo:gr.Markdown("# π€ AI Chatbot")gr.Markdown("Welcome to my simple AI chatbot! Try saying 'hello' or 'bye'.")# Chat interfacechatbot = gr.Chatbot(label="Chat",height=400,show_label=True,container=True,bubble_full_width=False)# Text inputmsg = gr.Textbox(label="Your message",placeholder="Type your message here...",lines=1,max_lines=3,show_label=True)# Submit buttonsubmit_btn = gr.Button("Send", variant="primary")# Clear buttonclear_btn = gr.Button("Clear", variant="secondary")# Event handlersdef user(user_message, history):return "", history + [[user_message, None]]def bot(history):user_message = history[-1][0]bot_message = chatbot_response(user_message, history)history[-1][1] = bot_messagereturn history# Connect the interfacemsg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, chatbot, chatbot)submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, chatbot, chatbot)clear_btn.click(lambda: None, None, chatbot, queue=False)if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210import osimport gradio as grimport pandas as pdimport numpy as npfrom ai_chatbot import AIChatbotfrom database_recommender import CourseRecommenderimport warningsimport logging# 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 = Nonetry:recommender = CourseRecommender()print("β Recommender initialized successfully")except Exception as e:print(f"β οΈ Warning: Could not initialize recommender: {e}")recommender = Nonedef 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 question."# Get answer from chatbotanswer, confidence = chatbot.find_best_match(message)# Get suggested questionssuggested_questions = chatbot.get_suggested_questions(message)# Format responseresponse = f"**Answer:** {answer}\n\n"response += f"**Confidence:** {confidence:.2f}\n\n"if suggested_questions:response += "**Suggested Questions:**\n"for i, q in enumerate(suggested_questions, 1):response += f"{i}. {q}\n"return responsedef 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 inputsstanine = int(stanine)gwa = float(gwa)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.strip():return "β Please enter your hobbies/interests"# Get recommendationsrecommendations = recommender.recommend_courses(stanine=stanine,gwa=gwa,strand=strand,hobbies=hobbies)if not recommendations:return "No recommendations available at the moment."# Format recommendationsresponse = 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)}"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_textreturn "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_textreturn "No courses available at the moment."# Create Gradio interfacewith gr.Blocks(title="PSAU AI Chatbot & Course Recommender", theme=gr.themes.Soft()) as demo:gr.Markdown("""# π€ PSAU AI Chatbot & Course RecommenderWelcome to the Pangasinan State University AI-powered admission assistant!Get instant answers to your questions and receive personalized course recommendations.""")with gr.Tabs():# Chatbot Tabwith gr.Tab("π€ AI Chatbot"):gr.Markdown("Ask me anything about university admissions, requirements, or general information!")chatbot_interface = gr.ChatInterface(fn=chat_with_bot,title="PSAU Admission Assistant",description="Type your question below and get instant answers!",examples=["What are the admission requirements?","When is the application deadline?","How much is the tuition fee?","Do you offer scholarships?","What courses are available?"],cache_examples=True)# Course Recommender Tabwith gr.Tab("π― Course Recommender"):gr.Markdown("Get personalized course recommendations based on your academic profile and interests!")with gr.Row():with gr.Column():stanine_input = gr.Slider(minimum=1, maximum=9, step=1, value=7,label="Stanine Score (1-9)",info="Your stanine score from entrance examination")gwa_input = gr.Slider(minimum=75, maximum=100, step=0.1, value=85.0,label="GWA (75-100)",info="Your General Weighted Average")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 Tabwith 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)
app.py+210-64