Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,8 @@ from datetime import datetime
|
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
import uuid
|
| 10 |
import re
|
|
|
|
|
|
|
| 11 |
|
| 12 |
app = Flask(__name__)
|
| 13 |
|
|
@@ -19,13 +21,96 @@ 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 |
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 27 |
print("✅ Embedding model loaded")
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# ---------- Helper: Load extra services from Firebase ----------
|
| 30 |
def get_extra_services():
|
| 31 |
snap = ref.child("extra_services").get()
|
|
@@ -119,30 +204,6 @@ def update_project_status(project_id, status, decline_reason=None):
|
|
| 119 |
def update_project_message(project_id, message):
|
| 120 |
ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})
|
| 121 |
|
| 122 |
-
# ---------- AI Helpers for Dynamic Deep Questions ----------
|
| 123 |
-
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 124 |
-
OPENROUTER_MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 125 |
-
|
| 126 |
-
def call_ai(prompt):
|
| 127 |
-
"""Call OpenRouter (Gemini) or fallback to a simple rule if key missing."""
|
| 128 |
-
if OPENROUTER_API_KEY:
|
| 129 |
-
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 130 |
-
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 131 |
-
payload = {
|
| 132 |
-
"model": OPENROUTER_MODEL,
|
| 133 |
-
"messages": [{"role": "user", "content": prompt}],
|
| 134 |
-
"temperature": 0.7,
|
| 135 |
-
"max_tokens": 200
|
| 136 |
-
}
|
| 137 |
-
try:
|
| 138 |
-
resp = requests.post(url, json=payload, headers=headers, timeout=10)
|
| 139 |
-
resp.raise_for_status()
|
| 140 |
-
return resp.json()["choices"][0]["message"]["content"].strip()
|
| 141 |
-
except Exception as e:
|
| 142 |
-
print(f"OpenRouter error: {e}")
|
| 143 |
-
# Fallback: return a generic deep question
|
| 144 |
-
return "Could you please provide more details about your target audience or business goals?"
|
| 145 |
-
|
| 146 |
# ---------- Step Builder with Validation ----------
|
| 147 |
user_sessions = {}
|
| 148 |
|
|
@@ -153,7 +214,6 @@ def is_start_project_request(text):
|
|
| 153 |
|
| 154 |
def process_step_by_step(session_id, message):
|
| 155 |
msg_lower = message.lower().strip()
|
| 156 |
-
# Start new session
|
| 157 |
if session_id not in user_sessions:
|
| 158 |
if is_start_project_request(message):
|
| 159 |
user_sessions[session_id] = {
|
|
@@ -161,8 +221,8 @@ def process_step_by_step(session_id, message):
|
|
| 161 |
"requirements": {},
|
| 162 |
"deep_answers": {},
|
| 163 |
"deep_index": 0,
|
| 164 |
-
"max_deep_rounds":
|
| 165 |
-
"deep_questions": []
|
| 166 |
}
|
| 167 |
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 168 |
return None
|
|
@@ -171,58 +231,32 @@ def process_step_by_step(session_id, message):
|
|
| 171 |
step = session.get("step")
|
| 172 |
req = session.get("requirements", {})
|
| 173 |
|
| 174 |
-
#
|
| 175 |
-
def is_valid_domain_answer(ans):
|
| 176 |
-
return ans.lower() in ["yes", "no", "han", "nahi"]
|
| 177 |
-
|
| 178 |
def is_valid_pages_answer(ans):
|
| 179 |
try:
|
| 180 |
-
|
| 181 |
-
return pages >= 1
|
| 182 |
except:
|
| 183 |
return False
|
| 184 |
-
|
| 185 |
-
def is_valid_yes_no(ans):
|
| 186 |
-
return ans.lower() in ["yes", "no", "han", "nahi"]
|
| 187 |
-
|
| 188 |
def is_valid_extra_feature_name(ans):
|
| 189 |
-
if ans.lower() in ["none", "done", "no"]:
|
| 190 |
-
return True
|
| 191 |
extra_services = get_extra_services()
|
| 192 |
for val in extra_services.values():
|
| 193 |
if val.get("name", "").lower() in ans.lower() or ans.lower() in val.get("name", "").lower():
|
| 194 |
return True
|
| 195 |
return False
|
|
|
|
|
|
|
| 196 |
|
| 197 |
-
|
| 198 |
-
return len(ans.strip()) > 0 # any non-empty
|
| 199 |
-
|
| 200 |
-
def is_valid_theme(ans):
|
| 201 |
-
return len(ans.strip()) > 0
|
| 202 |
-
|
| 203 |
-
def is_valid_content(ans):
|
| 204 |
-
return True # any answer is fine
|
| 205 |
-
|
| 206 |
-
def is_valid_inventory(ans):
|
| 207 |
-
return ans.lower() in ["yes", "no", "han", "nahi", "skip", "none"]
|
| 208 |
-
|
| 209 |
-
def is_valid_database(ans):
|
| 210 |
-
return ans.lower() in ["yes", "no", "han", "nahi", "skip", "none"]
|
| 211 |
-
|
| 212 |
-
def is_valid_mobile(ans):
|
| 213 |
-
return re.search(r'\d{10,15}', ans) is not None
|
| 214 |
-
|
| 215 |
-
def is_valid_email(ans):
|
| 216 |
-
return "@" in ans and "." in ans
|
| 217 |
-
|
| 218 |
-
# ---------- Handle "add more" command ----------
|
| 219 |
if msg_lower in ["add more", "add something", "extra add"]:
|
| 220 |
session["step"] = "asking_extra"
|
| 221 |
extra_services = get_extra_services()
|
| 222 |
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 223 |
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 224 |
|
| 225 |
-
#
|
| 226 |
if step == "asking_domain":
|
| 227 |
if not is_valid_domain_answer(message):
|
| 228 |
return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🌐 Do you need a domain name?"
|
|
@@ -272,7 +306,6 @@ def process_step_by_step(session_id, message):
|
|
| 272 |
# Move to dynamic deep questioning
|
| 273 |
session["step"] = "asking_deep"
|
| 274 |
session["deep_index"] = 0
|
| 275 |
-
# Generate first deep question using AI
|
| 276 |
prompt = f"""You are an expert project estimator. Based on the following client requirements, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).
|
| 277 |
|
| 278 |
Current requirements:
|
|
@@ -280,7 +313,10 @@ Current requirements:
|
|
| 280 |
|
| 281 |
Generated question:"""
|
| 282 |
first_q = call_ai(prompt)
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
| 284 |
return first_q
|
| 285 |
else:
|
| 286 |
if not is_valid_extra_feature_name(message):
|
|
@@ -304,9 +340,8 @@ Generated question:"""
|
|
| 304 |
return f"❌ Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**."
|
| 305 |
|
| 306 |
elif step == "asking_deep":
|
| 307 |
-
# Save the answer to the current deep question
|
| 308 |
idx = session.get("deep_index", 0)
|
| 309 |
-
if idx >= session.get("max_deep_rounds",
|
| 310 |
# No more deep questions, move to additional info
|
| 311 |
session["step"] = "asking_additional"
|
| 312 |
session["additional_index"] = 0
|
|
@@ -319,13 +354,12 @@ Generated question:"""
|
|
| 319 |
]
|
| 320 |
return session["additional_questions"][0]["question"]
|
| 321 |
else:
|
| 322 |
-
# Store
|
| 323 |
if "deep_answers" not in session:
|
| 324 |
session["deep_answers"] = {}
|
| 325 |
session["deep_answers"][f"deep_{idx}"] = message
|
| 326 |
session["deep_index"] = idx + 1
|
| 327 |
-
|
| 328 |
-
if session["deep_index"] < session.get("max_deep_rounds", 3):
|
| 329 |
prompt = f"""You are an expert project estimator. Based on the following client requirements and previous answers, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Keep your question concise (one sentence).
|
| 330 |
|
| 331 |
Current requirements:
|
|
@@ -336,9 +370,10 @@ Previous deep answers:
|
|
| 336 |
|
| 337 |
Generated question:"""
|
| 338 |
next_q = call_ai(prompt)
|
|
|
|
|
|
|
| 339 |
return next_q
|
| 340 |
else:
|
| 341 |
-
# Move to additional info step
|
| 342 |
session["step"] = "asking_additional"
|
| 343 |
session["additional_index"] = 0
|
| 344 |
session["additional_questions"] = [
|
|
@@ -365,7 +400,6 @@ Generated question:"""
|
|
| 365 |
if idx + 1 < len(qlist):
|
| 366 |
return qlist[idx+1]["question"]
|
| 367 |
else:
|
| 368 |
-
# All additional questions done, move to contact
|
| 369 |
session["step"] = "asking_contact"
|
| 370 |
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 371 |
else:
|
|
@@ -384,7 +418,6 @@ Generated question:"""
|
|
| 384 |
session["email"] = message
|
| 385 |
req["mobile"] = session.get("mobile", "")
|
| 386 |
req["email"] = session.get("email", "")
|
| 387 |
-
# Merge additional and deep answers
|
| 388 |
req["additional_answers"] = session.get("additional_answers", {})
|
| 389 |
req["deep_answers"] = session.get("deep_answers", {})
|
| 390 |
session["requirements"] = req
|
|
@@ -490,9 +523,41 @@ def get_final_response(user_message, session_id):
|
|
| 490 |
if pkg:
|
| 491 |
return pkg
|
| 492 |
|
|
|
|
| 493 |
return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"
|
| 494 |
|
| 495 |
-
# ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
@app.route('/api/projects', methods=['GET'])
|
| 497 |
def get_projects():
|
| 498 |
snap = ref.child("projects").get()
|
|
@@ -502,10 +567,9 @@ def get_projects():
|
|
| 502 |
def update_status(project_id):
|
| 503 |
data = request.json
|
| 504 |
status = data.get('status')
|
| 505 |
-
reason = data.get('reason', '')
|
| 506 |
if status not in ['pending', 'in-progress', 'completed', 'declined']:
|
| 507 |
return jsonify({"error": "Invalid status"}), 400
|
| 508 |
-
update_project_status(project_id, status
|
| 509 |
return jsonify({"message": "Status updated"})
|
| 510 |
|
| 511 |
@app.route('/api/project/<project_id>/message', methods=['PUT'])
|
|
@@ -560,24 +624,6 @@ def delete_service(key):
|
|
| 560 |
ref.child(f"extra_services/{key}").delete()
|
| 561 |
return jsonify({"message": "Service deleted"})
|
| 562 |
|
| 563 |
-
# ---------- Main chat endpoint ----------
|
| 564 |
-
@app.route('/api/chat', methods=['POST'])
|
| 565 |
-
def chat():
|
| 566 |
-
data = request.json
|
| 567 |
-
message = data.get('message', '')
|
| 568 |
-
session_id = data.get('session_id', str(uuid.uuid4()))
|
| 569 |
-
if not message:
|
| 570 |
-
return jsonify({"reply": "Please say something."})
|
| 571 |
-
reply = get_final_response(message, session_id)
|
| 572 |
-
# Save chat history
|
| 573 |
-
ref.child(f"chats/{session_id}/messages").push().set({
|
| 574 |
-
"role": "user", "content": message, "timestamp": datetime.now().isoformat()
|
| 575 |
-
})
|
| 576 |
-
ref.child(f"chats/{session_id}/messages").push().set({
|
| 577 |
-
"role": "assistant", "content": reply, "timestamp": datetime.now().isoformat()
|
| 578 |
-
})
|
| 579 |
-
return jsonify({"reply": reply, "session_id": session_id})
|
| 580 |
-
|
| 581 |
@app.route('/')
|
| 582 |
def index():
|
| 583 |
return send_from_directory('.', 'index.html')
|
|
|
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
import uuid
|
| 10 |
import re
|
| 11 |
+
import torch
|
| 12 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 13 |
|
| 14 |
app = Flask(__name__)
|
| 15 |
|
|
|
|
| 21 |
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
|
| 22 |
cred = credentials.Certificate(service_account_info)
|
| 23 |
firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
| 24 |
+
ref = firebase_admin.db.reference('/')
|
| 25 |
print("✅ Firebase connected")
|
| 26 |
|
| 27 |
+
# ---------- Sentence-Transformer ----------
|
| 28 |
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 29 |
print("✅ Embedding model loaded")
|
| 30 |
|
| 31 |
+
# ---------- Local GPT‑2 Setup (fallback for when OpenRouter fails) ----------
|
| 32 |
+
print("🔄 Loading local GPT‑2 model (fallback)...")
|
| 33 |
+
try:
|
| 34 |
+
gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 35 |
+
gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 36 |
+
gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
|
| 37 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 38 |
+
gpt_model = gpt_model.to(device)
|
| 39 |
+
print("✅ GPT‑2 loaded successfully (free, unlimited, always works)")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"⚠️ GPT‑2 load failed: {e}")
|
| 42 |
+
gpt_model = None
|
| 43 |
+
gpt_tokenizer = None
|
| 44 |
+
|
| 45 |
+
# ---------- Helper: Call OpenRouter (primary) or GPT‑2 (fallback) ----------
|
| 46 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 47 |
+
OPENROUTER_MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 48 |
+
|
| 49 |
+
def call_ai(prompt):
|
| 50 |
+
"""Try OpenRouter first; if fails, use local GPT‑2."""
|
| 51 |
+
# Try OpenRouter
|
| 52 |
+
if OPENROUTER_API_KEY:
|
| 53 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 54 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 55 |
+
payload = {
|
| 56 |
+
"model": OPENROUTER_MODEL,
|
| 57 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 58 |
+
"temperature": 0.7,
|
| 59 |
+
"max_tokens": 200
|
| 60 |
+
}
|
| 61 |
+
try:
|
| 62 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=10)
|
| 63 |
+
if resp.status_code == 200:
|
| 64 |
+
return resp.json()["choices"][0]["message"]["content"].strip()
|
| 65 |
+
else:
|
| 66 |
+
print(f"OpenRouter error status {resp.status_code}: {resp.text}")
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"OpenRouter exception: {e}")
|
| 69 |
+
# Fallback to GPT‑2
|
| 70 |
+
if gpt_model is not None:
|
| 71 |
+
inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
|
| 72 |
+
if torch.cuda.is_available():
|
| 73 |
+
inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
| 74 |
+
outputs = gpt_model.generate(
|
| 75 |
+
**inputs,
|
| 76 |
+
max_new_tokens=100,
|
| 77 |
+
do_sample=True,
|
| 78 |
+
temperature=0.7,
|
| 79 |
+
repetition_penalty=1.2,
|
| 80 |
+
pad_token_id=gpt_tokenizer.eos_token_id
|
| 81 |
+
)
|
| 82 |
+
return gpt_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 83 |
+
return "Could you please provide more details about your project?"
|
| 84 |
+
|
| 85 |
+
# ---------- IP Detection & Session Storage ----------
|
| 86 |
+
def get_client_ip():
|
| 87 |
+
if request.headers.get('X-Forwarded-For'):
|
| 88 |
+
ip = request.headers.get('X-Forwarded-For').split(',')[0]
|
| 89 |
+
else:
|
| 90 |
+
ip = request.remote_addr
|
| 91 |
+
return ip
|
| 92 |
+
|
| 93 |
+
def store_ip_for_session(session_id):
|
| 94 |
+
ip = get_client_ip()
|
| 95 |
+
ref.child(f"sessions/{session_id}/ip").set(ip)
|
| 96 |
+
ref.child(f"sessions/{session_id}/last_seen").set(datetime.now().isoformat())
|
| 97 |
+
|
| 98 |
+
# ---------- Chat History Functions ----------
|
| 99 |
+
def save_message(session_id, role, content, intent=None):
|
| 100 |
+
ref.child(f"chats/{session_id}/messages").push().set({
|
| 101 |
+
"role": role,
|
| 102 |
+
"content": content,
|
| 103 |
+
"timestamp": datetime.now().isoformat(),
|
| 104 |
+
"intent": intent
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
def get_chat_history(session_id):
|
| 108 |
+
snap = ref.child(f"chats/{session_id}/messages").order_by_child("timestamp").get()
|
| 109 |
+
if not snap:
|
| 110 |
+
return []
|
| 111 |
+
messages = list(snap.values())
|
| 112 |
+
return sorted(messages, key=lambda x: x.get("timestamp", ""))
|
| 113 |
+
|
| 114 |
# ---------- Helper: Load extra services from Firebase ----------
|
| 115 |
def get_extra_services():
|
| 116 |
snap = ref.child("extra_services").get()
|
|
|
|
| 204 |
def update_project_message(project_id, message):
|
| 205 |
ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})
|
| 206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
# ---------- Step Builder with Validation ----------
|
| 208 |
user_sessions = {}
|
| 209 |
|
|
|
|
| 214 |
|
| 215 |
def process_step_by_step(session_id, message):
|
| 216 |
msg_lower = message.lower().strip()
|
|
|
|
| 217 |
if session_id not in user_sessions:
|
| 218 |
if is_start_project_request(message):
|
| 219 |
user_sessions[session_id] = {
|
|
|
|
| 221 |
"requirements": {},
|
| 222 |
"deep_answers": {},
|
| 223 |
"deep_index": 0,
|
| 224 |
+
"max_deep_rounds": 2,
|
| 225 |
+
"deep_questions": []
|
| 226 |
}
|
| 227 |
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 228 |
return None
|
|
|
|
| 231 |
step = session.get("step")
|
| 232 |
req = session.get("requirements", {})
|
| 233 |
|
| 234 |
+
# Validation functions
|
| 235 |
+
def is_valid_domain_answer(ans): return ans.lower() in ["yes", "no", "han", "nahi"]
|
|
|
|
|
|
|
| 236 |
def is_valid_pages_answer(ans):
|
| 237 |
try:
|
| 238 |
+
return int(ans) >= 1
|
|
|
|
| 239 |
except:
|
| 240 |
return False
|
| 241 |
+
def is_valid_yes_no(ans): return ans.lower() in ["yes", "no", "han", "nahi"]
|
|
|
|
|
|
|
|
|
|
| 242 |
def is_valid_extra_feature_name(ans):
|
| 243 |
+
if ans.lower() in ["none", "done", "no"]: return True
|
|
|
|
| 244 |
extra_services = get_extra_services()
|
| 245 |
for val in extra_services.values():
|
| 246 |
if val.get("name", "").lower() in ans.lower() or ans.lower() in val.get("name", "").lower():
|
| 247 |
return True
|
| 248 |
return False
|
| 249 |
+
def is_valid_mobile(ans): return re.search(r'\d{10,15}', ans) is not None
|
| 250 |
+
def is_valid_email(ans): return "@" in ans and "." in ans
|
| 251 |
|
| 252 |
+
# Handle "add more"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
if msg_lower in ["add more", "add something", "extra add"]:
|
| 254 |
session["step"] = "asking_extra"
|
| 255 |
extra_services = get_extra_services()
|
| 256 |
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 257 |
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 258 |
|
| 259 |
+
# Step handlers
|
| 260 |
if step == "asking_domain":
|
| 261 |
if not is_valid_domain_answer(message):
|
| 262 |
return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🌐 Do you need a domain name?"
|
|
|
|
| 306 |
# Move to dynamic deep questioning
|
| 307 |
session["step"] = "asking_deep"
|
| 308 |
session["deep_index"] = 0
|
|
|
|
| 309 |
prompt = f"""You are an expert project estimator. Based on the following client requirements, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).
|
| 310 |
|
| 311 |
Current requirements:
|
|
|
|
| 313 |
|
| 314 |
Generated question:"""
|
| 315 |
first_q = call_ai(prompt)
|
| 316 |
+
# In case GPT‑2 returns a too‑long answer, we truncate
|
| 317 |
+
if len(first_q) > 300:
|
| 318 |
+
first_q = first_q[:300] + "..."
|
| 319 |
+
session["deep_questions"] = [first_q]
|
| 320 |
return first_q
|
| 321 |
else:
|
| 322 |
if not is_valid_extra_feature_name(message):
|
|
|
|
| 340 |
return f"❌ Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**."
|
| 341 |
|
| 342 |
elif step == "asking_deep":
|
|
|
|
| 343 |
idx = session.get("deep_index", 0)
|
| 344 |
+
if idx >= session.get("max_deep_rounds", 2):
|
| 345 |
# No more deep questions, move to additional info
|
| 346 |
session["step"] = "asking_additional"
|
| 347 |
session["additional_index"] = 0
|
|
|
|
| 354 |
]
|
| 355 |
return session["additional_questions"][0]["question"]
|
| 356 |
else:
|
| 357 |
+
# Store answer
|
| 358 |
if "deep_answers" not in session:
|
| 359 |
session["deep_answers"] = {}
|
| 360 |
session["deep_answers"][f"deep_{idx}"] = message
|
| 361 |
session["deep_index"] = idx + 1
|
| 362 |
+
if session["deep_index"] < session.get("max_deep_rounds", 2):
|
|
|
|
| 363 |
prompt = f"""You are an expert project estimator. Based on the following client requirements and previous answers, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Keep your question concise (one sentence).
|
| 364 |
|
| 365 |
Current requirements:
|
|
|
|
| 370 |
|
| 371 |
Generated question:"""
|
| 372 |
next_q = call_ai(prompt)
|
| 373 |
+
if len(next_q) > 300:
|
| 374 |
+
next_q = next_q[:300] + "..."
|
| 375 |
return next_q
|
| 376 |
else:
|
|
|
|
| 377 |
session["step"] = "asking_additional"
|
| 378 |
session["additional_index"] = 0
|
| 379 |
session["additional_questions"] = [
|
|
|
|
| 400 |
if idx + 1 < len(qlist):
|
| 401 |
return qlist[idx+1]["question"]
|
| 402 |
else:
|
|
|
|
| 403 |
session["step"] = "asking_contact"
|
| 404 |
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 405 |
else:
|
|
|
|
| 418 |
session["email"] = message
|
| 419 |
req["mobile"] = session.get("mobile", "")
|
| 420 |
req["email"] = session.get("email", "")
|
|
|
|
| 421 |
req["additional_answers"] = session.get("additional_answers", {})
|
| 422 |
req["deep_answers"] = session.get("deep_answers", {})
|
| 423 |
session["requirements"] = req
|
|
|
|
| 523 |
if pkg:
|
| 524 |
return pkg
|
| 525 |
|
| 526 |
+
# General fallback (not used often because step builder handles most cases)
|
| 527 |
return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"
|
| 528 |
|
| 529 |
+
# ---------- API Routes ----------
|
| 530 |
+
@app.route('/api/chat', methods=['POST'])
|
| 531 |
+
def chat():
|
| 532 |
+
data = request.json
|
| 533 |
+
message = data.get('message', '')
|
| 534 |
+
session_id = data.get('session_id', str(uuid.uuid4()))
|
| 535 |
+
if not message:
|
| 536 |
+
return jsonify({"reply": "Please say something."})
|
| 537 |
+
|
| 538 |
+
# Store IP for this session
|
| 539 |
+
store_ip_for_session(session_id)
|
| 540 |
+
|
| 541 |
+
reply = get_final_response(message, session_id)
|
| 542 |
+
save_message(session_id, "user", message)
|
| 543 |
+
save_message(session_id, "assistant", reply)
|
| 544 |
+
return jsonify({"reply": reply, "session_id": session_id})
|
| 545 |
+
|
| 546 |
+
@app.route('/api/history', methods=['GET'])
|
| 547 |
+
def history():
|
| 548 |
+
session_id = request.args.get('session_id')
|
| 549 |
+
if not session_id:
|
| 550 |
+
return jsonify({"error": "Missing session_id"}), 400
|
| 551 |
+
messages = get_chat_history(session_id)
|
| 552 |
+
return jsonify({"messages": messages})
|
| 553 |
+
|
| 554 |
+
@app.route('/api/get_ip', methods=['GET'])
|
| 555 |
+
def get_ip():
|
| 556 |
+
session_id = request.args.get('session_id')
|
| 557 |
+
if session_id:
|
| 558 |
+
store_ip_for_session(session_id)
|
| 559 |
+
return jsonify({"ip": get_client_ip()})
|
| 560 |
+
|
| 561 |
@app.route('/api/projects', methods=['GET'])
|
| 562 |
def get_projects():
|
| 563 |
snap = ref.child("projects").get()
|
|
|
|
| 567 |
def update_status(project_id):
|
| 568 |
data = request.json
|
| 569 |
status = data.get('status')
|
|
|
|
| 570 |
if status not in ['pending', 'in-progress', 'completed', 'declined']:
|
| 571 |
return jsonify({"error": "Invalid status"}), 400
|
| 572 |
+
update_project_status(project_id, status)
|
| 573 |
return jsonify({"message": "Status updated"})
|
| 574 |
|
| 575 |
@app.route('/api/project/<project_id>/message', methods=['PUT'])
|
|
|
|
| 624 |
ref.child(f"extra_services/{key}").delete()
|
| 625 |
return jsonify({"message": "Service deleted"})
|
| 626 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
@app.route('/')
|
| 628 |
def index():
|
| 629 |
return send_from_directory('.', 'index.html')
|