Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,7 +5,6 @@ import requests
|
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
from datetime import datetime, timedelta
|
| 8 |
-
from sentence_transformers import SentenceTransformer
|
| 9 |
import uuid
|
| 10 |
import re
|
| 11 |
|
|
@@ -19,52 +18,9 @@ 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)
|
| 21 |
firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
| 22 |
-
ref = db.reference('/')
|
| 23 |
print("✅ Firebase connected")
|
| 24 |
|
| 25 |
-
# ---------- Embedding model (unused, kept for compatibility) ----------
|
| 26 |
-
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 27 |
-
print("✅ Embedding model loaded")
|
| 28 |
-
|
| 29 |
-
# ---------- OpenRouter Setup (Primary) ----------
|
| 30 |
-
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 31 |
-
OPENROUTER_MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 32 |
-
|
| 33 |
-
def call_openrouter(prompt):
|
| 34 |
-
if not OPENROUTER_API_KEY:
|
| 35 |
-
return None
|
| 36 |
-
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 37 |
-
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 38 |
-
payload = {
|
| 39 |
-
"model": OPENROUTER_MODEL,
|
| 40 |
-
"messages": [{"role": "user", "content": prompt}],
|
| 41 |
-
"temperature": 0.7,
|
| 42 |
-
"max_tokens": 500
|
| 43 |
-
}
|
| 44 |
-
try:
|
| 45 |
-
resp = requests.post(url, json=payload, headers=headers, timeout=15)
|
| 46 |
-
resp.raise_for_status()
|
| 47 |
-
return resp.json()["choices"][0]["message"]["content"]
|
| 48 |
-
except Exception as e:
|
| 49 |
-
print(f"OpenRouter error: {e}")
|
| 50 |
-
return None
|
| 51 |
-
|
| 52 |
-
# ---------- Local GPT-2 Fallback (if OpenRouter fails) ----------
|
| 53 |
-
import torch
|
| 54 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 55 |
-
gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 56 |
-
gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 57 |
-
gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
|
| 58 |
-
if torch.cuda.is_available():
|
| 59 |
-
gpt_model = gpt_model.to("cuda")
|
| 60 |
-
|
| 61 |
-
def local_gpt2_answer(prompt):
|
| 62 |
-
inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
|
| 63 |
-
if torch.cuda.is_available():
|
| 64 |
-
inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
| 65 |
-
outputs = gpt_model.generate(**inputs, max_new_tokens=150, do_sample=True, temperature=0.7, pad_token_id=gpt_tokenizer.eos_token_id)
|
| 66 |
-
return gpt_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 67 |
-
|
| 68 |
# ---------- Helper: Load extra services from Firebase ----------
|
| 69 |
def get_extra_services():
|
| 70 |
snap = ref.child("extra_services").get()
|
|
@@ -143,7 +99,7 @@ def create_project(session_id, requirements):
|
|
| 143 |
"admin_message": "",
|
| 144 |
"update_requested": False,
|
| 145 |
"update_details": "",
|
| 146 |
-
"update_approved": None,
|
| 147 |
"updated_requirements": None,
|
| 148 |
"updated_price": None,
|
| 149 |
"updated_timeline": None,
|
|
@@ -168,7 +124,7 @@ def request_project_update(project_id, update_text):
|
|
| 168 |
return False
|
| 169 |
submission_date = datetime.fromisoformat(proj["submission_date"])
|
| 170 |
if datetime.now() - submission_date > timedelta(days=3):
|
| 171 |
-
return False
|
| 172 |
ref.child(f"projects/{project_id}").update({
|
| 173 |
"update_requested": True,
|
| 174 |
"update_details": update_text,
|
|
@@ -180,7 +136,6 @@ def approve_update(project_id, new_requirements):
|
|
| 180 |
proj = get_project(project_id)
|
| 181 |
if not proj:
|
| 182 |
return False
|
| 183 |
-
# Merge new requirements into original
|
| 184 |
orig_req = proj.get("requirements", {})
|
| 185 |
for key, val in new_requirements.items():
|
| 186 |
orig_req[key] = val
|
|
@@ -194,7 +149,7 @@ def approve_update(project_id, new_requirements):
|
|
| 194 |
"updated_requirements": new_requirements,
|
| 195 |
"updated_price": new_price,
|
| 196 |
"updated_timeline": new_timeline,
|
| 197 |
-
"status": "pending",
|
| 198 |
"updated_at": datetime.now().isoformat()
|
| 199 |
})
|
| 200 |
return True
|
|
@@ -207,18 +162,234 @@ def reject_update(project_id):
|
|
| 207 |
})
|
| 208 |
return True
|
| 209 |
|
| 210 |
-
# ----------
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
-
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
def get_final_response(user_message, session_id):
|
| 221 |
-
# 1.
|
| 222 |
status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
|
| 223 |
if status_match:
|
| 224 |
pid = status_match.group(1).upper()
|
|
@@ -229,7 +400,6 @@ def get_final_response(user_message, session_id):
|
|
| 229 |
emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
|
| 230 |
msg = proj.get("admin_message", "")
|
| 231 |
extra = f"\n📝 **Admin note:** {msg}" if msg else ""
|
| 232 |
-
# Check if update can be requested
|
| 233 |
submission_date = proj.get("submission_date")
|
| 234 |
can_request_update = False
|
| 235 |
if submission_date and status not in ["completed", "declined"]:
|
|
@@ -240,8 +410,7 @@ def get_final_response(user_message, session_id):
|
|
| 240 |
if proj.get("update_requested"):
|
| 241 |
update_info = f"\n🔄 **Update requested:** {proj.get('update_details', '')}\nStatus: {'Pending approval' if proj.get('update_approved') is None else ('Approved' if proj.get('update_approved') else 'Rejected')}"
|
| 242 |
elif can_request_update:
|
| 243 |
-
update_info = f"\n\n📝 You can request changes
|
| 244 |
-
# Show updated price/timeline if approved
|
| 245 |
if proj.get("update_approved") is True and proj.get("updated_price"):
|
| 246 |
price = proj.get("updated_price")
|
| 247 |
timeline = proj.get("updated_timeline")
|
|
@@ -251,33 +420,28 @@ def get_final_response(user_message, session_id):
|
|
| 251 |
timeline = proj.get("calculated_timeline", 0)
|
| 252 |
return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}{update_info}\nTotal: PKR {price:,}\nTimeline: {timeline} days"
|
| 253 |
|
| 254 |
-
# 2.
|
| 255 |
-
req_match = re.search(r'request update:\s*(.+)', user_message, re.IGNORECASE)
|
| 256 |
-
if req_match
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
else:
|
| 266 |
-
return f"❌ Cannot request update for `{pid}`. Either it doesn't exist or the 3‑day window has passed."
|
| 267 |
-
|
| 268 |
-
# 3. Check step builder (only if user explicitly starts a project)
|
| 269 |
step_resp = process_step_by_step(session_id, user_message)
|
| 270 |
if step_resp:
|
| 271 |
return step_resp
|
| 272 |
|
| 273 |
-
# 4.
|
| 274 |
-
|
| 275 |
-
if
|
| 276 |
-
return
|
| 277 |
-
|
| 278 |
-
return local_gpt2_answer(user_message)
|
| 279 |
|
| 280 |
-
# ---------- Admin API Routes
|
| 281 |
@app.route('/api/projects', methods=['GET'])
|
| 282 |
def get_projects():
|
| 283 |
snap = ref.child("projects").get()
|
|
@@ -306,8 +470,7 @@ def approve_update_route(project_id):
|
|
| 306 |
new_req = data.get('requirements', {})
|
| 307 |
if approve_update(project_id, new_req):
|
| 308 |
return jsonify({"message": "Update approved and applied"})
|
| 309 |
-
|
| 310 |
-
return jsonify({"error": "Project not found"}), 404
|
| 311 |
|
| 312 |
@app.route('/api/project/<project_id>/update/reject', methods=['POST'])
|
| 313 |
def reject_update_route(project_id):
|
|
|
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
from datetime import datetime, timedelta
|
|
|
|
| 8 |
import uuid
|
| 9 |
import re
|
| 10 |
|
|
|
|
| 18 |
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
|
| 19 |
cred = credentials.Certificate(service_account_info)
|
| 20 |
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()
|
|
|
|
| 99 |
"admin_message": "",
|
| 100 |
"update_requested": False,
|
| 101 |
"update_details": "",
|
| 102 |
+
"update_approved": None,
|
| 103 |
"updated_requirements": None,
|
| 104 |
"updated_price": None,
|
| 105 |
"updated_timeline": None,
|
|
|
|
| 124 |
return False
|
| 125 |
submission_date = datetime.fromisoformat(proj["submission_date"])
|
| 126 |
if datetime.now() - submission_date > timedelta(days=3):
|
| 127 |
+
return False
|
| 128 |
ref.child(f"projects/{project_id}").update({
|
| 129 |
"update_requested": True,
|
| 130 |
"update_details": update_text,
|
|
|
|
| 136 |
proj = get_project(project_id)
|
| 137 |
if not proj:
|
| 138 |
return False
|
|
|
|
| 139 |
orig_req = proj.get("requirements", {})
|
| 140 |
for key, val in new_requirements.items():
|
| 141 |
orig_req[key] = val
|
|
|
|
| 149 |
"updated_requirements": new_requirements,
|
| 150 |
"updated_price": new_price,
|
| 151 |
"updated_timeline": new_timeline,
|
| 152 |
+
"status": "pending",
|
| 153 |
"updated_at": datetime.now().isoformat()
|
| 154 |
})
|
| 155 |
return True
|
|
|
|
| 162 |
})
|
| 163 |
return True
|
| 164 |
|
| 165 |
+
# ---------- Rule‑Based Fallback (instead of GPT‑2) ----------
|
| 166 |
+
def simple_response(user_message):
|
| 167 |
+
msg = user_message.lower()
|
| 168 |
+
if any(word in msg for word in ["hello", "hi", "salam"]):
|
| 169 |
+
return "- Wa-Alaikum-Assalam! 👋\n- I can help with website design, e-commerce, SEO, and chatbots.\n- To start a new project, say **'I want to build a website'**."
|
| 170 |
+
if "package" in msg or "price" in msg or "cost" in msg:
|
| 171 |
+
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."
|
| 172 |
+
if "contact" in msg:
|
| 173 |
+
return "- 📞 Phone: +92 300 1234567\n- ✉️ Email: hello@elitevisuals.com\n- 🌐 Website: www.elitevisuals.com"
|
| 174 |
+
if "help" in msg:
|
| 175 |
+
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."
|
| 176 |
+
return "- I'm here to help with websites, e-commerce, SEO, and chatbots.\n- Say **'I want to build a website'** to get started."
|
| 177 |
+
|
| 178 |
+
# ---------- OpenRouter (Optional) ----------
|
| 179 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 180 |
+
OPENROUTER_MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 181 |
+
|
| 182 |
+
def call_openrouter(prompt):
|
| 183 |
+
if not OPENROUTER_API_KEY:
|
| 184 |
+
return None
|
| 185 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 186 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 187 |
+
payload = {
|
| 188 |
+
"model": OPENROUTER_MODEL,
|
| 189 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 190 |
+
"temperature": 0.7,
|
| 191 |
+
"max_tokens": 500
|
| 192 |
+
}
|
| 193 |
+
try:
|
| 194 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=10)
|
| 195 |
+
resp.raise_for_status()
|
| 196 |
+
return resp.json()["choices"][0]["message"]["content"]
|
| 197 |
+
except Exception as e:
|
| 198 |
+
print(f"OpenRouter error: {e}")
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
# ---------- Step Builder (Structured Project Creation) ----------
|
| 202 |
+
user_sessions = {}
|
| 203 |
+
|
| 204 |
+
def is_start_project_request(text):
|
| 205 |
+
keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
|
| 206 |
+
"i want to build a website", "web project", "website banana hai", "naya project"]
|
| 207 |
+
return any(k in text.lower() for k in keywords)
|
| 208 |
+
|
| 209 |
+
def process_step_by_step(session_id, message):
|
| 210 |
+
msg_lower = message.lower().strip()
|
| 211 |
+
if session_id not in user_sessions:
|
| 212 |
+
if is_start_project_request(message):
|
| 213 |
+
user_sessions[session_id] = {
|
| 214 |
+
"step": "asking_domain",
|
| 215 |
+
"requirements": {},
|
| 216 |
+
"deep_answers": {},
|
| 217 |
+
"deep_index": 0,
|
| 218 |
+
"deep_questions": [
|
| 219 |
+
"🤔 **Tell me more about your target audience or business goals.** (This helps us design the perfect website.)",
|
| 220 |
+
"⭐ **Are there any specific must‑have features or integrations you need?** (e.g., payment gateway, social login, analytics)",
|
| 221 |
+
"💰 **What is your budget range or any other requirements?** (We’ll try to match it as closely as possible.)"
|
| 222 |
+
]
|
| 223 |
+
}
|
| 224 |
+
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 225 |
+
return None
|
| 226 |
|
| 227 |
+
session = user_sessions[session_id]
|
| 228 |
+
step = session.get("step")
|
| 229 |
+
req = session.get("requirements", {})
|
| 230 |
|
| 231 |
+
def move_to_deep():
|
| 232 |
+
session["step"] = "asking_deep"
|
| 233 |
+
session["deep_index"] = 0
|
| 234 |
+
deep_qs = session.get("deep_questions", [])
|
| 235 |
+
if deep_qs:
|
| 236 |
+
return deep_qs[0]
|
| 237 |
+
else:
|
| 238 |
+
session["step"] = "asking_contact"
|
| 239 |
+
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 240 |
+
|
| 241 |
+
if msg_lower in ["add more", "add something", "extra add"]:
|
| 242 |
+
session["step"] = "asking_extra"
|
| 243 |
+
extra_services = get_extra_services()
|
| 244 |
+
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 245 |
+
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 246 |
+
|
| 247 |
+
if step == "asking_domain":
|
| 248 |
+
req["domain"] = "yes" in msg_lower or "han" in msg_lower
|
| 249 |
+
session["step"] = "asking_pages"
|
| 250 |
+
session["requirements"] = req
|
| 251 |
+
return "📄 **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**"
|
| 252 |
+
|
| 253 |
+
elif step == "asking_pages":
|
| 254 |
+
try:
|
| 255 |
+
pages = int(re.search(r'\d+', msg_lower).group())
|
| 256 |
+
req["pages"] = max(pages, 5)
|
| 257 |
+
except:
|
| 258 |
+
req["pages"] = 5
|
| 259 |
+
session["step"] = "asking_ecommerce"
|
| 260 |
+
session["requirements"] = req
|
| 261 |
+
return "🛒 **Need e‑commerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**"
|
| 262 |
+
|
| 263 |
+
elif step == "asking_ecommerce":
|
| 264 |
+
req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
|
| 265 |
+
session["step"] = "asking_chatbot"
|
| 266 |
+
session["requirements"] = req
|
| 267 |
+
return "🤖 **AI chatbot on your website?**\n\nReply: **Yes** or **No**"
|
| 268 |
+
|
| 269 |
+
elif step == "asking_chatbot":
|
| 270 |
+
req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
|
| 271 |
+
session["step"] = "asking_seo"
|
| 272 |
+
session["requirements"] = req
|
| 273 |
+
return "🔍 **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**"
|
| 274 |
+
|
| 275 |
+
elif step == "asking_seo":
|
| 276 |
+
req["seo"] = "yes" in msg_lower or "han" in msg_lower
|
| 277 |
+
session["step"] = "asking_extra"
|
| 278 |
+
session["requirements"] = req
|
| 279 |
+
extra_services = get_extra_services()
|
| 280 |
+
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 281 |
+
return f"✨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**."
|
| 282 |
+
|
| 283 |
+
elif step == "asking_extra":
|
| 284 |
+
extra_services = get_extra_services()
|
| 285 |
+
if msg_lower in ["none", "done", "no"]:
|
| 286 |
+
return move_to_deep()
|
| 287 |
+
else:
|
| 288 |
+
matched_key = None
|
| 289 |
+
for key, val in extra_services.items():
|
| 290 |
+
if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
|
| 291 |
+
matched_key = key
|
| 292 |
+
break
|
| 293 |
+
if matched_key:
|
| 294 |
+
extra_list = req.get("extra_features", [])
|
| 295 |
+
if matched_key not in extra_list:
|
| 296 |
+
extra_list.append(matched_key)
|
| 297 |
+
req["extra_features"] = extra_list
|
| 298 |
+
session["requirements"] = req
|
| 299 |
+
return f"✅ Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**."
|
| 300 |
+
else:
|
| 301 |
+
return f"ℹ️ Already added. Type another name or **done**."
|
| 302 |
+
else:
|
| 303 |
+
available = ', '.join([v['name'] for v in extra_services.values()])
|
| 304 |
+
return f"❌ Sorry, **'{message}'** is not offered. Available: {available}\n\nType a valid name or **done**."
|
| 305 |
+
|
| 306 |
+
elif step == "asking_deep":
|
| 307 |
+
idx = session.get("deep_index", 0)
|
| 308 |
+
deep_qs = session.get("deep_questions", [])
|
| 309 |
+
if idx < len(deep_qs):
|
| 310 |
+
session["deep_answers"][f"deep_{idx}"] = message
|
| 311 |
+
session["deep_index"] = idx + 1
|
| 312 |
+
if idx + 1 < len(deep_qs):
|
| 313 |
+
return deep_qs[idx + 1]
|
| 314 |
+
else:
|
| 315 |
+
req["deep_answers"] = session.get("deep_answers", {})
|
| 316 |
+
session["requirements"] = req
|
| 317 |
+
session["step"] = "asking_contact"
|
| 318 |
+
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 319 |
+
else:
|
| 320 |
+
session["step"] = "asking_contact"
|
| 321 |
+
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 322 |
|
| 323 |
+
elif step == "asking_contact":
|
| 324 |
+
if "mobile" not in session:
|
| 325 |
+
session["mobile"] = message
|
| 326 |
+
return "✉️ **Please provide your email address** (e.g., name@example.com) – We'll send the quote and updates."
|
| 327 |
+
else:
|
| 328 |
+
session["email"] = message
|
| 329 |
+
req["mobile"] = session.get("mobile", "")
|
| 330 |
+
req["email"] = session.get("email", "")
|
| 331 |
+
session["requirements"] = req
|
| 332 |
+
session["step"] = "confirm"
|
| 333 |
+
price, timeline = calculate_price_and_timeline(req)
|
| 334 |
+
extra_services = get_extra_services()
|
| 335 |
+
extra_names = [extra_services.get(f, {}).get("name", f) for f in req.get("extra_features", [])]
|
| 336 |
+
extra_display = ", ".join(extra_names) if extra_names else "None"
|
| 337 |
+
deep_answers = req.get("deep_answers", {})
|
| 338 |
+
deep_text = ""
|
| 339 |
+
if deep_answers:
|
| 340 |
+
deep_text = "\n\n📌 **Additional Details:**\n"
|
| 341 |
+
if deep_answers.get("deep_0"):
|
| 342 |
+
deep_text += f"• Goals: {deep_answers['deep_0']}\n"
|
| 343 |
+
if deep_answers.get("deep_1"):
|
| 344 |
+
deep_text += f"• Must‑have features: {deep_answers['deep_1']}\n"
|
| 345 |
+
if deep_answers.get("deep_2"):
|
| 346 |
+
deep_text += f"• Budget/Requirements: {deep_answers['deep_2']}\n"
|
| 347 |
+
contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"
|
| 348 |
+
return f"""📋 **Your Project Proposal**
|
| 349 |
+
|
| 350 |
+
✅ **Summary:**
|
| 351 |
+
• Domain: {'Yes' if req.get('domain') else 'No'}
|
| 352 |
+
• Pages: {req.get('pages', 5)}
|
| 353 |
+
• E‑commerce: {'Yes' if req.get('ecommerce') else 'No'}
|
| 354 |
+
• Chatbot: {'Yes' if req.get('chatbot') else 'No'}
|
| 355 |
+
• SEO: {'Yes' if req.get('seo') else 'No'}
|
| 356 |
+
• Extras: {extra_display}{deep_text}{contact_text}
|
| 357 |
+
|
| 358 |
+
💰 **Total Cost:** PKR {price:,}
|
| 359 |
+
⏱️ **Timeline:** {timeline} working days
|
| 360 |
+
|
| 361 |
+
❓ **Agree?** (Reply: **Confirm** or **Cancel**)
|
| 362 |
+
|
| 363 |
+
⚠️ *To add more extras, type 'add more'*"""
|
| 364 |
+
|
| 365 |
+
elif step == "confirm":
|
| 366 |
+
if "confirm" in msg_lower or "agree" in msg_lower:
|
| 367 |
+
project_id, price, timeline = create_project(session_id, req)
|
| 368 |
+
del user_sessions[session_id]
|
| 369 |
+
return f"""✅ **Project Confirmed!**
|
| 370 |
+
|
| 371 |
+
**Project ID:** `{project_id}`
|
| 372 |
+
**Total Cost:** PKR {price:,}
|
| 373 |
+
**Timeline:** {timeline} days
|
| 374 |
+
|
| 375 |
+
Use `status {project_id}` anytime.
|
| 376 |
+
We'll contact you within 24 hours. 🚀"""
|
| 377 |
+
elif "cancel" in msg_lower:
|
| 378 |
+
del user_sessions[session_id]
|
| 379 |
+
return "❌ Cancelled. Start again with 'I want to build a website'."
|
| 380 |
+
elif "add more" in msg_lower:
|
| 381 |
+
session["step"] = "asking_extra"
|
| 382 |
+
extra_services = get_extra_services()
|
| 383 |
+
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 384 |
+
return f"✨ **Add more extras**\n\nAvailable:\n{extra_list}\n\nType name or **done**."
|
| 385 |
+
else:
|
| 386 |
+
return "Please reply **Confirm**, **Cancel**, or **add more**."
|
| 387 |
+
|
| 388 |
+
return None
|
| 389 |
+
|
| 390 |
+
# ---------- Main Response Handler ----------
|
| 391 |
def get_final_response(user_message, session_id):
|
| 392 |
+
# 1. Project status query
|
| 393 |
status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
|
| 394 |
if status_match:
|
| 395 |
pid = status_match.group(1).upper()
|
|
|
|
| 400 |
emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
|
| 401 |
msg = proj.get("admin_message", "")
|
| 402 |
extra = f"\n📝 **Admin note:** {msg}" if msg else ""
|
|
|
|
| 403 |
submission_date = proj.get("submission_date")
|
| 404 |
can_request_update = False
|
| 405 |
if submission_date and status not in ["completed", "declined"]:
|
|
|
|
| 410 |
if proj.get("update_requested"):
|
| 411 |
update_info = f"\n🔄 **Update requested:** {proj.get('update_details', '')}\nStatus: {'Pending approval' if proj.get('update_approved') is None else ('Approved' if proj.get('update_approved') else 'Rejected')}"
|
| 412 |
elif can_request_update:
|
| 413 |
+
update_info = f"\n\n📝 You can request changes within 3 days of submission. Type:\n`request update {pid}: your change details`"
|
|
|
|
| 414 |
if proj.get("update_approved") is True and proj.get("updated_price"):
|
| 415 |
price = proj.get("updated_price")
|
| 416 |
timeline = proj.get("updated_timeline")
|
|
|
|
| 420 |
timeline = proj.get("calculated_timeline", 0)
|
| 421 |
return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}{update_info}\nTotal: PKR {price:,}\nTimeline: {timeline} days"
|
| 422 |
|
| 423 |
+
# 2. Update request
|
| 424 |
+
req_match = re.search(r'request update\s+([A-Z0-9\-]+):\s*(.+)', user_message, re.IGNORECASE)
|
| 425 |
+
if req_match:
|
| 426 |
+
pid = req_match.group(1).upper()
|
| 427 |
+
details = req_match.group(2).strip()
|
| 428 |
+
if request_project_update(pid, details):
|
| 429 |
+
return f"✅ Update request submitted for project `{pid}`. Admin will review within 24 hours."
|
| 430 |
+
else:
|
| 431 |
+
return f"❌ Cannot request update for `{pid}`. Either it doesn't exist or the 3‑day window has passed."
|
| 432 |
+
|
| 433 |
+
# 3. Step builder
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
step_resp = process_step_by_step(session_id, user_message)
|
| 435 |
if step_resp:
|
| 436 |
return step_resp
|
| 437 |
|
| 438 |
+
# 4. AI or fallback
|
| 439 |
+
ai_resp = call_openrouter(user_message)
|
| 440 |
+
if ai_resp:
|
| 441 |
+
return ai_resp
|
| 442 |
+
return simple_response(user_message)
|
|
|
|
| 443 |
|
| 444 |
+
# ---------- Admin API Routes ----------
|
| 445 |
@app.route('/api/projects', methods=['GET'])
|
| 446 |
def get_projects():
|
| 447 |
snap = ref.child("projects").get()
|
|
|
|
| 470 |
new_req = data.get('requirements', {})
|
| 471 |
if approve_update(project_id, new_req):
|
| 472 |
return jsonify({"message": "Update approved and applied"})
|
| 473 |
+
return jsonify({"error": "Project not found"}), 404
|
|
|
|
| 474 |
|
| 475 |
@app.route('/api/project/<project_id>/update/reject', methods=['POST'])
|
| 476 |
def reject_update_route(project_id):
|