Update chatbot.py
Browse files- chatbot.py +14 -8
chatbot.py
CHANGED
@@ -7,6 +7,7 @@ from dotenv import load_dotenv
|
|
7 |
from messages import krishna_blessings, ayush_teasing, keyword_groups
|
8 |
from ayush_messages import ayush_surprises
|
9 |
from sentence_transformers import SentenceTransformer, util
|
|
|
10 |
import numpy as np
|
11 |
|
12 |
# Configure logging
|
@@ -20,8 +21,14 @@ if not HUGGINGFACE_API_TOKEN:
|
|
20 |
logger.error("HUGGINGFACE_API_TOKEN not found in environment variables.")
|
21 |
raise ValueError("HUGGINGFACE_API_TOKEN is required.")
|
22 |
|
23 |
-
#
|
24 |
-
semantic_model =
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
# AI model for fallback responses
|
27 |
AI_MODELS = [
|
@@ -78,13 +85,13 @@ def analyze_sentiment(user_input):
|
|
78 |
if isinstance(result, list) and result:
|
79 |
emotions = result[0]
|
80 |
top_emotion = max(emotions, key=lambda x: x["score"])["label"]
|
81 |
-
return top_emotion
|
82 |
return "neutral"
|
83 |
except Exception as e:
|
84 |
logger.error(f"Error in analyze_sentiment: {str(e)}")
|
85 |
return "neutral"
|
86 |
|
87 |
-
def make_api_request(url, headers, payload, retries=
|
88 |
"""Make API requests with retry logic."""
|
89 |
for attempt in range(retries):
|
90 |
try:
|
@@ -108,14 +115,13 @@ def make_api_request(url, headers, payload, retries=3, delay=5):
|
|
108 |
|
109 |
def get_keyword_match(user_input_lower):
|
110 |
"""Find the best matching keyword group using semantic similarity."""
|
|
|
111 |
user_embedding = semantic_model.encode(user_input_lower, convert_to_tensor=True)
|
112 |
best_score = -1
|
113 |
best_group = None
|
114 |
|
115 |
-
for group
|
116 |
-
|
117 |
-
keyword_embeddings = semantic_model.encode(keyword_texts, convert_to_tensor=True)
|
118 |
-
similarities = util.cos_sim(user_embedding, keyword_embeddings)
|
119 |
max_similarity = similarities.max().item()
|
120 |
if max_similarity > best_score and max_similarity > 0.6:
|
121 |
best_score = max_similarity
|
|
|
7 |
from messages import krishna_blessings, ayush_teasing, keyword_groups
|
8 |
from ayush_messages import ayush_surprises
|
9 |
from sentence_transformers import SentenceTransformer, util
|
10 |
+
import joblib
|
11 |
import numpy as np
|
12 |
|
13 |
# Configure logging
|
|
|
21 |
logger.error("HUGGINGFACE_API_TOKEN not found in environment variables.")
|
22 |
raise ValueError("HUGGINGFACE_API_TOKEN is required.")
|
23 |
|
24 |
+
# Lazy load sentence transformer model and embeddings
|
25 |
+
semantic_model = None
|
26 |
+
keyword_embeddings_cache = joblib.load('embeddings_cache.joblib')
|
27 |
+
|
28 |
+
def init_semantic_model():
|
29 |
+
global semantic_model
|
30 |
+
if semantic_model is None:
|
31 |
+
semantic_model = SentenceTransformer('all-MiniLM-L6-v2')
|
32 |
|
33 |
# AI model for fallback responses
|
34 |
AI_MODELS = [
|
|
|
85 |
if isinstance(result, list) and result:
|
86 |
emotions = result[0]
|
87 |
top_emotion = max(emotions, key=lambda x: x["score"])["label"]
|
88 |
+
return top_emotion
|
89 |
return "neutral"
|
90 |
except Exception as e:
|
91 |
logger.error(f"Error in analyze_sentiment: {str(e)}")
|
92 |
return "neutral"
|
93 |
|
94 |
+
def make_api_request(url, headers, payload, retries=2, delay=3):
|
95 |
"""Make API requests with retry logic."""
|
96 |
for attempt in range(retries):
|
97 |
try:
|
|
|
115 |
|
116 |
def get_keyword_match(user_input_lower):
|
117 |
"""Find the best matching keyword group using semantic similarity."""
|
118 |
+
init_semantic_model()
|
119 |
user_embedding = semantic_model.encode(user_input_lower, convert_to_tensor=True)
|
120 |
best_score = -1
|
121 |
best_group = None
|
122 |
|
123 |
+
for group in keyword_embeddings_cache:
|
124 |
+
similarities = util.cos_sim(user_embedding, keyword_embeddings_cache[group])
|
|
|
|
|
125 |
max_similarity = similarities.max().item()
|
126 |
if max_similarity > best_score and max_similarity > 0.6:
|
127 |
best_score = max_similarity
|