ChatBot / app.py
Bwrite's picture
Update app.py
0d77067 verified
raw
history blame
28.1 kB
# BOUESTI Virtual Assistant Chatbot
# Bamidele Olumilua University of Education, Science, and Technology, Ikere Ekiti
import nltk
import re
import random
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import warnings
import gradio as gr
warnings.filterwarnings('ignore')
# Download required NLTK data
nltk.download('punkt')
nltk.download('punkt_tab')
nltk.download('wordnet')
nltk.download('stopwords')
nltk.download('omw-1.4')
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
class BOUESTIChatbot:
def __init__(self):
self.lemmatizer = WordNetLemmatizer()
self.stop_words = set(stopwords.words('english'))
self.first_greeting = True
self.user_name = None
self.awaiting_name = False # Flag to indicate if the bot is waiting for a name
# Initialize knowledge base
self.knowledge_base = {
# University Information
'university_info': {
'name': 'Bamidele Olumilua University of Education, Science, and Technology, Ikere Ekiti',
'acronym': 'BOUESTI',
'location': 'Ikere Ekiti, Nigeria',
'contact_email': ['[email protected]', '[email protected]'],
'contact_phone': ['+234-805-797-5157', '+234-814-008-0237', '+234-701-930-3769'],
'website': 'portal.bouesti.edu.ng',
'ranking': 'Listed in World Universities Ranking 2023 (Reporter\'s category)',
'mission': 'To generate, disseminate, advance knowledge, and educate students in science and technology with the aim of bringing this knowledge to finding solutions to the major challenges facing society and the world\'s challenges in the 21st century.',
'vision': 'To be an international University recognized and noted for innovation and self-reliance projecting culturally sound and disciplined researchers and products who are committed to learning for gainful engagement for the proper education of the total man.'
},
# Admission Requirements
'admission_requirements': {
'utme_score': 140,
'olevel_requirements': '5 O\'Level Credit passes including English Language, Mathematics, and 3 other relevant subjects at not more than 2 sittings',
'direct_entry': 'NCE, HND, ND, JUPEB, and IJMB qualifications are acceptable',
'jamb_requirements': 'Must change institution to BOUESTI on JAMB portal and upload WAEC/SSCE results'
},
# Application Process
'application_process': {
'post_utme_steps': [
'Visit portal.bouesti.edu.ng',
'Click on Admissions',
'Click on Apply for Admission',
'Create a new account',
'Supply required details and verify email',
'Login with email and password',
'Select 2024/2025 POST UTME application',
'Enter UTME Registration Number',
'Pay N2,000 application fee',
'Complete application form and attach passport (JPEG format)'
],
'post_utme_fee': 'N2,000',
'predegree_fee': 'N10,000',
'acceptance_fee': 'N50,000'
},
# Fees Structure
'fees': {
'new_students': {
'non_science': {'total': 175550, 'first_semester': 105330, 'second_semester': 70220},
'science': {'total': 200550, 'first_semester': 120330, 'second_semester': 80220},
'technology': {'total': 210550, 'first_semester': 126330, 'second_semester': 84220}
},
'returning_students': {
'non_science': {'total': 145550, 'first_semester': 87330, 'second_semester': 58220},
'science': {'total': 170550, 'first_semester': 102330, 'second_semester': 68220},
'technology': {'total': 180550, 'first_semester': 108330, 'second_semester': 72220}
},
'acceptance_fee': 50000
},
# Academic Programs
'programs': {
'biological_science': ['Science Laboratory Technology', 'Microbiology', 'Plant Science and Biotechnology'],
'health_science': ['Health Information Management', 'Public Health'],
'languages': ['English Education', 'French Education', 'English & Literary Studies'],
'management_science': ['Accounting', 'Business Administration', 'Office and Information Management', 'Procurement Management'],
'performing_arts': ['Theatre Arts', 'Music'],
'liberal_arts': ['French', 'History & International Studies', 'Islamic Studies', 'Linguistics', 'Religious Studies', 'Theology', 'Yoruba'],
'educational_foundations': ['Educational Management'],
'educational_technology': ['Educational Technology', 'Library & Information Science'],
'peace_security': ['Peace and Conflict Studies', 'Criminology and Security Studies', 'Social Work'],
'science_education': ['Mathematics Education', 'Physics Education', 'Biology Education', 'Chemistry Education', 'Integrated Science', 'Agricultural Science Education'],
'health_education': ['Health Education', 'Human Kinetics and Sport Science'],
'social_science_education': ['Social Studies Education', 'Economics Education', 'Geography Education', 'Political Science Education'],
'chemical_science': ['Industrial Chemistry', 'Biochemistry'],
'vocational_education': ['Agricultural Science Education', 'Home Economics Education', 'Industrial Technology Education'],
'business_education': ['Business Education'],
'counselling_psychology': ['Early Childhood Education', 'Guidance and Counselling'],
'mathematical_science': ['Industrial Mathematics', 'Mathematics', 'Statistics'],
'computing': ['Computer Science'],
'physics': ['Physics with Electronics'],
'economics': ['Cooperative and Rural Development', 'Economics'],
'communication': ['Mass Communication'],
'geography': ['Environmental Management', 'Transport & Logistics Management'],
'political_science': ['Political Science'],
'agriculture': ['Agricultural Economics & Extension', 'Animal Science', 'Aquaculture & Fisheries'],
'food_science': ['Food Science and Technology', 'Nutrition & Dietetics'],
'engineering': ['Civil Engineering', 'Electrical and Electronics Engineering', 'Mechanical Engineering'],
'architecture': ['Architecture', 'Estate Management'],
'building_technology': ['Building Technology', 'Quantity Surveying'],
'design_arts': ['Clothing and Textiles', 'Fashion Design', 'Industrial Design'],
'entrepreneurial': ['Entrepreneurial Studies'],
'tourism': ['Hospitality Management & Tourism']
},
# Documents for Screening
'screening_documents': [
'O’Level results (WAEC, NECO, or NABTEB).',
'JAMB UTME result slip.',
'JAMB admission letter',
'Birth certificate or age declaration.',
'Passport photographs.',
'Local Government Identification.',
'Bio-data form',
'School fees payment receipt',
'For Direct Entry, additional documents including A-Level results, HND certificates, or transcripts are required'
]
}
# Create response templates
self.responses = {
'greeting': [
"Hello! Welcome to BOUESTI Virtual Assistant. I'm here to help you with information about Bamidele Olumilua University of Education, Science, and Technology, Ikere Ekiti. How can I assist you today?",
"Hi there! I'm the BOUESTI Virtual Assistant. I can help you with admissions, programs, fees, and general information about our university. What would you like to know?",
"Welcome to BOUESTI! I'm here to help prospective students with information about our university. How can I help you today?"
],
'goodbye': [
"Thank you for using BOUESTI Virtual Assistant! If you have more questions, feel free to contact us at [email protected] or +234-805-797-5157. Good luck with your application!",
"Goodbye! Remember to visit portal.bouesti.edu.ng for applications. We look forward to welcoming you to BOUESTI!",
"Thank you for your interest in BOUESTI! Contact us anytime for more information. Best wishes!"
],
'thanks': [
"You're welcome! Is there anything else you'd like to know about BOUESTI?",
"Glad I could help! Feel free to ask if you have more questions.",
"You're welcome! I'm here to help with any other questions about BOUESTI."
],
'default': [
"I'm not sure about that specific question. Could you please rephrase or ask about admissions, programs, fees, or general university information?",
"I don't have information about that topic. Try asking about BOUESTI's admission requirements, academic programs, or fees.",
"I can help you with questions about BOUESTI admissions, programs, fees, and general information. Could you please ask about one of these topics?"
],
'screening_documents': [
'The Documents Required for Screening are: \n1. O’Level results (WAEC, NECO, or NABTEB).\n2. JAMB UTME result slip.\n3. JAMB admission letter\n4. Birth certificate or age declaration.\n5. Passport photographs.\n6. Local Government Identification.\n7. Bio-data form\n8. School fees payment receipt\n9. For Direct Entry, additional documents including A-Level results, HND certificates, or transcripts are required'
]
}
# Create pattern-response pairs for intent recognition
self.patterns = {
'greeting': [
r'hello|hi|hey|good morning|good afternoon|good evening',
r'start|begin|help'
],
'goodbye': [
r'bye|goodbye|see you|thanks and bye|exit|quit'
],
'thanks': [
r'thank you|thanks|thank|appreciate'
],
'admission_requirements': [
r'admission|requirement|qualify|eligible|utme|score|olevel|waec|ssce|direct entry',
r'how to apply|application requirement|minimum score|cut off|jamb'
],
'application_process': [
r'how to apply|application process|post utme|predegree|apply online',
r'application steps|registration|signup|create account'
],
'fees': [
r'fees|cost|tuition|payment|price|expensive|cheap|money|naira',
r'how much|school fees|acceptance fee|installment'
],
'programs': [
r'program|course|study|department|faculty|degree|major|field',
r'what can i study|available courses|list of programs'
],
'contact': [
r'contact|phone|email|address|location|reach|call',
r'contact information|how to reach|office|support'
],
'university_info': [
r'about|university|bouesti|history|mission|vision|ranking',
r'tell me about|information about|what is bouesti'
],
'admission_status': [
r'admission status|check admission|admitted|admission letter|print letter',
r'am i admitted|admission result|jamb caps'
],
'payment_process': [
r'how to pay|payment process|online payment|remitta|rrr',
r'pay fees|payment method|card payment|acceptance fee payment'
],
'screening_documents': [
r'\bscreening\b.*\bdocuments\b',
r'\bdocuments\b.*\bscreening\b',
r'what.*screening.*document',
r'require.*screening.*document',
r'document.*required.*screening',
r'checklist.*screening',
r'document.*screening',
],
'guide_request': [
r'\bguide me\b',
r'\bhelp guide\b',
r'\bshow.*guide\b'
]
}
self.vectorizer = TfidfVectorizer(tokenizer=self.tokenize, lowercase=True)
self.setup_vectorizer()
def tokenize(self, text):
"""Tokenize and lemmatize text"""
tokens = word_tokenize(text.lower())
return [self.lemmatizer.lemmatize(token) for token in tokens
if token not in string.punctuation and token not in self.stop_words]
def setup_vectorizer(self):
"""Setup TF-IDF vectorizer with knowledge base"""
corpus = []
for category, content in self.knowledge_base.items():
if isinstance(content, dict):
for key, value in content.items():
if isinstance(value, str):
corpus.append(value)
elif isinstance(value, list):
corpus.extend([str(item) for item in value])
elif isinstance(content, list):
corpus.extend([str(item) for item in content])
# Add pattern texts
for intent, patterns in self.patterns.items():
corpus.extend(patterns)
self.vectorizer.fit(corpus)
def detect_intent(self, user_input):
"""Detect user intent based on patterns"""
user_input_lower = user_input.lower()
# Check for user name if the bot is awaiting a name
if self.awaiting_name:
name_match = re.search(r"(?:my name is|i am|it's|this is)?\s*([a-zA-Z]+)", user_input_lower)
if name_match:
self.user_name = name_match.group(1).capitalize()
self.awaiting_name = False # Reset the flag
return 'name_provided'
# If it's just one word and alphabetic, assume it's the name
if user_input_lower.isalpha() and len(user_input_lower.split()) == 1:
self.user_name = user_input_lower.capitalize()
self.awaiting_name = False
return 'name_provided'
for intent, patterns in self.patterns.items():
for pattern in patterns:
if re.search(pattern, user_input_lower):
return intent
return 'unknown'
def get_admission_requirements_response(self):
"""Get admission requirements information"""
req = self.knowledge_base['admission_requirements']
return f"""πŸ“‹ **BOUESTI Admission Requirements:**
🎯 **UTME Score:** Minimum of {req['utme_score']} marks
πŸ“š **O'Level Requirements:** {req['olevel_requirements']}
πŸŽ“ **Direct Entry:** {req['direct_entry']}
πŸ“ **JAMB Requirements:** {req['jamb_requirements']}
**Important:** Ensure your UTME subject combinations are relevant to your chosen course of study."""
def get_application_process_response(self):
"""Get application process information"""
steps = self.knowledge_base['application_process']['post_utme_steps']
fee = self.knowledge_base['application_process']['post_utme_fee']
response = f"""πŸ“ **How to Apply for BOUESTI Post UTME:**
**Application Fee:** {fee}
**Steps:**
"""
for i, step in enumerate(steps, 1):
response += f"{i}. {step}\n"
response += f"""
**Pre-Degree Application Fee:** {self.knowledge_base['application_process']['predegree_fee']}
**Acceptance Fee:** {self.knowledge_base['application_process']['acceptance_fee']}"""
return response
def get_fees_response(self):
"""Get fees information"""
new_fees = self.knowledge_base['fees']['new_students']
returning_fees = self.knowledge_base['fees']['returning_students']
return f"""πŸ’° **BOUESTI Fees Structure (2023/2024 Session):**
**Acceptance Fee:** ₦{self.knowledge_base['fees']['acceptance_fee']:,} (All Programs)
**NEW STUDENTS:**
β€’ Non-Science: ₦{new_fees['non_science']['total']:,} total
β€’ Science: ₦{new_fees['science']['total']:,} total
β€’ Technology: ₦{new_fees['technology']['total']:,} total
**RETURNING STUDENTS (200L-500L):**
β€’ Non-Science: ₦{returning_fees['non_science']['total']:,} total
β€’ Science: ₦{returning_fees['science']['total']:,} total
β€’ Technology: ₦{returning_fees['technology']['total']:,} total
**Payment Options:** 60% first semester, 40% second semester
**Installment payments available**"""
def get_programs_response(self):
"""Get academic programs information"""
response = "πŸŽ“ **BOUESTI Academic Programs:**\n\n"
program_categories = [
('Engineering', 'engineering'),
('Sciences', 'biological_science'),
('Management', 'management_science'),
('Education', 'science_education'),
('Health Sciences', 'health_science'),
('Liberal Arts', 'liberal_arts'),
('Technology', 'computing')
]
for category_name, category_key in program_categories:
if category_key in self.knowledge_base['programs']:
programs = self.knowledge_base['programs'][category_key]
response += f"**{category_name}:**\n"
for program in programs[:3]: # Show first 3 programs
response += f"β€’ B.Sc./B.Tech/B.A. {program}\n"
response += "\n"
response += "πŸ“‹ **Total:** 70+ degree programs across all faculties\n"
response += "For complete list, visit: portal.bouesti.edu.ng"
return response
def get_contact_response(self):
"""Get contact information"""
contact = self.knowledge_base['university_info']
return f"""πŸ“ž **BOUESTI Contact Information:**
πŸ›οΈ **University:** {contact['name']}
🌐 **Website:** {contact['website']}
πŸ“§ **Email:** {', '.join(contact['contact_email'])}
πŸ“± **Phone:** {', '.join(contact['contact_phone'])}
πŸ“ **Location:** {contact['location']}
**Admission Enquiries:**
β€’ +234-814-008-0237
β€’ +234-701-930-3769"""
def get_university_info_response(self):
"""Get general university information"""
info = self.knowledge_base['university_info']
return f"""πŸ›οΈ **About BOUESTI:**
**Full Name:** {info['name']}
**Acronym:** {info['acronym']}
**Location:** {info['location']}
**Ranking:** {info['ranking']}
**Mission:** {info['mission']}
**Vision:** {info['vision']}
**Quick Facts:**
β€’ 70+ degree programs
β€’ Full NUC accreditation for 42 programs
β€’ Modern facilities and equipment
β€’ Experienced faculty"""
def get_admission_status_response(self):
"""Get admission status checking information"""
return """πŸ” **How to Check BOUESTI Admission Status:**
1. Visit portal.bouesti.edu.ng
2. Click on "Check Admission Status"
3. Enter your JAMB Registration Number
4. Select "2024/2025 Session"
5. Choose "DEGREE" as Admission Type
6. Use your JAMB REG as USERNAME
**If Admitted:** You'll be redirected to print your admission letter
**If Not Yet Admitted:** You'll see "NOT YET ADMITTED, ADMISSION IS DONE IN BATCHES"
**Important:** Accept your admission immediately on JAMB CAPS once offered!"""
def get_payment_process_response(self):
"""Get payment process information"""
return """πŸ’³ **BOUESTI Payment Process:**
**For Acceptance Fee:**
1. Visit portal.bouesti.edu.ng
2. Click "Student Login"
3. Username: Your JAMB REG
4. Password: password1
5. Complete bio-data
6. Click "Fees Payment"
7. Select "ACCEPTANCE"
8. Follow payment procedures
**For All Fee Payments:**
1. Login to your dashboard
2. Click "FEES"
3. Select "FEES PAYMENT"
4. Choose payment type (ACCEPTANCE, TUITION, HOSTEL)
5. Generate Remitta (RRR)
6. Complete payment
**Payment Methods:** ATM Card, Online Banking, Bank Transfer"""
def get_screening_documents_response(self):
"""Get required documents for screening"""
documents = self.knowledge_base['screening_documents']
response = 'The Documents Required for Screening are: \n'
for i, doc in enumerate(documents, 1):
response += f"{i}. {doc}\n"
return response
def generate_response(self, user_input):
"""Generate response based on user input"""
intent = self.detect_intent(user_input)
if intent == 'guide_request':
return "🧭 No problem! Please download the [Guide to Using this Chatbot](https://wa.me/2349120744751)."
if self.first_greeting and intent == 'greeting':
self.first_greeting = False
self.awaiting_name = True # Set flag to true after the first greeting
return "Hey friend 😊, I am BOUESTI Chatbot, you can give me a name or simply call me a Chatbot, what is your name?"
if intent == 'name_provided' and self.user_name:
# This intent is handled in detect_intent and sets self.user_name
return f"Nice to have you {self.user_name}, 🀝 do you want to know about admissions, courses, tuition or more at BOUESTI?"
if intent == 'greeting':
return random.choice(self.responses['greeting'])
if intent == 'goodbye':
return random.choice(self.responses['goodbye'])
elif intent == 'thanks':
return random.choice(self.responses['thanks'])
elif intent == 'admission_requirements':
return self.get_admission_requirements_response()
elif intent == 'application_process':
return self.get_application_process_response()
elif intent == 'fees':
return self.get_fees_response()
elif intent == 'programs':
return self.get_programs_response()
elif intent == 'contact':
return self.get_contact_response()
elif intent == 'university_info':
return self.get_university_info_response()
elif intent == 'admission_status':
return self.get_admission_status_response()
elif intent == 'payment_process':
return self.get_payment_process_response()
elif intent == 'screening_documents':
return self.get_screening_documents_response()
else:
return random.choice(self.responses['default'])
def create_gradio_interface(self):
"""Create Gradio interface"""
with gr.Blocks(
title="BOUESTI Virtual Assistant",
theme=gr.themes.Soft(),
css="""
.gradio-container {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.chatbot {
height: 400px;
}
.header-text {
text-align: center;
padding: 20px;
background: #1C842D;
color: white;
border-radius: 10px;
margin-bottom: 20px;
}
.instruction-box {
border: 2px solid #e0e0e0;
padding: 15px;
border-radius: 10px;
margin-bottom: 15px;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
"""
) as interface:
# Header
gr.HTML("""
<div class="header-text">
<h1 style="color: white; font-weight: bold; font-size: 2em;"><span style="font-size: 1.33em;">πŸŽ“</span> I am ChatBot</h1>
<h3 style="color:white; font-size: 1em;">BOUESTI Virtual Assistance at your Service </h3>
<p style="color:white;">Get instant answers about admissions, programs, fees, and more!</p>
</div>
""")
# Chat interface
with gr.Row():
with gr.Column(scale=4):
chatbot = gr.Chatbot(
[],
elem_id="chatbot",
bubble_full_width=False,
height=400,
show_label=False,
elem_classes=["chatbot"]
)
with gr.Row():
msg = gr.Textbox(
placeholder="Ask me about BOUESTI admissions, programs, fees, or any other questions...",
container=False,
scale=7,
show_label=False
)
submit_btn = gr.Button("Send", variant="primary", scale=1)
clear_btn = gr.Button("Clear Chat", variant="secondary", size="sm")
with gr.Column(scale=2):
# Instruction box
gr.HTML("""
<div class="instruction-box">
<h4>πŸ’‘ Quick Help</h4>
<p>Whenever you are stuck, enter the magic word:</p>
<p><strong style="color: red; font-size: 1.1em;">Guide me</strong></p>
</div>
""")
# Quick buttons
gr.HTML("<h4>πŸš€ Quick Actions</h4>")
quick_btns = [
("πŸ“‹ Admission Requirements", "admission requirements"),
("πŸ’° Fees Structure", "fees"),
("πŸŽ“ Programs", "programs"),
("πŸ“ž Contact Info", "contact"),
("πŸ“„ Screening Documents", "screening documents")
]
quick_buttons = []
for btn_text, btn_value in quick_btns:
btn = gr.Button(btn_text, variant="outline", size="sm")
quick_buttons.append((btn, btn_value))
# Event handlers
def respond(message, history):
if not message.strip():
return history, ""
# Generate response
response = self.generate_response(message)
# Add to history
history.append([message, response])
return history, ""
def clear_chat():
return [], ""
def quick_response(quick_msg, history):
return respond(quick_msg, history)
# Button events
submit_btn.click(respond, [msg, chatbot], [chatbot, msg])
msg.submit(respond, [msg, chatbot], [chatbot, msg])
clear_btn.click(clear_chat, [], [chatbot, msg])
# Quick button events
for btn, value in quick_buttons:
btn.click(
lambda x=value: quick_response(x, []),
[],
[chatbot, msg]
)
return interface
# Initialize and launch the chatbot
def main():
chatbot = BOUESTIChatbot()
interface = chatbot.create_gradio_interface()
interface.launch()
if __name__ == "__main__":
main()