Update app.py
Browse files
app.py
CHANGED
|
@@ -25,18 +25,51 @@ print("π Loading sentence-transformers...")
|
|
| 25 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 26 |
print("β
Embedding model loaded")
|
| 27 |
|
|
|
|
| 28 |
INTENT_EXAMPLES = {
|
| 29 |
-
"greeting": ["hello", "hi", "salam", "namaste", "hey"],
|
| 30 |
-
"pricing": ["price", "cost", "rate", "kitne ka hai", "charges", "fee"],
|
| 31 |
"complaint": ["sad", "problem", "issue", "complaint", "shikayat", "not working", "late"],
|
| 32 |
-
"order_status": ["order status", "track order", "mera order", "delivery"],
|
| 33 |
"refund": ["refund", "paise wapas", "return", "cancel order"],
|
| 34 |
-
"contact": ["contact number", "phone number", "customer support", "call", "number"],
|
| 35 |
-
"portfolio": ["portfolio", "sample", "example", "kaam dikhao", "gallery"],
|
| 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
|
|
@@ -49,11 +82,12 @@ def classify_intent_sbert(text):
|
|
| 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 |
# ---------- OpenRouter API Setup ----------
|
| 55 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 56 |
-
MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 57 |
|
| 58 |
SYSTEM_PROMPT = """You are "VisionCraft AI" β a professional sales and support assistant for "Elite Visuals", a premium imagery business.
|
| 59 |
|
|
@@ -67,7 +101,7 @@ Services offered:
|
|
| 67 |
|
| 68 |
Tone: Polite, professional, enthusiastic. Use Urdu/Hindi mix if customer does.
|
| 69 |
|
| 70 |
-
**IMPORTANT OUTPUT RULE:** Always answer in bullet points (using dashes or asterisks). Never write long paragraphs.
|
| 71 |
|
| 72 |
Example correct output for "contact number":
|
| 73 |
- π Phone: +92 300 1234567
|
|
@@ -77,15 +111,11 @@ Example correct output for "contact number":
|
|
| 77 |
Example for pricing:
|
| 78 |
- Product photography: PKR 15,000β25,000 per session
|
| 79 |
- Architecture renders: PKR 30,000β50,000 per project
|
| 80 |
-
- Corporate video: PKR 50,000β2,00,000 (depending on length)
|
| 81 |
-
|
| 82 |
-
Guidelines:
|
| 83 |
-
- For complaints: apologize in one line, then bullet points for solution.
|
| 84 |
-
- Never generate random legal/contract text.
|
| 85 |
-
- Keep each bullet point short (max 15 words)."""
|
| 86 |
|
| 87 |
def call_openrouter(prompt):
|
| 88 |
if not OPENROUTER_API_KEY:
|
|
|
|
| 89 |
return None
|
| 90 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 91 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
|
@@ -106,31 +136,32 @@ def call_openrouter(prompt):
|
|
| 106 |
print(f"OpenRouter error: {e}")
|
| 107 |
return None
|
| 108 |
|
| 109 |
-
# ---------- Smart Fallback (
|
| 110 |
-
def fallback_response(
|
| 111 |
-
p = prompt.lower()
|
| 112 |
if intent == "greeting":
|
| 113 |
-
return "- Wa-Alaikum-Assalam! π\n- Main Elite Visuals ka assistant hoon.\n- Main aapki in cheezon mein madad kar sakta hoon:
|
| 114 |
elif intent == "contact":
|
| 115 |
-
return "- π Phone: +92 300 1234567\n- βοΈ Email: hello@elitevisuals.com\n- π Website: www.elitevisuals.com"
|
| 116 |
elif intent == "pricing":
|
| 117 |
-
return "- πΈ Product photography: PKR 15,000β25,000/session\n- ποΈ Architecture renders: PKR 30,000β50,000/project\n- π₯ Corporate video: PKR 50,000β2,00,000\n- π‘ Exact quote ke liye apni requirement bhejein
|
| 118 |
elif intent == "portfolio":
|
| 119 |
-
return "- π· Instagram: @elitevisuals\n- π₯οΈ
|
| 120 |
elif intent == "complaint":
|
| 121 |
-
return "- π Maazrat, issue ke liye.\n- π’ Apna order ID bhejein.\n- π Priority resolve karenge.\n- π Next order par 10% discount
|
| 122 |
elif intent == "order_status":
|
| 123 |
-
return "- π¦ Order status
|
|
|
|
|
|
|
| 124 |
else:
|
| 125 |
-
return "- Main aapki kaise madad kar sakta hoon?\n-
|
| 126 |
|
| 127 |
-
def get_ai_response(
|
| 128 |
-
resp = call_openrouter(
|
| 129 |
if resp and resp.strip() and "error" not in resp.lower():
|
| 130 |
print("β
OpenRouter succeeded")
|
| 131 |
return resp
|
| 132 |
-
print("β οΈ OpenRouter failed, using smart fallback")
|
| 133 |
-
return fallback_response(
|
| 134 |
|
| 135 |
# ---------- Firebase Helpers ----------
|
| 136 |
def save_message(session_id, role, content, intent=None):
|
|
@@ -145,7 +176,7 @@ def save_message(session_id, role, content, intent=None):
|
|
| 145 |
data["intent"] = intent
|
| 146 |
new_msg_ref.set(data)
|
| 147 |
|
| 148 |
-
# ---------- Chat API
|
| 149 |
@app.route('/api/chat', methods=['POST'])
|
| 150 |
def chat():
|
| 151 |
data = request.get_json()
|
|
@@ -155,13 +186,10 @@ def chat():
|
|
| 155 |
return jsonify({"error": "No message"}), 400
|
| 156 |
|
| 157 |
intent = classify_intent_sbert(user_message)
|
| 158 |
-
print(f"π―
|
| 159 |
-
|
| 160 |
-
# System prompt already guides bullet points, so just pass user message
|
| 161 |
-
prompt = user_message
|
| 162 |
|
| 163 |
save_message(session_id, "user", user_message, intent)
|
| 164 |
-
bot_reply = get_ai_response(
|
| 165 |
save_message(session_id, "assistant", bot_reply)
|
| 166 |
|
| 167 |
return jsonify({"reply": bot_reply, "intent": intent})
|
|
|
|
| 25 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 26 |
print("β
Embedding model loaded")
|
| 27 |
|
| 28 |
+
# Intent examples for SBERT
|
| 29 |
INTENT_EXAMPLES = {
|
| 30 |
+
"greeting": ["hello", "hi", "salam", "namaste", "hey", "assalam o alaikum"],
|
| 31 |
+
"pricing": ["price", "cost", "rate", "kitne ka hai", "charges", "fee", "kitna paisa", "quote"],
|
| 32 |
"complaint": ["sad", "problem", "issue", "complaint", "shikayat", "not working", "late"],
|
| 33 |
+
"order_status": ["order status", "track order", "mera order", "delivery", "order ka pata"],
|
| 34 |
"refund": ["refund", "paise wapas", "return", "cancel order"],
|
| 35 |
+
"contact": ["contact number", "phone number", "customer support", "call", "number", "mobile", "whatsapp", "telephone", "raabta"],
|
| 36 |
+
"portfolio": ["portfolio", "sample", "example", "kaam dikhao", "gallery", "previous work"],
|
| 37 |
"general": []
|
| 38 |
}
|
| 39 |
|
| 40 |
+
# Rule-based keyword mapping (HIGHEST PRIORITY)
|
| 41 |
+
KEYWORD_INTENT = {
|
| 42 |
+
"contact number": "contact",
|
| 43 |
+
"phone number": "contact",
|
| 44 |
+
"whatsapp": "contact",
|
| 45 |
+
"call": "contact",
|
| 46 |
+
"raabta": "contact",
|
| 47 |
+
"price": "pricing",
|
| 48 |
+
"cost": "pricing",
|
| 49 |
+
"rate": "pricing",
|
| 50 |
+
"kitne ka": "pricing",
|
| 51 |
+
"order status": "order_status",
|
| 52 |
+
"track order": "order_status",
|
| 53 |
+
"portfolio": "portfolio",
|
| 54 |
+
"sample": "portfolio",
|
| 55 |
+
"gallery": "portfolio",
|
| 56 |
+
"refund": "refund",
|
| 57 |
+
"return": "refund",
|
| 58 |
+
"complaint": "complaint",
|
| 59 |
+
"shikayat": "complaint",
|
| 60 |
+
"salam": "greeting",
|
| 61 |
+
"hello": "greeting"
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
def classify_intent_sbert(text):
|
| 65 |
+
# Step 1: Check keyword rules (fast and accurate)
|
| 66 |
+
text_lower = text.lower()
|
| 67 |
+
for keyword, intent in KEYWORD_INTENT.items():
|
| 68 |
+
if keyword in text_lower:
|
| 69 |
+
print(f"π Keyword match: '{keyword}' -> {intent}")
|
| 70 |
+
return intent
|
| 71 |
+
|
| 72 |
+
# Step 2: Use SBERT for other queries
|
| 73 |
text_emb = embedding_model.encode(text, convert_to_tensor=True)
|
| 74 |
best_intent = "general"
|
| 75 |
best_score = 0.0
|
|
|
|
| 82 |
if max_score > best_score:
|
| 83 |
best_score = max_score
|
| 84 |
best_intent = intent
|
| 85 |
+
print(f"π€ SBERT intent: {best_intent} (score: {best_score:.2f})")
|
| 86 |
return best_intent if best_score >= 0.5 else "general"
|
| 87 |
|
| 88 |
# ---------- OpenRouter API Setup ----------
|
| 89 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 90 |
+
MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 91 |
|
| 92 |
SYSTEM_PROMPT = """You are "VisionCraft AI" β a professional sales and support assistant for "Elite Visuals", a premium imagery business.
|
| 93 |
|
|
|
|
| 101 |
|
| 102 |
Tone: Polite, professional, enthusiastic. Use Urdu/Hindi mix if customer does.
|
| 103 |
|
| 104 |
+
**IMPORTANT OUTPUT RULE:** Always answer in bullet points (using dashes or asterisks). Never write long paragraphs.
|
| 105 |
|
| 106 |
Example correct output for "contact number":
|
| 107 |
- π Phone: +92 300 1234567
|
|
|
|
| 111 |
Example for pricing:
|
| 112 |
- Product photography: PKR 15,000β25,000 per session
|
| 113 |
- Architecture renders: PKR 30,000β50,000 per project
|
| 114 |
+
- Corporate video: PKR 50,000β2,00,000 (depending on length)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
def call_openrouter(prompt):
|
| 117 |
if not OPENROUTER_API_KEY:
|
| 118 |
+
print("β οΈ OPENROUTER_API_KEY missing")
|
| 119 |
return None
|
| 120 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 121 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
|
|
|
| 136 |
print(f"OpenRouter error: {e}")
|
| 137 |
return None
|
| 138 |
|
| 139 |
+
# ---------- Smart Fallback (Intent ke mutabiq jawab) ----------
|
| 140 |
+
def fallback_response(intent):
|
|
|
|
| 141 |
if intent == "greeting":
|
| 142 |
+
return "- Wa-Alaikum-Assalam! π\n- Main Elite Visuals ka assistant hoon.\n- Main aapki in cheezon mein madad kar sakta hoon:\n β’ Product photography\n β’ Architecture renders\n β’ Corporate videos\n β’ Drone cinematography"
|
| 143 |
elif intent == "contact":
|
| 144 |
+
return "- π Phone: +92 300 1234567\n- βοΈ Email: hello@elitevisuals.com\n- π Website: www.elitevisuals.com\n- β° Timings: Mon-Sat, 10am-7pm"
|
| 145 |
elif intent == "pricing":
|
| 146 |
+
return "- πΈ Product photography: PKR 15,000β25,000/session\n- ποΈ Architecture renders: PKR 30,000β50,000/project\n- π₯ Corporate video: PKR 50,000β2,00,000\n- π‘ Exact quote ke liye apni requirement bhejein"
|
| 147 |
elif intent == "portfolio":
|
| 148 |
+
return "- π· Instagram: @elitevisuals\n- π₯οΈ Gallery: www.elitevisuals.com/gallery\n- π Sample PDF: email par bhej sakte hain"
|
| 149 |
elif intent == "complaint":
|
| 150 |
+
return "- π Maazrat, issue ke liye.\n- π’ Apna order ID bhejein.\n- π Priority resolve karenge.\n- π Next order par 10% discount"
|
| 151 |
elif intent == "order_status":
|
| 152 |
+
return "- π¦ Order status ke liye:\n β’ Order ID\n β’ Email address\n- β±οΈ 24 ghante mein update"
|
| 153 |
+
elif intent == "refund":
|
| 154 |
+
return "- π° Refund policy:\n β’ 24 hours cancellation: 100% refund\n β’ After 24 hours: 50% refund\n β’ Work started: no refund"
|
| 155 |
else:
|
| 156 |
+
return "- Main aapki kaise madad kar sakta hoon?\n- Services: product photography, architecture renders, corporate videos, drone cinematography"
|
| 157 |
|
| 158 |
+
def get_ai_response(user_message, intent):
|
| 159 |
+
resp = call_openrouter(user_message)
|
| 160 |
if resp and resp.strip() and "error" not in resp.lower():
|
| 161 |
print("β
OpenRouter succeeded")
|
| 162 |
return resp
|
| 163 |
+
print("β οΈ OpenRouter failed, using smart fallback for intent:", intent)
|
| 164 |
+
return fallback_response(intent)
|
| 165 |
|
| 166 |
# ---------- Firebase Helpers ----------
|
| 167 |
def save_message(session_id, role, content, intent=None):
|
|
|
|
| 176 |
data["intent"] = intent
|
| 177 |
new_msg_ref.set(data)
|
| 178 |
|
| 179 |
+
# ---------- Chat API ----------
|
| 180 |
@app.route('/api/chat', methods=['POST'])
|
| 181 |
def chat():
|
| 182 |
data = request.get_json()
|
|
|
|
| 186 |
return jsonify({"error": "No message"}), 400
|
| 187 |
|
| 188 |
intent = classify_intent_sbert(user_message)
|
| 189 |
+
print(f"π― Final intent: {intent}")
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
save_message(session_id, "user", user_message, intent)
|
| 192 |
+
bot_reply = get_ai_response(user_message, intent)
|
| 193 |
save_message(session_id, "assistant", bot_reply)
|
| 194 |
|
| 195 |
return jsonify({"reply": bot_reply, "intent": intent})
|