Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,12 +8,10 @@ from datetime import datetime
|
|
| 8 |
from sentence_transformers import SentenceTransformer, util
|
| 9 |
import uuid
|
| 10 |
import re
|
| 11 |
-
import torch
|
| 12 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 13 |
|
| 14 |
app = Flask(__name__)
|
| 15 |
|
| 16 |
-
# ---------- Firebase
|
| 17 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 18 |
if not firebase_service_account_json:
|
| 19 |
raise ValueError("FIREBASE_SERVICE_ACCOUNT secret set karo.")
|
|
@@ -24,257 +22,194 @@ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
|
| 24 |
ref = db.reference('/')
|
| 25 |
print("β
Firebase connected")
|
| 26 |
|
| 27 |
-
# ---------- Sentence-Transformer
|
| 28 |
print("π Loading sentence-transformers...")
|
| 29 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 30 |
print("β
Embedding model loaded")
|
| 31 |
|
| 32 |
-
# ----------
|
| 33 |
-
print("π Loading local GPT-2 model...")
|
| 34 |
-
try:
|
| 35 |
-
gpt2_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 36 |
-
gpt2_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 37 |
-
gpt2_tokenizer.pad_token = gpt2_tokenizer.eos_token
|
| 38 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 39 |
-
gpt2_model = gpt2_model.to(device)
|
| 40 |
-
print(f"β
GPT-2 loaded on {device}")
|
| 41 |
-
except Exception as e:
|
| 42 |
-
print(f"β οΈ GPT-2 load failed: {e}")
|
| 43 |
-
gpt2_model = None
|
| 44 |
-
gpt2_tokenizer = None
|
| 45 |
-
|
| 46 |
-
# ---------- Detailed Service Packages ----------
|
| 47 |
SERVICE_PACKAGES = {
|
| 48 |
-
"basic
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
"price": "PKR 1,20,000",
|
| 55 |
-
"timeline": "15-20 working days",
|
| 56 |
-
"includes": ["10 pages", "CMS (WordPress or custom)", "Advanced SEO", "Blog integration", "Chatbot integration", "Performance optimization", "1 month free support"]
|
| 57 |
-
},
|
| 58 |
-
"premium website": {
|
| 59 |
-
"price": "PKR 2,50,000",
|
| 60 |
-
"timeline": "25-30 working days",
|
| 61 |
-
"includes": ["Unlimited pages", "E-commerce functionality", "Payment gateway", "User accounts", "Custom animations", "Database design", "Advanced security", "6 months free support", "Training session"]
|
| 62 |
-
}
|
| 63 |
}
|
| 64 |
|
| 65 |
EXTRA_FEATURES = {
|
| 66 |
-
"additional language": {"price": "+ PKR 15,000", "timeline": "+ 2 days"},
|
| 67 |
-
"multi-vendor": {"price": "+ PKR 80,000", "timeline": "+ 10 days"},
|
| 68 |
"live chat": {"price": "+ PKR 20,000", "timeline": "+ 3 days"},
|
| 69 |
"booking system": {"price": "+ PKR 35,000", "timeline": "+ 5 days"},
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
}
|
| 73 |
|
| 74 |
-
ALL_SERVICES =
|
| 75 |
-
"website design & development": "Custom website from scratch, responsive, modern design.",
|
| 76 |
-
"e-commerce setup": "Online store with product catalog, cart, checkout, payment integration.",
|
| 77 |
-
"SEO optimization": "On-page, off-page, technical SEO to rank higher on Google.",
|
| 78 |
-
"chatbot integration": "AI chatbot for customer support (like this one).",
|
| 79 |
-
"maintenance & support": "Regular updates, backups, security, 24/7 monitoring.",
|
| 80 |
-
"content writing": "Professional copywriting for web pages, blogs, product descriptions.",
|
| 81 |
-
"graphic design": "Logos, banners, social media graphics, brochures.",
|
| 82 |
-
"digital marketing": "Social media management, Google Ads, email campaigns.",
|
| 83 |
-
"custom web application": "Tailored web apps with database, user authentication, dashboards."
|
| 84 |
-
}
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
service_name_lower = service_name.lower()
|
| 89 |
-
for key in ALL_SERVICES:
|
| 90 |
-
if key in service_name_lower:
|
| 91 |
-
return f"- β
**{key.title()}**: {ALL_SERVICES[key]}\n- π° Pricing: depends on complexity β starting from PKR 30,000\n- β±οΈ Timeline: 5-20 working days"
|
| 92 |
-
return None
|
| 93 |
-
|
| 94 |
-
def handle_package_inquiry(package):
|
| 95 |
-
for pkg, details in SERVICE_PACKAGES.items():
|
| 96 |
-
if pkg in package.lower():
|
| 97 |
-
includes = "\n β’ ".join(details["includes"])
|
| 98 |
-
return f"- **{pkg.title()} Package**\n- π° Price: {details['price']}\n- β±οΈ Timeline: {details['timeline']}\n- β
Includes:\n β’ {includes}"
|
| 99 |
-
return None
|
| 100 |
-
|
| 101 |
-
def handle_extra_feature(user_message):
|
| 102 |
-
text = user_message.lower()
|
| 103 |
-
matched_features = []
|
| 104 |
-
for feature, details in EXTRA_FEATURES.items():
|
| 105 |
-
if feature in text:
|
| 106 |
-
matched_features.append(f"- {feature.title()}: {details['price']} (timeline {details['timeline']})")
|
| 107 |
-
if matched_features:
|
| 108 |
-
return "**Extra features cost additional:**\n" + "\n".join(matched_features) + "\n- π‘ Kya aap apni exact requirement bata sakte hain? Hum custom quote de sakte hain."
|
| 109 |
-
return None
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
# irrelevant topics
|
| 115 |
-
if any(kw in text for kw in ["weather", "cricket", "politics", "imran", "nawaz", "stock", "bitcoin"]):
|
| 116 |
return "irrelevant"
|
| 117 |
-
|
| 118 |
-
if any(x in text for x in ["contact", "phone", "number", "whatsapp", "email", "call", "raabta"]):
|
| 119 |
return "contact"
|
| 120 |
-
|
| 121 |
-
if any(x in text for x in ["price", "cost", "rate", "kitne", "quote", "charges", "fee", "timeline", "time", "days", "weeks"]):
|
| 122 |
return "pricing_timeline"
|
| 123 |
-
|
| 124 |
-
if any(x in text for x in ["basic website", "standard website", "premium website", "package"]):
|
| 125 |
return "package"
|
| 126 |
-
|
| 127 |
-
if any(x in text for x in ["extra", "additional", "also want", "add", "plus", "more features", "custom"]):
|
| 128 |
return "custom_request"
|
| 129 |
-
|
| 130 |
-
if any(x in text for x in ["service", "website design", "ecommerce", "seo", "maintenance", "marketing"]):
|
| 131 |
return "service_inquiry"
|
| 132 |
-
|
| 133 |
-
if any(x in text for x in ["portfolio", "sample", "gallery", "kaam dikhao"]):
|
| 134 |
return "portfolio"
|
| 135 |
-
|
| 136 |
-
if any(x in text for x in ["salam", "hello", "hi", "hey"]):
|
| 137 |
return "greeting"
|
| 138 |
return "general"
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
if intent == "contact":
|
| 143 |
-
|
| 144 |
elif intent == "pricing_timeline":
|
| 145 |
-
|
| 146 |
elif intent == "package":
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
elif intent == "custom_request":
|
| 157 |
-
extra =
|
| 158 |
if extra:
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
elif intent == "service_inquiry":
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
elif intent == "portfolio":
|
| 170 |
-
|
| 171 |
elif intent == "greeting":
|
| 172 |
-
|
| 173 |
elif intent == "irrelevant":
|
| 174 |
-
|
| 175 |
else:
|
| 176 |
-
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
# ---------- OpenRouter
|
| 179 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 180 |
MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 181 |
-
|
| 182 |
-
SYSTEM_PROMPT = """You are "VisionCraft AI" β assistant for "Elite Visuals", a web & digital agency.
|
| 183 |
-
|
| 184 |
-
Services: website design & development, e-commerce, SEO, chatbot integration, maintenance, digital marketing, custom web apps.
|
| 185 |
-
Packages: Basic (PKR 50k, 7-10 days), Standard (PKR 1.2L, 15-20 days), Premium (PKR 2.5L, 25-30 days).
|
| 186 |
-
Extra features cost additional and increase timeline.
|
| 187 |
-
|
| 188 |
-
Always answer in bullet points. If user asks for extra features, clearly state price and timeline increase.
|
| 189 |
-
Be concise, helpful, and personalized. Never repeat the same list."""
|
| 190 |
|
| 191 |
def call_openrouter(prompt):
|
| 192 |
if not OPENROUTER_API_KEY:
|
| 193 |
return None
|
| 194 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 195 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 196 |
-
payload = {
|
| 197 |
-
"model": MODEL,
|
| 198 |
-
"messages": [
|
| 199 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 200 |
-
{"role": "user", "content": prompt}
|
| 201 |
-
],
|
| 202 |
-
"temperature": 0.7,
|
| 203 |
-
"max_tokens": 400
|
| 204 |
-
}
|
| 205 |
try:
|
| 206 |
-
resp = requests.post(url, json=payload, headers=headers, timeout=
|
| 207 |
resp.raise_for_status()
|
| 208 |
return resp.json()["choices"][0]["message"]["content"]
|
| 209 |
-
except Exception
|
| 210 |
-
print(f"OpenRouter error: {e}")
|
| 211 |
return None
|
| 212 |
|
| 213 |
-
def
|
| 214 |
-
|
| 215 |
-
if
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
**inputs,
|
| 228 |
-
max_new_tokens=120,
|
| 229 |
-
temperature=0.7,
|
| 230 |
-
do_sample=True,
|
| 231 |
-
repetition_penalty=1.5,
|
| 232 |
-
no_repeat_ngram_size=3,
|
| 233 |
-
pad_token_id=gpt2_tokenizer.eos_token_id
|
| 234 |
-
)
|
| 235 |
-
response = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 236 |
-
if "Assistant:" in response:
|
| 237 |
-
response = response.split("Assistant:")[-1].strip()
|
| 238 |
-
else:
|
| 239 |
-
response = response[len(full_prompt):].strip()
|
| 240 |
-
# remove duplicates
|
| 241 |
-
lines = list(dict.fromkeys([line.strip() for line in response.split('\n') if line.strip()]))
|
| 242 |
-
response = '\n'.join(lines[:6])
|
| 243 |
-
if len(response) < 20:
|
| 244 |
-
return None
|
| 245 |
-
return response
|
| 246 |
-
|
| 247 |
-
def get_ai_response(user_message, intent):
|
| 248 |
-
# First try OpenRouter
|
| 249 |
-
resp = call_openrouter(user_message)
|
| 250 |
-
if resp and len(resp) > 20 and "error" not in resp.lower():
|
| 251 |
-
return resp
|
| 252 |
-
# Then try GPT-2
|
| 253 |
-
gpt_resp = generate_with_gpt2(user_message)
|
| 254 |
-
if gpt_resp:
|
| 255 |
-
return gpt_resp
|
| 256 |
-
# Final intent-based fallback
|
| 257 |
-
return intent_based_reply(user_message, intent)
|
| 258 |
-
|
| 259 |
-
# ---------- Firebase ----------
|
| 260 |
-
def save_message(session_id, role, content, intent=None):
|
| 261 |
-
ref.child(f"chats/{session_id}/messages").push().set({
|
| 262 |
-
"role": role, "content": content, "timestamp": datetime.now().isoformat(), "intent": intent
|
| 263 |
-
})
|
| 264 |
-
|
| 265 |
@app.route('/api/chat', methods=['POST'])
|
| 266 |
def chat():
|
| 267 |
-
|
| 268 |
-
user_message =
|
| 269 |
-
session_id =
|
| 270 |
if not user_message:
|
| 271 |
return jsonify({"error": "No message"}), 400
|
| 272 |
intent = classify_intent(user_message)
|
| 273 |
print(f"π― [{session_id[:8]}] Intent: {intent}")
|
|
|
|
| 274 |
save_message(session_id, "user", user_message, intent)
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
@app.route('/')
|
| 280 |
def index():
|
|
|
|
| 8 |
from sentence_transformers import SentenceTransformer, util
|
| 9 |
import uuid
|
| 10 |
import re
|
|
|
|
|
|
|
| 11 |
|
| 12 |
app = Flask(__name__)
|
| 13 |
|
| 14 |
+
# ---------- Firebase ----------
|
| 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 karo.")
|
|
|
|
| 22 |
ref = db.reference('/')
|
| 23 |
print("β
Firebase connected")
|
| 24 |
|
| 25 |
+
# ---------- Sentence-Transformer ----------
|
| 26 |
print("π Loading sentence-transformers...")
|
| 27 |
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 28 |
print("β
Embedding model loaded")
|
| 29 |
|
| 30 |
+
# ---------- Static Data ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
SERVICE_PACKAGES = {
|
| 32 |
+
"basic": {"name": "Basic Website", "price": "PKR 50,000", "timeline": "7-10 days",
|
| 33 |
+
"features": ["5 pages", "responsive", "basic SEO", "contact form", "social links"]},
|
| 34 |
+
"standard": {"name": "Standard Website", "price": "PKR 1,20,000", "timeline": "15-20 days",
|
| 35 |
+
"features": ["10 pages", "CMS", "advanced SEO", "blog", "chatbot", "1 month support"]},
|
| 36 |
+
"premium": {"name": "Premium Website", "price": "PKR 2,50,000", "timeline": "25-30 days",
|
| 37 |
+
"features": ["unlimited pages", "e-commerce", "payment gateway", "user accounts", "custom animations", "6 months support"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
EXTRA_FEATURES = {
|
|
|
|
|
|
|
| 41 |
"live chat": {"price": "+ PKR 20,000", "timeline": "+ 3 days"},
|
| 42 |
"booking system": {"price": "+ PKR 35,000", "timeline": "+ 5 days"},
|
| 43 |
+
"multi-language": {"price": "+ PKR 25,000", "timeline": "+ 4 days"},
|
| 44 |
+
"custom backend": {"price": "+ PKR 1,00,000+", "timeline": "+ 15 days"}
|
| 45 |
}
|
| 46 |
|
| 47 |
+
ALL_SERVICES = ["Website Design", "E-commerce Setup", "SEO Optimization", "Chatbot Integration", "Maintenance", "Content Writing", "Graphic Design", "Digital Marketing"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
# ---------- Intent Classification ----------
|
| 50 |
+
IRRELEVANT = ["weather", "cricket", "politics", "imran", "nawaz", "stock", "bitcoin", "covid"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
def classify_intent(text):
|
| 53 |
+
t = text.lower()
|
| 54 |
+
if any(k in t for k in IRRELEVANT):
|
|
|
|
|
|
|
| 55 |
return "irrelevant"
|
| 56 |
+
if any(x in t for x in ["contact", "phone", "number", "whatsapp", "email", "call"]):
|
|
|
|
| 57 |
return "contact"
|
| 58 |
+
if any(x in t for x in ["price", "cost", "rate", "kitne", "quote", "charges", "fee", "timeline", "time", "days"]):
|
|
|
|
| 59 |
return "pricing_timeline"
|
| 60 |
+
if any(x in t for x in ["basic", "standard", "premium", "package"]):
|
|
|
|
| 61 |
return "package"
|
| 62 |
+
if any(x in t for x in ["extra", "additional", "also want", "add", "more", "custom", "live chat", "booking", "multi-language"]):
|
|
|
|
| 63 |
return "custom_request"
|
| 64 |
+
if any(x in t for x in ["service", "ecommerce", "seo", "chatbot", "maintenance", "marketing", "design"]):
|
|
|
|
| 65 |
return "service_inquiry"
|
| 66 |
+
if any(x in t for x in ["portfolio", "sample", "gallery"]):
|
|
|
|
| 67 |
return "portfolio"
|
| 68 |
+
if any(x in t for x in ["salam", "hello", "hi", "hey"]):
|
|
|
|
| 69 |
return "greeting"
|
| 70 |
return "general"
|
| 71 |
|
| 72 |
+
def detect_package(text):
|
| 73 |
+
t = text.lower()
|
| 74 |
+
if "basic" in t:
|
| 75 |
+
return "basic"
|
| 76 |
+
if "standard" in t:
|
| 77 |
+
return "standard"
|
| 78 |
+
if "premium" in t:
|
| 79 |
+
return "premium"
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
def detect_extra_feature(text):
|
| 83 |
+
t = text.lower()
|
| 84 |
+
for feat in EXTRA_FEATURES:
|
| 85 |
+
if feat in t:
|
| 86 |
+
return feat
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
# ---------- Response Generator (with structured data) ----------
|
| 90 |
+
def get_response_and_data(user_message, intent):
|
| 91 |
+
data = {
|
| 92 |
+
"package": None,
|
| 93 |
+
"price": None,
|
| 94 |
+
"timeline": None,
|
| 95 |
+
"features": None,
|
| 96 |
+
"extra_feature": None,
|
| 97 |
+
"extra_cost": None,
|
| 98 |
+
"extra_timeline": None,
|
| 99 |
+
"service": None
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
if intent == "contact":
|
| 103 |
+
reply = "- π Phone: +92 300 1234567\n- βοΈ Email: hello@elitevisuals.com\n- π Website: www.elitevisuals.com"
|
| 104 |
elif intent == "pricing_timeline":
|
| 105 |
+
reply = "**Packages:**\n- Basic: PKR 50,000 (7-10 days)\n- Standard: PKR 1,20,000 (15-20 days)\n- Premium: PKR 2,50,000 (25-30 days)"
|
| 106 |
elif intent == "package":
|
| 107 |
+
pkg = detect_package(user_message)
|
| 108 |
+
if pkg and pkg in SERVICE_PACKAGES:
|
| 109 |
+
p = SERVICE_PACKAGES[pkg]
|
| 110 |
+
data["package"] = p["name"]
|
| 111 |
+
data["price"] = p["price"]
|
| 112 |
+
data["timeline"] = p["timeline"]
|
| 113 |
+
data["features"] = p["features"]
|
| 114 |
+
features = "\n β’ ".join(p["features"])
|
| 115 |
+
reply = f"**{p['name']}** β {p['price']}, {p['timeline']}\nβ
Includes:\n β’ {features}"
|
| 116 |
+
else:
|
| 117 |
+
reply = "**Our Packages:**\n- Basic: PKR 50,000 (7-10 days)\n- Standard: PKR 1,20,000 (15-20 days)\n- Premium: PKR 2,50,000 (25-30 days)"
|
| 118 |
elif intent == "custom_request":
|
| 119 |
+
extra = detect_extra_feature(user_message)
|
| 120 |
if extra:
|
| 121 |
+
info = EXTRA_FEATURES[extra]
|
| 122 |
+
data["extra_feature"] = extra
|
| 123 |
+
data["extra_cost"] = info["price"]
|
| 124 |
+
data["extra_timeline"] = info["timeline"]
|
| 125 |
+
reply = f"- β
{extra.title()} feature available.\n- π° Additional cost: {info['price']}\n- β±οΈ Timeline increase: {info['timeline']}\n- π‘ Custom quote possible."
|
| 126 |
+
else:
|
| 127 |
+
reply = "- β
Custom requirements handled.\n- π° Extra features increase price/timeline.\n- π Send your requirement for free quote."
|
| 128 |
elif intent == "service_inquiry":
|
| 129 |
+
if "ecommerce" in user_message.lower():
|
| 130 |
+
data["service"] = "E-commerce Website"
|
| 131 |
+
data["price"] = "Starting PKR 1,50,000"
|
| 132 |
+
data["timeline"] = "20-30 days"
|
| 133 |
+
reply = "- β
E-commerce websites with payment gateway.\n- π° Starting PKR 1,50,000\n- β±οΈ 20-30 days"
|
| 134 |
+
elif "seo" in user_message.lower():
|
| 135 |
+
data["service"] = "SEO Optimization"
|
| 136 |
+
data["price"] = "PKR 25,000/month"
|
| 137 |
+
data["timeline"] = "ongoing"
|
| 138 |
+
reply = "- β
SEO (on-page, off-page, technical).\n- π° PKR 25,000/month\n- β±οΈ Results in 2-3 months"
|
| 139 |
+
elif "chatbot" in user_message.lower():
|
| 140 |
+
data["service"] = "Chatbot Integration"
|
| 141 |
+
data["price"] = "PKR 30,000 one-time + PKR 5,000/month"
|
| 142 |
+
data["timeline"] = "7-10 days"
|
| 143 |
+
reply = "- β
Custom AI chatbot integration.\n- π° PKR 30,000 setup + PKR 5,000/month\n- β±οΈ 7-10 days"
|
| 144 |
+
else:
|
| 145 |
+
services = "\n β’ ".join(ALL_SERVICES)
|
| 146 |
+
reply = f"- Services:\n β’ {services}\n- Ask about specific service."
|
| 147 |
elif intent == "portfolio":
|
| 148 |
+
reply = "- π· Instagram: @elitevisuals\n- π₯οΈ Gallery: www.elitevisuals.com/work"
|
| 149 |
elif intent == "greeting":
|
| 150 |
+
reply = "- Wa-Alaikum-Assalam! π\n- I help with websites, e-commerce, SEO, chatbots.\n- Ask about packages or extra features."
|
| 151 |
elif intent == "irrelevant":
|
| 152 |
+
reply = "- β Out of scope. I only answer web & digital services."
|
| 153 |
else:
|
| 154 |
+
reply = "- How can I help? Services: website design, e-commerce, SEO, chatbots, maintenance."
|
| 155 |
+
|
| 156 |
+
return reply, data
|
| 157 |
|
| 158 |
+
# ---------- OpenRouter (optional) ----------
|
| 159 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 160 |
MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 161 |
+
SYSTEM_PROMPT = """You are Elite Visuals AI assistant. Answer in bullet points. Include price and timeline when relevant."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
def call_openrouter(prompt):
|
| 164 |
if not OPENROUTER_API_KEY:
|
| 165 |
return None
|
| 166 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 167 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 168 |
+
payload = {"model": MODEL, "messages": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}], "temperature": 0.7, "max_tokens": 300}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
try:
|
| 170 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=10)
|
| 171 |
resp.raise_for_status()
|
| 172 |
return resp.json()["choices"][0]["message"]["content"]
|
| 173 |
+
except Exception:
|
|
|
|
| 174 |
return None
|
| 175 |
|
| 176 |
+
def get_final_response(user_message, intent):
|
| 177 |
+
# Try OpenRouter
|
| 178 |
+
if OPENROUTER_API_KEY:
|
| 179 |
+
ai_reply = call_openrouter(user_message)
|
| 180 |
+
if ai_reply and len(ai_reply) > 20:
|
| 181 |
+
# For dynamic widget, we can't parse AI output easily, so fallback to structured data as well.
|
| 182 |
+
# But we still need data. We'll also generate structured data from intent as backup.
|
| 183 |
+
reply, data = get_response_and_data(user_message, intent)
|
| 184 |
+
# If AI reply is good, use it but keep data from intent.
|
| 185 |
+
return ai_reply, data
|
| 186 |
+
# Fallback to rule-based
|
| 187 |
+
return get_response_and_data(user_message, intent)
|
| 188 |
+
|
| 189 |
+
# ---------- API ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
@app.route('/api/chat', methods=['POST'])
|
| 191 |
def chat():
|
| 192 |
+
data_req = request.get_json()
|
| 193 |
+
user_message = data_req.get('message', '')
|
| 194 |
+
session_id = data_req.get('session_id', str(uuid.uuid4()))
|
| 195 |
if not user_message:
|
| 196 |
return jsonify({"error": "No message"}), 400
|
| 197 |
intent = classify_intent(user_message)
|
| 198 |
print(f"π― [{session_id[:8]}] Intent: {intent}")
|
| 199 |
+
reply, structured = get_final_response(user_message, intent)
|
| 200 |
save_message(session_id, "user", user_message, intent)
|
| 201 |
+
save_message(session_id, "assistant", reply)
|
| 202 |
+
return jsonify({
|
| 203 |
+
"reply": reply,
|
| 204 |
+
"intent": intent,
|
| 205 |
+
"session_id": session_id,
|
| 206 |
+
"widget": structured # send structured data to frontend
|
| 207 |
+
})
|
| 208 |
+
|
| 209 |
+
def save_message(session_id, role, content, intent=None):
|
| 210 |
+
ref.child(f"chats/{session_id}/messages").push().set({
|
| 211 |
+
"role": role, "content": content, "timestamp": datetime.now().isoformat(), "intent": intent
|
| 212 |
+
})
|
| 213 |
|
| 214 |
@app.route('/')
|
| 215 |
def index():
|