markobinario commited on
Commit
05a9821
Β·
verified Β·
1 Parent(s): fa3716c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -64
app.py CHANGED
@@ -1,64 +1,210 @@
1
- # app.py
2
- import gradio as gr
3
-
4
- def chatbot_response(message, history):
5
- """Process user input and return chatbot response"""
6
- user_input = message.lower()
7
-
8
- if "hello" in user_input:
9
- return "Hello there! How can I help you today?"
10
- elif "bye" in user_input:
11
- return "Goodbye! πŸ‘‹"
12
- else:
13
- return f"You said: {message}. I'm still learning!"
14
-
15
- # Create Gradio interface
16
- with gr.Blocks(title="AI Chatbot", theme=gr.themes.Soft()) as demo:
17
- gr.Markdown("# πŸ€– AI Chatbot")
18
- gr.Markdown("Welcome to my simple AI chatbot! Try saying 'hello' or 'bye'.")
19
-
20
- # Chat interface
21
- chatbot = gr.Chatbot(
22
- label="Chat",
23
- height=400,
24
- show_label=True,
25
- container=True,
26
- bubble_full_width=False
27
- )
28
-
29
- # Text input
30
- msg = gr.Textbox(
31
- label="Your message",
32
- placeholder="Type your message here...",
33
- lines=1,
34
- max_lines=3,
35
- show_label=True
36
- )
37
-
38
- # Submit button
39
- submit_btn = gr.Button("Send", variant="primary")
40
-
41
- # Clear button
42
- clear_btn = gr.Button("Clear", variant="secondary")
43
-
44
- # Event handlers
45
- def user(user_message, history):
46
- return "", history + [[user_message, None]]
47
-
48
- def bot(history):
49
- user_message = history[-1][0]
50
- bot_message = chatbot_response(user_message, history)
51
- history[-1][1] = bot_message
52
- return history
53
-
54
- # Connect the interface
55
- msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
56
- bot, chatbot, chatbot
57
- )
58
- submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(
59
- bot, chatbot, chatbot
60
- )
61
- clear_btn.click(lambda: None, None, chatbot, queue=False)
62
-
63
- if __name__ == "__main__":
64
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import numpy as np
5
+ from ai_chatbot import AIChatbot
6
+ from database_recommender import CourseRecommender
7
+ import warnings
8
+ import logging
9
+
10
+ # Suppress warnings
11
+ warnings.filterwarnings('ignore')
12
+ logging.getLogger('tensorflow').setLevel(logging.ERROR)
13
+
14
+ # Initialize components
15
+ try:
16
+ chatbot = AIChatbot()
17
+ print("βœ… Chatbot initialized successfully")
18
+ except Exception as e:
19
+ print(f"⚠️ Warning: Could not initialize chatbot: {e}")
20
+ chatbot = None
21
+
22
+ try:
23
+ recommender = CourseRecommender()
24
+ print("βœ… Recommender initialized successfully")
25
+ except Exception as e:
26
+ print(f"⚠️ Warning: Could not initialize recommender: {e}")
27
+ recommender = None
28
+
29
+ def chat_with_bot(message, history):
30
+ """Handle chatbot interactions"""
31
+ if chatbot is None:
32
+ return "Sorry, the chatbot is not available at the moment. Please try again later."
33
+
34
+ if not message.strip():
35
+ return "Please enter a question."
36
+
37
+ # Get answer from chatbot
38
+ answer, confidence = chatbot.find_best_match(message)
39
+
40
+ # Get suggested questions
41
+ suggested_questions = chatbot.get_suggested_questions(message)
42
+
43
+ # Format response
44
+ response = f"**Answer:** {answer}\n\n"
45
+ response += f"**Confidence:** {confidence:.2f}\n\n"
46
+
47
+ if suggested_questions:
48
+ response += "**Suggested Questions:**\n"
49
+ for i, q in enumerate(suggested_questions, 1):
50
+ response += f"{i}. {q}\n"
51
+
52
+ return response
53
+
54
+ def get_course_recommendations(stanine, gwa, strand, hobbies):
55
+ """Get course recommendations"""
56
+ if recommender is None:
57
+ return "Sorry, the recommendation system is not available at the moment. Please try again later."
58
+
59
+ try:
60
+ # Validate inputs
61
+ stanine = int(stanine)
62
+ gwa = float(gwa)
63
+
64
+ if not (1 <= stanine <= 9):
65
+ return "❌ Stanine score must be between 1 and 9"
66
+
67
+ if not (75 <= gwa <= 100):
68
+ return "❌ GWA must be between 75 and 100"
69
+
70
+ if not strand:
71
+ return "❌ Please select a strand"
72
+
73
+ if not hobbies.strip():
74
+ return "❌ Please enter your hobbies/interests"
75
+
76
+ # Get recommendations
77
+ recommendations = recommender.recommend_courses(
78
+ stanine=stanine,
79
+ gwa=gwa,
80
+ strand=strand,
81
+ hobbies=hobbies
82
+ )
83
+
84
+ if not recommendations:
85
+ return "No recommendations available at the moment."
86
+
87
+ # Format recommendations
88
+ response = f"## 🎯 Course Recommendations for You\n\n"
89
+ response += f"**Profile:** Stanine {stanine}, GWA {gwa}, {strand} Strand\n"
90
+ response += f"**Interests:** {hobbies}\n\n"
91
+
92
+ for i, rec in enumerate(recommendations, 1):
93
+ response += f"### {i}. {rec['code']} - {rec['name']}\n"
94
+ response += f"**Match Score:** {rec.get('rating', rec.get('probability', 0)):.1f}%\n\n"
95
+
96
+ return response
97
+
98
+ except Exception as e:
99
+ return f"❌ Error getting recommendations: {str(e)}"
100
+
101
+ def get_faqs():
102
+ """Get available FAQs"""
103
+ if chatbot and chatbot.faqs:
104
+ faq_text = "## πŸ“š Frequently Asked Questions\n\n"
105
+ for i, faq in enumerate(chatbot.faqs, 1):
106
+ faq_text += f"**{i}. {faq['question']}**\n"
107
+ faq_text += f"{faq['answer']}\n\n"
108
+ return faq_text
109
+ return "No FAQs available at the moment."
110
+
111
+ def get_available_courses():
112
+ """Get available courses"""
113
+ if recommender and recommender.courses:
114
+ course_text = "## πŸŽ“ Available Courses\n\n"
115
+ for code, name in recommender.courses.items():
116
+ course_text += f"**{code}** - {name}\n"
117
+ return course_text
118
+ return "No courses available at the moment."
119
+
120
+ # Create Gradio interface
121
+ with gr.Blocks(title="PSAU AI Chatbot & Course Recommender", theme=gr.themes.Soft()) as demo:
122
+ gr.Markdown(
123
+ """
124
+ # πŸ€– PSAU AI Chatbot & Course Recommender
125
+
126
+ Welcome to the Pangasinan State University AI-powered admission assistant!
127
+ Get instant answers to your questions and receive personalized course recommendations.
128
+ """
129
+ )
130
+
131
+ with gr.Tabs():
132
+ # Chatbot Tab
133
+ with gr.Tab("πŸ€– AI Chatbot"):
134
+ gr.Markdown("Ask me anything about university admissions, requirements, or general information!")
135
+
136
+ chatbot_interface = gr.ChatInterface(
137
+ fn=chat_with_bot,
138
+ title="PSAU Admission Assistant",
139
+ description="Type your question below and get instant answers!",
140
+ examples=[
141
+ "What are the admission requirements?",
142
+ "When is the application deadline?",
143
+ "How much is the tuition fee?",
144
+ "Do you offer scholarships?",
145
+ "What courses are available?"
146
+ ],
147
+ cache_examples=True
148
+ )
149
+
150
+ # Course Recommender Tab
151
+ with gr.Tab("🎯 Course Recommender"):
152
+ gr.Markdown("Get personalized course recommendations based on your academic profile and interests!")
153
+
154
+ with gr.Row():
155
+ with gr.Column():
156
+ stanine_input = gr.Slider(
157
+ minimum=1, maximum=9, step=1, value=7,
158
+ label="Stanine Score (1-9)",
159
+ info="Your stanine score from entrance examination"
160
+ )
161
+ gwa_input = gr.Slider(
162
+ minimum=75, maximum=100, step=0.1, value=85.0,
163
+ label="GWA (75-100)",
164
+ info="Your General Weighted Average"
165
+ )
166
+ strand_input = gr.Dropdown(
167
+ choices=["STEM", "ABM", "HUMSS"],
168
+ value="STEM",
169
+ label="High School Strand",
170
+ info="Your senior high school strand"
171
+ )
172
+ hobbies_input = gr.Textbox(
173
+ label="Hobbies & Interests",
174
+ placeholder="e.g., programming, gaming, business, teaching, healthcare...",
175
+ info="Describe your interests and hobbies"
176
+ )
177
+
178
+ recommend_btn = gr.Button("Get Recommendations", variant="primary")
179
+
180
+ with gr.Column():
181
+ recommendations_output = gr.Markdown()
182
+
183
+ recommend_btn.click(
184
+ fn=get_course_recommendations,
185
+ inputs=[stanine_input, gwa_input, strand_input, hobbies_input],
186
+ outputs=recommendations_output
187
+ )
188
+
189
+ # Information Tab
190
+ with gr.Tab("πŸ“š Information"):
191
+ with gr.Row():
192
+ with gr.Column():
193
+ gr.Markdown("### FAQ Section")
194
+ faq_btn = gr.Button("Show FAQs")
195
+ faq_output = gr.Markdown()
196
+ faq_btn.click(fn=get_faqs, outputs=faq_output)
197
+
198
+ with gr.Column():
199
+ gr.Markdown("### Available Courses")
200
+ courses_btn = gr.Button("Show Courses")
201
+ courses_output = gr.Markdown()
202
+ courses_btn.click(fn=get_available_courses, outputs=courses_output)
203
+
204
+ if __name__ == "__main__":
205
+ demo.launch(
206
+ server_name="0.0.0.0",
207
+ server_port=7860,
208
+ share=False,
209
+ show_error=True
210
+ )