Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,6 +7,9 @@ import json
|
|
| 7 |
from datetime import datetime, timedelta
|
| 8 |
import uuid
|
| 9 |
import re
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
|
@@ -21,6 +24,10 @@ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
|
| 21 |
ref = firebase_admin.db.reference('/')
|
| 22 |
print("✅ Firebase connected")
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# ---------- Helper: Load extra services from Firebase ----------
|
| 25 |
def get_extra_services():
|
| 26 |
snap = ref.child("extra_services").get()
|
|
@@ -185,7 +192,37 @@ def call_openrouter(prompt):
|
|
| 185 |
print(f"OpenRouter error: {e}")
|
| 186 |
return None
|
| 187 |
|
| 188 |
-
# ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
def simple_response(user_message):
|
| 190 |
msg = user_message.lower()
|
| 191 |
if any(word in msg for word in ["hello", "hi", "salam"]):
|
|
@@ -198,7 +235,7 @@ def simple_response(user_message):
|
|
| 198 |
return "- Say **'I want to build a website'** to start a step‑by‑step project.\n- Type **'status PROJ-XXXX'** to check your project.\n- Use the quick buttons below."
|
| 199 |
return "- I'm here to help with websites, e-commerce, SEO, and chatbots.\n- Say **'I want to build a website'** to get started."
|
| 200 |
|
| 201 |
-
# ---------- Step Builder (
|
| 202 |
user_sessions = {}
|
| 203 |
|
| 204 |
def is_start_project_request(text):
|
|
@@ -209,9 +246,8 @@ def is_start_project_request(text):
|
|
| 209 |
def process_step_by_step(session_id, message):
|
| 210 |
msg_lower = message.lower().strip()
|
| 211 |
|
| 212 |
-
#
|
| 213 |
if is_start_project_request(message):
|
| 214 |
-
# Clear any existing session
|
| 215 |
if session_id in user_sessions:
|
| 216 |
del user_sessions[session_id]
|
| 217 |
user_sessions[session_id] = {
|
|
@@ -227,7 +263,6 @@ def process_step_by_step(session_id, message):
|
|
| 227 |
}
|
| 228 |
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 229 |
|
| 230 |
-
# If no active session, ignore step builder (let AI handle)
|
| 231 |
if session_id not in user_sessions:
|
| 232 |
return None
|
| 233 |
|
|
@@ -245,14 +280,12 @@ def process_step_by_step(session_id, message):
|
|
| 245 |
session["step"] = "asking_contact"
|
| 246 |
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 247 |
|
| 248 |
-
# Handle "add more" command
|
| 249 |
if msg_lower in ["add more", "add something", "extra add"]:
|
| 250 |
session["step"] = "asking_extra"
|
| 251 |
extra_services = get_extra_services()
|
| 252 |
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 253 |
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 254 |
|
| 255 |
-
# Step handlers
|
| 256 |
if step == "asking_domain":
|
| 257 |
req["domain"] = "yes" in msg_lower or "han" in msg_lower
|
| 258 |
session["step"] = "asking_pages"
|
|
@@ -398,7 +431,7 @@ We'll contact you within 24 hours. 🚀"""
|
|
| 398 |
|
| 399 |
# ---------- Main Response Handler ----------
|
| 400 |
def get_final_response(user_message, session_id):
|
| 401 |
-
# 1.
|
| 402 |
status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
|
| 403 |
if status_match:
|
| 404 |
pid = status_match.group(1).upper()
|
|
@@ -439,12 +472,12 @@ def get_final_response(user_message, session_id):
|
|
| 439 |
else:
|
| 440 |
return f"❌ Cannot request update for `{pid}`. Either it doesn't exist or the 3‑day window has passed."
|
| 441 |
|
| 442 |
-
# 3. Step builder
|
| 443 |
step_resp = process_step_by_step(session_id, user_message)
|
| 444 |
if step_resp:
|
| 445 |
return step_resp
|
| 446 |
|
| 447 |
-
# 4. Special commands (packages, contact, help) – handled
|
| 448 |
lower = user_message.lower()
|
| 449 |
if "show packages" in lower:
|
| 450 |
return "**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)\n- For exact quote, start a project."
|
|
@@ -453,13 +486,20 @@ def get_final_response(user_message, session_id):
|
|
| 453 |
if "help" in lower:
|
| 454 |
return "- Say **'I want to build a website'** to start a step‑by‑step project.\n- Type **'status PROJ-XXXX'** to check your project.\n- Use the quick buttons below."
|
| 455 |
|
| 456 |
-
# 5.
|
| 457 |
ai_resp = call_openrouter(user_message)
|
| 458 |
if ai_resp:
|
| 459 |
return ai_resp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
return simple_response(user_message)
|
| 461 |
|
| 462 |
-
# ---------- Admin API Routes ----------
|
| 463 |
@app.route('/api/projects', methods=['GET'])
|
| 464 |
def get_projects():
|
| 465 |
snap = ref.child("projects").get()
|
|
|
|
| 7 |
from datetime import datetime, timedelta
|
| 8 |
import uuid
|
| 9 |
import re
|
| 10 |
+
import torch
|
| 11 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 12 |
+
from sentence_transformers import SentenceTransformer
|
| 13 |
|
| 14 |
app = Flask(__name__)
|
| 15 |
|
|
|
|
| 24 |
ref = firebase_admin.db.reference('/')
|
| 25 |
print("✅ Firebase connected")
|
| 26 |
|
| 27 |
+
# ---------- Sentence‑Transformers for Intent (used in step builder) ----------
|
| 28 |
+
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 29 |
+
print("✅ Sentence‑Transformers model loaded")
|
| 30 |
+
|
| 31 |
# ---------- Helper: Load extra services from Firebase ----------
|
| 32 |
def get_extra_services():
|
| 33 |
snap = ref.child("extra_services").get()
|
|
|
|
| 192 |
print(f"OpenRouter error: {e}")
|
| 193 |
return None
|
| 194 |
|
| 195 |
+
# ---------- Local GPT‑2 Fallback (sentence‑transformers is for intent, not generation) ----------
|
| 196 |
+
print("🔄 Loading local GPT‑2 model (fallback)...")
|
| 197 |
+
try:
|
| 198 |
+
gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 199 |
+
gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 200 |
+
gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
|
| 201 |
+
if torch.cuda.is_available():
|
| 202 |
+
gpt_model = gpt_model.to("cuda")
|
| 203 |
+
print("✅ GPT‑2 loaded")
|
| 204 |
+
except Exception as e:
|
| 205 |
+
print(f"⚠️ GPT‑2 load failed: {e}")
|
| 206 |
+
gpt_model = None
|
| 207 |
+
gpt_tokenizer = None
|
| 208 |
+
|
| 209 |
+
def call_gpt2(prompt):
|
| 210 |
+
if gpt_model is None:
|
| 211 |
+
return None
|
| 212 |
+
inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
|
| 213 |
+
if torch.cuda.is_available():
|
| 214 |
+
inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
| 215 |
+
outputs = gpt_model.generate(
|
| 216 |
+
**inputs,
|
| 217 |
+
max_new_tokens=150,
|
| 218 |
+
do_sample=True,
|
| 219 |
+
temperature=0.7,
|
| 220 |
+
repetition_penalty=1.2,
|
| 221 |
+
pad_token_id=gpt_tokenizer.eos_token_id
|
| 222 |
+
)
|
| 223 |
+
return gpt_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 224 |
+
|
| 225 |
+
# ---------- Rule‑Based Fallback (when all else fails) ----------
|
| 226 |
def simple_response(user_message):
|
| 227 |
msg = user_message.lower()
|
| 228 |
if any(word in msg for word in ["hello", "hi", "salam"]):
|
|
|
|
| 235 |
return "- Say **'I want to build a website'** to start a step‑by‑step project.\n- Type **'status PROJ-XXXX'** to check your project.\n- Use the quick buttons below."
|
| 236 |
return "- I'm here to help with websites, e-commerce, SEO, and chatbots.\n- Say **'I want to build a website'** to get started."
|
| 237 |
|
| 238 |
+
# ---------- Step Builder (resets on start command) ----------
|
| 239 |
user_sessions = {}
|
| 240 |
|
| 241 |
def is_start_project_request(text):
|
|
|
|
| 246 |
def process_step_by_step(session_id, message):
|
| 247 |
msg_lower = message.lower().strip()
|
| 248 |
|
| 249 |
+
# Reset session if user says start command
|
| 250 |
if is_start_project_request(message):
|
|
|
|
| 251 |
if session_id in user_sessions:
|
| 252 |
del user_sessions[session_id]
|
| 253 |
user_sessions[session_id] = {
|
|
|
|
| 263 |
}
|
| 264 |
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 265 |
|
|
|
|
| 266 |
if session_id not in user_sessions:
|
| 267 |
return None
|
| 268 |
|
|
|
|
| 280 |
session["step"] = "asking_contact"
|
| 281 |
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 282 |
|
|
|
|
| 283 |
if msg_lower in ["add more", "add something", "extra add"]:
|
| 284 |
session["step"] = "asking_extra"
|
| 285 |
extra_services = get_extra_services()
|
| 286 |
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 287 |
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 288 |
|
|
|
|
| 289 |
if step == "asking_domain":
|
| 290 |
req["domain"] = "yes" in msg_lower or "han" in msg_lower
|
| 291 |
session["step"] = "asking_pages"
|
|
|
|
| 431 |
|
| 432 |
# ---------- Main Response Handler ----------
|
| 433 |
def get_final_response(user_message, session_id):
|
| 434 |
+
# 1. Project status
|
| 435 |
status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
|
| 436 |
if status_match:
|
| 437 |
pid = status_match.group(1).upper()
|
|
|
|
| 472 |
else:
|
| 473 |
return f"❌ Cannot request update for `{pid}`. Either it doesn't exist or the 3‑day window has passed."
|
| 474 |
|
| 475 |
+
# 3. Step builder
|
| 476 |
step_resp = process_step_by_step(session_id, user_message)
|
| 477 |
if step_resp:
|
| 478 |
return step_resp
|
| 479 |
|
| 480 |
+
# 4. Special commands (packages, contact, help) – handled directly
|
| 481 |
lower = user_message.lower()
|
| 482 |
if "show packages" in lower:
|
| 483 |
return "**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)\n- For exact quote, start a project."
|
|
|
|
| 486 |
if "help" in lower:
|
| 487 |
return "- Say **'I want to build a website'** to start a step‑by‑step project.\n- Type **'status PROJ-XXXX'** to check your project.\n- Use the quick buttons below."
|
| 488 |
|
| 489 |
+
# 5. OpenRouter (primary)
|
| 490 |
ai_resp = call_openrouter(user_message)
|
| 491 |
if ai_resp:
|
| 492 |
return ai_resp
|
| 493 |
+
|
| 494 |
+
# 6. GPT‑2 fallback (local)
|
| 495 |
+
gpt_resp = call_gpt2(user_message)
|
| 496 |
+
if gpt_resp:
|
| 497 |
+
return gpt_resp
|
| 498 |
+
|
| 499 |
+
# 7. Final rule‑based fallback
|
| 500 |
return simple_response(user_message)
|
| 501 |
|
| 502 |
+
# ---------- Admin API Routes (same as before) ----------
|
| 503 |
@app.route('/api/projects', methods=['GET'])
|
| 504 |
def get_projects():
|
| 505 |
snap = ref.child("projects").get()
|