flaskbot / ai_chatbot.py
markobinario's picture
Rename chatbot.py to ai_chatbot.py
1768954 verified
raw
history blame
5.91 kB
from sentence_transformers import SentenceTransformer
import numpy as np
from typing import List, Dict, Tuple
import re
class AIChatbot:
def __init__(self):
# Load the pre-trained model (can use a smaller model for more speed)
self.model = SentenceTransformer('all-MiniLM-L6-v2')
# Warm up the model to avoid first-request slowness
_ = self.model.encode(["Hello, world!"])
self.faq_embeddings = None
self.faqs = None
self.load_faqs()
def load_faqs(self):
"""Disable FAQs entirely; operate as a general-conversation bot."""
self.faqs = []
self.faq_embeddings = None
def save_unanswered_question(self, question):
"""Log unanswered questions to console (can be extended to save to file)"""
print(f"Unanswered question logged: {question}")
# In a real implementation, you could save this to a file or send to an admin
def _tokenize(self, text: str):
if not text:
return []
return [t for t in re.findall(r"[a-z0-9]+", text.lower()) if len(t) > 2]
def _overlap_ratio(self, q_tokens, faq_tokens):
if not q_tokens or not faq_tokens:
return 0.0
q_set = set(q_tokens)
f_set = set(faq_tokens)
inter = len(q_set & f_set)
denom = max(len(q_set), 1)
return inter / denom
def _wh_class(self, text: str) -> str:
if not text:
return ''
s = text.strip().lower()
# simple heuristic classification by leading wh-word
for key in ['who', 'where', 'when', 'what', 'how', 'why', 'which']:
if s.startswith(key + ' ') or s.startswith(key + "?"):
return key
# also check presence if not leading
for key in ['who', 'where', 'when', 'what', 'how', 'why', 'which']:
if f' {key} ' in f' {s} ':
return key
return ''
def find_best_match(self, question: str, threshold: float = 0.7) -> Tuple[str, float]:
print(f"find_best_match called with: {question}") # Debug print
# Always act as a general-conversation bot
return self._generate_general_response(question)
def _generate_general_response(self, question: str) -> Tuple[str, float]:
"""Generate general conversation responses for non-FAQ questions"""
question_lower = question.lower().strip()
# Greeting responses
if any(greeting in question_lower for greeting in ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening']):
return "Hello! I'm the PSAU AI assistant. I'm here to help you with questions about university admissions, courses, and general information about Pangasinan State University. How can I assist you today?", 0.8
# Thank you responses
if any(thanks in question_lower for thanks in ['thank you', 'thanks', 'thank', 'appreciate']):
return "You're very welcome! I'm happy to help. Is there anything else you'd like to know about PSAU or university admissions?", 0.9
# Goodbye responses
if any(goodbye in question_lower for goodbye in ['bye', 'goodbye', 'see you', 'farewell']):
return "Goodbye! It was nice chatting with you. Feel free to come back anytime if you have more questions about PSAU. Good luck with your academic journey!", 0.9
# How are you responses
if any(how in question_lower for how in ['how are you', 'how do you do', 'how is it going']):
return "I'm doing great, thank you for asking! I'm here and ready to help you with any questions about PSAU admissions, courses, or university life. What would you like to know?", 0.8
# What can you do responses
if any(what in question_lower for what in ['what can you do', 'what do you do', 'what are your capabilities']):
return "I can help you with:\n• University admission requirements and procedures\n• Course information and recommendations\n• General questions about PSAU\n• Academic guidance and support\n• Information about campus life\n\nWhat specific information are you looking for?", 0.9
# About PSAU responses
if any(about in question_lower for about in ['about psa', 'about psu', 'about pangasinan state', 'tell me about']):
return "Pangasinan State University (PSAU) is a premier state university in the Philippines offering quality education across various fields. We provide undergraduate and graduate programs in areas like Computer Science, Business, Education, Nursing, and more. We're committed to academic excellence and student success. What would you like to know more about?", 0.8
# Help responses
if any(help in question_lower for help in ['help', 'assist', 'support']):
return "I'm here to help! I can assist you with:\n• Admission requirements and deadlines\n• Course information and recommendations\n• Academic programs and majors\n• Campus facilities and services\n• General university information\n\nJust ask me any question and I'll do my best to help you!", 0.9
# Default general response
return "I understand you're asking about something, but I'm specifically designed to help with PSAU-related questions like admissions, courses, and university information. Could you rephrase your question to be more specific about what you'd like to know about Pangasinan State University? I'm here to help with academic guidance and university-related inquiries!", 0.6
def get_suggested_questions(self, question: str, num_suggestions: int = 3) -> List[str]:
"""No suggestions when FAQs are disabled."""
return []
def add_faq(self, question: str, answer: str) -> bool:
"""No-op when FAQs are disabled."""
return False