Ahmad140 commited on
Commit
7102d02
·
verified ·
1 Parent(s): 434ea69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +782 -85
app.py CHANGED
@@ -1,96 +1,793 @@
1
- price, timeline = calculate_price_and_timeline(req)
2
- extra_services = get_extra_services()
3
- extra_features_list = req.get("extra_features", [])
4
-
5
- # ----- Itemized Services -----
6
- items = []
7
-
8
- # Domain
9
- if req.get("domain"):
10
- items.append("• Domain Registration: PKR 5,000")
11
-
12
- # Pages (base 5 included, extra pages cost)
13
- pages = req.get("pages", 5)
14
- if pages > 5:
15
- extra_pages = pages - 5
16
- extra_cost = extra_pages * 5000
17
- items.append(f"• {extra_pages} extra page(s): +PKR {extra_cost:,}")
18
-
19
- # E‑commerce
20
- if req.get("ecommerce"):
21
- items.append("• E‑commerce Functionality: PKR 50,000")
22
-
23
- # Chatbot
24
- if req.get("chatbot"):
25
- items.append("• AI Chatbot: PKR 30,000")
26
-
27
- # SEO
28
- if req.get("seo"):
29
- items.append("• SEO Optimization: PKR 25,000")
30
-
31
- # Extra features (from Firebase)
32
- for feat_key in extra_features_list:
33
- if feat_key in extra_services:
34
- svc = extra_services[feat_key]
35
- items.append(f"• {svc['name'].title()}: +PKR {svc['price']:,} (timeline +{svc['timeline']} days)")
36
-
37
- # Inventory management (optional)
38
- if req.get("inventory", "").lower() == "yes":
39
- items.append("• Inventory Management: +PKR 30,000 (+5 days)")
40
-
41
- # Database integration (optional)
42
- if req.get("data", "").lower() == "yes":
43
- items.append("• Database Integration: +PKR 40,000 (+8 days)")
44
-
45
- # Convert items to a multi‑line bullet list
46
- itemized_text = "\n".join(items) if items else "• No services selected"
47
-
48
- # ----- Additional info (unchanged) -----
49
- add_answers = session.get("additional_answers", {})
50
- add_text = ""
51
- if any(add_answers.values()):
52
- add_text = "\n\n📌 **Additional Info:**\n"
53
- if add_answers.get("purpose"):
54
- add_text += f"• Purpose: {add_answers['purpose']}\n"
55
- if add_answers.get("theme"):
56
- add_text += f"• Theme: {add_answers['theme']}\n"
57
- if add_answers.get("content"):
58
- add_text += f"• Content: {add_answers['content']}\n"
59
- if add_answers.get("inventory"):
60
- add_text += f"• Inventory Management: {add_answers['inventory']}\n"
61
- if add_answers.get("data"):
62
- add_text += f"• Database Integration: {add_answers['data']}\n"
63
-
64
- # ----- Deep answers (unchanged) -----
65
- deep_answers = session.get("deep_answers", {})
66
- deep_text = ""
67
- if deep_answers:
68
- deep_text = "\n\n📌 **Deep Dive Responses:**\n"
69
- for key, val in deep_answers.items():
70
- deep_text += f"• {key}: {val}\n"
71
-
72
- # ----- Media (unchanged) -----
73
- media_text = ""
74
- if req.get("media_text"):
75
- media_text += f"\n\n📝 **Client Notes:** {req['media_text']}\n"
76
- if req.get("media_image"):
77
- media_text += f"\n🖼️ **Image uploaded** (view in admin panel)\n"
78
-
79
- # ----- Contact details (unchanged) -----
80
- contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"
81
-
82
- # ----- Final proposal -----
83
- proposal = f"""📋 **Your Project Proposal**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  **Selected Services (itemized):**
86
  {itemized_text}
87
 
88
  💰 **Total Cost:** PKR {price:,}
89
- ⏱️ **Timeline:** {timeline} working days
90
  {add_text}{deep_text}{media_text}{contact_text}
91
 
92
  ❓ **Agree?** (Reply: **Confirm** or **Cancel**)
93
 
94
  ⚠️ *To add more extras, type 'add more'*"""
95
 
96
- return proposal
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+ import uuid
10
+ import re
11
+ import torch
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM
13
+
14
+ # Try to load llama-cpp-python (GGUF support)
15
+ try:
16
+ from llama_cpp import Llama
17
+ LLAMA_AVAILABLE = True
18
+ except ImportError:
19
+ LLAMA_AVAILABLE = False
20
+ print("⚠️ llama-cpp-python not installed. Llama fallback unavailable.")
21
+
22
+ app = Flask(__name__)
23
+
24
+ # ---------- Firebase ----------
25
+ firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
26
+ if not firebase_service_account_json:
27
+ raise ValueError("FIREBASE_SERVICE_ACCOUNT secret missing")
28
+ service_account_info = json.loads(firebase_service_account_json)
29
+ database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
30
+ cred = credentials.Certificate(service_account_info)
31
+ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
32
+ ref = firebase_admin.db.reference('/')
33
+ print("✅ Firebase connected")
34
+
35
+ # ---------- Sentence-Transformer ----------
36
+ embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
37
+ print("✅ Embedding model loaded")
38
+
39
+ # ---------- Load Llama 3.2 1B GGUF (if available) ----------
40
+ llama_model = None
41
+ llama_path = os.getenv("LLAMA_GGUF_PATH")
42
+ if LLAMA_AVAILABLE and llama_path and os.path.exists(llama_path):
43
+ try:
44
+ llama_model = Llama(model_path=llama_path, n_ctx=2048, n_threads=2, verbose=False)
45
+ print("✅ Llama 3.2 1B GGUF loaded (fallback)")
46
+ except Exception as e:
47
+ print(f"⚠️ Failed to load Llama GGUF: {e}")
48
+ else:
49
+ print("⚠️ Llama GGUF not configured – will use GPT‑2 fallback if available")
50
+
51
+ # ---------- Load GPT‑2 (final fallback) ----------
52
+ gpt_model = None
53
+ gpt_tokenizer = None
54
+ if not llama_model:
55
+ try:
56
+ gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
57
+ gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
58
+ gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
59
+ if torch.cuda.is_available():
60
+ gpt_model = gpt_model.to("cuda")
61
+ print("✅ GPT‑2 loaded (final fallback)")
62
+ except Exception as e:
63
+ print(f"⚠️ GPT‑2 load failed: {e}")
64
+
65
+ # ---------- AI Call (Groq → Owl Alpha → Gemini → Llama GGUF → GPT‑2 → rule) ----------
66
+ def call_ai(prompt):
67
+ # 1. Groq (fast, free)
68
+ groq_key = os.getenv("GROQ_API_KEY")
69
+ if groq_key:
70
+ url = "https://api.groq.com/openai/v1/chat/completions"
71
+ headers = {"Authorization": f"Bearer {groq_key}", "Content-Type": "application/json"}
72
+ payload = {
73
+ "model": "llama3-8b-8192",
74
+ "messages": [{"role": "user", "content": prompt}],
75
+ "temperature": 0.7,
76
+ "max_tokens": 150
77
+ }
78
+ try:
79
+ resp = requests.post(url, json=payload, headers=headers, timeout=10)
80
+ if resp.status_code == 200:
81
+ return resp.json()["choices"][0]["message"]["content"].strip()
82
+ except Exception as e:
83
+ print(f"Groq error: {e}")
84
+
85
+ # 2. OpenRouter Owl Alpha (primary – free, 1M context)
86
+ openrouter_key = os.getenv("OPENROUTER_API_KEY")
87
+ if openrouter_key:
88
+ url = "https://openrouter.ai/api/v1/chat/completions"
89
+ headers = {"Authorization": f"Bearer {openrouter_key}", "Content-Type": "application/json"}
90
+ payload = {
91
+ "model": "openrouter/owl-alpha",
92
+ "messages": [{"role": "user", "content": prompt}],
93
+ "temperature": 0.7,
94
+ "max_tokens": 150
95
+ }
96
+ try:
97
+ resp = requests.post(url, json=payload, headers=headers, timeout=10)
98
+ if resp.status_code == 200:
99
+ return resp.json()["choices"][0]["message"]["content"].strip()
100
+ except Exception as e:
101
+ print(f"Owl Alpha error: {e}")
102
+
103
+ # 3. OpenRouter Gemini (fallback)
104
+ if openrouter_key:
105
+ url = "https://openrouter.ai/api/v1/chat/completions"
106
+ headers = {"Authorization": f"Bearer {openrouter_key}", "Content-Type": "application/json"}
107
+ payload = {
108
+ "model": "google/gemini-2.0-flash-lite-preview-02-05",
109
+ "messages": [{"role": "user", "content": prompt}],
110
+ "temperature": 0.7,
111
+ "max_tokens": 150
112
+ }
113
+ try:
114
+ resp = requests.post(url, json=payload, headers=headers, timeout=10)
115
+ if resp.status_code == 200:
116
+ return resp.json()["choices"][0]["message"]["content"].strip()
117
+ except Exception as e:
118
+ print(f"Gemini error: {e}")
119
+
120
+ # 4. Llama 3.2 1B GGUF (local)
121
+ if llama_model:
122
+ try:
123
+ output = llama_model.create_chat_completion(
124
+ messages=[{"role": "user", "content": prompt}],
125
+ temperature=0.7,
126
+ max_tokens=150
127
+ )
128
+ return output["choices"][0]["message"]["content"].strip()
129
+ except Exception as e:
130
+ print(f"Llama GGUF error: {e}")
131
+
132
+ # 5. GPT‑2 fallback
133
+ if gpt_model is not None:
134
+ try:
135
+ inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
136
+ if torch.cuda.is_available():
137
+ inputs = {k: v.to("cuda") for k, v in inputs.items()}
138
+ outputs = gpt_model.generate(
139
+ **inputs,
140
+ max_new_tokens=120,
141
+ do_sample=True,
142
+ temperature=0.7,
143
+ repetition_penalty=1.2,
144
+ pad_token_id=gpt_tokenizer.eos_token_id
145
+ )
146
+ response = gpt_tokenizer.decode(outputs[0], skip_special_tokens=True)
147
+ if response.startswith(prompt):
148
+ response = response[len(prompt):].strip()
149
+ return response if response else "What else would you like to share about your project?"
150
+ except Exception as e:
151
+ print(f"GPT‑2 error: {e}")
152
+
153
+ # 6. Ultimate rule‑based
154
+ return "What else would you like to share about your project?"
155
+
156
+ # ---------- Helper: Load extra services from Firebase ----------
157
+ def get_extra_services():
158
+ snap = ref.child("extra_services").get()
159
+ if not snap:
160
+ default = {
161
+ "live_chat": {"name": "live chat", "price": 20000, "timeline": 3, "display": "Live Chat (+PKR 20,000, +3 days)"},
162
+ "booking_system": {"name": "booking system", "price": 35000, "timeline": 5, "display": "Booking System (+PKR 35,000, +5 days)"},
163
+ "multi_language": {"name": "multi-language", "price": 25000, "timeline": 4, "display": "Multi-Language (+PKR 25,000, +4 days)"},
164
+ "custom_backend": {"name": "custom backend", "price": 100000, "timeline": 15, "display": "Custom Backend (+PKR 1,00,000, +15 days)"}
165
+ }
166
+ ref.child("extra_services").set(default)
167
+ return default
168
+ return snap
169
+
170
+ # ---------- Pricing Helpers ----------
171
+ BASE_PRICE = 50000
172
+ BASE_PAGES = 5
173
+ EXTRA_PAGE_PRICE = 5000
174
+ BASE_TIMELINE = 10
175
+
176
+ def calculate_price_and_timeline(req):
177
+ extra_services = get_extra_services()
178
+ pages = req.get("pages", 5)
179
+ domain = req.get("domain", False)
180
+ ecommerce = req.get("ecommerce", False)
181
+ chatbot = req.get("chatbot", False)
182
+ seo = req.get("seo", False)
183
+ extra_features = req.get("extra_features", [])
184
+ inventory = req.get("inventory", "").lower() == "yes"
185
+ database = req.get("data", "").lower() == "yes"
186
+
187
+ price = BASE_PRICE
188
+ timeline = BASE_TIMELINE
189
+ if pages > BASE_PAGES:
190
+ price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE
191
+ timeline += (pages - BASE_PAGES)
192
+ if domain:
193
+ price += 5000
194
+ timeline += 1
195
+ if ecommerce:
196
+ price += 50000
197
+ timeline += 10
198
+ if chatbot:
199
+ price += 30000
200
+ timeline += 5
201
+ if seo:
202
+ price += 25000
203
+ timeline += 5
204
+ for feat in extra_features:
205
+ if feat in extra_services:
206
+ info = extra_services[feat]
207
+ price += info.get("price", 0)
208
+ timeline += info.get("timeline", 0)
209
+ if inventory:
210
+ price += 30000
211
+ timeline += 5
212
+ if database:
213
+ price += 40000
214
+ timeline += 8
215
+ return price, timeline
216
+
217
+ def generate_project_id():
218
+ return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}"
219
+
220
+ def create_project(session_id, requirements):
221
+ project_id = generate_project_id()
222
+ price, timeline = calculate_price_and_timeline(requirements)
223
+ project_data = {
224
+ "project_id": project_id,
225
+ "session_id": session_id,
226
+ "requirements": requirements,
227
+ "calculated_price": price,
228
+ "calculated_timeline": timeline,
229
+ "status": "pending",
230
+ "admin_message": "",
231
+ "created_at": datetime.now().isoformat(),
232
+ "updated_at": datetime.now().isoformat()
233
+ }
234
+ ref.child(f"projects/{project_id}").set(project_data)
235
+ return project_id, price, timeline
236
+
237
+ def get_project(project_id):
238
+ return ref.child(f"projects/{project_id}").get()
239
+
240
+ def update_project_status(project_id, status, decline_reason=None):
241
+ data = {"status": status, "updated_at": datetime.now().isoformat()}
242
+ if decline_reason:
243
+ data["admin_message"] = decline_reason
244
+ ref.child(f"projects/{project_id}").update(data)
245
+
246
+ def update_project_message(project_id, message):
247
+ ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})
248
+
249
+ # ---------- IP & Session ----------
250
+ def get_client_ip():
251
+ if request.headers.get('X-Forwarded-For'):
252
+ ip = request.headers.get('X-Forwarded-For').split(',')[0]
253
+ else:
254
+ ip = request.remote_addr
255
+ return ip
256
+
257
+ def store_ip_for_session(session_id):
258
+ ip = get_client_ip()
259
+ ref.child(f"sessions/{session_id}/ip").set(ip)
260
+ ref.child(f"sessions/{session_id}/last_seen").set(datetime.now().isoformat())
261
+
262
+ def save_message(session_id, role, content, intent=None):
263
+ ref.child(f"chats/{session_id}/messages").push().set({
264
+ "role": role,
265
+ "content": content,
266
+ "timestamp": datetime.now().isoformat(),
267
+ "intent": intent
268
+ })
269
+
270
+ def get_chat_history(session_id):
271
+ snap = ref.child(f"chats/{session_id}/messages").order_by_child("timestamp").get()
272
+ if not snap:
273
+ return []
274
+ messages = list(snap.values())
275
+ return sorted(messages, key=lambda x: x.get("timestamp", ""))
276
+
277
+ # ---------- Step Builder (no auto-add in step answers) ----------
278
+ user_sessions = {}
279
+
280
+ def is_start_project_request(text):
281
+ keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
282
+ "i want to build a website", "web project", "website banana hai", "naya project"]
283
+ return any(k in text.lower() for k in keywords)
284
+
285
+ def process_step_by_step(session_id, message):
286
+ msg_lower = message.lower().strip()
287
+ if session_id not in user_sessions:
288
+ if is_start_project_request(message):
289
+ user_sessions[session_id] = {
290
+ "step": "asking_domain",
291
+ "requirements": {},
292
+ "deep_answers": {},
293
+ "deep_index": 0,
294
+ "max_deep_rounds": 2,
295
+ "deep_questions": []
296
+ }
297
+ return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
298
+ return None
299
+
300
+ session = user_sessions[session_id]
301
+ step = session.get("step")
302
+ req = session.get("requirements", {})
303
+
304
+ def is_valid_domain_answer(ans): return ans.lower() in ["yes", "no", "han", "nahi"]
305
+ def is_valid_pages_answer(ans):
306
+ try:
307
+ return int(ans) >= 1
308
+ except:
309
+ return False
310
+ def is_valid_yes_no(ans): return ans.lower() in ["yes", "no", "han", "nahi"]
311
+ def is_valid_extra_feature_name(ans):
312
+ if ans.lower() in ["none", "done", "no"]: return True
313
+ extra_services = get_extra_services()
314
+ for val in extra_services.values():
315
+ if val.get("name", "").lower() in ans.lower() or ans.lower() in val.get("name", "").lower():
316
+ return True
317
+ return False
318
+ def is_valid_mobile(ans): return re.search(r'\d{10,15}', ans) is not None
319
+ def is_valid_email(ans): return "@" in ans and "." in ans
320
+
321
+ # Handle "add more"
322
+ if msg_lower in ["add more", "add something", "extra add"]:
323
+ session["step"] = "asking_extra"
324
+ extra_services = get_extra_services()
325
+ extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
326
+ return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
327
+
328
+ # Main step handlers (no invoice auto-add here)
329
+ if step == "asking_domain":
330
+ if not is_valid_domain_answer(message):
331
+ return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🌐 Do you need a domain name?"
332
+ req["domain"] = "yes" in msg_lower or "han" in msg_lower
333
+ session["step"] = "asking_pages"
334
+ session["requirements"] = req
335
+ return "📄 **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**"
336
+
337
+ elif step == "asking_pages":
338
+ if not is_valid_pages_answer(message):
339
+ return "❌ Invalid number. Please enter a valid number of pages (minimum 1).\n\n📄 How many pages?"
340
+ pages = int(re.search(r'\d+', msg_lower).group())
341
+ req["pages"] = max(pages, 5)
342
+ session["step"] = "asking_ecommerce"
343
+ session["requirements"] = req
344
+ return "🛒 **Need e‑commerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**"
345
+
346
+ elif step == "asking_ecommerce":
347
+ if not is_valid_yes_no(message):
348
+ return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🛒 Need e‑commerce?"
349
+ req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
350
+ session["step"] = "asking_chatbot"
351
+ session["requirements"] = req
352
+ return "🤖 **AI chatbot on your website?**\n\nReply: **Yes** or **No**"
353
+
354
+ elif step == "asking_chatbot":
355
+ if not is_valid_yes_no(message):
356
+ return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🤖 AI chatbot on your website?"
357
+ req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
358
+ session["step"] = "asking_seo"
359
+ session["requirements"] = req
360
+ return "🔍 **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**"
361
+
362
+ elif step == "asking_seo":
363
+ if not is_valid_yes_no(message):
364
+ return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🔍 SEO optimization?"
365
+ req["seo"] = "yes" in msg_lower or "han" in msg_lower
366
+ session["step"] = "asking_extra"
367
+ session["requirements"] = req
368
+ extra_services = get_extra_services()
369
+ extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
370
+ return f"✨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**."
371
+
372
+ elif step == "asking_extra":
373
+ extra_services = get_extra_services()
374
+ if msg_lower in ["none", "done", "no"]:
375
+ session["step"] = "asking_deep"
376
+ session["deep_index"] = 0
377
+ 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).
378
+
379
+ Current requirements:
380
+ {json.dumps(req, indent=2)}
381
+
382
+ Generated question:"""
383
+ first_q = call_ai(prompt)
384
+ if len(first_q) > 300 or '{' in first_q or '}' in first_q or '```' in first_q:
385
+ first_q = "Could you please provide more details about your target audience or business goals?"
386
+ session["deep_questions"] = [first_q]
387
+ return first_q
388
+ else:
389
+ if not is_valid_extra_feature_name(message):
390
+ available = ', '.join([v['name'] for v in extra_services.values()])
391
+ return f"❌ Sorry, **'{message}'** is not offered. Available: {available}\n\nType a valid name or **done**."
392
+ matched_key = None
393
+ for key, val in extra_services.items():
394
+ if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
395
+ matched_key = key
396
+ break
397
+ if matched_key:
398
+ extra_list = req.get("extra_features", [])
399
+ if matched_key not in extra_list:
400
+ extra_list.append(matched_key)
401
+ req["extra_features"] = extra_list
402
+ session["requirements"] = req
403
+ # This triggers invoice add in the frontend
404
+ return f"✅ Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**."
405
+ else:
406
+ return f"ℹ️ Already added. Type another name or **done**."
407
+ else:
408
+ return f"❌ Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**."
409
+
410
+ elif step == "asking_deep":
411
+ idx = session.get("deep_index", 0)
412
+ if idx < session.get("max_deep_rounds", 2):
413
+ if "deep_answers" not in session:
414
+ session["deep_answers"] = {}
415
+ session["deep_answers"][f"deep_{idx}"] = message
416
+ session["deep_index"] = idx + 1
417
+ if idx + 1 < session.get("max_deep_rounds", 2):
418
+ 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).
419
+
420
+ Current requirements:
421
+ {json.dumps(req, indent=2)}
422
+
423
+ Previous deep answers:
424
+ {json.dumps(session.get("deep_answers", {}), indent=2)}
425
+
426
+ Generated question:"""
427
+ next_q = call_ai(prompt)
428
+ if len(next_q) > 300 or '{' in next_q or '}' in next_q or '```' in next_q:
429
+ next_q = "Is there any specific functionality or integration you consider essential for your project?"
430
+ return next_q
431
+ else:
432
+ session["step"] = "asking_additional"
433
+ session["additional_index"] = 0
434
+ session["additional_questions"] = [
435
+ {"key": "purpose", "question": "📌 **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) – Type **skip** to leave blank."},
436
+ {"key": "theme", "question": "🎨 **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) – Type **skip** or describe."},
437
+ {"key": "content", "question": "📝 **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"},
438
+ {"key": "inventory", "question": "📦 **Do you need inventory management?** (For products, stock tracking) – Yes/No or **skip**."},
439
+ {"key": "data", "question": "🗄️ **Do you need database integration?** (e.g., user accounts, data storage) – Yes/No or **skip**."}
440
+ ]
441
+ return session["additional_questions"][0]["question"]
442
+ else:
443
+ session["step"] = "asking_additional"
444
+ session["additional_index"] = 0
445
+ session["additional_questions"] = [
446
+ {"key": "purpose", "question": "📌 **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) – Type **skip** to leave blank."},
447
+ {"key": "theme", "question": "🎨 **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) – Type **skip** or describe."},
448
+ {"key": "content", "question": "📝 **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"},
449
+ {"key": "inventory", "question": "📦 **Do you need inventory management?** (For products, stock tracking) – Yes/No or **skip**."},
450
+ {"key": "data", "question": "🗄️ **Do you need database integration?** (e.g., user accounts, data storage) – Yes/No or **skip**."}
451
+ ]
452
+ return session["additional_questions"][0]["question"]
453
+
454
+ elif step == "asking_additional":
455
+ idx = session.get("additional_index", 0)
456
+ qlist = session.get("additional_questions", [])
457
+ if idx < len(qlist):
458
+ current_q = qlist[idx]
459
+ key = current_q["key"]
460
+ if "additional_answers" not in session:
461
+ session["additional_answers"] = {}
462
+ if msg_lower in ["skip", "none", "no"]:
463
+ session["additional_answers"][key] = ""
464
+ else:
465
+ session["additional_answers"][key] = message
466
+ session["additional_index"] = idx + 1
467
+ if idx + 1 < len(qlist):
468
+ return qlist[idx+1]["question"]
469
+ else:
470
+ session["step"] = "asking_media"
471
+ return "🖼️ **Do you want to add any additional text or images?** (Reply: Yes/No)\n\nIf Yes, a text area and image upload will appear. Type **skip** if none."
472
+ else:
473
+ session["step"] = "asking_media"
474
+ return "🖼️ **Do you want to add any additional text or images?** (Reply: Yes/No)\n\nIf Yes, a text area and image upload will appear. Type **skip** if none."
475
+
476
+ elif step == "asking_media":
477
+ if msg_lower in ["yes", "han"]:
478
+ session["waiting_for_media"] = True
479
+ session["media_text"] = ""
480
+ session["media_image"] = None
481
+ return "MEDIA_REQUEST|Please provide your additional notes in the text area below and/or upload an image.\n\n(After done, type **DONE** to finish.)"
482
+ elif msg_lower in ["no", "skip", "none"]:
483
+ session["step"] = "asking_contact"
484
+ return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
485
+ else:
486
+ return "Please reply **Yes** to add media, **No** to skip."
487
+
488
+ elif step == "waiting_media":
489
+ if msg_lower == "done":
490
+ if "media_text" in session and session["media_text"]:
491
+ req["media_text"] = session["media_text"]
492
+ if "media_image" in session and session["media_image"]:
493
+ req["media_image"] = session["media_image"]
494
+ session["requirements"] = req
495
+ session["step"] = "asking_contact"
496
+ del session["waiting_media"]
497
+ return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
498
+ else:
499
+ return "Please type **DONE** when you have finished adding text/image."
500
+
501
+ elif step == "asking_contact":
502
+ if "mobile" not in session:
503
+ if not is_valid_mobile(message):
504
+ return "❌ Invalid mobile number. Please enter a valid phone number (10-15 digits).\n\n📞 Please provide your mobile number:"
505
+ session["mobile"] = message
506
+ return "✉️ **Please provide your email address** (e.g., name@example.com) – We'll send the quote and updates."
507
+ else:
508
+ if not is_valid_email(message):
509
+ return "❌ Invalid email address. Please enter a valid email (e.g., name@example.com).\n\n✉️ Please provide your email address:"
510
+ session["email"] = message
511
+ req["mobile"] = session.get("mobile", "")
512
+ req["email"] = session.get("email", "")
513
+ req["additional_answers"] = session.get("additional_answers", {})
514
+ req["deep_answers"] = session.get("deep_answers", {})
515
+ session["requirements"] = req
516
+ session["step"] = "confirm"
517
+
518
+ # ----- ITEMIZED PROPOSAL -----
519
+ price, timeline = calculate_price_and_timeline(req)
520
+ extra_services = get_extra_services()
521
+ extra_features_list = req.get("extra_features", [])
522
+
523
+ items = []
524
+
525
+ if req.get("domain"):
526
+ items.append("• Domain Registration: PKR 5,000")
527
+
528
+ pages = req.get("pages", 5)
529
+ if pages > 5:
530
+ extra_pages = pages - 5
531
+ extra_cost = extra_pages * 5000
532
+ items.append(f"• {extra_pages} extra page(s): +PKR {extra_cost:,}")
533
+
534
+ if req.get("ecommerce"):
535
+ items.append("• E‑commerce Functionality: PKR 50,000")
536
+
537
+ if req.get("chatbot"):
538
+ items.append("• AI Chatbot: PKR 30,000")
539
+
540
+ if req.get("seo"):
541
+ items.append("• SEO Optimization: PKR 25,000")
542
+
543
+ for feat_key in extra_features_list:
544
+ if feat_key in extra_services:
545
+ svc = extra_services[feat_key]
546
+ items.append(f"• {svc['name'].title()}: +PKR {svc['price']:,} (timeline +{svc['timeline']} days)")
547
+
548
+ if req.get("inventory", "").lower() == "yes":
549
+ items.append("• Inventory Management: +PKR 30,000 (+5 days)")
550
+
551
+ if req.get("data", "").lower() == "yes":
552
+ items.append("• Database Integration: +PKR 40,000 (+8 days)")
553
+
554
+ itemized_text = "\n".join(items) if items else "• No services selected"
555
+
556
+ # Additional info
557
+ add_answers = session.get("additional_answers", {})
558
+ add_text = ""
559
+ if any(add_answers.values()):
560
+ add_text = "\n\n📌 **Additional Info:**\n"
561
+ if add_answers.get("purpose"):
562
+ add_text += f"• Purpose: {add_answers['purpose']}\n"
563
+ if add_answers.get("theme"):
564
+ add_text += f"• Theme: {add_answers['theme']}\n"
565
+ if add_answers.get("content"):
566
+ add_text += f"• Content: {add_answers['content']}\n"
567
+ if add_answers.get("inventory"):
568
+ add_text += f"• Inventory Management: {add_answers['inventory']}\n"
569
+ if add_answers.get("data"):
570
+ add_text += f"• Database Integration: {add_answers['data']}\n"
571
+
572
+ deep_answers = session.get("deep_answers", {})
573
+ deep_text = ""
574
+ if deep_answers:
575
+ deep_text = "\n\n📌 **Deep Dive Responses:**\n"
576
+ for key, val in deep_answers.items():
577
+ deep_text += f"• {key}: {val}\n"
578
+
579
+ media_text = ""
580
+ if req.get("media_text"):
581
+ media_text += f"\n\n📝 **Client Notes:** {req['media_text']}\n"
582
+ if req.get("media_image"):
583
+ media_text += f"\n🖼️ **Image uploaded** (view in admin panel)\n"
584
+
585
+ contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"
586
+
587
+ return f"""📋 **Your Project Proposal**
588
 
589
  **Selected Services (itemized):**
590
  {itemized_text}
591
 
592
  💰 **Total Cost:** PKR {price:,}
593
+ ⏱️ **Total Timeline:** {timeline} working days
594
  {add_text}{deep_text}{media_text}{contact_text}
595
 
596
  ❓ **Agree?** (Reply: **Confirm** or **Cancel**)
597
 
598
  ⚠️ *To add more extras, type 'add more'*"""
599
 
600
+ elif step == "confirm":
601
+ if "confirm" in msg_lower or "agree" in msg_lower:
602
+ project_id, price, timeline = create_project(session_id, req)
603
+ del user_sessions[session_id]
604
+ return f"""✅ **Project Confirmed!**
605
+
606
+ **Project ID:** `{project_id}`
607
+ **Total Cost:** PKR {price:,}
608
+ **Timeline:** {timeline} days
609
+
610
+ Use `status {project_id}` anytime.
611
+ We'll contact you within 24 hours. 🚀"""
612
+ elif "cancel" in msg_lower:
613
+ del user_sessions[session_id]
614
+ return "❌ Cancelled. Start again with 'I want to build a website'.\n📞 For special requests, contact admin: +92 300 1234567"
615
+ elif "add more" in msg_lower:
616
+ session["step"] = "asking_extra"
617
+ extra_services = get_extra_services()
618
+ extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
619
+ return f"✨ **Add more extras**\n\nAvailable:\n{extra_list}\n\nType name or **done**."
620
+ else:
621
+ return "Please reply **Confirm**, **Cancel**, or **add more**."
622
+
623
+ return None
624
+
625
+ # ---------- Media upload endpoint ----------
626
+ @app.route('/api/upload_media', methods=['POST'])
627
+ def upload_media():
628
+ data = request.json
629
+ session_id = data.get('session_id')
630
+ media_text = data.get('text', '')
631
+ image_base64 = data.get('image', '')
632
+ if session_id in user_sessions:
633
+ session = user_sessions[session_id]
634
+ if session.get("waiting_for_media"):
635
+ if media_text:
636
+ session["media_text"] = media_text
637
+ if image_base64:
638
+ session["media_image"] = image_base64
639
+ return jsonify({"status": "ok", "message": "Media saved"})
640
+ return jsonify({"status": "error", "message": "Session not in media upload mode"}), 400
641
+
642
+ # ---------- Package details ----------
643
+ def package_details(query):
644
+ q = query.lower()
645
+ if "basic" in q:
646
+ return "**Basic Website** – PKR 50,000 (7-10 days)\n✅ 5 pages, responsive, basic SEO, contact form, social links."
647
+ if "standard" in q:
648
+ return "**Standard Website** – PKR 1,20,000 (15-20 days)\n✅ 10 pages, CMS, advanced SEO, blog, chatbot, 1 month support."
649
+ if "premium" in q:
650
+ return "**Premium Website** – PKR 2,50,000 (25-30 days)\n✅ Unlimited pages, e‑commerce, payment gateway, user accounts, custom animations, 6 months support."
651
+ return None
652
+
653
+ # ---------- Main response handler ----------
654
+ def get_final_response(user_message, session_id):
655
+ step_resp = process_step_by_step(session_id, user_message)
656
+ if step_resp:
657
+ return step_resp
658
+
659
+ status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
660
+ if status_match:
661
+ pid = status_match.group(1).upper()
662
+ proj = get_project(pid)
663
+ if proj:
664
+ status = proj.get("status", "pending")
665
+ emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
666
+ msg = proj.get("admin_message", "")
667
+ extra = f"\n📝 **Admin note:** {msg}" if msg else ""
668
+ req = proj.get("requirements", {})
669
+ media_info = ""
670
+ if req.get("media_text"):
671
+ media_info += f"\n📝 **Client Notes:** {req['media_text']}"
672
+ if req.get("media_image"):
673
+ media_info += "\n🖼️ **Image uploaded** (view in admin panel)"
674
+ return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}{media_info}\nTotal: PKR {proj.get('calculated_price',0):,}\nTimeline: {proj.get('calculated_timeline',0)} days"
675
+ else:
676
+ return f"❌ Project ID `{pid}` not found."
677
+
678
+ pkg = package_details(user_message)
679
+ if pkg:
680
+ return pkg
681
+
682
+ return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"
683
+
684
+ # ---------- API Routes ----------
685
+ @app.route('/api/chat', methods=['POST'])
686
+ def chat():
687
+ data = request.json
688
+ message = data.get('message', '')
689
+ session_id = data.get('session_id', str(uuid.uuid4()))
690
+ if not message:
691
+ return jsonify({"reply": "Please say something."})
692
+ store_ip_for_session(session_id)
693
+ reply = get_final_response(message, session_id)
694
+ save_message(session_id, "user", message)
695
+ save_message(session_id, "assistant", reply)
696
+ return jsonify({"reply": reply, "session_id": session_id})
697
+
698
+ @app.route('/api/history', methods=['GET'])
699
+ def history():
700
+ session_id = request.args.get('session_id')
701
+ if not session_id:
702
+ return jsonify({"error": "Missing session_id"}), 400
703
+ messages = get_chat_history(session_id)
704
+ return jsonify({"messages": messages})
705
+
706
+ @app.route('/api/get_ip', methods=['GET'])
707
+ def get_ip():
708
+ session_id = request.args.get('session_id')
709
+ if session_id:
710
+ store_ip_for_session(session_id)
711
+ return jsonify({"ip": get_client_ip()})
712
+
713
+ @app.route('/api/projects', methods=['GET'])
714
+ def get_projects():
715
+ snap = ref.child("projects").get()
716
+ return jsonify({"projects": list(snap.values()) if snap else []})
717
+
718
+ @app.route('/api/project/<project_id>/status', methods=['PUT'])
719
+ def update_status(project_id):
720
+ data = request.json
721
+ status = data.get('status')
722
+ if status not in ['pending', 'in-progress', 'completed', 'declined']:
723
+ return jsonify({"error": "Invalid status"}), 400
724
+ update_project_status(project_id, status)
725
+ return jsonify({"message": "Status updated"})
726
+
727
+ @app.route('/api/project/<project_id>/message', methods=['PUT'])
728
+ def update_message(project_id):
729
+ data = request.json
730
+ msg = data.get('message', '')
731
+ update_project_message(project_id, msg)
732
+ return jsonify({"message": "Message updated"})
733
+
734
+ @app.route('/api/services', methods=['GET'])
735
+ def get_services():
736
+ services = get_extra_services()
737
+ return jsonify({"services": services})
738
+
739
+ @app.route('/api/services', methods=['POST'])
740
+ def add_service():
741
+ data = request.json
742
+ key = data.get('key')
743
+ name = data.get('name')
744
+ price = int(data.get('price', 0))
745
+ timeline = int(data.get('timeline', 0))
746
+ if not key or not name:
747
+ return jsonify({"error": "Missing key or name"}), 400
748
+ service = {
749
+ "name": name,
750
+ "price": price,
751
+ "timeline": timeline,
752
+ "display": f"{name} (+PKR {price:,}, +{timeline} days)"
753
+ }
754
+ ref.child(f"extra_services/{key}").set(service)
755
+ return jsonify({"message": "Service added"})
756
+
757
+ @app.route('/api/services/<key>', methods=['PUT'])
758
+ def update_service(key):
759
+ data = request.json
760
+ name = data.get('name')
761
+ price = int(data.get('price', 0))
762
+ timeline = int(data.get('timeline', 0))
763
+ if not name:
764
+ return jsonify({"error": "Missing name"}), 400
765
+ service = {
766
+ "name": name,
767
+ "price": price,
768
+ "timeline": timeline,
769
+ "display": f"{name} (+PKR {price:,}, +{timeline} days)"
770
+ }
771
+ ref.child(f"extra_services/{key}").update(service)
772
+ return jsonify({"message": "Service updated"})
773
+
774
+ @app.route('/api/services/<key>', methods=['DELETE'])
775
+ def delete_service(key):
776
+ ref.child(f"extra_services/{key}").delete()
777
+ return jsonify({"message": "Service deleted"})
778
+
779
+ @app.route('/api/delete_all_projects', methods=['DELETE'])
780
+ def delete_all_projects():
781
+ confirm = request.args.get('confirm')
782
+ if confirm != 'YES':
783
+ return jsonify({"error": "Must provide ?confirm=YES"}), 400
784
+ ref.child("projects").delete()
785
+ return jsonify({"message": "All projects deleted"})
786
+
787
+ @app.route('/')
788
+ def index():
789
+ return send_from_directory('.', 'index.html')
790
+
791
+ if __name__ == '__main__':
792
+ port = int(os.environ.get('PORT', 7860))
793
+ app.run(host='0.0.0.0', port=port)