Update app.py
Browse files
app.py
CHANGED
|
@@ -25,7 +25,7 @@ print("π Loading sentence-transformers model...")
|
|
| 25 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 26 |
print("β
Embedding model loaded")
|
| 27 |
|
| 28 |
-
# Intent examples
|
| 29 |
INTENT_EXAMPLES = {
|
| 30 |
"greeting": ["hello", "hi", "salam", "namaste", "hey there", "good morning"],
|
| 31 |
"pricing": ["price", "cost", "rate", "kitne ka hai", "charges", "fee"],
|
|
@@ -33,11 +33,10 @@ INTENT_EXAMPLES = {
|
|
| 33 |
"order_status": ["order status", "track order", "mera order", "delivery"],
|
| 34 |
"refund": ["refund", "paise wapas", "return", "cancel order"],
|
| 35 |
"contact": ["contact number", "phone number", "customer support", "call"],
|
| 36 |
-
"general": []
|
| 37 |
}
|
| 38 |
|
| 39 |
def classify_intent_sbert(text):
|
| 40 |
-
"""Sentence-BERT based intent classification"""
|
| 41 |
text_emb = embedding_model.encode(text, convert_to_tensor=True)
|
| 42 |
best_intent = "general"
|
| 43 |
best_score = 0.0
|
|
@@ -45,16 +44,12 @@ def classify_intent_sbert(text):
|
|
| 45 |
if not examples:
|
| 46 |
continue
|
| 47 |
example_embs = embedding_model.encode(examples, convert_to_tensor=True)
|
| 48 |
-
# Cosine similarity between user text and each example
|
| 49 |
scores = util.cos_sim(text_emb, example_embs)[0]
|
| 50 |
max_score = scores.max().item()
|
| 51 |
if max_score > best_score:
|
| 52 |
best_score = max_score
|
| 53 |
best_intent = intent
|
| 54 |
-
|
| 55 |
-
if best_score < 0.5:
|
| 56 |
-
return "general"
|
| 57 |
-
return best_intent
|
| 58 |
|
| 59 |
# ---------- 3. OpenRouter API Setup ----------
|
| 60 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
|
@@ -114,14 +109,13 @@ def call_gpt2(prompt):
|
|
| 114 |
return f"GPT-2 error: {e}"
|
| 115 |
|
| 116 |
def get_ai_response(prompt):
|
| 117 |
-
print(
|
| 118 |
resp = call_openrouter(prompt)
|
| 119 |
if resp and resp.strip():
|
| 120 |
print("β
OpenRouter succeeded")
|
| 121 |
return resp
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
return call_gpt2(prompt)
|
| 125 |
|
| 126 |
# ---------- 5. Firebase Helpers ----------
|
| 127 |
def save_message(session_id, role, content, intent=None):
|
|
@@ -136,13 +130,12 @@ def save_message(session_id, role, content, intent=None):
|
|
| 136 |
data["intent"] = intent
|
| 137 |
new_msg_ref.set(data)
|
| 138 |
|
| 139 |
-
# ---------- 6. Main Chat Function
|
| 140 |
def chat_with_ai(user_message, session_id="default_user"):
|
| 141 |
-
# Step 1: Classify intent using Sentence-BERT
|
| 142 |
intent = classify_intent_sbert(user_message)
|
| 143 |
print(f"π― Detected intent: {intent}")
|
| 144 |
|
| 145 |
-
#
|
| 146 |
if intent == "greeting":
|
| 147 |
prompt = f"User greeted: {user_message}. Respond warmly and friendly."
|
| 148 |
elif intent == "pricing":
|
|
@@ -158,28 +151,15 @@ def chat_with_ai(user_message, session_id="default_user"):
|
|
| 158 |
else:
|
| 159 |
prompt = user_message
|
| 160 |
|
| 161 |
-
# Step 3: Save user message
|
| 162 |
save_message(session_id, "user", user_message, intent)
|
| 163 |
-
|
| 164 |
-
# Step 4: Get AI response (OpenRouter -> GPT-2 fallback)
|
| 165 |
bot_reply = get_ai_response(prompt)
|
| 166 |
-
|
| 167 |
-
# Step 5: Save bot reply
|
| 168 |
save_message(session_id, "assistant", bot_reply)
|
| 169 |
-
|
| 170 |
return bot_reply
|
| 171 |
|
| 172 |
-
# ---------- 7. Gradio
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
gr.Textbox(label="Aap ka message", lines=2, placeholder="Yahan likhein..."),
|
| 177 |
-
gr.Textbox(label="Session ID", value="default_user", visible=False)
|
| 178 |
-
],
|
| 179 |
-
outputs=gr.Textbox(label="Chatbot ka jawab", lines=4),
|
| 180 |
-
title="π€ AI Chatbot: SBERT Intent + OpenRouter + GPT-2 Fallback | Firebase",
|
| 181 |
-
description="Sentence-BERT se intent detection, OpenRouter primary, GPT-2 fallback. Firebase mein chat history save hoti hai.",
|
| 182 |
-
examples=[["Assalam-o-Alaikum!"], ["Mujhe laptop ki price chahiye"], ["Mera order late hai"], ["mera order track karo"]]
|
| 183 |
-
)
|
| 184 |
|
|
|
|
| 185 |
demo.launch()
|
|
|
|
| 25 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 26 |
print("β
Embedding model loaded")
|
| 27 |
|
| 28 |
+
# Intent examples
|
| 29 |
INTENT_EXAMPLES = {
|
| 30 |
"greeting": ["hello", "hi", "salam", "namaste", "hey there", "good morning"],
|
| 31 |
"pricing": ["price", "cost", "rate", "kitne ka hai", "charges", "fee"],
|
|
|
|
| 33 |
"order_status": ["order status", "track order", "mera order", "delivery"],
|
| 34 |
"refund": ["refund", "paise wapas", "return", "cancel order"],
|
| 35 |
"contact": ["contact number", "phone number", "customer support", "call"],
|
| 36 |
+
"general": []
|
| 37 |
}
|
| 38 |
|
| 39 |
def classify_intent_sbert(text):
|
|
|
|
| 40 |
text_emb = embedding_model.encode(text, convert_to_tensor=True)
|
| 41 |
best_intent = "general"
|
| 42 |
best_score = 0.0
|
|
|
|
| 44 |
if not examples:
|
| 45 |
continue
|
| 46 |
example_embs = embedding_model.encode(examples, convert_to_tensor=True)
|
|
|
|
| 47 |
scores = util.cos_sim(text_emb, example_embs)[0]
|
| 48 |
max_score = scores.max().item()
|
| 49 |
if max_score > best_score:
|
| 50 |
best_score = max_score
|
| 51 |
best_intent = intent
|
| 52 |
+
return best_intent if best_score >= 0.5 else "general"
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
# ---------- 3. OpenRouter API Setup ----------
|
| 55 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
|
|
|
| 109 |
return f"GPT-2 error: {e}"
|
| 110 |
|
| 111 |
def get_ai_response(prompt):
|
| 112 |
+
print("π΅ Trying OpenRouter...")
|
| 113 |
resp = call_openrouter(prompt)
|
| 114 |
if resp and resp.strip():
|
| 115 |
print("β
OpenRouter succeeded")
|
| 116 |
return resp
|
| 117 |
+
print("β οΈ OpenRouter failed, falling back to GPT-2")
|
| 118 |
+
return call_gpt2(prompt)
|
|
|
|
| 119 |
|
| 120 |
# ---------- 5. Firebase Helpers ----------
|
| 121 |
def save_message(session_id, role, content, intent=None):
|
|
|
|
| 130 |
data["intent"] = intent
|
| 131 |
new_msg_ref.set(data)
|
| 132 |
|
| 133 |
+
# ---------- 6. Main Chat Function ----------
|
| 134 |
def chat_with_ai(user_message, session_id="default_user"):
|
|
|
|
| 135 |
intent = classify_intent_sbert(user_message)
|
| 136 |
print(f"π― Detected intent: {intent}")
|
| 137 |
|
| 138 |
+
# Customize prompt based on intent
|
| 139 |
if intent == "greeting":
|
| 140 |
prompt = f"User greeted: {user_message}. Respond warmly and friendly."
|
| 141 |
elif intent == "pricing":
|
|
|
|
| 151 |
else:
|
| 152 |
prompt = user_message
|
| 153 |
|
|
|
|
| 154 |
save_message(session_id, "user", user_message, intent)
|
|
|
|
|
|
|
| 155 |
bot_reply = get_ai_response(prompt)
|
|
|
|
|
|
|
| 156 |
save_message(session_id, "assistant", bot_reply)
|
|
|
|
| 157 |
return bot_reply
|
| 158 |
|
| 159 |
+
# ---------- 7. Gradio Blocks with Custom HTML ----------
|
| 160 |
+
# Note: index.html must be in the same directory as app.py
|
| 161 |
+
with gr.Blocks() as demo:
|
| 162 |
+
gr.HTML(open("index.html").read()) # Custom frontend with chat icon
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
+
# ---------- 8. Launch ----------
|
| 165 |
demo.launch()
|