Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456727 unmodified lines3536373839404142434445464748491 unmodified line5152535455565758596061626364656629 unmodified lines9697989910010110210310410510610735 unmodified lines1431441451461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731741751761771781791801811 unmodified line1831841851861871881891901911921931941951961971982 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222322410 unmodified lines23523623723823924024124224324424515 unmodified lines26126226326426526626752 unmodified lines3203213223233243253267 unmodified lines33433533633733833934034134234334434534634757 unmodified lines4054064074084094104114 unmodified lines41641741841942042142229 unmodified lines4524534544554564574583 unmodified lines46246346446546646746813 unmodified lines48248348448548648748848 unmodified lines537538539540541542543126 unmodified lines670671672673674675676677678679680681682683684685686687688689690691692import osimport reimport loggingfrom datetime import datetime, timedeltafrom typing import List, Dict, Optional, Tuplefrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.responses import PlainTextResponse27 unmodified lines"https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000").split(",")# Compile pricing keywords for deterministic matchingPRICING_KEYWORDS = re.compile(r'\b(how much|cost|price|pricing|retainer|fee|quote|bill|charge|what.*pay|budget)\b',re.IGNORECASE)# Fallback pricing in case database is unreachable (matches your services page)FALLBACK_PRICING = [{"service_key": "inventory_system", "service_name": "Inventory Management System","price_naira": None, "price_range_low": 450000, "price_range_high": 750000, "is_one_time": True,"note": "One-time setup. Includes deployment and training."},{"service_key": "ai_workflow_automation", "service_name": "AI Workflow Automation",1 unmodified line"note": "One-time setup."},{"service_key": "erp_design", "service_name": "ERP Design & Integration","price_naira": None, "price_range_low": 600000, "price_range_high": 1200000, "is_one_time": True,"note": "One-time setup."},{"service_key": "ai_concierge", "service_name": "AI Business Concierge","price_naira": None, "price_range_low": 450000, "price_range_high": 800000, "is_one_time": True,"note": "One-time setup."},{"service_key": "business_systems_audit", "service_name": "Business Systems Audit","price_naira": 150000, "price_range_low": None, "price_range_high": None, "is_one_time": True,"note": "One-time engagement."},{"service_key": "monthly_systems_management", "service_name": "Business Systems Management & Support","price_naira": None, "price_range_low": 200000, "price_range_high": 350000, "is_one_time": False,"note": "Per month."},]# ------------------------------------------------------------------29 unmodified linesembedder: Optional[SentenceTransformer] = Nonesupabase: Optional[Client] = None# Pricing cache (loaded from DB at startup and refreshed via endpoint)pricing_cache: List[Dict] = []pricing_cache_loaded = False# ------------------------------------------------------------------# Greeting & small-talk detection (unchanged)# ------------------------------------------------------------------GREETINGS = {"hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up",35 unmodified linesreturn None# ------------------------------------------------------------------# Pricing helpers (deterministic, from DB cache)# ------------------------------------------------------------------async def load_pricing_from_db() -> List[Dict]:"""Fetch active pricing from Supabase service_pricing table."""try:db = get_supabase()result = db.table("service_pricing").select("*").eq("is_active", True).execute()3 unmodified linesreturn []def get_deterministic_pricing(user_query: str) -> Optional[str]:"""Return pricing information based on keyword matching, using cached DB data."""global pricing_cacheif not PRICING_KEYWORDS.search(user_query):return Nonequery_lower = user_query.lower()response_lines = []matched = False# Use cached pricing (fallback to FALLBACK_PRICING if empty)pricing_data = pricing_cache if pricing_cache else FALLBACK_PRICING# Map keywords to service_keykeyword_to_service = {"inventory": "inventory_system","expiry": "inventory_system","erp": "erp_design","concierge": "ai_concierge","chatbot": "ai_concierge","website": "website_design", # may not be in pricing_data, will fall back to general"site": "website_design","audit": "business_systems_audit","retainer": "monthly_systems_management",1 unmodified line"workflow": "ai_workflow_automation","automation": "ai_workflow_automation",}service_key = Nonefor kw, key in keyword_to_service.items():if kw in query_lower:service_key = keymatched = Truebreakif service_key:# Find the service in pricing_dataservice = next((s for s in pricing_data if s.get("service_key") == service_key), None)if service:desc = service.get("service_name", "")2 unmodified lineshigh = service.get("price_range_high")is_one_time = service.get("is_one_time", True)note = service.get("note", "")if price_naira:price_str = f"₦{price_naira:,}"elif low and high:price_str = f"₦{low:,} – ₦{high:,}"else:price_str = "custom quote required"period = "one-time setup" if is_one_time else "per month"response_lines.append(f"{desc} – {price_str} ({period})")if note:response_lines.append(f"_{note}_")else:# No exact match, fallback to general pricing overviewmatched = Falseif not matched:# General pricing overviewresponse_lines.append("Here are Michael's standard pricing ranges for common services:\n")for s in pricing_data:name = s.get("service_name", "")10 unmodified linesperiod = "(one-time)" if is_one_time else "(per month)"response_lines.append(f"• {name} – {price_str} {period}")matched = Trueif matched:response_lines.append("\n📞 For a precise quote tailored to your specific needs, click the WhatsApp button (📱) in this chat to contact Michael directly.")return "\n".join(response_lines)return None# ------------------------------------------------------------------15 unmodified linesreturn embedder# ------------------------------------------------------------------# HTML fetching & chunking (unchanged)# ------------------------------------------------------------------async def fetch_html(url: str) -> str:async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:52 unmodified lineslogger.info("Knowledge base refresh complete.")# ------------------------------------------------------------------# Vector search (returns chunks with source_url)# ------------------------------------------------------------------def vector_search(query: str, top_k: int = TOP_K) -> List[Dict]:model = get_embedder()7 unmodified linesreturn result.data or []# ------------------------------------------------------------------# LLM with source grounding# ------------------------------------------------------------------async def get_grounded_reply_with_sources(user_message: str, relevant_chunks: List[Dict]) -> Tuple[str, List[str]]:if not relevant_chunks:escalation_msg = ("I couldn't find specific information about that in Michael's knowledge base. ""Please reach out directly on WhatsApp for a detailed answer:\n"f"https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}\n\n""You can also ask me about his AI systems, skills, experience, or services.")return escalation_msg, []57 unmodified linesif not reply:reply = ("I'm experiencing technical difficulties. "f"Please reach Michael directly on WhatsApp: https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}")if sources:4 unmodified linesreturn reply, sources# ------------------------------------------------------------------# Manual knowledge management (unchanged)# ------------------------------------------------------------------async def add_manual_chunk(content: str, source_url: str = "manual"):model = get_embedder()29 unmodified linesif smalltalk:return {"response": smalltalk}# 2. Deterministic pricing (bypass LLM) – uses cached DB or fallbackpricing_answer = get_deterministic_pricing(req.message)if pricing_answer:return {"response": pricing_answer}3 unmodified linesif not results:escalation = ("I don't have specific information on that in my knowledge base. "f"Please contact Michael directly on WhatsApp: https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}\n\n""I can help with his AI systems, skills, work experience, and services.")return {"response": escalation}13 unmodified lines@app.post("/api/admin/refresh-pricing")async def refresh_pricing(background_tasks: BackgroundTasks):"""Admin endpoint to reload pricing from database into memory."""async def reload():global pricing_cachepricing_cache = await load_pricing_from_db()48 unmodified lines}# ------------------------------------------------------------------# Chat widget JS (unchanged – same as original)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():126 unmodified lines"""# ------------------------------------------------------------------# Startup: load pricing cache and embedder# ------------------------------------------------------------------@app.on_event("startup")async def startup():global pricing_cachelogger.info("Starting Kevs Portfolio AI Assistant (deterministic pricing from DB)...")get_embedder()# Load pricing from databasepricing_cache = await load_pricing_from_db()if not pricing_cache:logger.warning("No pricing data loaded from DB, using fallback.")pricing_cache = FALLBACK_PRICINGelse:logger.info(f"Loaded {len(pricing_cache)} pricing entries from database.")try:db = get_supabase()count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0logger.info(f"Supabase connected. {count} knowledge chunks in database.")if count == 0:123456727 unmodified lines35363738394041424344454647484950511 unmodified line5354555657585960616263646566676869707129 unmodified lines10110210310410510610710810911011135 unmodified lines1471481491501511521531541553 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821 unmodified line1841851861871881891901911921931941951961971982 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222310 unmodified lines23423523623723823924024124224324415 unmodified lines26026126226326426526652 unmodified lines3193203213223233243257 unmodified lines33333433533633733833934034134234334434557 unmodified lines4034044054064074084094 unmodified lines41441541641741841942029 unmodified lines4504514524534544554563 unmodified lines46046146246346446546613 unmodified lines48048148248348448548648 unmodified lines535536537538539540541126 unmodified lines668669670671672673674675676677678679680681682683684685686687688689690691import osimport reimport loggingfrom datetime import datetimefrom typing import List, Dict, Optional, Tuplefrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.responses import PlainTextResponse27 unmodified lines"https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000").split(",")# ------------------------------------------------------------------# Pricing: keywords for deterministic interception# ------------------------------------------------------------------PRICING_KEYWORDS = re.compile(r'\b(how much|cost|price|pricing|retainer|fee|quote|bill|charge|what.*pay|budget)\b',re.IGNORECASE)# Fallback pricing (matches your services.html) – used if DB is unreachableFALLBACK_PRICING = [{"service_key": "inventory_system", "service_name": "Inventory Management System","price_naira": None, "price_range_low": 450000, "price_range_high": 750000, "is_one_time": True,"note": "One-time setup. Includes deployment and training."},{"service_key": "ai_workflow_automation", "service_name": "AI Workflow Automation",1 unmodified line"note": "One-time setup."},{"service_key": "erp_design", "service_name": "ERP Design & Integration","price_naira": None, "price_range_low": 600000, "price_range_high": 1200000, "is_one_time": True,"note": "One-time setup. Optional monthly support."},{"service_key": "ai_concierge", "service_name": "AI Business Concierge","price_naira": None, "price_range_low": 450000, "price_range_high": 800000, "is_one_time": True,"note": "One-time setup."},{"service_key": "website_design", "service_name": "Website Design","price_naira": None, "price_range_low": 300000, "price_range_high": 450000, "is_one_time": True,"note": "One-time setup. Hosting and domain not included."},{"service_key": "business_systems_audit", "service_name": "Business Systems Audit","price_naira": 150000, "price_range_low": None, "price_range_high": None, "is_one_time": True,"note": "One-time engagement."},{"service_key": "monthly_systems_management", "service_name": "Business Systems Management & Support","price_naira": None, "price_range_low": 200000, "price_range_high": 350000, "is_one_time": False,"note": "Per month. Includes monitoring and support."},]# ------------------------------------------------------------------29 unmodified linesembedder: Optional[SentenceTransformer] = Nonesupabase: Optional[Client] = None# Pricing cache (loaded from DB at startup, can be refreshed)pricing_cache: List[Dict] = []# ------------------------------------------------------------------# Greeting & small-talk detection# ------------------------------------------------------------------GREETINGS = {"hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up",35 unmodified linesreturn None# ------------------------------------------------------------------# Pricing: load from DB + deterministic answer (no LLM)# ------------------------------------------------------------------async def load_pricing_from_db() -> List[Dict]:try:db = get_supabase()result = db.table("service_pricing").select("*").eq("is_active", True).execute()3 unmodified linesreturn []def get_deterministic_pricing(user_query: str) -> Optional[str]:"""Return plain‑text pricing answer without any LLM."""global pricing_cacheif not PRICING_KEYWORDS.search(user_query):return Nonequery_lower = user_query.lower()response_lines = []matched = Falsepricing_data = pricing_cache if pricing_cache else FALLBACK_PRICINGkeyword_to_service = {"inventory": "inventory_system","expiry": "inventory_system","erp": "erp_design","concierge": "ai_concierge","chatbot": "ai_concierge","website": "website_design","site": "website_design","audit": "business_systems_audit","retainer": "monthly_systems_management",1 unmodified line"workflow": "ai_workflow_automation","automation": "ai_workflow_automation",}service_key = Nonefor kw, key in keyword_to_service.items():if kw in query_lower:service_key = keymatched = Truebreakif service_key:service = next((s for s in pricing_data if s.get("service_key") == service_key), None)if service:desc = service.get("service_name", "")2 unmodified lineshigh = service.get("price_range_high")is_one_time = service.get("is_one_time", True)note = service.get("note", "")if price_naira:price_str = f"₦{price_naira:,}"elif low and high:price_str = f"₦{low:,} – ₦{high:,}"else:price_str = "custom quote required"period = "one-time setup" if is_one_time else "per month"response_lines.append(f"{desc} – {price_str} ({period})")if note:# No underscores – plain textresponse_lines.append(note)else:matched = Falseif not matched:response_lines.append("Here are Michael's standard pricing ranges for common services:\n")for s in pricing_data:name = s.get("service_name", "")10 unmodified linesperiod = "(one-time)" if is_one_time else "(per month)"response_lines.append(f"• {name} – {price_str} {period}")matched = Trueif matched:response_lines.append("\n📞 For a precise quote tailored to your specific needs, click the WhatsApp button (📱) in this chat to contact Michael directly.")return "\n".join(response_lines)return None# ------------------------------------------------------------------15 unmodified linesreturn embedder# ------------------------------------------------------------------# HTML fetching & chunking# ------------------------------------------------------------------async def fetch_html(url: str) -> str:async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:52 unmodified lineslogger.info("Knowledge base refresh complete.")# ------------------------------------------------------------------# Vector search# ------------------------------------------------------------------def vector_search(query: str, top_k: int = TOP_K) -> List[Dict]:model = get_embedder()7 unmodified linesreturn result.data or []# ------------------------------------------------------------------# LLM reply with grounding and source citations# ------------------------------------------------------------------async def get_grounded_reply_with_sources(user_message: str, relevant_chunks: List[Dict]) -> Tuple[str, List[str]]:if not relevant_chunks:escalation_msg = ("I couldn't find specific information about that in Michael's knowledge base. ""Please click the WhatsApp button (📱) in this chat to contact Michael directly.\n\n""You can also ask me about his AI systems, skills, experience, or services.")return escalation_msg, []57 unmodified linesif not reply:reply = ("I'm experiencing technical difficulties. ""Please click the WhatsApp button (📱) in this chat to reach Michael directly.")if sources:4 unmodified linesreturn reply, sources# ------------------------------------------------------------------# Manual knowledge management# ------------------------------------------------------------------async def add_manual_chunk(content: str, source_url: str = "manual"):model = get_embedder()29 unmodified linesif smalltalk:return {"response": smalltalk}# 2. Deterministic pricing (bypass LLM)pricing_answer = get_deterministic_pricing(req.message)if pricing_answer:return {"response": pricing_answer}3 unmodified linesif not results:escalation = ("I don't have specific information on that in my knowledge base. ""Please click the WhatsApp button (📱) in this chat to contact Michael directly.\n\n""I can help with his AI systems, skills, work experience, and services.")return {"response": escalation}13 unmodified lines@app.post("/api/admin/refresh-pricing")async def refresh_pricing(background_tasks: BackgroundTasks):"""Reload pricing cache from database without restarting."""async def reload():global pricing_cachepricing_cache = await load_pricing_from_db()48 unmodified lines}# ------------------------------------------------------------------# Chat widget (embedded JS) – same as original but no changes needed# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():126 unmodified lines"""# ------------------------------------------------------------------# Startup: load embedder, pricing cache, and check knowledge base# ------------------------------------------------------------------@app.on_event("startup")async def startup():global pricing_cachelogger.info("Starting Kevs Portfolio AI Assistant (deterministic pricing from DB)...")get_embedder()# Load pricing from database (fallback to FALLBACK_PRICING if DB fails)pricing_cache = await load_pricing_from_db()if not pricing_cache:logger.warning("No pricing data from DB, using fallback.")pricing_cache = FALLBACK_PRICINGelse:logger.info(f"Loaded {len(pricing_cache)} pricing entries from database.")try:db = get_supabase()count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0logger.info(f"Supabase connected. {count} knowledge chunks in database.")if count == 0:
app.py+44-45