Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,220 +1,345 @@
|
|
|
|
|
| 1 |
from flask import Flask, request, jsonify, send_from_directory
|
|
|
|
|
|
|
|
|
|
| 2 |
import firebase_admin
|
| 3 |
from firebase_admin import credentials, db
|
| 4 |
-
import
|
| 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 |
-
# ----------
|
| 15 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 16 |
if not firebase_service_account_json:
|
| 17 |
-
raise ValueError("FIREBASE_SERVICE_ACCOUNT
|
|
|
|
| 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, {
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 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 |
-
# ----------
|
| 159 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 160 |
-
|
| 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":
|
| 169 |
try:
|
| 170 |
-
resp = requests.post(
|
| 171 |
resp.raise_for_status()
|
| 172 |
return resp.json()["choices"][0]["message"]["content"]
|
| 173 |
-
except
|
| 174 |
return None
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
@app.route('/')
|
| 215 |
def index():
|
| 216 |
return send_from_directory('.', 'index.html')
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
if __name__ == '__main__':
|
| 219 |
port = int(os.environ.get('PORT', 7860))
|
| 220 |
app.run(host='0.0.0.0', port=port)
|
|
|
|
| 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 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
+
CORS(app)
|
| 12 |
|
| 13 |
+
# ------------------- FIREBASE ADMIN -------------------
|
| 14 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 15 |
if not firebase_service_account_json:
|
| 16 |
+
raise ValueError("FIREBASE_SERVICE_ACCOUNT missing")
|
| 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 |
+
'databaseURL': 'https://YOUR-PROJECT-default-rtdb.firebaseio.com' # CHANGE THIS
|
| 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 |
def call_openrouter(prompt):
|
| 48 |
if not OPENROUTER_API_KEY:
|
| 49 |
return None
|
|
|
|
| 50 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 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 |
+
# ------------------- PROJECT MANAGEMENT -------------------
|
| 60 |
+
def generate_project_id():
|
| 61 |
+
return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}"
|
| 62 |
+
|
| 63 |
+
def create_project(user_id, requirements):
|
| 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
|
| 96 |
+
BASE_TIMELINE = 10 # days
|
| 97 |
+
|
| 98 |
+
def calculate_price_and_timeline(requirements):
|
| 99 |
+
pages = requirements.get("pages", 5)
|
| 100 |
+
domain = requirements.get("domain", False)
|
| 101 |
+
ecommerce = requirements.get("ecommerce", False)
|
| 102 |
+
chatbot = requirements.get("chatbot", False)
|
| 103 |
+
seo = requirements.get("seo", False)
|
| 104 |
+
extra_features = requirements.get("extra_features", [])
|
| 105 |
+
|
| 106 |
+
price = BASE_PRICE
|
| 107 |
+
timeline = BASE_TIMELINE
|
| 108 |
+
|
| 109 |
+
if pages > BASE_PAGES:
|
| 110 |
+
price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE
|
| 111 |
+
timeline += (pages - BASE_PAGES) * 1
|
| 112 |
+
|
| 113 |
+
if domain:
|
| 114 |
+
price += 5000
|
| 115 |
+
timeline += 1
|
| 116 |
+
|
| 117 |
+
if ecommerce:
|
| 118 |
+
price += 50000
|
| 119 |
+
timeline += 10
|
| 120 |
+
|
| 121 |
+
if chatbot:
|
| 122 |
+
price += 30000
|
| 123 |
+
timeline += 5
|
| 124 |
+
|
| 125 |
+
if seo:
|
| 126 |
+
price += 25000
|
| 127 |
+
timeline += 5
|
| 128 |
+
|
| 129 |
+
for feature in extra_features:
|
| 130 |
+
if feature == "live_chat":
|
| 131 |
+
price += 20000
|
| 132 |
+
timeline += 3
|
| 133 |
+
elif feature == "booking_system":
|
| 134 |
+
price += 35000
|
| 135 |
+
timeline += 5
|
| 136 |
+
elif feature == "multi_language":
|
| 137 |
+
price += 25000
|
| 138 |
+
timeline += 4
|
| 139 |
+
|
| 140 |
+
return price, timeline
|
| 141 |
+
|
| 142 |
+
# ------------------- CHATBOT INTENT & RESPONSE -------------------
|
| 143 |
+
user_sessions = {} # user_id -> {"step": "asking_pages", "requirements": {...}}
|
| 144 |
|
| 145 |
+
def process_chat(user_id, message):
|
| 146 |
+
msg_lower = message.lower()
|
| 147 |
+
|
| 148 |
+
# Check if user is in active session
|
| 149 |
+
if user_id in user_sessions:
|
| 150 |
+
session = user_sessions[user_id]
|
| 151 |
+
step = session.get("step", "start")
|
| 152 |
+
req = session.get("requirements", {})
|
| 153 |
+
|
| 154 |
+
if step == "asking_domain":
|
| 155 |
+
if "yes" in msg_lower or "han" in msg_lower or "chahiye" in msg_lower:
|
| 156 |
+
req["domain"] = True
|
| 157 |
+
else:
|
| 158 |
+
req["domain"] = False
|
| 159 |
+
session["step"] = "asking_pages"
|
| 160 |
+
session["requirements"] = req
|
| 161 |
+
return "📄 **How many pages do you need?** (Minimum 5, extra pages will cost additional PKR 5,000 each)\n\nType a number like: 5, 10, 15"
|
| 162 |
+
|
| 163 |
+
elif step == "asking_pages":
|
| 164 |
+
try:
|
| 165 |
+
pages = int(re.search(r'\d+', msg_lower).group())
|
| 166 |
+
req["pages"] = max(pages, 5)
|
| 167 |
+
except:
|
| 168 |
+
req["pages"] = 5
|
| 169 |
+
session["step"] = "asking_ecommerce"
|
| 170 |
+
session["requirements"] = req
|
| 171 |
+
return "🛒 **Do you need e‑commerce functionality?** (Shopping cart, payment gateway)\n\nReply: Yes or No"
|
| 172 |
+
|
| 173 |
+
elif step == "asking_ecommerce":
|
| 174 |
+
req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
|
| 175 |
+
session["step"] = "asking_chatbot"
|
| 176 |
+
session["requirements"] = req
|
| 177 |
+
return "🤖 **Do you want an AI chatbot on your website?** (Like this one)\n\nReply: Yes or No"
|
| 178 |
+
|
| 179 |
+
elif step == "asking_chatbot":
|
| 180 |
+
req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
|
| 181 |
+
session["step"] = "asking_seo"
|
| 182 |
+
session["requirements"] = req
|
| 183 |
+
return "🔍 **Do you need SEO optimization?** (To rank on Google)\n\nReply: Yes or No"
|
| 184 |
+
|
| 185 |
+
elif step == "asking_seo":
|
| 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 |
+
elif step == "asking_extra":
|
| 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'}
|
| 213 |
+
• Pages: {req.get('pages', 5)}
|
| 214 |
+
• E-commerce: {'Yes' if req.get('ecommerce') else 'No'}
|
| 215 |
+
• AI Chatbot: {'Yes' if req.get('chatbot') else 'No'}
|
| 216 |
+
• SEO: {'Yes' if req.get('seo') else 'No'}
|
| 217 |
+
• Extra features: {', '.join(extra_features) if extra_features else 'None'}
|
| 218 |
+
|
| 219 |
+
💰 **Total Cost:** PKR {price:,}
|
| 220 |
+
⏱️ **Estimated Timeline:** {timeline} working days
|
| 221 |
+
|
| 222 |
+
❓ Do you agree with this proposal? (Reply: Confirm / Cancel)"""
|
| 223 |
+
return proposal
|
| 224 |
+
|
| 225 |
+
elif step == "confirm":
|
| 226 |
+
if "confirm" in msg_lower or "agree" in msg_lower or "yes" in msg_lower:
|
| 227 |
+
# Create project
|
| 228 |
+
project_id = create_project(user_id, req)
|
| 229 |
+
del user_sessions[user_id]
|
| 230 |
+
return f"""✅ **Project Confirmed!**
|
| 231 |
+
|
| 232 |
+
Your Project ID: `{project_id}`
|
| 233 |
+
|
| 234 |
+
You can use this ID anytime to check your project status.
|
| 235 |
+
Just type: `status {project_id}`
|
| 236 |
+
|
| 237 |
+
Our team will contact you within 24 hours.
|
| 238 |
+
Thank you for choosing Elite Visuals! 🚀"""
|
| 239 |
+
elif "cancel" in msg_lower or "no" in msg_lower:
|
| 240 |
+
del user_sessions[user_id]
|
| 241 |
+
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"
|
| 242 |
+
else:
|
| 243 |
+
return "Please reply **Confirm** to proceed or **Cancel** to cancel the proposal."
|
| 244 |
+
|
| 245 |
+
else:
|
| 246 |
+
# Fallback - start new session
|
| 247 |
+
del user_sessions[user_id]
|
| 248 |
+
return "Let's start over. Tell me about your website requirements."
|
| 249 |
+
|
| 250 |
+
# Check for project status query
|
| 251 |
+
status_match = re.search(r'status\s+([A-Z0-9\-]+)', msg_lower, re.IGNORECASE)
|
| 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 |
+
answer = call_openrouter(prompt)
|
| 299 |
+
if not answer:
|
| 300 |
+
answer = local_answer(prompt)
|
| 301 |
+
return answer[:500]
|
| 302 |
+
|
| 303 |
+
# ------------------- FLASK ROUTES -------------------
|
| 304 |
@app.route('/')
|
| 305 |
def index():
|
| 306 |
return send_from_directory('.', 'index.html')
|
| 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()
|
| 327 |
+
return jsonify({"projects": projects})
|
| 328 |
+
|
| 329 |
+
@app.route('/api/project/<project_id>', methods=['GET'])
|
| 330 |
+
def get_project_route(project_id):
|
| 331 |
+
project = get_project(project_id)
|
| 332 |
+
return jsonify({"project": project})
|
| 333 |
+
|
| 334 |
+
@app.route('/api/project/<project_id>/status', methods=['PUT'])
|
| 335 |
+
def update_status(project_id):
|
| 336 |
+
data = request.json
|
| 337 |
+
status = data.get('status')
|
| 338 |
+
if status not in ['pending', 'in-progress', 'completed']:
|
| 339 |
+
return jsonify({"error": "Invalid status"}), 400
|
| 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)
|