Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011125 unmodified lines181920212223242526272829302 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301312 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581592 unmodified lines1621631641651661671689 unmodified lines17817918018118218318458 unmodified lines243244245246247248249250251252253254255256257258259260261262263264import osimport loggingimport httpxfrom datetime import datetimefrom typing import List, Dictfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import PlainTextResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom sentence_transformers import SentenceTransformerimport faissimport numpy as np5 unmodified lines# ------------------------------------------------------------------GROQ_API_KEY = os.environ.get("GROQ_API_KEY")GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")WHATSAPP_NUMBER = os.environ.get("WHATSAPP_NUMBER", "+2347067666205") # Your WhatsAppPRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://YOUR-SPACE-NAME.hf.space")app = FastAPI(title="Kevs Portfolio AI Assistant")app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],2 unmodified lineslogger = logging.getLogger(__name__)# ------------------------------------------------------------------# Knowledge base (extracted from your portfolio HTML)# ------------------------------------------------------------------KNOWLEDGE_CHUNKS = [# Hero & About"Michael Onoriode is a Business Automation & Systems Engineer. He builds AI pipelines, inventory intelligence, and workflow automation. Grew MuzoScents from 0 to ₦900k revenue in 11 months with 42% margin.","He engineered an inventory intelligence system that pinpoints ₦2M+ monthly expiry loss across 36,000+ SKUs using custom FEFO risk matrices.","Deployed 4 live AI systems: RAG concierge, anomaly detection, custom ERP (MZIMS), and a growth advisor.","Built a temporary e-commerce operational layer with Paystack webhooks + Supabase + CSV exports ahead of platform launch.",# Automation Skills"Technical stack: Python, Streamlit, Supabase, PostgreSQL (pg_cron, views, RPC), Pandas, FastAPI, Hugging Face Spaces.","AI & intelligence: RAG (retrieval-augmented generation), LLM pipelines (Groq, Gemini), vector retrieval, autonomous anomaly detection with pg_cron.","Workflow automation: Google Apps Script (Gmail API), ERP logic (FEFO risk scoring), inventory intelligence systems.",# Case study – Inventory Intelligence"Case Study: Production‑Hardened Inventory Engine for 36,000+ SKUs. Problem: ₦1.5–2M monthly expiry loss. Solution: Python/Streamlit + Supabase + pg_cron. Custom FEFO risk scoring, automated every 6 hours. Results: pinpoints exact loss drivers, runs on free tier, eliminated manual accounting overhead.",# Case study – MuzoScents (organic growth)"Case Study: Strategic Organic Traffic Growth for E‑commerce Brand (MuzoScents). Used CJM, JTBD, Blue Ocean Strategy, TAM‑SAM‑SOM. Result: 46.7% organic traffic growth, landed client with 27× average deal profit.",# Case study – Full‑stack MarTech"Case Study: Full‑Stack MarTech Engineering for Content Authority. Built serverless lead capture (Node.js), MongoDB Atlas, Brevo API integration. Achieved data ownership and automated CRM nurturing.",# Experience – Kevs Digital"Kevs Digital: Founder & Principal Automation Engineer. Built 4 live AI systems, modular backend APIs (rate limiting, vector retrieval, JWT) on free‑tier infrastructure. Designed proprietary reporting dashboards, managed Meta/Google Ads.",# Experience – MuzoScents (CedarScentHub)"MuzoScents: Co‑creator & Digital Marketing Specialist. Zero to ₦900k sales (42% margin) in 11 months, no paid ads. Built custom ERP (MZIMS) for sales tracking, FEFO inventory, profit margin, automated financial reporting.",# Frameworks & strategy"Strategic frameworks used: SWOT, VRIO, PESTLE, TAM‑SAM‑SOM, Ansoff Matrix, BCG Matrix, CJM, JTBD, OKRs, RACI, Agile Marketing, PMF, NPS.",# Certifications"Certifications: HubSpot Digital Marketing, Google Search Ads, Social Media Marketing, Content Marketing, Canva, CapCut, WordPress/Elementor.",]# ------------------------------------------------------------------# Embedding & vector store# ------------------------------------------------------------------embedder = SentenceTransformer('all-MiniLM-L6-v2')dim = 384index = faiss.IndexFlatL2(dim)# Embed all chunkschunk_embeddings = embedder.encode(KNOWLEDGE_CHUNKS, convert_to_numpy=True)index.add(chunk_embeddings)def vector_search(query: str, top_k: int = 5) -> List[str]:q_emb = embedder.encode([query], convert_to_numpy=True)distances, indices = index.search(q_emb, top_k)results = [KNOWLEDGE_CHUNKS[i] for i in indices[0] if i >= 0]return results# ------------------------------------------------------------------# LLM call (Groq → Gemini fallback)# ------------------------------------------------------------------async def get_ai_reply(user_message: str, context_chunks: List[str]) -> str:context = "\n\n".join(context_chunks)system_prompt = f"""You are Kevs AI Assistant – a helpful, professional guide for Michael Onoriode's portfolio.Your knowledge (from his portfolio):{context}Instructions:- Answer questions about Michael's skills, projects, experience, and services.- If the user asks for contact or human help, offer to connect via WhatsApp.- If you cannot answer, say: "I'm not sure, but you can talk to Michael directly on WhatsApp."- Keep answers concise and friendly.User: {user_message}Assistant:"""if GROQ_API_KEY:try:groq = Groq(api_key=GROQ_API_KEY)resp = groq.chat.completions.create(messages=[{"role": "user", "content": system_prompt}],model="llama-3.3-70b-versatile",temperature=0.7,max_tokens=500)return resp.choices[0].message.contentexcept Exception as e:logger.warning(f"Groq 70B error: {e}, trying 8B")try:resp = groq.chat.completions.create(messages=[{"role": "user", "content": system_prompt}],model="llama3-8b-8192",temperature=0.7,max_tokens=500)return resp.choices[0].message.contentexcept Exception as e2:logger.error(f"Groq 8B error: {e2}")if GEMINI_API_KEY:try:genai.configure(api_key=GEMINI_API_KEY)2 unmodified linesreturn response.textexcept Exception as e:logger.error(f"Gemini error: {e}")return "I'm having technical issues. Please reach out via WhatsApp (button below)."# ------------------------------------------------------------------# API endpoint# ------------------------------------------------------------------class ChatRequest(BaseModel):message: str@app.post("/api/chat")async def chat(req: ChatRequest):try:chunks = vector_search(req.message, top_k=4)reply = await get_ai_reply(req.message, chunks)return {"response": reply}except Exception as e:logger.exception("Chat error")raise HTTPException(status_code=500, detail=str(e))# ------------------------------------------------------------------# Chat widget JS (with WhatsApp handoff button)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():2 unmodified linesconst API_URL = '{PRODUCTION_HOST}';const WHATSAPP_NUMBER = '{WHATSAPP_NUMBER}';// Create widget containerconst widgetDiv = document.createElement('div');widgetDiv.innerHTML = `<div id="kevs-chat-btn" style="position:fixed; bottom:20px; right:20px; width:60px; height:60px; background:#2563eb; border-radius:50%; cursor:pointer; z-index:10000; display:flex; align-items:center; justify-content:center; box-shadow:0 4px 12px rgba(0,0,0,0.2);">9 unmodified lines</div><div id="kevs-messages" style="flex:1; overflow-y:auto; padding:12px; background:#f9fafb;"></div><div style="padding:12px; border-top:1px solid #e5e7eb; display:flex; gap:8px;"><input id="kevs-input" placeholder="Ask about my skills or projects..." style="flex:1; padding:8px; border:1px solid #d1d5db; border-radius:24px; outline:none;" /><button id="kevs-send" style="background:#2563eb; color:white; border:none; padding:8px 16px; border-radius:24px; cursor:pointer;">Send</button></div></div>58 unmodified lineswindow.open(waUrl, '_blank');}};addMessage("👋 Hi! I'm Kevs AI. Ask me about Michael's skills, projects, automation systems, or experience. Or click WhatsApp to talk directly.", false);}})();"""# ------------------------------------------------------------------# Health & root# ------------------------------------------------------------------@app.get("/")async def root():return {"service": "Kevs Portfolio AI Assistant","status": "active","endpoints": "/api/chat, /chat-widget.js","whatsapp_handoff": f"https://wa.me/{WHATSAPP_NUMBER}"}@app.get("/health")async def health():return {"status": "ok", "timestamp": datetime.now().isoformat()}123456789101112131415165 unmodified lines222324252627282930313233343536373839404142434445464748492 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552 unmodified lines2582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982992 unmodified lines3023033043053063079 unmodified lines31731831932032132232358 unmodified lines382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416import osimport loggingimport reimport pickleimport asynciofrom datetime import datetimefrom typing import List, Dict, Optionalfrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.responses import PlainTextResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport httpxfrom bs4 import BeautifulSoupfrom sentence_transformers import SentenceTransformerimport faissimport numpy as np5 unmodified lines# ------------------------------------------------------------------GROQ_API_KEY = os.environ.get("GROQ_API_KEY")GEMINI_API_KEY = os.environ.get("GEMINI_API_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.7"))TEMPERATURE = float(os.environ.get("TEMPERATURE", "0.2"))# Disk cache paths (Hugging Face Spaces persistent storage)CACHE_DIR = "/data"os.makedirs(CACHE_DIR, exist_ok=True)CHUNKS_CACHE = os.path.join(CACHE_DIR, "knowledge_chunks.pkl")INDEX_CACHE = os.path.join(CACHE_DIR, "faiss_index.bin")# CORS: restrict to your Netlify URL + localhost for devALLOWED_ORIGINS = os.environ.get("ALLOWED_ORIGINS", "https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000").split(",")app = FastAPI(title="Kevs Portfolio + Services AI Assistant")app.add_middleware(CORSMiddleware,allow_origins=ALLOWED_ORIGINS,allow_credentials=True,allow_methods=["*"],allow_headers=["*"],2 unmodified lineslogger = logging.getLogger(__name__)# ------------------------------------------------------------------# Global state# ------------------------------------------------------------------knowledge_chunks: List[str] = []index: Optional[faiss.IndexFlatL2] = Noneembedder: Optional[SentenceTransformer] = None# ------------------------------------------------------------------# HTML fetching & text extraction# ------------------------------------------------------------------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_text_from_html(html: str, url: str) -> List[str]:soup = BeautifulSoup(html, 'html.parser')# Remove irrelevant elementsfor tag in soup(['script', 'style', 'nav', 'footer', 'header']):tag.decompose()chunks = []# Services page specific extractionif "services" in url:for service_heading in soup.find_all(['h3', 'h4']):heading_text = service_heading.get_text(strip=True)next_elem = service_heading.find_next_sibling()service_desc = ""while next_elem and next_elem.name not in ['h3', 'h4', 'h2']:if next_elem.name in ['p', 'ul', 'li']:service_desc += next_elem.get_text(strip=True) + " "next_elem = next_elem.find_next_sibling()if service_desc:chunks.append(f"{heading_text}: {service_desc}")# Pricing tabletable = soup.find('table')if table:table_text = table.get_text(strip=True)chunks.append(f"Service Pricing: {table_text}")else:# Main portfolio pagesections = []for section_id in ['hero', 'about', 'skills', 'portfolio', 'experience', 'automation-skills']:elem = soup.find(id=section_id)if elem:sections.append(elem)for card in soup.find_all(class_=re.compile(r'card|collapsible-container|prose')):if card not in sections:sections.append(card)if not sections:sections.append(soup.body)for section in sections:for elem in section.find_all(['h1', 'h2', 'h3', 'h4', 'p', 'li']):text = elem.get_text(strip=True)if len(text) > 50:chunks.append(text)elif text and elem.name in ['h1','h2','h3','h4']:chunks.append(text)# Deduplicateseen = set()unique_chunks = []for c in chunks:if c not in seen:seen.add(c)unique_chunks.append(c)logger.info(f"Extracted {len(unique_chunks)} text chunks from {url}")return unique_chunksasync def refresh_knowledge_base():global embedder, index, knowledge_chunkslogger.info("Refreshing knowledge base from portfolio and services pages...")all_chunks = []for url in PORTFOLIO_URLS:try:html = await fetch_html(url)chunks = extract_text_from_html(html, url)all_chunks.extend(chunks)except Exception as e:logger.exception(f"Failed to fetch or parse {url}: {e}")if all_chunks:# Deduplicate across all pagesseen = set()unique_all_chunks = []for c in all_chunks:if c not in seen:seen.add(c)unique_all_chunks.append(c)if embedder is None:embedder = SentenceTransformer('all-MiniLM-L6-v2')knowledge_chunks = unique_all_chunksembeddings = embedder.encode(unique_all_chunks, convert_to_numpy=True)dim = embeddings.shape[1]index = faiss.IndexFlatL2(dim)index.add(embeddings)# Save to disk cachewith open(CHUNKS_CACHE, "wb") as f:pickle.dump(knowledge_chunks, f)faiss.write_index(index, INDEX_CACHE)logger.info(f"Saved {len(knowledge_chunks)} chunks and index to {CACHE_DIR}")else:logger.error("No chunks extracted – keeping existing index")def load_from_cache():global knowledge_chunks, index, embedderif os.path.exists(CHUNKS_CACHE) and os.path.exists(INDEX_CACHE):try:with open(CHUNKS_CACHE, "rb") as f:knowledge_chunks = pickle.load(f)index = faiss.read_index(INDEX_CACHE)embedder = SentenceTransformer('all-MiniLM-L6-v2')logger.info(f"Loaded {len(knowledge_chunks)} chunks and FAISS index from disk cache")return Trueexcept Exception as e:logger.warning(f"Failed to load from cache: {e}")return Falsereturn False# ------------------------------------------------------------------# Vector search with threshold# ------------------------------------------------------------------def vector_search(query: str, top_k: int = 5) -> List[Dict[str, any]]:if index is None or embedder is None:return []q_emb = embedder.encode([query], convert_to_numpy=True)distances, indices = index.search(q_emb, top_k)results = []for i, idx in enumerate(indices[0]):if idx == -1:continuedistance = distances[0][i]similarity = 1 / (1 + distance)if similarity >= SIMILARITY_THRESHOLD:results.append({"chunk": knowledge_chunks[idx],"similarity": similarity})return results# ------------------------------------------------------------------# LLM call with strict grounding# ------------------------------------------------------------------async def get_grounded_reply(user_message: str, relevant_chunks: List[str]) -> str:if not relevant_chunks:return ("I can only answer questions based on Michael Onoriode's portfolio and services. ""Your question doesn't seem to match the content I have. ""Please ask about his skills, projects, automation systems, experience, or the services he offers (web design, SEO, analytics, email marketing, audits). ""You can also click the WhatsApp button to talk directly with Michael.")context = "\n\n---\n\n".join(relevant_chunks)system_prompt = f"""You are Kevs AI Assistant, a strict, grounded chatbot for Michael Onoriode's professional portfolio and services.**CRITICAL RULES:**1. ONLY use the provided context below to answer. DO NOT use any external knowledge or prior training.2. If the user asks something not covered in the context, say: "I don't have that information in my knowledge base. Please ask about Michael's skills, projects (like inventory intelligence, MuzoScents, Kevs Digital), automation systems, experience, or the digital marketing services he offers (web design, SEO, analytics, email marketing, audits)."3. Never invent facts, URLs, or projects.4. Keep answers concise (max 3 sentences unless context requires more).5. If the user asks for pricing or service details, provide the information from the context if available, otherwise direct them to request a detailed pricelist via WhatsApp.6. If the user asks for contact, offer the WhatsApp button (provide the WhatsApp number from configuration).**Context (from portfolio and services pages):**{context}User question: {user_message}Answer strictly from context:"""if GROQ_API_KEY:try:groq = Groq(api_key=GROQ_API_KEY)resp = groq.chat.completions.create(messages=[{"role": "user", "content": system_prompt}],model="llama-3.3-70b-versatile",temperature=TEMPERATURE,max_tokens=400)return resp.choices[0].message.contentexcept Exception as e:logger.warning(f"Groq error: {e}, falling back to 8B")try:resp = groq.chat.completions.create(messages=[{"role": "user", "content": system_prompt}],model="llama3-8b-8192",temperature=TEMPERATURE,max_tokens=400)return resp.choices[0].message.contentexcept Exception as e2:logger.error(f"Groq 8B error: {e2}")if GEMINI_API_KEY:try:genai.configure(api_key=GEMINI_API_KEY)2 unmodified linesreturn response.textexcept Exception as e:logger.error(f"Gemini error: {e}")return "I'm having technical difficulties. Please use the WhatsApp button to reach Michael directly."# ------------------------------------------------------------------# API endpoints# ------------------------------------------------------------------class ChatRequest(BaseModel):message: str@app.post("/api/chat")async def chat(req: ChatRequest):if index is None or embedder is None:raise HTTPException(status_code=503, detail="Knowledge base not ready. Please refresh.")relevant = vector_search(req.message, top_k=4)reply = await get_grounded_reply(req.message, [r["chunk"] for r in relevant])return {"response": reply}@app.post("/api/refresh")async def refresh(background_tasks: BackgroundTasks):background_tasks.add_task(refresh_knowledge_base)return {"message": "Refresh started. Will take a few seconds."}@app.get("/api/status")async def status():return {"knowledge_chunks": len(knowledge_chunks),"index_ready": index is not None,"last_refresh": datetime.now().isoformat(),"threshold": SIMILARITY_THRESHOLD,"temperature": TEMPERATURE,"urls": PORTFOLIO_URLS,"cache_used": os.path.exists(CHUNKS_CACHE) and os.path.exists(INDEX_CACHE)}# ------------------------------------------------------------------# Widget JS (with WhatsApp handoff)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():2 unmodified linesconst API_URL = '{PRODUCTION_HOST}';const WHATSAPP_NUMBER = '{WHATSAPP_NUMBER}';const widgetDiv = document.createElement('div');widgetDiv.innerHTML = `<div id="kevs-chat-btn" style="position:fixed; bottom:20px; right:20px; width:60px; height:60px; background:#2563eb; border-radius:50%; cursor:pointer; z-index:10000; display:flex; align-items:center; justify-content:center; box-shadow:0 4px 12px rgba(0,0,0,0.2);">9 unmodified lines</div><div id="kevs-messages" style="flex:1; overflow-y:auto; padding:12px; background:#f9fafb;"></div><div style="padding:12px; border-top:1px solid #e5e7eb; display:flex; gap:8px;"><input id="kevs-input" placeholder="Ask about my skills, projects, services, or experience..." style="flex:1; padding:8px; border:1px solid #d1d5db; border-radius:24px; outline:none;" /><button id="kevs-send" style="background:#2563eb; color:white; border:none; padding:8px 16px; border-radius:24px; cursor:pointer;">Send</button></div></div>58 unmodified lineswindow.open(waUrl, '_blank');}};addMessage("👋 Hi! I'm Kevs AI. I can answer questions about Michael's skills, automation systems, projects, experience, and the digital marketing services he offers. If I can't help, click WhatsApp to talk directly.", false);}})();"""# ------------------------------------------------------------------# Startup & health# ------------------------------------------------------------------@app.on_event("startup")async def startup():# Try to load from disk cache firstif not load_from_cache():logger.info("Cache not found or invalid; scraping and building fresh index.")await refresh_knowledge_base()else:# Optionally run a background refresh to check for updates (you can schedule this)logger.info("Loaded from cache. Use /api/refresh to manually update from live site.")@app.get("/")async def root():return {"service": "Kevs Portfolio + Services AI Assistant","status": "active","endpoints": "/api/chat, /chat-widget.js, /api/refresh, /api/status","whatsapp_handoff": f"https://wa.me/{WHATSAPP_NUMBER}","urls_loaded": PORTFOLIO_URLS,"threshold": SIMILARITY_THRESHOLD,"temperature": TEMPERATURE}@app.get("/health")async def health():return {"status": "ok", "chunks_loaded": len(knowledge_chunks), "timestamp": datetime.now().isoformat()}
app.py+234-82