Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,95 +1,36 @@
|
|
| 1 |
-
import os, json, uuid, re, requests, torch
|
| 2 |
from flask import Flask, request, jsonify, send_from_directory
|
| 3 |
-
from flask_cors import CORS
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
from sentence_transformers import SentenceTransformer
|
| 6 |
import firebase_admin
|
| 7 |
from firebase_admin import credentials, db
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
-
CORS(app)
|
| 12 |
|
| 13 |
-
# ----------
|
| 14 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 15 |
if not firebase_service_account_json:
|
| 16 |
-
raise ValueError("FIREBASE_SERVICE_ACCOUNT
|
| 17 |
-
|
| 18 |
service_account_info = json.loads(firebase_service_account_json)
|
|
|
|
| 19 |
cred = credentials.Certificate(service_account_info)
|
| 20 |
-
firebase_admin.initialize_app(cred, {
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
db_ref = firebase_admin.db.reference('/')
|
| 24 |
-
|
| 25 |
-
# ------------------- SENTENCE BERT -------------------
|
| 26 |
-
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 27 |
-
|
| 28 |
-
# ------------------- LOCAL GPT-2 FALLBACK -------------------
|
| 29 |
-
gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 30 |
-
gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 31 |
-
gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
|
| 32 |
-
if torch.cuda.is_available():
|
| 33 |
-
gpt_model = gpt_model.to("cuda")
|
| 34 |
-
|
| 35 |
-
def local_answer(prompt):
|
| 36 |
-
inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
|
| 37 |
-
if torch.cuda.is_available():
|
| 38 |
-
inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
| 39 |
-
outputs = gpt_model.generate(**inputs, max_new_tokens=200, do_sample=False, temperature=0.3)
|
| 40 |
-
full = gpt_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 41 |
-
return full.strip()
|
| 42 |
-
|
| 43 |
-
# ------------------- OPENROUTER -------------------
|
| 44 |
-
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 45 |
-
OPENROUTER_MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
payload = {"model": OPENROUTER_MODEL, "messages": [{"role": "user", "content": prompt}], "temperature": 0.3, "max_tokens": 500}
|
| 52 |
-
try:
|
| 53 |
-
resp = requests.post("https://openrouter.ai/api/v1/chat/completions", json=payload, headers=headers, timeout=15)
|
| 54 |
-
resp.raise_for_status()
|
| 55 |
-
return resp.json()["choices"][0]["message"]["content"]
|
| 56 |
-
except:
|
| 57 |
-
return None
|
| 58 |
|
| 59 |
-
# ----------
|
| 60 |
-
|
| 61 |
-
return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}"
|
| 62 |
|
| 63 |
-
|
| 64 |
-
project_id = generate_project_id()
|
| 65 |
-
project_data = {
|
| 66 |
-
"project_id": project_id,
|
| 67 |
-
"user_id": user_id,
|
| 68 |
-
"requirements": requirements,
|
| 69 |
-
"status": "pending",
|
| 70 |
-
"created_at": datetime.now().isoformat(),
|
| 71 |
-
"updated_at": datetime.now().isoformat()
|
| 72 |
-
}
|
| 73 |
-
db_ref.child(f"projects/{project_id}").set(project_data)
|
| 74 |
-
return project_id
|
| 75 |
-
|
| 76 |
-
def update_project_status(project_id, status):
|
| 77 |
-
db_ref.child(f"projects/{project_id}").update({"status": status, "updated_at": datetime.now().isoformat()})
|
| 78 |
-
|
| 79 |
-
def get_project(project_id):
|
| 80 |
-
snap = db_ref.child(f"projects/{project_id}").get()
|
| 81 |
-
return snap
|
| 82 |
-
|
| 83 |
-
def get_all_projects():
|
| 84 |
-
snap = db_ref.child("projects").get()
|
| 85 |
-
if not snap:
|
| 86 |
-
return []
|
| 87 |
-
projects = []
|
| 88 |
-
for key, val in snap.items():
|
| 89 |
-
projects.append(val)
|
| 90 |
-
return projects
|
| 91 |
-
|
| 92 |
-
# ------------------- PRICING & TIMELINE HELPERS -------------------
|
| 93 |
BASE_PRICE = 50000
|
| 94 |
BASE_PAGES = 5
|
| 95 |
EXTRA_PAGE_PRICE = 5000
|
|
@@ -139,74 +80,104 @@ def calculate_price_and_timeline(requirements):
|
|
| 139 |
|
| 140 |
return price, timeline
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
-
|
| 186 |
-
req["seo"] = "yes" in msg_lower or "han" in msg_lower
|
| 187 |
-
session["step"] = "asking_extra"
|
| 188 |
-
session["requirements"] = req
|
| 189 |
-
return "β¨ **Any extra features?** (Type numbers separated by commas)\n1: Live Chat (+PKR 20,000, +3 days)\n2: Booking System (+PKR 35,000, +5 days)\n3: MultiβLanguage (+PKR 25,000, +4 days)\n4: None / Done\n\nExample: 1,3"
|
| 190 |
|
| 191 |
-
|
| 192 |
-
extra_features = []
|
| 193 |
-
if "1" in msg_lower or "live" in msg_lower:
|
| 194 |
-
extra_features.append("live_chat")
|
| 195 |
-
if "2" in msg_lower or "booking" in msg_lower:
|
| 196 |
-
extra_features.append("booking_system")
|
| 197 |
-
if "3" in msg_lower or "multi" in msg_lower:
|
| 198 |
-
extra_features.append("multi_language")
|
| 199 |
-
req["extra_features"] = extra_features
|
| 200 |
-
session["step"] = "confirm"
|
| 201 |
-
session["requirements"] = req
|
| 202 |
-
|
| 203 |
-
# Calculate price and timeline
|
| 204 |
-
price, timeline = calculate_price_and_timeline(req)
|
| 205 |
-
req["calculated_price"] = price
|
| 206 |
-
req["calculated_timeline"] = timeline
|
| 207 |
-
|
| 208 |
-
# Generate proposal
|
| 209 |
-
proposal = f"""π **Your Project Proposal**
|
| 210 |
|
| 211 |
β
**Requirements Summary:**
|
| 212 |
β’ Domain: {'Yes' if req.get('domain') else 'No'}
|
|
@@ -219,108 +190,218 @@ def process_chat(user_id, message):
|
|
| 219 |
π° **Total Cost:** PKR {price:,}
|
| 220 |
β±οΈ **Estimated Timeline:** {timeline} working days
|
| 221 |
|
| 222 |
-
β Do you agree with this proposal? (Reply: Confirm
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
| 231 |
|
| 232 |
Your Project ID: `{project_id}`
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
Our team will contact you within 24 hours.
|
| 238 |
Thank you for choosing Elite Visuals! π"""
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
else:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
# Check for project status query
|
| 251 |
-
status_match = re.search(r'status\s+([A-Z0-9\-]+)',
|
| 252 |
if status_match:
|
| 253 |
project_id = status_match.group(1).upper()
|
| 254 |
project = get_project(project_id)
|
| 255 |
if project:
|
| 256 |
status = project.get("status", "pending")
|
| 257 |
status_emoji = "β³" if status == "pending" else "π" if status == "in-progress" else "β
"
|
|
|
|
|
|
|
| 258 |
return f"""π¦ **Project Status**
|
| 259 |
|
| 260 |
Project ID: `{project_id}`
|
| 261 |
Status: {status_emoji} {status.upper()}
|
|
|
|
|
|
|
| 262 |
Created: {project.get('created_at', 'N/A')}
|
| 263 |
-
Last Updated: {project.get('updated_at', 'N/A')}
|
| 264 |
|
| 265 |
-
π¬ For more details, contact support
|
| 266 |
else:
|
| 267 |
-
return f"β Project ID `{project_id}` not found. Please check and try again."
|
| 268 |
-
|
| 269 |
-
# Check for "new project" or "build website" intent
|
| 270 |
-
if any(phrase in msg_lower for phrase in ["website banwani", "build website", "new project", "website chahiye", "project start"]):
|
| 271 |
-
user_sessions[user_id] = {"step": "asking_domain", "requirements": {}}
|
| 272 |
-
return "π **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: Yes or No"
|
| 273 |
-
|
| 274 |
-
# General help
|
| 275 |
-
if "hello" in msg_lower or "salam" in msg_lower or "hi" in msg_lower:
|
| 276 |
-
return """π **Assalam-o-Alaikum!**
|
| 277 |
-
|
| 278 |
-
I'm Elite Visuals AI assistant. I can help you plan your website project.
|
| 279 |
-
|
| 280 |
-
**Commands:**
|
| 281 |
-
β’ Type "I want to build a website" to start a new project
|
| 282 |
-
β’ Type "status PROJ-XXXX" to check your project status
|
| 283 |
-
β’ For special requests, contact admin: +92 300 1234567
|
| 284 |
-
|
| 285 |
-
Let's get started! Tell me about your website requirements."""
|
| 286 |
-
|
| 287 |
-
# Contact
|
| 288 |
-
if "contact" in msg_lower or "number" in msg_lower or "call" in msg_lower:
|
| 289 |
-
return "π **Contact Us:**\nβ’ Phone: +92 300 1234567\nβ’ Email: hello@elitevisuals.com\nβ’ Hours: Mon-Sat, 10am-7pm"
|
| 290 |
-
|
| 291 |
-
# Fallback using LLM
|
| 292 |
-
prompt = f"""You are Elite Visuals AI assistant. User asked: "{message}"
|
| 293 |
-
|
| 294 |
-
If user wants to build a website, guide them to say "I want to build a website".
|
| 295 |
-
If they ask about pricing, tell them to start a project for exact quote.
|
| 296 |
-
Keep answer short (2-3 lines). Reply directly:"""
|
| 297 |
|
| 298 |
-
|
| 299 |
-
if
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
@app.route('/admin')
|
| 309 |
-
def admin():
|
| 310 |
-
return send_from_directory('.', 'admin.html')
|
| 311 |
-
|
| 312 |
-
@app.route('/api/chat', methods=['POST'])
|
| 313 |
-
def chat():
|
| 314 |
-
data = request.json
|
| 315 |
-
user_id = data.get('user_id')
|
| 316 |
-
message = data.get('message', '').strip()
|
| 317 |
-
if not user_id:
|
| 318 |
-
user_id = str(uuid.uuid4())
|
| 319 |
-
if not message:
|
| 320 |
-
return jsonify({"reply": "Please say something."})
|
| 321 |
-
reply = process_chat(user_id, message)
|
| 322 |
-
return jsonify({"reply": reply, "user_id": user_id})
|
| 323 |
-
|
| 324 |
@app.route('/api/projects', methods=['GET'])
|
| 325 |
def get_projects():
|
| 326 |
projects = get_all_projects()
|
|
@@ -340,6 +421,44 @@ def update_status(project_id):
|
|
| 340 |
update_project_status(project_id, status)
|
| 341 |
return jsonify({"message": "Status updated"})
|
| 342 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
if __name__ == '__main__':
|
| 344 |
port = int(os.environ.get('PORT', 7860))
|
| 345 |
app.run(host='0.0.0.0', port=port)
|
|
|
|
|
|
|
| 1 |
from flask import Flask, request, jsonify, send_from_directory
|
|
|
|
|
|
|
|
|
|
| 2 |
import firebase_admin
|
| 3 |
from firebase_admin import credentials, db
|
| 4 |
+
import requests
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
from datetime import datetime
|
| 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.")
|
|
|
|
| 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)
|
| 21 |
+
firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
| 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 |
+
# ---------- User Sessions for Step-by-Step Requirements ----------
|
| 31 |
+
user_sessions = {} # session_id -> {"step": "asking_domain", "requirements": {}}
|
|
|
|
| 32 |
|
| 33 |
+
# ---------- Pricing & Timeline Helpers ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
BASE_PRICE = 50000
|
| 35 |
BASE_PAGES = 5
|
| 36 |
EXTRA_PAGE_PRICE = 5000
|
|
|
|
| 80 |
|
| 81 |
return price, timeline
|
| 82 |
|
| 83 |
+
def generate_project_id():
|
| 84 |
+
return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}"
|
| 85 |
+
|
| 86 |
+
def create_project(session_id, requirements):
|
| 87 |
+
project_id = generate_project_id()
|
| 88 |
+
price, timeline = calculate_price_and_timeline(requirements)
|
| 89 |
+
project_data = {
|
| 90 |
+
"project_id": project_id,
|
| 91 |
+
"session_id": session_id,
|
| 92 |
+
"requirements": requirements,
|
| 93 |
+
"calculated_price": price,
|
| 94 |
+
"calculated_timeline": timeline,
|
| 95 |
+
"status": "pending",
|
| 96 |
+
"created_at": datetime.now().isoformat(),
|
| 97 |
+
"updated_at": datetime.now().isoformat()
|
| 98 |
+
}
|
| 99 |
+
ref.child(f"projects/{project_id}").set(project_data)
|
| 100 |
+
return project_id, price, timeline
|
| 101 |
+
|
| 102 |
+
def get_project(project_id):
|
| 103 |
+
return ref.child(f"projects/{project_id}").get()
|
| 104 |
+
|
| 105 |
+
def get_all_projects():
|
| 106 |
+
snap = ref.child("projects").get()
|
| 107 |
+
if not snap:
|
| 108 |
+
return []
|
| 109 |
+
projects = []
|
| 110 |
+
for key, val in snap.items():
|
| 111 |
+
projects.append(val)
|
| 112 |
+
return projects
|
| 113 |
+
|
| 114 |
+
def update_project_status(project_id, status):
|
| 115 |
+
ref.child(f"projects/{project_id}").update({"status": status, "updated_at": datetime.now().isoformat()})
|
| 116 |
|
| 117 |
+
# ---------- Step-by-Step Requirement Collection ----------
|
| 118 |
+
def process_step_by_step(session_id, message):
|
| 119 |
+
msg_lower = message.lower().strip()
|
| 120 |
|
| 121 |
+
if session_id not in user_sessions:
|
| 122 |
+
# Check if user wants to start new project
|
| 123 |
+
if any(phrase in msg_lower for phrase in ["website banwani", "build website", "new project", "website chahiye", "start project"]):
|
| 124 |
+
user_sessions[session_id] = {"step": "asking_domain", "requirements": {}}
|
| 125 |
+
return "π **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 126 |
+
return None # Not in project creation mode
|
| 127 |
+
|
| 128 |
+
session = user_sessions[session_id]
|
| 129 |
+
step = session.get("step")
|
| 130 |
+
req = session.get("requirements", {})
|
| 131 |
+
|
| 132 |
+
if step == "asking_domain":
|
| 133 |
+
req["domain"] = "yes" in msg_lower or "han" in msg_lower
|
| 134 |
+
session["step"] = "asking_pages"
|
| 135 |
+
session["requirements"] = req
|
| 136 |
+
return "π **How many pages do you need?** (Minimum 5, extra pages +PKR 5,000 each)\n\nType a number like: **5**, **10**, **15**"
|
| 137 |
+
|
| 138 |
+
elif step == "asking_pages":
|
| 139 |
+
try:
|
| 140 |
+
pages = int(re.search(r'\d+', msg_lower).group())
|
| 141 |
+
req["pages"] = max(pages, 5)
|
| 142 |
+
except:
|
| 143 |
+
req["pages"] = 5
|
| 144 |
+
session["step"] = "asking_ecommerce"
|
| 145 |
+
session["requirements"] = req
|
| 146 |
+
return "π **Do you need eβcommerce functionality?** (Shopping cart, payment gateway)\n\nReply: **Yes** or **No**"
|
| 147 |
+
|
| 148 |
+
elif step == "asking_ecommerce":
|
| 149 |
+
req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
|
| 150 |
+
session["step"] = "asking_chatbot"
|
| 151 |
+
session["requirements"] = req
|
| 152 |
+
return "π€ **Do you want an AI chatbot on your website?**\n\nReply: **Yes** or **No**"
|
| 153 |
+
|
| 154 |
+
elif step == "asking_chatbot":
|
| 155 |
+
req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
|
| 156 |
+
session["step"] = "asking_seo"
|
| 157 |
+
session["requirements"] = req
|
| 158 |
+
return "π **Do you need SEO optimization?** (To rank on Google)\n\nReply: **Yes** or **No**"
|
| 159 |
+
|
| 160 |
+
elif step == "asking_seo":
|
| 161 |
+
req["seo"] = "yes" in msg_lower or "han" in msg_lower
|
| 162 |
+
session["step"] = "asking_extra"
|
| 163 |
+
session["requirements"] = req
|
| 164 |
+
return "β¨ **Any extra features?** (Type numbers separated by commas)\n\n**1** - Live Chat (+PKR 20,000, +3 days)\n**2** - Booking System (+PKR 35,000, +5 days)\n**3** - Multi-Language (+PKR 25,000, +4 days)\n**4** - None / Done\n\nExample: **1,3**"
|
| 165 |
+
|
| 166 |
+
elif step == "asking_extra":
|
| 167 |
+
extra_features = []
|
| 168 |
+
if "1" in msg_lower or "live" in msg_lower:
|
| 169 |
+
extra_features.append("live_chat")
|
| 170 |
+
if "2" in msg_lower or "booking" in msg_lower:
|
| 171 |
+
extra_features.append("booking_system")
|
| 172 |
+
if "3" in msg_lower or "multi" in msg_lower:
|
| 173 |
+
extra_features.append("multi_language")
|
| 174 |
+
req["extra_features"] = extra_features
|
| 175 |
+
session["step"] = "confirm"
|
| 176 |
+
session["requirements"] = req
|
| 177 |
|
| 178 |
+
price, timeline = calculate_price_and_timeline(req)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
+
proposal = f"""π **Your Project Proposal**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
β
**Requirements Summary:**
|
| 183 |
β’ Domain: {'Yes' if req.get('domain') else 'No'}
|
|
|
|
| 190 |
π° **Total Cost:** PKR {price:,}
|
| 191 |
β±οΈ **Estimated Timeline:** {timeline} working days
|
| 192 |
|
| 193 |
+
β **Do you agree with this proposal?** (Reply: **Confirm** or **Cancel**)
|
| 194 |
+
|
| 195 |
+
β οΈ *If you disagree, please contact admin: +92 300 1234567*"""
|
| 196 |
+
return proposal
|
| 197 |
+
|
| 198 |
+
elif step == "confirm":
|
| 199 |
+
if "confirm" in msg_lower or "agree" in msg_lower or "yes" in msg_lower:
|
| 200 |
+
project_id, price, timeline = create_project(session_id, req)
|
| 201 |
+
del user_sessions[session_id]
|
| 202 |
+
return f"""β
**Project Confirmed!**
|
| 203 |
|
| 204 |
Your Project ID: `{project_id}`
|
| 205 |
|
| 206 |
+
π **Use this ID to check your project status anytime.**
|
| 207 |
+
Type: `status {project_id}`
|
| 208 |
+
|
| 209 |
+
π° Total Cost: PKR {price:,}
|
| 210 |
+
β±οΈ Timeline: {timeline} working days
|
| 211 |
|
| 212 |
Our team will contact you within 24 hours.
|
| 213 |
Thank you for choosing Elite Visuals! π"""
|
| 214 |
+
elif "cancel" in msg_lower or "no" in msg_lower:
|
| 215 |
+
del user_sessions[session_id]
|
| 216 |
+
return "β Project cancelled. If you change your mind, just say **'I want to build a website'** again.\n\nπ For special requests, contact admin: +92 300 1234567"
|
| 217 |
+
else:
|
| 218 |
+
return "Please reply **Confirm** to proceed or **Cancel** to cancel the proposal."
|
| 219 |
+
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
# ---------- Static Data for Existing Chatbot Features ----------
|
| 223 |
+
SERVICE_PACKAGES = {
|
| 224 |
+
"basic": {"name": "Basic Website", "price": "PKR 50,000", "timeline": "7-10 days",
|
| 225 |
+
"features": ["5 pages", "responsive", "basic SEO", "contact form", "social links"]},
|
| 226 |
+
"standard": {"name": "Standard Website", "price": "PKR 1,20,000", "timeline": "15-20 days",
|
| 227 |
+
"features": ["10 pages", "CMS", "advanced SEO", "blog", "chatbot", "1 month support"]},
|
| 228 |
+
"premium": {"name": "Premium Website", "price": "PKR 2,50,000", "timeline": "25-30 days",
|
| 229 |
+
"features": ["unlimited pages", "e-commerce", "payment gateway", "user accounts", "custom animations", "6 months support"]}
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
EXTRA_FEATURES = {
|
| 233 |
+
"live chat": {"price": "+ PKR 20,000", "timeline": "+ 3 days"},
|
| 234 |
+
"booking system": {"price": "+ PKR 35,000", "timeline": "+ 5 days"},
|
| 235 |
+
"multi-language": {"price": "+ PKR 25,000", "timeline": "+ 4 days"},
|
| 236 |
+
"custom backend": {"price": "+ PKR 1,00,000+", "timeline": "+ 15 days"}
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
ALL_SERVICES = ["Website Design", "E-commerce Setup", "SEO Optimization", "Chatbot Integration", "Maintenance", "Content Writing", "Graphic Design", "Digital Marketing"]
|
| 240 |
+
|
| 241 |
+
# ---------- Intent Classification ----------
|
| 242 |
+
IRRELEVANT = ["weather", "cricket", "politics", "imran", "nawaz", "stock", "bitcoin", "covid"]
|
| 243 |
+
|
| 244 |
+
def classify_intent(text):
|
| 245 |
+
t = text.lower()
|
| 246 |
+
if any(k in t for k in IRRELEVANT):
|
| 247 |
+
return "irrelevant"
|
| 248 |
+
if any(x in t for x in ["contact", "phone", "number", "whatsapp", "email", "call"]):
|
| 249 |
+
return "contact"
|
| 250 |
+
if any(x in t for x in ["price", "cost", "rate", "kitne", "quote", "charges", "fee", "timeline", "time", "days"]):
|
| 251 |
+
return "pricing_timeline"
|
| 252 |
+
if any(x in t for x in ["basic", "standard", "premium", "package"]):
|
| 253 |
+
return "package"
|
| 254 |
+
if any(x in t for x in ["extra", "additional", "also want", "add", "more", "custom", "live chat", "booking", "multi-language"]):
|
| 255 |
+
return "custom_request"
|
| 256 |
+
if any(x in t for x in ["service", "ecommerce", "seo", "chatbot", "maintenance", "marketing", "design"]):
|
| 257 |
+
return "service_inquiry"
|
| 258 |
+
if any(x in t for x in ["portfolio", "sample", "gallery"]):
|
| 259 |
+
return "portfolio"
|
| 260 |
+
if any(x in t for x in ["salam", "hello", "hi", "hey"]):
|
| 261 |
+
return "greeting"
|
| 262 |
+
return "general"
|
| 263 |
+
|
| 264 |
+
def detect_package(text):
|
| 265 |
+
t = text.lower()
|
| 266 |
+
if "basic" in t:
|
| 267 |
+
return "basic"
|
| 268 |
+
if "standard" in t:
|
| 269 |
+
return "standard"
|
| 270 |
+
if "premium" in t:
|
| 271 |
+
return "premium"
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
def detect_extra_feature(text):
|
| 275 |
+
t = text.lower()
|
| 276 |
+
for feat in EXTRA_FEATURES:
|
| 277 |
+
if feat in t:
|
| 278 |
+
return feat
|
| 279 |
+
return None
|
| 280 |
+
|
| 281 |
+
# ---------- Response Generator (with structured data) ----------
|
| 282 |
+
def get_response_and_data(user_message, intent):
|
| 283 |
+
data = {
|
| 284 |
+
"package": None,
|
| 285 |
+
"price": None,
|
| 286 |
+
"timeline": None,
|
| 287 |
+
"features": None,
|
| 288 |
+
"extra_feature": None,
|
| 289 |
+
"extra_cost": None,
|
| 290 |
+
"extra_timeline": None,
|
| 291 |
+
"service": None
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
if intent == "contact":
|
| 295 |
+
reply = "- π Phone: +92 300 1234567\n- βοΈ Email: hello@elitevisuals.com\n- π Website: www.elitevisuals.com"
|
| 296 |
+
elif intent == "pricing_timeline":
|
| 297 |
+
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)"
|
| 298 |
+
elif intent == "package":
|
| 299 |
+
pkg = detect_package(user_message)
|
| 300 |
+
if pkg and pkg in SERVICE_PACKAGES:
|
| 301 |
+
p = SERVICE_PACKAGES[pkg]
|
| 302 |
+
data["package"] = p["name"]
|
| 303 |
+
data["price"] = p["price"]
|
| 304 |
+
data["timeline"] = p["timeline"]
|
| 305 |
+
data["features"] = p["features"]
|
| 306 |
+
features = "\n β’ ".join(p["features"])
|
| 307 |
+
reply = f"**{p['name']}** β {p['price']}, {p['timeline']}\nβ
Includes:\n β’ {features}"
|
| 308 |
+
else:
|
| 309 |
+
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)"
|
| 310 |
+
elif intent == "custom_request":
|
| 311 |
+
extra = detect_extra_feature(user_message)
|
| 312 |
+
if extra:
|
| 313 |
+
info = EXTRA_FEATURES[extra]
|
| 314 |
+
data["extra_feature"] = extra
|
| 315 |
+
data["extra_cost"] = info["price"]
|
| 316 |
+
data["extra_timeline"] = info["timeline"]
|
| 317 |
+
reply = f"- β
{extra.title()} feature available.\n- π° Additional cost: {info['price']}\n- β±οΈ Timeline increase: {info['timeline']}\n- π‘ Custom quote possible."
|
| 318 |
else:
|
| 319 |
+
reply = "- β
Custom requirements handled.\n- π° Extra features increase price/timeline.\n- π Send your requirement for free quote."
|
| 320 |
+
elif intent == "service_inquiry":
|
| 321 |
+
if "ecommerce" in user_message.lower():
|
| 322 |
+
data["service"] = "E-commerce Website"
|
| 323 |
+
data["price"] = "Starting PKR 1,50,000"
|
| 324 |
+
data["timeline"] = "20-30 days"
|
| 325 |
+
reply = "- β
E-commerce websites with payment gateway.\n- π° Starting PKR 1,50,000\n- β±οΈ 20-30 days"
|
| 326 |
+
elif "seo" in user_message.lower():
|
| 327 |
+
data["service"] = "SEO Optimization"
|
| 328 |
+
data["price"] = "PKR 25,000/month"
|
| 329 |
+
data["timeline"] = "ongoing"
|
| 330 |
+
reply = "- β
SEO (on-page, off-page, technical).\n- π° PKR 25,000/month\n- β±οΈ Results in 2-3 months"
|
| 331 |
+
elif "chatbot" in user_message.lower():
|
| 332 |
+
data["service"] = "Chatbot Integration"
|
| 333 |
+
data["price"] = "PKR 30,000 one-time + PKR 5,000/month"
|
| 334 |
+
data["timeline"] = "7-10 days"
|
| 335 |
+
reply = "- β
Custom AI chatbot integration.\n- π° PKR 30,000 setup + PKR 5,000/month\n- β±οΈ 7-10 days"
|
| 336 |
+
else:
|
| 337 |
+
services = "\n β’ ".join(ALL_SERVICES)
|
| 338 |
+
reply = f"- Services:\n β’ {services}\n- Ask about specific service."
|
| 339 |
+
elif intent == "portfolio":
|
| 340 |
+
reply = "- π· Instagram: @elitevisuals\n- π₯οΈ Gallery: www.elitevisuals.com/work"
|
| 341 |
+
elif intent == "greeting":
|
| 342 |
+
reply = "- Wa-Alaikum-Assalam! π\n- I help with websites, e-commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**\n- Ask about packages or extra features."
|
| 343 |
+
elif intent == "irrelevant":
|
| 344 |
+
reply = "- β Out of scope. I only answer web & digital services."
|
| 345 |
+
else:
|
| 346 |
+
reply = "- How can I help? Services: website design, e-commerce, SEO, chatbots, maintenance.\n- **To start a project, say 'I want to build a website'**"
|
| 347 |
+
|
| 348 |
+
return reply, data
|
| 349 |
+
|
| 350 |
+
# ---------- OpenRouter (optional) ----------
|
| 351 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 352 |
+
MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 353 |
+
SYSTEM_PROMPT = """You are Elite Visuals AI assistant. Answer in bullet points. Include price and timeline when relevant."""
|
| 354 |
+
|
| 355 |
+
def call_openrouter(prompt):
|
| 356 |
+
if not OPENROUTER_API_KEY:
|
| 357 |
+
return None
|
| 358 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 359 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 360 |
+
payload = {"model": MODEL, "messages": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}], "temperature": 0.7, "max_tokens": 300}
|
| 361 |
+
try:
|
| 362 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=10)
|
| 363 |
+
resp.raise_for_status()
|
| 364 |
+
return resp.json()["choices"][0]["message"]["content"]
|
| 365 |
+
except Exception:
|
| 366 |
+
return None
|
| 367 |
+
|
| 368 |
+
def get_final_response(user_message, intent, session_id):
|
| 369 |
+
# First, check if this is part of step-by-step project builder
|
| 370 |
+
step_response = process_step_by_step(session_id, user_message)
|
| 371 |
+
if step_response:
|
| 372 |
+
return step_response, {}
|
| 373 |
|
| 374 |
# Check for project status query
|
| 375 |
+
status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower(), re.IGNORECASE)
|
| 376 |
if status_match:
|
| 377 |
project_id = status_match.group(1).upper()
|
| 378 |
project = get_project(project_id)
|
| 379 |
if project:
|
| 380 |
status = project.get("status", "pending")
|
| 381 |
status_emoji = "β³" if status == "pending" else "π" if status == "in-progress" else "β
"
|
| 382 |
+
price = project.get("calculated_price", 0)
|
| 383 |
+
timeline = project.get("calculated_timeline", 0)
|
| 384 |
return f"""π¦ **Project Status**
|
| 385 |
|
| 386 |
Project ID: `{project_id}`
|
| 387 |
Status: {status_emoji} {status.upper()}
|
| 388 |
+
Total Cost: PKR {price:,}
|
| 389 |
+
Timeline: {timeline} days
|
| 390 |
Created: {project.get('created_at', 'N/A')}
|
|
|
|
| 391 |
|
| 392 |
+
π¬ For more details, contact support: +92 300 1234567""", {}
|
| 393 |
else:
|
| 394 |
+
return f"β Project ID `{project_id}` not found. Please check and try again.", {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
|
| 396 |
+
# Normal intent-based response
|
| 397 |
+
if OPENROUTER_API_KEY:
|
| 398 |
+
ai_reply = call_openrouter(user_message)
|
| 399 |
+
if ai_reply and len(ai_reply) > 20:
|
| 400 |
+
reply, data = get_response_and_data(user_message, intent)
|
| 401 |
+
return ai_reply, data
|
| 402 |
+
return get_response_and_data(user_message, intent)
|
| 403 |
+
|
| 404 |
+
# ---------- Admin API Routes ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
@app.route('/api/projects', methods=['GET'])
|
| 406 |
def get_projects():
|
| 407 |
projects = get_all_projects()
|
|
|
|
| 421 |
update_project_status(project_id, status)
|
| 422 |
return jsonify({"message": "Status updated"})
|
| 423 |
|
| 424 |
+
# ---------- Existing Chat API ----------
|
| 425 |
+
@app.route('/api/chat', methods=['POST'])
|
| 426 |
+
def chat():
|
| 427 |
+
data_req = request.get_json()
|
| 428 |
+
user_message = data_req.get('message', '')
|
| 429 |
+
session_id = data_req.get('session_id', str(uuid.uuid4()))
|
| 430 |
+
if not user_message:
|
| 431 |
+
return jsonify({"error": "No message"}), 400
|
| 432 |
+
|
| 433 |
+
intent = classify_intent(user_message)
|
| 434 |
+
print(f"π― [{session_id[:8]}] Intent: {intent}")
|
| 435 |
+
|
| 436 |
+
reply, structured = get_final_response(user_message, intent, session_id)
|
| 437 |
+
|
| 438 |
+
# Save message to chat history (existing functionality)
|
| 439 |
+
save_message(session_id, "user", user_message, intent)
|
| 440 |
+
save_message(session_id, "assistant", reply)
|
| 441 |
+
|
| 442 |
+
return jsonify({
|
| 443 |
+
"reply": reply,
|
| 444 |
+
"intent": intent,
|
| 445 |
+
"session_id": session_id,
|
| 446 |
+
"widget": structured
|
| 447 |
+
})
|
| 448 |
+
|
| 449 |
+
def save_message(session_id, role, content, intent=None):
|
| 450 |
+
ref.child(f"chats/{session_id}/messages").push().set({
|
| 451 |
+
"role": role, "content": content, "timestamp": datetime.now().isoformat(), "intent": intent
|
| 452 |
+
})
|
| 453 |
+
|
| 454 |
+
@app.route('/')
|
| 455 |
+
def index():
|
| 456 |
+
return send_from_directory('.', 'index.html')
|
| 457 |
+
|
| 458 |
+
@app.route('/admin')
|
| 459 |
+
def admin():
|
| 460 |
+
return send_from_directory('.', 'admin.html')
|
| 461 |
+
|
| 462 |
if __name__ == '__main__':
|
| 463 |
port = int(os.environ.get('PORT', 7860))
|
| 464 |
app.run(host='0.0.0.0', port=port)
|