Update app.py
Browse files
app.py
CHANGED
|
@@ -5,16 +5,14 @@ import requests
|
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
from datetime import datetime
|
| 8 |
-
import torch
|
| 9 |
-
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
| 10 |
from sentence_transformers import SentenceTransformer, util
|
| 11 |
|
| 12 |
app = Flask(__name__)
|
| 13 |
|
| 14 |
-
# ----------
|
| 15 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 16 |
if not firebase_service_account_json:
|
| 17 |
-
raise ValueError("FIREBASE_SERVICE_ACCOUNT secret set
|
| 18 |
service_account_info = json.loads(firebase_service_account_json)
|
| 19 |
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
|
| 20 |
cred = credentials.Certificate(service_account_info)
|
|
@@ -22,18 +20,19 @@ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
|
| 22 |
ref = db.reference('/')
|
| 23 |
print("โ
Firebase connected")
|
| 24 |
|
| 25 |
-
# ----------
|
| 26 |
-
print("๐ Loading sentence-transformers
|
| 27 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 28 |
print("โ
Embedding model loaded")
|
| 29 |
|
| 30 |
INTENT_EXAMPLES = {
|
| 31 |
-
"greeting": ["hello", "hi", "salam", "namaste", "hey
|
| 32 |
"pricing": ["price", "cost", "rate", "kitne ka hai", "charges", "fee"],
|
| 33 |
"complaint": ["sad", "problem", "issue", "complaint", "shikayat", "not working", "late"],
|
| 34 |
"order_status": ["order status", "track order", "mera order", "delivery"],
|
| 35 |
"refund": ["refund", "paise wapas", "return", "cancel order"],
|
| 36 |
"contact": ["contact number", "phone number", "customer support", "call"],
|
|
|
|
| 37 |
"general": []
|
| 38 |
}
|
| 39 |
|
|
@@ -52,73 +51,84 @@ def classify_intent_sbert(text):
|
|
| 52 |
best_intent = intent
|
| 53 |
return best_intent if best_score >= 0.5 else "general"
|
| 54 |
|
| 55 |
-
# ----------
|
| 56 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 57 |
-
MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
def call_openrouter(prompt):
|
| 60 |
if not OPENROUTER_API_KEY:
|
| 61 |
return None
|
| 62 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 63 |
-
headers = {
|
| 64 |
-
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 65 |
-
"Content-Type": "application/json"
|
| 66 |
-
}
|
| 67 |
payload = {
|
| 68 |
"model": MODEL,
|
| 69 |
-
"messages": [
|
|
|
|
|
|
|
|
|
|
| 70 |
"temperature": 0.7,
|
| 71 |
"max_tokens": 500
|
| 72 |
}
|
| 73 |
try:
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
return
|
| 77 |
except Exception as e:
|
| 78 |
print(f"OpenRouter error: {e}")
|
| 79 |
return None
|
| 80 |
|
| 81 |
-
# ----------
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
outputs = gpt2_model.generate(
|
| 99 |
-
inputs.input_ids,
|
| 100 |
-
max_new_tokens=150,
|
| 101 |
-
temperature=0.7,
|
| 102 |
-
do_sample=True,
|
| 103 |
-
pad_token_id=gpt2_tokenizer.eos_token_id
|
| 104 |
-
)
|
| 105 |
-
response = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 106 |
-
if response.startswith(prompt):
|
| 107 |
-
response = response[len(prompt):].strip()
|
| 108 |
-
return response if response else "GPT-2 generated empty response."
|
| 109 |
-
except Exception as e:
|
| 110 |
-
return f"GPT-2 error: {e}"
|
| 111 |
|
| 112 |
-
def get_ai_response(prompt):
|
| 113 |
-
print("๐ต Trying OpenRouter...")
|
| 114 |
resp = call_openrouter(prompt)
|
| 115 |
-
if resp and resp.strip():
|
| 116 |
print("โ
OpenRouter succeeded")
|
| 117 |
return resp
|
| 118 |
-
print("โ ๏ธ OpenRouter failed,
|
| 119 |
-
return
|
| 120 |
|
| 121 |
-
# ----------
|
| 122 |
def save_message(session_id, role, content, intent=None):
|
| 123 |
messages_ref = ref.child(f"chats/{session_id}/messages")
|
| 124 |
new_msg_ref = messages_ref.push()
|
|
@@ -131,53 +141,32 @@ def save_message(session_id, role, content, intent=None):
|
|
| 131 |
data["intent"] = intent
|
| 132 |
new_msg_ref.set(data)
|
| 133 |
|
| 134 |
-
# ----------
|
| 135 |
@app.route('/api/chat', methods=['POST'])
|
| 136 |
def chat():
|
| 137 |
data = request.get_json()
|
| 138 |
user_message = data.get('message', '')
|
| 139 |
session_id = data.get('session_id', 'default_user')
|
| 140 |
-
|
| 141 |
if not user_message:
|
| 142 |
-
return jsonify({"error": "No message
|
| 143 |
|
| 144 |
-
# Intent classification
|
| 145 |
intent = classify_intent_sbert(user_message)
|
| 146 |
print(f"๐ฏ Intent: {intent}")
|
| 147 |
|
| 148 |
-
#
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
elif intent == "pricing":
|
| 152 |
-
prompt = f"User asked about price: {user_message}. Give helpful pricing information."
|
| 153 |
-
elif intent == "complaint":
|
| 154 |
-
prompt = f"User complained: {user_message}. Respond empathetically and offer solution."
|
| 155 |
-
elif intent == "order_status":
|
| 156 |
-
prompt = f"User asked order status: {user_message}. Provide tracking info or ask for order ID."
|
| 157 |
-
elif intent == "refund":
|
| 158 |
-
prompt = f"User wants refund: {user_message}. Explain refund policy and process."
|
| 159 |
-
elif intent == "contact":
|
| 160 |
-
prompt = f"User asked contact: {user_message}. Provide customer support contact details."
|
| 161 |
-
else:
|
| 162 |
-
prompt = user_message
|
| 163 |
|
| 164 |
-
# Save user message
|
| 165 |
save_message(session_id, "user", user_message, intent)
|
| 166 |
-
|
| 167 |
-
# Get AI response
|
| 168 |
-
bot_reply = get_ai_response(prompt)
|
| 169 |
-
|
| 170 |
-
# Save bot reply
|
| 171 |
save_message(session_id, "assistant", bot_reply)
|
| 172 |
|
| 173 |
return jsonify({"reply": bot_reply, "intent": intent})
|
| 174 |
|
| 175 |
-
# ---------- 7. Serve Frontend HTML ----------
|
| 176 |
@app.route('/')
|
| 177 |
def index():
|
| 178 |
return send_from_directory('.', 'index.html')
|
| 179 |
|
| 180 |
-
# ---------- 8. Run Flask App ----------
|
| 181 |
if __name__ == '__main__':
|
| 182 |
port = int(os.environ.get('PORT', 7860))
|
| 183 |
app.run(host='0.0.0.0', port=port)
|
|
|
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
from datetime import datetime
|
|
|
|
|
|
|
| 8 |
from sentence_transformers import SentenceTransformer, util
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
| 12 |
+
# ---------- Firebase Initialization ----------
|
| 13 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 14 |
if not firebase_service_account_json:
|
| 15 |
+
raise ValueError("FIREBASE_SERVICE_ACCOUNT secret set karo.")
|
| 16 |
service_account_info = json.loads(firebase_service_account_json)
|
| 17 |
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
|
| 18 |
cred = credentials.Certificate(service_account_info)
|
|
|
|
| 20 |
ref = db.reference('/')
|
| 21 |
print("โ
Firebase connected")
|
| 22 |
|
| 23 |
+
# ---------- Sentence-Transformer Model ----------
|
| 24 |
+
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"],
|
| 35 |
+
"portfolio": ["portfolio", "sample", "example", "kaam dikhao", "gallery"],
|
| 36 |
"general": []
|
| 37 |
}
|
| 38 |
|
|
|
|
| 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" # free
|
| 57 |
+
|
| 58 |
+
SYSTEM_PROMPT = """You are "VisionCraft AI" โ a professional sales and support assistant for "Elite Visuals", a premium imagery business.
|
| 59 |
+
|
| 60 |
+
Services offered:
|
| 61 |
+
- High-end product photography (jewelry, cars, luxury goods)
|
| 62 |
+
- Architectural visualization & 3D renders
|
| 63 |
+
- Corporate headshots & branding visuals
|
| 64 |
+
- Drone cinematography & virtual tours
|
| 65 |
+
- AI-enhanced photo editing & retouching
|
| 66 |
+
- 4K/8K video production for commercials
|
| 67 |
+
|
| 68 |
+
Tone: Polite, professional, enthusiastic. Use Urdu/Hindi mix if customer does, but keep technical terms in English.
|
| 69 |
+
|
| 70 |
+
Guidelines:
|
| 71 |
+
- For pricing: give ranges (e.g., product photography PKR 15,000-25,000/session)
|
| 72 |
+
- For contact: +92 300 1234567, email hello@elitevisuals.com, website www.elitevisuals.com
|
| 73 |
+
- For portfolio: "Hamaare Instagram @elitevisuals ya website par samples hain"
|
| 74 |
+
- For complaints: apologize, offer discount on next service
|
| 75 |
+
- Never generate random legal/contract text. Stay focused on imagery.
|
| 76 |
+
- Keep answers concise but helpful.
|
| 77 |
+
|
| 78 |
+
Example:
|
| 79 |
+
Customer: "Contact number?"
|
| 80 |
+
You: "Sir, Elite Visuals ka contact: +92 300 1234567. Kya main aapki service mein madad kar sakta hoon?"
|
| 81 |
+
"""
|
| 82 |
|
| 83 |
def call_openrouter(prompt):
|
| 84 |
if not OPENROUTER_API_KEY:
|
| 85 |
return None
|
| 86 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 87 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
|
|
|
|
|
|
|
|
|
| 88 |
payload = {
|
| 89 |
"model": MODEL,
|
| 90 |
+
"messages": [
|
| 91 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 92 |
+
{"role": "user", "content": prompt}
|
| 93 |
+
],
|
| 94 |
"temperature": 0.7,
|
| 95 |
"max_tokens": 500
|
| 96 |
}
|
| 97 |
try:
|
| 98 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=15)
|
| 99 |
+
resp.raise_for_status()
|
| 100 |
+
return resp.json()["choices"][0]["message"]["content"]
|
| 101 |
except Exception as e:
|
| 102 |
print(f"OpenRouter error: {e}")
|
| 103 |
return None
|
| 104 |
|
| 105 |
+
# ---------- Smart Fallback (No GPT-2 nonsense) ----------
|
| 106 |
+
def fallback_response(prompt, intent):
|
| 107 |
+
p = prompt.lower()
|
| 108 |
+
if intent == "greeting":
|
| 109 |
+
return "Wa-Alaikum-Assalam! Main Elite Visuals ka assistant hoon. Aap photography, 3D rendering ya video production ki baat kar sakte hain."
|
| 110 |
+
elif intent == "contact":
|
| 111 |
+
return "Elite Visuals ka contact: +92 300 1234567, email: hello@elitevisuals.com, website: www.elitevisuals.com"
|
| 112 |
+
elif intent == "pricing":
|
| 113 |
+
return "Pricing: Product photography PKR 15,000-25,000/session, Architecture renders PKR 30,000-50,000/project, Corporate videos PKR 50,000-2,00,000 depending on length. Exact quote ke liye apni requirement bhejein."
|
| 114 |
+
elif intent == "portfolio":
|
| 115 |
+
return "Aap hamaare Instagram @elitevisuals ya website www.elitevisuals.com/gallery par sample dekh sakte hain."
|
| 116 |
+
elif intent == "complaint":
|
| 117 |
+
return "Maazrat, problem ke liye. Kya aap apna order ID bata sakte hain? Hum priority se resolve karenge aur next order par 10% discount denge."
|
| 118 |
+
elif intent == "order_status":
|
| 119 |
+
return "Order status check karne ke liye apna order ID aur email bhejein. Hum 24 ghante mein update karenge."
|
| 120 |
+
else:
|
| 121 |
+
return "Main aapki kaise madad kar sakta hoon? Hum product photography, architecture renders, corporate videos, aur drone cinematography mein specialist hain."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
def get_ai_response(prompt, intent):
|
|
|
|
| 124 |
resp = call_openrouter(prompt)
|
| 125 |
+
if resp and resp.strip() and "error" not in resp.lower():
|
| 126 |
print("โ
OpenRouter succeeded")
|
| 127 |
return resp
|
| 128 |
+
print("โ ๏ธ OpenRouter failed, using smart fallback")
|
| 129 |
+
return fallback_response(prompt, intent)
|
| 130 |
|
| 131 |
+
# ---------- Firebase Helpers ----------
|
| 132 |
def save_message(session_id, role, content, intent=None):
|
| 133 |
messages_ref = ref.child(f"chats/{session_id}/messages")
|
| 134 |
new_msg_ref = messages_ref.push()
|
|
|
|
| 141 |
data["intent"] = intent
|
| 142 |
new_msg_ref.set(data)
|
| 143 |
|
| 144 |
+
# ---------- Chat API Endpoint ----------
|
| 145 |
@app.route('/api/chat', methods=['POST'])
|
| 146 |
def chat():
|
| 147 |
data = request.get_json()
|
| 148 |
user_message = data.get('message', '')
|
| 149 |
session_id = data.get('session_id', 'default_user')
|
|
|
|
| 150 |
if not user_message:
|
| 151 |
+
return jsonify({"error": "No message"}), 400
|
| 152 |
|
|
|
|
| 153 |
intent = classify_intent_sbert(user_message)
|
| 154 |
print(f"๐ฏ Intent: {intent}")
|
| 155 |
|
| 156 |
+
# Use original message or customize based on intent?
|
| 157 |
+
# System prompt already has rules, so just pass user message
|
| 158 |
+
prompt = user_message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
|
|
|
| 160 |
save_message(session_id, "user", user_message, intent)
|
| 161 |
+
bot_reply = get_ai_response(prompt, intent)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
save_message(session_id, "assistant", bot_reply)
|
| 163 |
|
| 164 |
return jsonify({"reply": bot_reply, "intent": intent})
|
| 165 |
|
|
|
|
| 166 |
@app.route('/')
|
| 167 |
def index():
|
| 168 |
return send_from_directory('.', 'index.html')
|
| 169 |
|
|
|
|
| 170 |
if __name__ == '__main__':
|
| 171 |
port = int(os.environ.get('PORT', 7860))
|
| 172 |
app.run(host='0.0.0.0', port=port)
|