Spaces:
Sleeping
Sleeping
Update chatbot.py
Browse files8 unmodified lines9101112131415161718199 unmodified lines2930313233343536373811 unmodified lines5051525354555657585960616263646566676869707172737475767737 unmodified lines1151161171181191208 unmodified linesdef __init__(self):self.qa_pairs = []self.question_embeddings = []self.model = SentenceTransformer('all-MiniLM-L6-v2')self.database_url = "https://database-46m3.onrender.com"self.recommender = CourseRecommender()self.load_qa_data()def load_qa_data(self):"""Load Q&A pairs from the faqs table in the database"""try:9 unmodified lines# If it's a single object, wrap it in a listself.qa_pairs = [data]# Generate embeddings for all questionsquestions = [item.get('question', '') for item in self.qa_pairs]self.question_embeddings = self.model.encode(questions)print(f"Loaded {len(self.qa_pairs)} FAQ pairs from database")else:print(f"Failed to load data from faqs table. Status code: {response.status_code}")self._load_fallback_data()11 unmodified lines{"question": "What is a neural network?", "answer": "A neural network is a computing system inspired by biological neural networks that constitute animal brains. It consists of interconnected nodes (neurons) that process information."}]questions = [item['question'] for item in self.qa_pairs]self.question_embeddings = self.model.encode(questions)print("Loaded fallback Q&A data")def find_best_match(self, user_input, threshold=0.7):"""Find the best matching question using semantic similarity"""if not self.qa_pairs:return None, 0# Encode the user inputuser_embedding = self.model.encode([user_input])# Calculate cosine similarity with all questionssimilarities = cosine_similarity(user_embedding, self.question_embeddings)[0]# Find the best matchbest_match_idx = np.argmax(similarities)best_similarity = similarities[best_match_idx]if best_similarity >= threshold:return self.qa_pairs[best_match_idx], best_similarityelse:return None, best_similaritydef get_response(self, user_input):"""Get response for user input"""37 unmodified linesif not hobbies or not str(hobbies).strip():return "❌ Please enter your hobbies/interests"# Get recommendationsrecommendations = self.recommender.recommend_courses(stanine=stanine,8 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667689 unmodified lines7879808182838485868788899011 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814937 unmodified lines1871881891901911921931941958 unmodified linesdef __init__(self):self.qa_pairs = []self.question_embeddings = []self.model = Noneself.database_url = "https://database-46m3.onrender.com"self.recommender = Noneself.load_model()self.load_recommender()self.load_qa_data()def load_model(self):"""Load the sentence transformer model with error handling"""import timeimport os# List of models to try in order of preferencemodels_to_try = ['all-MiniLM-L6-v2','paraphrase-MiniLM-L6-v2','all-MiniLM-L12-v2']for model_name in models_to_try:try:print(f"Loading sentence transformer model: {model_name}...")# Try with cache directory firstcache_dir = os.path.join(os.getcwd(), 'model_cache')os.makedirs(cache_dir, exist_ok=True)self.model = SentenceTransformer(model_name, cache_folder=cache_dir)print(f"✅ Model {model_name} loaded successfully")returnexcept Exception as e:print(f"❌ Error loading {model_name}: {str(e)}")continue# If all models fail, try without cachetry:print("Trying without cache directory...")self.model = SentenceTransformer('all-MiniLM-L6-v2')print("✅ Model loaded successfully without cache")except Exception as e:print(f"❌ Final attempt failed: {str(e)}")raise Exception("Could not load any sentence transformer model")def load_recommender(self):"""Load the course recommender with error handling"""try:print("Loading course recommender...")self.recommender = CourseRecommender()print("✅ Recommender loaded successfully")except Exception as e:print(f"❌ Error loading recommender: {str(e)}")self.recommender = Nonedef load_qa_data(self):"""Load Q&A pairs from the faqs table in the database"""try:9 unmodified lines# If it's a single object, wrap it in a listself.qa_pairs = [data]# Generate embeddings for all questions if model is availablequestions = [item.get('question', '') for item in self.qa_pairs]if self.model is not None:self.question_embeddings = self.model.encode(questions)print(f"Loaded {len(self.qa_pairs)} FAQ pairs with embeddings from database")else:print(f"Loaded {len(self.qa_pairs)} FAQ pairs from database (using fallback matching)")else:print(f"Failed to load data from faqs table. Status code: {response.status_code}")self._load_fallback_data()11 unmodified lines{"question": "What is a neural network?", "answer": "A neural network is a computing system inspired by biological neural networks that constitute animal brains. It consists of interconnected nodes (neurons) that process information."}]questions = [item['question'] for item in self.qa_pairs]if self.model is not None:self.question_embeddings = self.model.encode(questions)print("Loaded fallback Q&A data with embeddings")else:print("Loaded fallback Q&A data (using fallback matching)")def find_best_match(self, user_input, threshold=0.7):"""Find the best matching question using semantic similarity or fallback text matching"""if not self.qa_pairs:return None, 0if self.model is not None and len(self.question_embeddings) > 0:# Use AI model for semantic matchinguser_embedding = self.model.encode([user_input])similarities = cosine_similarity(user_embedding, self.question_embeddings)[0]best_match_idx = np.argmax(similarities)best_similarity = similarities[best_match_idx]if best_similarity >= threshold:return self.qa_pairs[best_match_idx], best_similarityelse:return None, best_similarityelse:# Fallback to simple text matchinguser_input_lower = user_input.lower()best_match = Nonebest_score = 0for qa_pair in self.qa_pairs:question = qa_pair.get('question', '').lower()# Simple keyword matchingcommon_words = set(user_input_lower.split()) & set(question.split())if common_words:score = len(common_words) / max(len(user_input_lower.split()), len(question.split()))if score > best_score and score >= 0.3: # Lower threshold for fallbackbest_score = scorebest_match = qa_pairif best_match:return best_match, best_scoreelse:return None, 0def get_response(self, user_input):"""Get response for user input"""37 unmodified linesif not hobbies or not str(hobbies).strip():return "❌ Please enter your hobbies/interests"if self.recommender is None:return "❌ Course recommendation system is not available at the moment. Please try again later."# Get recommendationsrecommendations = self.recommender.recommend_courses(stanine=stanine,
chatbot.py+96-21