Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707128 unmodified lines10010110210310410510610710810911011135 unmodified lines1471481491501511521535 unmodified lines1591601611621631641651 unmodified line16716816917017117217327 unmodified lines20120220320420520620720820921021121221321421521621721819 unmodified lines23823924024124224324415 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833922 unmodified lines36236336436536636736836937037137237344 unmodified lines4184194204214224234244254264274284293 unmodified lines43343443543643743843910 unmodified lines4504514524534544554564574584594604613 unmodified lines4654664674684694704711 unmodified line47347447547647747847948048148248348448548648748848949049149249324 unmodified lines518519520521522523524525526527528529530531532533534535536537538539540541126 unmodified lines6686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187196 unmodified linesfrom fastapi.responses import PlainTextResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport httpxfrom bs4 import BeautifulSoupfrom sentence_transformers import SentenceTransformerfrom google import genaifrom groq import Groqfrom supabase import create_client, Client# ------------------------------------------------------------------# Configuration# ------------------------------------------------------------------GROQ_API_KEY = os.environ.get("GROQ_API_KEY")GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")WHATSAPP_NUMBER = os.environ.get("WHATSAPP_NUMBER", "+2347067666205")PORTFOLIO_URLS = [os.environ.get("PORTFOLIO_URL", "https://kevs-ono-portfolio.netlify.app/"),os.environ.get("SERVICES_URL", "https://kevs-ono-portfolio.netlify.app/services.html"),]PRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://YOUR-SPACE.hf.space")SIMILARITY_THRESHOLD = float(os.environ.get("SIMILARITY_THRESHOLD", "0.30"))TEMPERATURE = float(os.environ.get("TEMPERATURE", "0.2"))TOP_K = int(os.environ.get("TOP_K", "6"))ALLOWED_ORIGINS = os.environ.get("ALLOWED_ORIGINS","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","price_naira": None, "price_range_low": 500000, "price_range_high": 900000, "is_one_time": True,"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."},]# ------------------------------------------------------------------28 unmodified lines# ------------------------------------------------------------------embedder: 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:5 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 None1 unmodified linequery_lower = user_query.lower()response_lines = []matched = Falsepricing_data = pricing_cache if pricing_cache else FALLBACK_PRICINGkeyword_to_service = {27 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 = False19 unmodified linesif 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:resp = await client.get(url)resp.raise_for_status()return resp.textdef extract_chunks_from_html(html: str, url: str) -> List[str]:soup = BeautifulSoup(html, "html.parser")for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):tag.decompose()main = soup.find("main") or soup.find("body")if not main:return []chunks = []for el in main.find_all(["h1", "h2", "h3", "h4", "p", "li"]):text = el.get_text(strip=True)if len(text) > 40 and not text.startswith(("Skip", "Menu", "Cookie")):chunks.append(text)seen, unique = set(), []for c in chunks:if c not in seen:seen.add(c)unique.append(c)logger.info(f"Extracted {len(unique)} chunks from {url}")return uniqueasync def upsert_chunks_to_supabase(chunks: List[str], source_url: str):db = get_supabase()model = get_embedder()embeddings = model.encode(chunks, convert_to_numpy=True, show_progress_bar=False)db.table("portfolio_knowledge").delete().eq("source_url", source_url).execute()logger.info(f"Cleared old chunks for {source_url}")rows = [{"source_url": source_url, "content": chunk, "embedding": emb.tolist()}for chunk, emb in zip(chunks, embeddings)]batch_size = 100for i in range(0, len(rows), batch_size):db.table("portfolio_knowledge").insert(rows[i:i + batch_size]).execute()logger.info(f"Inserted batch {i // batch_size + 1} ({len(rows[i:i+batch_size])} rows) for {source_url}")logger.info(f"Upserted {len(rows)} chunks for {source_url}")async def refresh_knowledge_base():logger.info("Refreshing knowledge base from live pages...")for url in PORTFOLIO_URLS:try:html = await fetch_html(url)chunks = extract_chunks_from_html(html, url)if chunks:await upsert_chunks_to_supabase(chunks, url)else:logger.warning(f"No chunks extracted from {url}")except Exception as e:logger.exception(f"Failed to refresh {url}: {e}")logger.info("Knowledge base refresh complete.")# ------------------------------------------------------------------# Vector search# ------------------------------------------------------------------def vector_search(query: str, top_k: int = TOP_K) -> List[Dict]:model = get_embedder()q_emb = model.encode([query], convert_to_numpy=True)[0].tolist()db = get_supabase()result = db.rpc("match_portfolio_chunks", {"query_embedding": q_emb,"match_threshold": SIMILARITY_THRESHOLD,"match_count": top_k,}).execute()return 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:22 unmodified linesSTRICT GROUNDING RULES:1. ONLY use the provided context below. Never invent facts, prices, or projects.2. When answering, include inline citations like [1], [2] referencing the numbered chunks.3. If the question is about pricing, do NOT answer β the system already handled pricing deterministically. Instead say: "For pricing, please check the pricing information above or contact Michael on WhatsApp."4. For skill questions, synthesize all relevant categories from context.5. For project questions, include problem, tech stack, outcome if available.6. If partially covered, answer what you can and suggest WhatsApp for details.7. Never invent URLs, names, or dates.8. End with a short "π Want a tailored quote? β WhatsApp" only if the user seems interested in hiring.CONTEXT (with sources):{context}44 unmodified lines# ------------------------------------------------------------------async def add_manual_chunk(content: str, source_url: str = "manual"):model = get_embedder()emb = model.encode([content], convert_to_numpy=True)[0].tolist()db = get_supabase()db.table("portfolio_knowledge").insert({"source_url": source_url,"content": content,"embedding": emb,}).execute()logger.info(f"Manually added chunk: {content[:60]}...")3 unmodified lineslogger.info(f"Deleted chunk ID {chunk_id}")async def list_chunks(source_url: Optional[str] = None, limit: int = 50) -> List[Dict]:db = get_supabase()query = db.table("portfolio_knowledge").select("id, source_url, content, created_at").limit(limit)if source_url:query = query.eq("source_url", source_url)10 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. Vector searchresults = vector_search(req.message, top_k=TOP_K)if not results:escalation = (3 unmodified lines)return {"response": escalation}# 4. Grounded LLM reply with sourcesreply, _ = await get_grounded_reply_with_sources(req.message, results)return {"response": reply}1 unmodified linelogger.exception(f"Chat error: {e}")raise HTTPException(status_code=500, detail="Internal error during search.")@app.post("/api/refresh")async def refresh(background_tasks: BackgroundTasks):background_tasks.add_task(refresh_knowledge_base)return {"message": "Refresh started β scraping portfolio and services pages into Supabase."}@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()logger.info(f"Pricing cache refreshed. {len(pricing_cache)} entries loaded.")background_tasks.add_task(reload)return {"message": "Pricing cache refresh started."}@app.post("/api/knowledge/add")async def add_knowledge(req: ManualChunkRequest):try:24 unmodified lines@app.get("/api/status")async def status():try:db = get_supabase()count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0except Exception:count = -1return {"knowledge_chunks_in_db": count,"embedder_loaded": embedder is not None,"supabase_connected": supabase is not None,"pricing_cache_entries": len(pricing_cache),"threshold": SIMILARITY_THRESHOLD,"top_k": TOP_K,"temperature": TEMPERATURE,"urls": PORTFOLIO_URLS,"timestamp": datetime.now().isoformat(),}# ------------------------------------------------------------------# 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:logger.info("Database empty β running initial scrape.")await refresh_knowledge_base()else:logger.info(f"Knowledge base ready ({count} chunks). Use /api/refresh to update.")except Exception as e:logger.error(f"Startup error: {e}")@app.get("/")async def root():return {"service": "Kevs Portfolio + Services AI Assistant (Deterministic pricing from Supabase)","status": "active","backend": "Supabase pgvector + Groq Llama 3.3 70B","pricing_source": "database (cached)","endpoints": ["/api/chat","/api/refresh","/api/admin/refresh-pricing","/api/status","/api/knowledge/add","/api/knowledge/list","/api/knowledge/delete","/chat-widget.js",],"whatsapp": f"https://wa.me/{WHATSAPP_NUMBER}",}@app.get("/health")6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575828 unmodified lines8788899091929394959635 unmodified lines1321331341351361371381391401411421431441451461471481491505 unmodified lines1561571581591601611 unmodified line16316416516616716827 unmodified lines19619719819920020120220320420520620720820921019 unmodified lines23023123223323423515 unmodified lines25125225325425525625725825926026126226326426526626726826927027122 unmodified lines29429529629729829930030130230330430544 unmodified lines3503513523533543553563573583593603613 unmodified lines36536636736836937037110 unmodified lines3823833843853863873883893903913923933943953963973983 unmodified lines4024034044054064074081 unmodified line41041141241341441524 unmodified lines440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471126 unmodified lines5985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336 unmodified linesfrom fastapi.responses import PlainTextResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom sentence_transformers import SentenceTransformerfrom google import genaifrom groq import Groqfrom supabase import create_client, Client# ------------------------------------------------------------------# Configuration (reads from environment variables)# ------------------------------------------------------------------GROQ_API_KEY = os.environ.get("GROQ_API_KEY")GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")WHATSAPP_NUMBER = os.environ.get("WHATSAPP_NUMBER", "+2347067666205")PRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://YOUR-SPACE.hf.space")SIMILARITY_THRESHOLD = float(os.environ.get("SIMILARITY_THRESHOLD", "0.15"))TEMPERATURE = float(os.environ.get("TEMPERATURE", "0.2"))TOP_K = int(os.environ.get("TOP_K", "12"))ALLOWED_ORIGINS = os.environ.get("ALLOWED_ORIGINS","https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000").split(",")# ------------------------------------------------------------------# Pricing keywords & deterministic contact# ------------------------------------------------------------------PRICING_KEYWORDS = re.compile(r'\b(how much|cost|price|pricing|retainer|fee|quote|bill|charge|what.*pay|budget)\b',re.IGNORECASE)CONTACT_KEYWORDS = re.compile(r'\b(phone|contact|whatsapp|number|reach|call|email|get in touch)\b',re.IGNORECASE)# Fallback pricing (only used if DB fails)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."},{"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": "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."},]# ------------------------------------------------------------------28 unmodified lines# ------------------------------------------------------------------embedder: Optional[SentenceTransformer] = Nonesupabase: Optional[Client] = Nonepricing_cache: List[Dict] = []# ------------------------------------------------------------------# Greeting & small-talk (unchanged)# ------------------------------------------------------------------GREETINGS = {"hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up",35 unmodified linesreturn None# ------------------------------------------------------------------# Deterministic contact handler# ------------------------------------------------------------------def get_deterministic_contact(user_query: str) -> Optional[str]:if CONTACT_KEYWORDS.search(user_query):return (f"Michael's WhatsApp number is {WHATSAPP_NUMBER}. "f"Click the WhatsApp button (π±) in this chat to message him directly.\n\n"f"You can also email him at mickevsono@gmail.com.")return None# ------------------------------------------------------------------# Deterministic pricing (from DB cache)# ------------------------------------------------------------------async def load_pricing_from_db() -> List[Dict]:try:5 unmodified linesreturn []def get_deterministic_pricing(user_query: str) -> Optional[str]:global pricing_cacheif not PRICING_KEYWORDS.search(user_query):return None1 unmodified linequery_lower = user_query.lower()response_lines = []matched = Falsepricing_data = pricing_cache if pricing_cache else FALLBACK_PRICINGkeyword_to_service = {27 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(note)else:matched = False19 unmodified linesif 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# ------------------------------------------------------------------# Vector search (only over manual chunks now)# ------------------------------------------------------------------def vector_search(query: str, top_k: int = TOP_K) -> List[Dict]:model = get_embedder()q_emb = model.encode([query], convert_to_numpy=True)[0].tolist()db = get_supabase()result = db.rpc("match_portfolio_chunks", {"query_embedding": q_emb,"match_threshold": SIMILARITY_THRESHOLD,"match_count": top_k,}).execute()return result.data or []# ------------------------------------------------------------------# LLM reply with grounding# ------------------------------------------------------------------async def get_grounded_reply_with_sources(user_message: str, relevant_chunks: List[Dict]) -> Tuple[str, List[str]]:if not relevant_chunks:22 unmodified linesSTRICT GROUNDING RULES:1. ONLY use the provided context below. Never invent facts, prices, or projects.2. When answering, include inline citations like [1], [2] referencing the numbered chunks.3. If the question is about pricing, do NOT answer β the system already handled pricing deterministically.4. For broad skill questions, retrieve ALL skill categories from context (AI & Systems, Growth & Marketing, Technical, Analytics, Creative, Frameworks) and synthesise them into a grouped answer. Do not limit to one category.5. For project questions, include problem, tech stack, outcome if available.6. If partially covered, answer what you can and suggest WhatsApp for details.7. Never invent URLs, names, or dates.8. End with "π Want a tailored quote? β WhatsApp" only if the user seems interested in hiring.CONTEXT (with sources):{context}44 unmodified lines# ------------------------------------------------------------------async def add_manual_chunk(content: str, source_url: str = "manual"):model = get_embedder()emb = model.encode([content], convert_to_numpy=True)[0].tolist()db = get_supabase()db.table("portfolio_knowledge").insert({"source_url": source_url,"content": content,"embedding": emb,}).execute()logger.info(f"Manually added chunk: {content[:60]}...")3 unmodified lineslogger.info(f"Deleted chunk ID {chunk_id}")async def list_chunks(source_url: Optional[str] = None, limit: int = 50) -> List[Dict]:db = get_supabase()query = db.table("portfolio_knowledge").select("id, source_url, content, created_at").limit(limit)if source_url:query = query.eq("source_url", source_url)10 unmodified linesif smalltalk:return {"response": smalltalk}# 2. Deterministic contactcontact_answer = get_deterministic_contact(req.message)if contact_answer:return {"response": contact_answer}# 3. Deterministic pricingpricing_answer = get_deterministic_pricing(req.message)if pricing_answer:return {"response": pricing_answer}# 4. Vector search over manual knowledge baseresults = vector_search(req.message, top_k=TOP_K)if not results:escalation = (3 unmodified lines)return {"response": escalation}# 5. Grounded LLM replyreply, _ = await get_grounded_reply_with_sources(req.message, results)return {"response": reply}1 unmodified linelogger.exception(f"Chat error: {e}")raise HTTPException(status_code=500, detail="Internal error during search.")@app.post("/api/knowledge/add")async def add_knowledge(req: ManualChunkRequest):try:24 unmodified lines@app.get("/api/status")async def status():try:db = get_supabase()count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0except Exception:count = -1return {"knowledge_chunks_in_db": count,"embedder_loaded": embedder is not None,"supabase_connected": supabase is not None,"pricing_cache_entries": len(pricing_cache),"threshold": SIMILARITY_THRESHOLD,"top_k": TOP_K,"temperature": TEMPERATURE,"timestamp": datetime.now().isoformat(),}@app.post("/api/admin/refresh-pricing")async def refresh_pricing(background_tasks: BackgroundTasks):async def reload():global pricing_cachepricing_cache = await load_pricing_from_db()logger.info(f"Pricing cache refreshed. {len(pricing_cache)} entries loaded.")background_tasks.add_task(reload)return {"message": "Pricing cache refresh started."}# ------------------------------------------------------------------# Chat widget JS (full, with green WhatsApp button)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():126 unmodified lines"""# ------------------------------------------------------------------# Startup# ------------------------------------------------------------------@app.on_event("startup")async def startup():global pricing_cachelogger.info("Starting Kevs Portfolio AI Assistant (manual knowledge base only)...")get_embedder()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.")try:db = get_supabase()count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0logger.info(f"Supabase connected. {count} knowledge chunks (manual only).")except Exception as e:logger.error(f"Startup error: {e}")@app.get("/")async def root():return {"service": "Kevs Portfolio AI Assistant (Deterministic + Manual KB)","status": "active","backend": "Supabase pgvector + Groq Llama 3.3 70B","pricing_source": "database","knowledge_source": "manual chunks only (no scraping)","endpoints": ["/api/chat", "/api/status", "/api/knowledge/add", "/api/knowledge/list", "/api/knowledge/delete", "/api/admin/refresh-pricing", "/chat-widget.js"],"whatsapp": f"https://wa.me/{WHATSAPP_NUMBER}",}@app.get("/health")
app.py+76-162