Download app.py from Ahmad140/ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 35.4 kB
-
https://huggingface.co/spaces/Ahmad140/ChatBot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Ahmad140/ChatBot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Ahmad140/ChatBot/resolve/main/app.py
35.4 kB
| from flask import Flask, request, jsonify, send_from_directory | |
| import firebase_admin | |
| from firebase_admin import credentials, db | |
| import requests | |
| import os | |
| import json | |
| from datetime import datetime | |
| from sentence_transformers import SentenceTransformer | |
| import uuid | |
| import re | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| # Try to load llama-cpp-python (GGUF support) | |
| try: | |
| from llama_cpp import Llama | |
| LLAMA_AVAILABLE = True | |
| except ImportError: | |
| LLAMA_AVAILABLE = False | |
| print("β οΈ llama-cpp-python not installed. Llama fallback unavailable.") | |
| app = Flask(__name__) | |
| # ---------- Firebase ---------- | |
| firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT") | |
| if not firebase_service_account_json: | |
| raise ValueError("FIREBASE_SERVICE_ACCOUNT secret missing") | |
| service_account_info = json.loads(firebase_service_account_json) | |
| database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/" | |
| cred = credentials.Certificate(service_account_info) | |
| firebase_admin.initialize_app(cred, {'databaseURL': database_url}) | |
| ref = firebase_admin.db.reference('/') | |
| print("β Firebase connected") | |
| # ---------- Sentence-Transformer ---------- | |
| embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") | |
| print("β Embedding model loaded") | |
| # ---------- Load Llama 3.2 1B GGUF (if available) ---------- | |
| llama_model = None | |
| llama_path = os.getenv("LLAMA_GGUF_PATH") | |
| if LLAMA_AVAILABLE and llama_path and os.path.exists(llama_path): | |
| try: | |
| llama_model = Llama(model_path=llama_path, n_ctx=2048, n_threads=2, verbose=False) | |
| print("β Llama 3.2 1B GGUF loaded (fallback)") | |
| except Exception as e: | |
| print(f"β οΈ Failed to load Llama GGUF: {e}") | |
| else: | |
| print("β οΈ Llama GGUF not configured β will use GPTβ2 fallback if available") | |
| # ---------- Load GPTβ2 (final fallback) ---------- | |
| gpt_model = None | |
| gpt_tokenizer = None | |
| if not llama_model: | |
| try: | |
| gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2") | |
| gpt_model = AutoModelForCausalLM.from_pretrained("gpt2") | |
| gpt_tokenizer.pad_token = gpt_tokenizer.eos_token | |
| if torch.cuda.is_available(): | |
| gpt_model = gpt_model.to("cuda") | |
| print("β GPTβ2 loaded (final fallback)") | |
| except Exception as e: | |
| print(f"β οΈ GPTβ2 load failed: {e}") | |
| # ---------- AI Call (Groq β Owl Alpha β Gemini β Llama GGUF β GPTβ2 β rule) ---------- | |
| def call_ai(prompt): | |
| # 1. Groq (fast, free) | |
| groq_key = os.getenv("GROQ_API_KEY") | |
| if groq_key: | |
| url = "https://api.groq.com/openai/v1/chat/completions" | |
| headers = {"Authorization": f"Bearer {groq_key}", "Content-Type": "application/json"} | |
| payload = { | |
| "model": "llama3-8b-8192", | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": 0.7, | |
| "max_tokens": 150 | |
| } | |
| try: | |
| resp = requests.post(url, json=payload, headers=headers, timeout=10) | |
| if resp.status_code == 200: | |
| return resp.json()["choices"][0]["message"]["content"].strip() | |
| except Exception as e: | |
| print(f"Groq error: {e}") | |
| # 2. OpenRouter Owl Alpha (primary β free, 1M context) | |
| openrouter_key = os.getenv("OPENROUTER_API_KEY") | |
| if openrouter_key: | |
| url = "https://openrouter.ai/api/v1/chat/completions" | |
| headers = {"Authorization": f"Bearer {openrouter_key}", "Content-Type": "application/json"} | |
| payload = { | |
| "model": "openrouter/owl-alpha", | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": 0.7, | |
| "max_tokens": 150 | |
| } | |
| try: | |
| resp = requests.post(url, json=payload, headers=headers, timeout=10) | |
| if resp.status_code == 200: | |
| return resp.json()["choices"][0]["message"]["content"].strip() | |
| except Exception as e: | |
| print(f"Owl Alpha error: {e}") | |
| # 3. OpenRouter Gemini (fallback) | |
| if openrouter_key: | |
| url = "https://openrouter.ai/api/v1/chat/completions" | |
| headers = {"Authorization": f"Bearer {openrouter_key}", "Content-Type": "application/json"} | |
| payload = { | |
| "model": "google/gemini-2.0-flash-lite-preview-02-05", | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": 0.7, | |
| "max_tokens": 150 | |
| } | |
| try: | |
| resp = requests.post(url, json=payload, headers=headers, timeout=10) | |
| if resp.status_code == 200: | |
| return resp.json()["choices"][0]["message"]["content"].strip() | |
| except Exception as e: | |
| print(f"Gemini error: {e}") | |
| # 4. Llama 3.2 1B GGUF (local) | |
| if llama_model: | |
| try: | |
| output = llama_model.create_chat_completion( | |
| messages=[{"role": "user", "content": prompt}], | |
| temperature=0.7, | |
| max_tokens=150 | |
| ) | |
| return output["choices"][0]["message"]["content"].strip() | |
| except Exception as e: | |
| print(f"Llama GGUF error: {e}") | |
| # 5. GPTβ2 fallback | |
| if gpt_model is not None: | |
| try: | |
| inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024) | |
| if torch.cuda.is_available(): | |
| inputs = {k: v.to("cuda") for k, v in inputs.items()} | |
| outputs = gpt_model.generate( | |
| **inputs, | |
| max_new_tokens=120, | |
| do_sample=True, | |
| temperature=0.7, | |
| repetition_penalty=1.2, | |
| pad_token_id=gpt_tokenizer.eos_token_id | |
| ) | |
| response = gpt_tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| if response.startswith(prompt): | |
| response = response[len(prompt):].strip() | |
| return response if response else "What else would you like to share about your project?" | |
| except Exception as e: | |
| print(f"GPTβ2 error: {e}") | |
| # 6. Ultimate ruleβbased | |
| return "What else would you like to share about your project?" | |
| # ---------- Helper: Load extra services from Firebase ---------- | |
| def get_extra_services(): | |
| snap = ref.child("extra_services").get() | |
| if not snap: | |
| default = { | |
| "live_chat": {"name": "live chat", "price": 20000, "timeline": 3, "display": "Live Chat (+PKR 20,000, +3 days)"}, | |
| "booking_system": {"name": "booking system", "price": 35000, "timeline": 5, "display": "Booking System (+PKR 35,000, +5 days)"}, | |
| "multi_language": {"name": "multi-language", "price": 25000, "timeline": 4, "display": "Multi-Language (+PKR 25,000, +4 days)"}, | |
| "custom_backend": {"name": "custom backend", "price": 100000, "timeline": 15, "display": "Custom Backend (+PKR 1,00,000, +15 days)"} | |
| } | |
| ref.child("extra_services").set(default) | |
| return default | |
| return snap | |
| # ---------- Pricing Helpers ---------- | |
| BASE_PRICE = 50000 | |
| BASE_PAGES = 5 | |
| EXTRA_PAGE_PRICE = 5000 | |
| BASE_TIMELINE = 10 | |
| def calculate_price_and_timeline(req): | |
| extra_services = get_extra_services() | |
| pages = req.get("pages", 5) | |
| domain = req.get("domain", False) | |
| ecommerce = req.get("ecommerce", False) | |
| chatbot = req.get("chatbot", False) | |
| seo = req.get("seo", False) | |
| extra_features = req.get("extra_features", []) | |
| inventory = req.get("inventory", "").lower() == "yes" | |
| database = req.get("data", "").lower() == "yes" | |
| price = BASE_PRICE | |
| timeline = BASE_TIMELINE | |
| if pages > BASE_PAGES: | |
| price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE | |
| timeline += (pages - BASE_PAGES) | |
| if domain: | |
| price += 5000 | |
| timeline += 1 | |
| if ecommerce: | |
| price += 50000 | |
| timeline += 10 | |
| if chatbot: | |
| price += 30000 | |
| timeline += 5 | |
| if seo: | |
| price += 25000 | |
| timeline += 5 | |
| for feat in extra_features: | |
| if feat in extra_services: | |
| info = extra_services[feat] | |
| price += info.get("price", 0) | |
| timeline += info.get("timeline", 0) | |
| if inventory: | |
| price += 30000 | |
| timeline += 5 | |
| if database: | |
| price += 40000 | |
| timeline += 8 | |
| return price, timeline | |
| def generate_project_id(): | |
| return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}" | |
| def create_project(session_id, requirements): | |
| project_id = generate_project_id() | |
| price, timeline = calculate_price_and_timeline(requirements) | |
| project_data = { | |
| "project_id": project_id, | |
| "session_id": session_id, | |
| "requirements": requirements, | |
| "calculated_price": price, | |
| "calculated_timeline": timeline, | |
| "status": "pending", | |
| "admin_message": "", | |
| "created_at": datetime.now().isoformat(), | |
| "updated_at": datetime.now().isoformat() | |
| } | |
| ref.child(f"projects/{project_id}").set(project_data) | |
| return project_id, price, timeline | |
| def get_project(project_id): | |
| return ref.child(f"projects/{project_id}").get() | |
| def update_project_status(project_id, status, decline_reason=None): | |
| data = {"status": status, "updated_at": datetime.now().isoformat()} | |
| if decline_reason: | |
| data["admin_message"] = decline_reason | |
| ref.child(f"projects/{project_id}").update(data) | |
| def update_project_message(project_id, message): | |
| ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()}) | |
| # ---------- IP & Session ---------- | |
| def get_client_ip(): | |
| if request.headers.get('X-Forwarded-For'): | |
| ip = request.headers.get('X-Forwarded-For').split(',')[0] | |
| else: | |
| ip = request.remote_addr | |
| return ip | |
| def store_ip_for_session(session_id): | |
| ip = get_client_ip() | |
| ref.child(f"sessions/{session_id}/ip").set(ip) | |
| ref.child(f"sessions/{session_id}/last_seen").set(datetime.now().isoformat()) | |
| def save_message(session_id, role, content, intent=None): | |
| ref.child(f"chats/{session_id}/messages").push().set({ | |
| "role": role, | |
| "content": content, | |
| "timestamp": datetime.now().isoformat(), | |
| "intent": intent | |
| }) | |
| def get_chat_history(session_id): | |
| snap = ref.child(f"chats/{session_id}/messages").order_by_child("timestamp").get() | |
| if not snap: | |
| return [] | |
| messages = list(snap.values()) | |
| return sorted(messages, key=lambda x: x.get("timestamp", "")) | |
| # ---------- Step Builder (no auto-add in step answers) ---------- | |
| user_sessions = {} | |
| def is_start_project_request(text): | |
| keywords = ["website banwani", "build website", "new project", "website chahiye", "start project", | |
| "i want to build a website", "web project", "website banana hai", "naya project"] | |
| return any(k in text.lower() for k in keywords) | |
| def process_step_by_step(session_id, message): | |
| msg_lower = message.lower().strip() | |
| if session_id not in user_sessions: | |
| if is_start_project_request(message): | |
| user_sessions[session_id] = { | |
| "step": "asking_domain", | |
| "requirements": {}, | |
| "deep_answers": {}, | |
| "deep_index": 0, | |
| "max_deep_rounds": 2, | |
| "deep_questions": [] | |
| } | |
| return "π **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**" | |
| return None | |
| session = user_sessions[session_id] | |
| step = session.get("step") | |
| req = session.get("requirements", {}) | |
| def is_valid_domain_answer(ans): return ans.lower() in ["yes", "no", "han", "nahi"] | |
| def is_valid_pages_answer(ans): | |
| try: | |
| return int(ans) >= 1 | |
| except: | |
| return False | |
| def is_valid_yes_no(ans): return ans.lower() in ["yes", "no", "han", "nahi"] | |
| def is_valid_extra_feature_name(ans): | |
| if ans.lower() in ["none", "done", "no"]: return True | |
| extra_services = get_extra_services() | |
| for val in extra_services.values(): | |
| if val.get("name", "").lower() in ans.lower() or ans.lower() in val.get("name", "").lower(): | |
| return True | |
| return False | |
| def is_valid_mobile(ans): return re.search(r'\d{10,15}', ans) is not None | |
| def is_valid_email(ans): return "@" in ans and "." in ans | |
| # Handle "add more" | |
| if msg_lower in ["add more", "add something", "extra add"]: | |
| session["step"] = "asking_extra" | |
| extra_services = get_extra_services() | |
| extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()]) | |
| return f"β¨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**." | |
| # Main step handlers (no invoice auto-add here) | |
| if step == "asking_domain": | |
| if not is_valid_domain_answer(message): | |
| return "β Invalid answer. Please reply **Yes** or **No**.\n\nπ Do you need a domain name?" | |
| req["domain"] = "yes" in msg_lower or "han" in msg_lower | |
| session["step"] = "asking_pages" | |
| session["requirements"] = req | |
| return "π **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**" | |
| elif step == "asking_pages": | |
| if not is_valid_pages_answer(message): | |
| return "β Invalid number. Please enter a valid number of pages (minimum 1).\n\nπ How many pages?" | |
| pages = int(re.search(r'\d+', msg_lower).group()) | |
| req["pages"] = max(pages, 5) | |
| session["step"] = "asking_ecommerce" | |
| session["requirements"] = req | |
| return "π **Need eβcommerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**" | |
| elif step == "asking_ecommerce": | |
| if not is_valid_yes_no(message): | |
| return "β Invalid answer. Please reply **Yes** or **No**.\n\nπ Need eβcommerce?" | |
| req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower | |
| session["step"] = "asking_chatbot" | |
| session["requirements"] = req | |
| return "π€ **AI chatbot on your website?**\n\nReply: **Yes** or **No**" | |
| elif step == "asking_chatbot": | |
| if not is_valid_yes_no(message): | |
| return "β Invalid answer. Please reply **Yes** or **No**.\n\nπ€ AI chatbot on your website?" | |
| req["chatbot"] = "yes" in msg_lower or "han" in msg_lower | |
| session["step"] = "asking_seo" | |
| session["requirements"] = req | |
| return "π **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**" | |
| elif step == "asking_seo": | |
| if not is_valid_yes_no(message): | |
| return "β Invalid answer. Please reply **Yes** or **No**.\n\nπ SEO optimization?" | |
| req["seo"] = "yes" in msg_lower or "han" in msg_lower | |
| session["step"] = "asking_extra" | |
| session["requirements"] = req | |
| extra_services = get_extra_services() | |
| extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()]) | |
| return f"β¨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**." | |
| elif step == "asking_extra": | |
| extra_services = get_extra_services() | |
| if msg_lower in ["none", "done", "no"]: | |
| session["step"] = "asking_deep" | |
| session["deep_index"] = 0 | |
| 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). | |
| Current requirements: | |
| {json.dumps(req, indent=2)} | |
| Generated question:""" | |
| first_q = call_ai(prompt) | |
| if len(first_q) > 300 or '{' in first_q or '}' in first_q or '```' in first_q: | |
| first_q = "Could you please provide more details about your target audience or business goals?" | |
| session["deep_questions"] = [first_q] | |
| return first_q | |
| else: | |
| if not is_valid_extra_feature_name(message): | |
| available = ', '.join([v['name'] for v in extra_services.values()]) | |
| return f"β Sorry, **'{message}'** is not offered. Available: {available}\n\nType a valid name or **done**." | |
| matched_key = None | |
| for key, val in extra_services.items(): | |
| if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower(): | |
| matched_key = key | |
| break | |
| if matched_key: | |
| extra_list = req.get("extra_features", []) | |
| if matched_key not in extra_list: | |
| extra_list.append(matched_key) | |
| req["extra_features"] = extra_list | |
| session["requirements"] = req | |
| # This triggers invoice add in the frontend | |
| return f"β Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**." | |
| else: | |
| return f"βΉοΈ Already added. Type another name or **done**." | |
| else: | |
| return f"β Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**." | |
| elif step == "asking_deep": | |
| idx = session.get("deep_index", 0) | |
| if idx < session.get("max_deep_rounds", 2): | |
| if "deep_answers" not in session: | |
| session["deep_answers"] = {} | |
| session["deep_answers"][f"deep_{idx}"] = message | |
| session["deep_index"] = idx + 1 | |
| if idx + 1 < session.get("max_deep_rounds", 2): | |
| 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). | |
| Current requirements: | |
| {json.dumps(req, indent=2)} | |
| Previous deep answers: | |
| {json.dumps(session.get("deep_answers", {}), indent=2)} | |
| Generated question:""" | |
| next_q = call_ai(prompt) | |
| if len(next_q) > 300 or '{' in next_q or '}' in next_q or '```' in next_q: | |
| next_q = "Is there any specific functionality or integration you consider essential for your project?" | |
| return next_q | |
| else: | |
| session["step"] = "asking_additional" | |
| session["additional_index"] = 0 | |
| session["additional_questions"] = [ | |
| {"key": "purpose", "question": "π **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) β Type **skip** to leave blank."}, | |
| {"key": "theme", "question": "π¨ **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) β Type **skip** or describe."}, | |
| {"key": "content", "question": "π **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"}, | |
| {"key": "inventory", "question": "π¦ **Do you need inventory management?** (For products, stock tracking) β Yes/No or **skip**."}, | |
| {"key": "data", "question": "ποΈ **Do you need database integration?** (e.g., user accounts, data storage) β Yes/No or **skip**."} | |
| ] | |
| return session["additional_questions"][0]["question"] | |
| else: | |
| session["step"] = "asking_additional" | |
| session["additional_index"] = 0 | |
| session["additional_questions"] = [ | |
| {"key": "purpose", "question": "π **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) β Type **skip** to leave blank."}, | |
| {"key": "theme", "question": "π¨ **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) β Type **skip** or describe."}, | |
| {"key": "content", "question": "π **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"}, | |
| {"key": "inventory", "question": "π¦ **Do you need inventory management?** (For products, stock tracking) β Yes/No or **skip**."}, | |
| {"key": "data", "question": "ποΈ **Do you need database integration?** (e.g., user accounts, data storage) β Yes/No or **skip**."} | |
| ] | |
| return session["additional_questions"][0]["question"] | |
| elif step == "asking_additional": | |
| idx = session.get("additional_index", 0) | |
| qlist = session.get("additional_questions", []) | |
| if idx < len(qlist): | |
| current_q = qlist[idx] | |
| key = current_q["key"] | |
| if "additional_answers" not in session: | |
| session["additional_answers"] = {} | |
| if msg_lower in ["skip", "none", "no"]: | |
| session["additional_answers"][key] = "" | |
| else: | |
| session["additional_answers"][key] = message | |
| session["additional_index"] = idx + 1 | |
| if idx + 1 < len(qlist): | |
| return qlist[idx+1]["question"] | |
| else: | |
| session["step"] = "asking_media" | |
| 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." | |
| else: | |
| session["step"] = "asking_media" | |
| 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." | |
| elif step == "asking_media": | |
| if msg_lower in ["yes", "han"]: | |
| session["waiting_for_media"] = True | |
| session["media_text"] = "" | |
| session["media_image"] = None | |
| 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.)" | |
| elif msg_lower in ["no", "skip", "none"]: | |
| session["step"] = "asking_contact" | |
| return "π **Please provide your mobile number** (e.g., 03001234567) β We'll use this to contact you." | |
| else: | |
| return "Please reply **Yes** to add media, **No** to skip." | |
| elif step == "waiting_media": | |
| if msg_lower == "done": | |
| if "media_text" in session and session["media_text"]: | |
| req["media_text"] = session["media_text"] | |
| if "media_image" in session and session["media_image"]: | |
| req["media_image"] = session["media_image"] | |
| session["requirements"] = req | |
| session["step"] = "asking_contact" | |
| del session["waiting_media"] | |
| return "π **Please provide your mobile number** (e.g., 03001234567) β We'll use this to contact you." | |
| else: | |
| return "Please type **DONE** when you have finished adding text/image." | |
| elif step == "asking_contact": | |
| if "mobile" not in session: | |
| if not is_valid_mobile(message): | |
| return "β Invalid mobile number. Please enter a valid phone number (10-15 digits).\n\nπ Please provide your mobile number:" | |
| session["mobile"] = message | |
| return "βοΈ **Please provide your email address** (e.g., name@example.com) β We'll send the quote and updates." | |
| else: | |
| if not is_valid_email(message): | |
| return "β Invalid email address. Please enter a valid email (e.g., name@example.com).\n\nβοΈ Please provide your email address:" | |
| session["email"] = message | |
| req["mobile"] = session.get("mobile", "") | |
| req["email"] = session.get("email", "") | |
| req["additional_answers"] = session.get("additional_answers", {}) | |
| req["deep_answers"] = session.get("deep_answers", {}) | |
| session["requirements"] = req | |
| session["step"] = "confirm" | |
| # ----- ITEMIZED PROPOSAL ----- | |
| price, timeline = calculate_price_and_timeline(req) | |
| extra_services = get_extra_services() | |
| extra_features_list = req.get("extra_features", []) | |
| items = [] | |
| if req.get("domain"): | |
| items.append("β’ Domain Registration: PKR 5,000") | |
| pages = req.get("pages", 5) | |
| if pages > 5: | |
| extra_pages = pages - 5 | |
| extra_cost = extra_pages * 5000 | |
| items.append(f"β’ {extra_pages} extra page(s): +PKR {extra_cost:,}") | |
| if req.get("ecommerce"): | |
| items.append("β’ Eβcommerce Functionality: PKR 50,000") | |
| if req.get("chatbot"): | |
| items.append("β’ AI Chatbot: PKR 30,000") | |
| if req.get("seo"): | |
| items.append("β’ SEO Optimization: PKR 25,000") | |
| for feat_key in extra_features_list: | |
| if feat_key in extra_services: | |
| svc = extra_services[feat_key] | |
| items.append(f"β’ {svc['name'].title()}: +PKR {svc['price']:,} (timeline +{svc['timeline']} days)") | |
| if req.get("inventory", "").lower() == "yes": | |
| items.append("β’ Inventory Management: +PKR 30,000 (+5 days)") | |
| if req.get("data", "").lower() == "yes": | |
| items.append("β’ Database Integration: +PKR 40,000 (+8 days)") | |
| itemized_text = "\n".join(items) if items else "β’ No services selected" | |
| # Additional info | |
| add_answers = session.get("additional_answers", {}) | |
| add_text = "" | |
| if any(add_answers.values()): | |
| add_text = "\n\nπ **Additional Info:**\n" | |
| if add_answers.get("purpose"): | |
| add_text += f"β’ Purpose: {add_answers['purpose']}\n" | |
| if add_answers.get("theme"): | |
| add_text += f"β’ Theme: {add_answers['theme']}\n" | |
| if add_answers.get("content"): | |
| add_text += f"β’ Content: {add_answers['content']}\n" | |
| if add_answers.get("inventory"): | |
| add_text += f"β’ Inventory Management: {add_answers['inventory']}\n" | |
| if add_answers.get("data"): | |
| add_text += f"β’ Database Integration: {add_answers['data']}\n" | |
| deep_answers = session.get("deep_answers", {}) | |
| deep_text = "" | |
| if deep_answers: | |
| deep_text = "\n\nπ **Deep Dive Responses:**\n" | |
| for key, val in deep_answers.items(): | |
| deep_text += f"β’ {key}: {val}\n" | |
| media_text = "" | |
| if req.get("media_text"): | |
| media_text += f"\n\nπ **Client Notes:** {req['media_text']}\n" | |
| if req.get("media_image"): | |
| media_text += f"\nπΌοΈ **Image uploaded** (view in admin panel)\n" | |
| contact_text = f"\n\nπ **Contact Details:**\nβ’ Mobile: {req.get('mobile', '')}\nβ’ Email: {req.get('email', '')}" | |
| return f"""π **Your Project Proposal** | |
| **Selected Services (itemized):** | |
| {itemized_text} | |
| π° **Total Cost:** PKR {price:,} | |
| β±οΈ **Total Timeline:** {timeline} working days | |
| {add_text}{deep_text}{media_text}{contact_text} | |
| β **Agree?** (Reply: **Confirm** or **Cancel**) | |
| β οΈ *To add more extras, type 'add more'*""" | |
| elif step == "confirm": | |
| if "confirm" in msg_lower or "agree" in msg_lower: | |
| project_id, price, timeline = create_project(session_id, req) | |
| del user_sessions[session_id] | |
| return f"""β **Project Confirmed!** | |
| **Project ID:** `{project_id}` | |
| **Total Cost:** PKR {price:,} | |
| **Timeline:** {timeline} days | |
| Use `status {project_id}` anytime. | |
| We'll contact you within 24 hours. π""" | |
| elif "cancel" in msg_lower: | |
| del user_sessions[session_id] | |
| return "β Cancelled. Start again with 'I want to build a website'.\nπ For special requests, contact admin: +92 300 1234567" | |
| elif "add more" in msg_lower: | |
| session["step"] = "asking_extra" | |
| extra_services = get_extra_services() | |
| extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()]) | |
| return f"β¨ **Add more extras**\n\nAvailable:\n{extra_list}\n\nType name or **done**." | |
| else: | |
| return "Please reply **Confirm**, **Cancel**, or **add more**." | |
| return None | |
| # ---------- Media upload endpoint ---------- | |
| def upload_media(): | |
| data = request.json | |
| session_id = data.get('session_id') | |
| media_text = data.get('text', '') | |
| image_base64 = data.get('image', '') | |
| if session_id in user_sessions: | |
| session = user_sessions[session_id] | |
| if session.get("waiting_for_media"): | |
| if media_text: | |
| session["media_text"] = media_text | |
| if image_base64: | |
| session["media_image"] = image_base64 | |
| return jsonify({"status": "ok", "message": "Media saved"}) | |
| return jsonify({"status": "error", "message": "Session not in media upload mode"}), 400 | |
| # ---------- Package details ---------- | |
| def package_details(query): | |
| q = query.lower() | |
| if "basic" in q: | |
| return "**Basic Website** β PKR 50,000 (7-10 days)\nβ 5 pages, responsive, basic SEO, contact form, social links." | |
| if "standard" in q: | |
| return "**Standard Website** β PKR 1,20,000 (15-20 days)\nβ 10 pages, CMS, advanced SEO, blog, chatbot, 1 month support." | |
| if "premium" in q: | |
| return "**Premium Website** β PKR 2,50,000 (25-30 days)\nβ Unlimited pages, eβcommerce, payment gateway, user accounts, custom animations, 6 months support." | |
| return None | |
| # ---------- Main response handler ---------- | |
| def get_final_response(user_message, session_id): | |
| step_resp = process_step_by_step(session_id, user_message) | |
| if step_resp: | |
| return step_resp | |
| status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower()) | |
| if status_match: | |
| pid = status_match.group(1).upper() | |
| proj = get_project(pid) | |
| if proj: | |
| status = proj.get("status", "pending") | |
| emoji = {"pending":"β³", "in-progress":"π", "completed":"β ", "declined":"β"}.get(status, "β") | |
| msg = proj.get("admin_message", "") | |
| extra = f"\nπ **Admin note:** {msg}" if msg else "" | |
| req = proj.get("requirements", {}) | |
| media_info = "" | |
| if req.get("media_text"): | |
| media_info += f"\nπ **Client Notes:** {req['media_text']}" | |
| if req.get("media_image"): | |
| media_info += "\nπΌοΈ **Image uploaded** (view in admin panel)" | |
| 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" | |
| else: | |
| return f"β Project ID `{pid}` not found." | |
| pkg = package_details(user_message) | |
| if pkg: | |
| return pkg | |
| return "- How can I help? Services: website design, eβcommerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**" | |
| # ---------- API Routes ---------- | |
| def chat(): | |
| data = request.json | |
| message = data.get('message', '') | |
| session_id = data.get('session_id', str(uuid.uuid4())) | |
| if not message: | |
| return jsonify({"reply": "Please say something."}) | |
| store_ip_for_session(session_id) | |
| reply = get_final_response(message, session_id) | |
| save_message(session_id, "user", message) | |
| save_message(session_id, "assistant", reply) | |
| return jsonify({"reply": reply, "session_id": session_id}) | |
| def history(): | |
| session_id = request.args.get('session_id') | |
| if not session_id: | |
| return jsonify({"error": "Missing session_id"}), 400 | |
| messages = get_chat_history(session_id) | |
| return jsonify({"messages": messages}) | |
| def get_ip(): | |
| session_id = request.args.get('session_id') | |
| if session_id: | |
| store_ip_for_session(session_id) | |
| return jsonify({"ip": get_client_ip()}) | |
| def get_projects(): | |
| snap = ref.child("projects").get() | |
| return jsonify({"projects": list(snap.values()) if snap else []}) | |
| def update_status(project_id): | |
| data = request.json | |
| status = data.get('status') | |
| if status not in ['pending', 'in-progress', 'completed', 'declined']: | |
| return jsonify({"error": "Invalid status"}), 400 | |
| update_project_status(project_id, status) | |
| return jsonify({"message": "Status updated"}) | |
| def update_message(project_id): | |
| data = request.json | |
| msg = data.get('message', '') | |
| update_project_message(project_id, msg) | |
| return jsonify({"message": "Message updated"}) | |
| def get_services(): | |
| services = get_extra_services() | |
| return jsonify({"services": services}) | |
| def add_service(): | |
| data = request.json | |
| key = data.get('key') | |
| name = data.get('name') | |
| price = int(data.get('price', 0)) | |
| timeline = int(data.get('timeline', 0)) | |
| if not key or not name: | |
| return jsonify({"error": "Missing key or name"}), 400 | |
| service = { | |
| "name": name, | |
| "price": price, | |
| "timeline": timeline, | |
| "display": f"{name} (+PKR {price:,}, +{timeline} days)" | |
| } | |
| ref.child(f"extra_services/{key}").set(service) | |
| return jsonify({"message": "Service added"}) | |
| def update_service(key): | |
| data = request.json | |
| name = data.get('name') | |
| price = int(data.get('price', 0)) | |
| timeline = int(data.get('timeline', 0)) | |
| if not name: | |
| return jsonify({"error": "Missing name"}), 400 | |
| service = { | |
| "name": name, | |
| "price": price, | |
| "timeline": timeline, | |
| "display": f"{name} (+PKR {price:,}, +{timeline} days)" | |
| } | |
| ref.child(f"extra_services/{key}").update(service) | |
| return jsonify({"message": "Service updated"}) | |
| def delete_service(key): | |
| ref.child(f"extra_services/{key}").delete() | |
| return jsonify({"message": "Service deleted"}) | |
| def delete_all_projects(): | |
| confirm = request.args.get('confirm') | |
| if confirm != 'YES': | |
| return jsonify({"error": "Must provide ?confirm=YES"}), 400 | |
| ref.child("projects").delete() | |
| return jsonify({"message": "All projects deleted"}) | |
| def admin(): | |
| return send_from_directory('.', 'admin.html') | |
| def index(): | |
| return send_from_directory('.', 'index.html') | |
| if __name__ == '__main__': | |
| port = int(os.environ.get('PORT', 7860)) | |
| app.run(host='0.0.0.0', port=port) |