Spaces:
Runtime error
Runtime error
Download app.py from low-key-007/chatbot-2: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/low-key-007/chatbot-2/resolve/main/app.py
- Command line
-
hf download hf://spaces/low-key-007/chatbot-2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/low-key-007/chatbot-2/resolve/main/app.py
16.5 kB
| import os, json | |
| import io | |
| from typing import List, Dict, Optional | |
| from pathlib import Path | |
| from fastapi import FastAPI, File, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, Field | |
| # ----------------------------- | |
| # Config: pick provider | |
| # ----------------------------- | |
| USE_MODEL_ENV = (os.getenv("USE_MODEL") or "").strip().lower() | |
| HAS_OPENAI = bool(os.getenv("OPENAI_API_KEY")) | |
| HAS_GEMINI = bool(os.getenv("GOOGLE_API_KEY")) | |
| if USE_MODEL_ENV == "openai" and not HAS_OPENAI: | |
| provider = "none" | |
| elif USE_MODEL_ENV == "gemini" and not HAS_GEMINI: | |
| provider = "none" | |
| elif USE_MODEL_ENV == "openai": | |
| provider = "openai" | |
| elif USE_MODEL_ENV == "gemini": | |
| provider = "gemini" | |
| else: | |
| provider = "openai" if HAS_OPENAI else ("gemini" if HAS_GEMINI else "none") | |
| # Lazy init | |
| openai_client = None | |
| gemini_model = None | |
| if provider == "openai": | |
| from openai import OpenAI | |
| openai_client = OpenAI() | |
| elif provider == "gemini": | |
| import google.generativeai as genai | |
| genai.configure(api_key=os.environ["GOOGLE_API_KEY"]) | |
| gemini_model = genai.GenerativeModel("gemini-1.5-flash") | |
| # ----------------------------- | |
| # Minimal site knowledge & rules | |
| # ----------------------------- | |
| ABOUT_ME = """ | |
| You are the website assistant for the portfolio of Nehanth Reddy. | |
| You can talk about: About, Projects, Blogs, Contact. | |
| Project categories include: Agentic AI, Deep Learning, LLMs, RAG, Security, Web Apps. | |
| NEVER reveal or output any website source code or internal files. | |
| """ | |
| NAV_HINT = """ | |
| If the user clearly asks to navigate to a site section, add exactly one marker at the very end: | |
| [[NAVIGATE: home|about|projects|blogs|contact|agentic-ai-projects|deep-learning-projects|llm-projects|machine-learning-projects|rag-projects|security-projects|web-apps-projects]] | |
| Only include a marker when navigation is explicitly requested. Never output code. | |
| """ | |
| # ----------------------------- | |
| # Persistent storage (portable) | |
| # ----------------------------- | |
| STORE_DIR = Path(os.getenv("STORE_DIR", "/data/store")) # β changed from /tmp/store | |
| STORE_DIR.mkdir(parents=True, exist_ok=True) | |
| KNOWLEDGE_FILE = STORE_DIR / "knowledge.json" | |
| FAISS_FILE = STORE_DIR / "knowledge.faiss" | |
| CHUNKS_FILE = STORE_DIR / "chunks.json" | |
| # ----------------------------- | |
| # Vector DB setup (Embeddings) | |
| # ----------------------------- | |
| import faiss | |
| import numpy as np | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| from langchain_openai import OpenAIEmbeddings | |
| from langchain_google_genai import GoogleGenerativeAIEmbeddings | |
| dimension = 1536 | |
| index = None | |
| knowledge_chunks = [] | |
| if provider == "openai": | |
| embedding_model = OpenAIEmbeddings( | |
| model="text-embedding-3-small", | |
| openai_api_key=os.getenv("OPENAI_API_KEY") | |
| ) | |
| dimension = 1536 | |
| print("β Using OpenAI embeddings for FAISS RAG.") | |
| elif provider == "gemini": | |
| embedding_model = GoogleGenerativeAIEmbeddings( | |
| model="models/embedding-001", | |
| google_api_key=os.getenv("GOOGLE_API_KEY") | |
| ) | |
| dimension = 768 | |
| print("β Using Google Generative AI embeddings for FAISS RAG.") | |
| else: | |
| class DummyEmbedder: | |
| def embed_documents(self, docs): | |
| return [[0.0] * dimension for _ in docs] | |
| def embed_query(self, q): | |
| return [0.0] * dimension | |
| embedding_model = DummyEmbedder() | |
| print("β οΈ No API key detected β using Dummy embeddings (RAG disabled).") | |
| def init_vectorstore(): | |
| """Load FAISS and chunks if available, else create new.""" | |
| global index, knowledge_chunks | |
| if FAISS_FILE.exists() and CHUNKS_FILE.exists(): | |
| index = faiss.read_index(str(FAISS_FILE)) | |
| with open(CHUNKS_FILE, "r", encoding="utf-8") as f: | |
| knowledge_chunks = json.load(f) | |
| print("β Loaded FAISS index with", len(knowledge_chunks), "chunks") | |
| else: | |
| index = faiss.IndexFlatL2(dimension) | |
| knowledge_chunks = [] | |
| print("β οΈ No FAISS index found, starting fresh") | |
| def save_vectorstore(): | |
| """Save FAISS + chunks to disk.""" | |
| faiss.write_index(index, str(FAISS_FILE)) | |
| with open(CHUNKS_FILE, "w", encoding="utf-8") as f: | |
| json.dump(knowledge_chunks, f) | |
| def add_to_vectorstore(text: str): | |
| """Split, embed and add text to FAISS index.""" | |
| global knowledge_chunks, index | |
| splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50) | |
| chunks = splitter.split_text(text) | |
| if not chunks: | |
| return | |
| vectors = embedding_model.embed_documents(chunks) | |
| vectors_np = np.array(vectors, dtype="float32") | |
| index.add(vectors_np) | |
| knowledge_chunks.extend(chunks) | |
| save_vectorstore() | |
| def retrieve_relevant(query: str, k=3): | |
| """Search top-k relevant chunks.""" | |
| if index is None or index.ntotal == 0: | |
| return [] | |
| q_vec = embedding_model.embed_query(query) | |
| q_vec_np = np.array([q_vec], dtype="float32") | |
| D, I = index.search(q_vec_np, k) | |
| return [knowledge_chunks[i] for i in I[0] if i < len(knowledge_chunks)] | |
| # NEW: Delete specific knowledge | |
| def delete_knowledge(entry: str) -> bool: | |
| """Delete a specific knowledge entry and rebuild FAISS.""" | |
| global knowledge_chunks, index | |
| # Update JSON | |
| if KNOWLEDGE_FILE.exists(): | |
| with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| else: | |
| data = {"knowledge": [], "instructions": []} | |
| if entry not in data.get("knowledge", []): | |
| return False | |
| data["knowledge"].remove(entry) | |
| with open(KNOWLEDGE_FILE, "w", encoding="utf-8") as f: | |
| json.dump(data, f, indent=2) | |
| # Rebuild FAISS from remaining knowledge | |
| index = faiss.IndexFlatL2(dimension) | |
| knowledge_chunks = [] | |
| for k in data.get("knowledge", []): | |
| add_to_vectorstore(k) | |
| return True | |
| # Initialize FAISS | |
| init_vectorstore() | |
| # ----------------------------- | |
| # Knowledge & Instructions Handling | |
| # ----------------------------- | |
| def load_data() -> dict: | |
| if os.path.exists(KNOWLEDGE_FILE): | |
| try: | |
| with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| except Exception: | |
| return {"knowledge": [], "instructions": []} | |
| return {"knowledge": [], "instructions": []} | |
| def save_data(data: dict): | |
| with open(KNOWLEDGE_FILE, "w", encoding="utf-8") as f: | |
| json.dump(data, f, indent=2) | |
| def load_knowledge() -> str: | |
| data = load_data() | |
| return "\n".join(data.get("knowledge", [])) | |
| def add_knowledge(text: str): | |
| data = load_data() | |
| data.setdefault("knowledge", []).append(text) | |
| save_data(data) | |
| def add_instruction(text: str): | |
| data = load_data() | |
| data.setdefault("instructions", []).append(text) | |
| save_data(data) | |
| def clear_instructions(): | |
| data = load_data() | |
| data["instructions"] = [] | |
| save_data(data) | |
| def delete_instruction(idx: int) -> Optional[str]: | |
| data = load_data() | |
| if 0 <= idx < len(data.get("instructions", [])): | |
| removed = data["instructions"].pop(idx) | |
| save_data(data) | |
| return removed | |
| return None | |
| def load_instructions() -> List[str]: | |
| data = load_data() | |
| return data.get("instructions", []) | |
| # ----------------------------- | |
| # File Parsing Helpers | |
| # ----------------------------- | |
| def extract_text_from_file(filename: str, content: bytes) -> str: | |
| ext = filename.lower() | |
| try: | |
| if ext.endswith(".txt") or ext.endswith(".md"): | |
| return content.decode("utf-8", errors="ignore") | |
| elif ext.endswith(".csv"): | |
| return content.decode("utf-8", errors="ignore") | |
| elif ext.endswith(".pdf"): | |
| import pypdf | |
| pdf = pypdf.PdfReader(io.BytesIO(content)) # β io works (imported at top) | |
| return "\n".join(page.extract_text() or "" for page in pdf.pages) | |
| elif ext.endswith(".docx"): | |
| from docx import Document | |
| import io | |
| doc = Document(io.BytesIO(content)) | |
| return "\n".join(p.text for p in doc.paragraphs if p.text.strip()) | |
| else: | |
| return content.decode("utf-8", errors="ignore") | |
| except Exception as e: | |
| return f"[Error extracting {filename}: {str(e)}]" | |
| # ----------------------------- | |
| # FastAPI app | |
| # ----------------------------- | |
| app = FastAPI(title="Portfolio Chatbot API") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| BASE_DIR = Path(__file__).parent | |
| STATIC_DIR = BASE_DIR / "static" | |
| if STATIC_DIR.is_dir(): | |
| app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") | |
| class ChatRequest(BaseModel): | |
| message: str = Field(..., min_length=1, max_length=4000) | |
| class ChatResponse(BaseModel): | |
| reply: str | |
| provider: str | |
| # ----------------------------- | |
| # LLM Call | |
| # ----------------------------- | |
| def call_llm(messages: List[Dict[str, str]]) -> str: | |
| try: | |
| if provider == "openai": | |
| resp = openai_client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=messages, | |
| temperature=0.3, | |
| ) | |
| return resp.choices[0].message.content.strip() | |
| if provider == "gemini": | |
| prompt = "\n".join([f"{m['role'].upper()}: {m['content']}" for m in messages]) | |
| resp = gemini_model.generate_content(prompt) | |
| if hasattr(resp, "text") and resp.text: | |
| return resp.text.strip() | |
| if hasattr(resp, "candidates") and resp.candidates: | |
| cand = resp.candidates[0] | |
| if hasattr(cand, "content") and hasattr(cand.content, "parts"): | |
| parts = [p.text for p in cand.content.parts if hasattr(p, "text")] | |
| if parts: | |
| return "\n".join(parts).strip() | |
| return "β οΈ Gemini did not return a valid response." | |
| return "The chatbot isnβt configured yet. Please set OPENAI_API_KEY or GOOGLE_API_KEY." | |
| except Exception as e: | |
| return f"β οΈ LLM call failed: {str(e)}" | |
| # ----------------------------- | |
| # Creator Mode State | |
| # ----------------------------- | |
| CREATOR_MODE = {"active": False} | |
| # ----------------------------- | |
| # Endpoints | |
| # ----------------------------- | |
| def root(): | |
| return {"ok": True, "message": "Portfolio Chatbot running.", "provider": provider} | |
| def health(): | |
| return {"status": "healthy", "provider": provider} | |
| def list_instructions(): | |
| """List all saved instructions with index numbers.""" | |
| instructions = load_instructions() | |
| return {"instructions": [{"id": i, "text": instr} for i, instr in enumerate(instructions)]} | |
| def chat(req: ChatRequest): | |
| global CREATOR_MODE | |
| user_msg = req.message.strip() | |
| if user_msg.lower() == "hi i am creator i want to make you learn": | |
| CREATOR_MODE["active"] = True | |
| return ChatResponse( | |
| reply="π Creator mode activated. Upload files or add knowledge text here: /creator.html\n(To exit, type: exit creator mode)", | |
| provider=provider | |
| ) | |
| if user_msg.lower() == "exit creator mode": | |
| CREATOR_MODE["active"] = False | |
| return ChatResponse( | |
| reply="π Creator mode deactivated. You are back to normal chat.", | |
| provider=provider | |
| ) | |
| # NEW: delete specific knowledge | |
| if CREATOR_MODE["active"] and user_msg.lower().startswith("delete knowledge:"): | |
| target = user_msg[len("delete knowledge:"):].strip() | |
| if delete_knowledge(target): | |
| return ChatResponse( | |
| reply=f"ποΈ Deleted knowledge: \"{target}\"", | |
| provider=provider | |
| ) | |
| else: | |
| return ChatResponse( | |
| reply=f"β οΈ Knowledge not found: \"{target}\"", | |
| provider=provider | |
| ) | |
| # NEW: vector check | |
| if CREATOR_MODE["active"] and user_msg.lower() == "vector check": | |
| return ChatResponse( | |
| reply=f"π Vectorstore contains {index.ntotal} vectors.\nSample chunks: {knowledge_chunks[:3]}\nSample embedding (first 5 dims): {embedding_model.embed_query('test')[:5]}", | |
| provider=provider | |
| ) | |
| # NEW: instructions handling | |
| if CREATOR_MODE["active"] and user_msg.lower().startswith("instructions list"): | |
| instrs = load_instructions() | |
| if instrs: | |
| formatted = "\n".join([f"{i}. {t}" for i, t in enumerate(instrs)]) | |
| return ChatResponse( | |
| reply=f"π Current Instructions:\n{formatted}", | |
| provider=provider | |
| ) | |
| else: | |
| return ChatResponse( | |
| reply="π No instructions saved.", | |
| provider=provider | |
| ) | |
| if CREATOR_MODE["active"] and user_msg.lower().startswith("instructions"): | |
| instr_text = user_msg[len("instructions"):].strip() | |
| if instr_text: | |
| add_instruction(instr_text) | |
| return ChatResponse( | |
| reply="β Instruction stored successfully.", | |
| provider=provider | |
| ) | |
| else: | |
| return ChatResponse( | |
| reply="β οΈ Please provide instruction text.", | |
| provider=provider | |
| ) | |
| if CREATOR_MODE["active"] and user_msg.lower() == "clear instructions": | |
| clear_instructions() | |
| return ChatResponse( | |
| reply="ποΈ All instructions cleared.", | |
| provider=provider | |
| ) | |
| if CREATOR_MODE["active"] and user_msg.lower().startswith("delete instruction:"): | |
| try: | |
| idx = int(user_msg.split(":", 1)[1].strip()) | |
| deleted = delete_instruction(idx) | |
| if deleted: | |
| return ChatResponse( | |
| reply=f"ποΈ Deleted instruction: {deleted}", | |
| provider=provider | |
| ) | |
| else: | |
| return ChatResponse( | |
| reply="β οΈ Invalid instruction index.", | |
| provider=provider | |
| ) | |
| except ValueError: | |
| return ChatResponse( | |
| reply="β οΈ Please provide a valid index number.", | |
| provider=provider | |
| ) | |
| if CREATOR_MODE["active"]: | |
| add_knowledge(f"Manual-entry: {user_msg}") | |
| add_to_vectorstore(user_msg) | |
| return ChatResponse( | |
| reply=f"βοΈ Learned: '{user_msg}' (stored in active knowledge).", | |
| provider=provider | |
| ) | |
| retrieved = retrieve_relevant(user_msg, k=3) | |
| context = "\n".join(retrieved) | |
| system_prompt = ( | |
| "You are a helpful assistant for a developer portfolio website. " | |
| "Answer concisely, be friendly, and help users navigate ONLY if they ask. " | |
| + NAV_HINT | |
| + "\n\nRelevant Knowledge:\n" | |
| + context | |
| + "\n\nAdditional Uploaded Knowledge:\n" | |
| + load_knowledge() | |
| ) | |
| # Inject stored instructions | |
| instructions = load_instructions() | |
| if instructions: | |
| system_prompt += "\n\nSpecial Instructions:\n" + "\n".join( | |
| [f"{i}. {instr}" for i, instr in enumerate(instructions)] | |
| ) | |
| messages = [ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "system", "content": ABOUT_ME}, | |
| {"role": "user", "content": user_msg}, | |
| ] | |
| reply = call_llm(messages) | |
| return ChatResponse(reply=reply, provider=provider) | |
| async def upload_file(file: UploadFile = File(...)): | |
| try: | |
| contents = await file.read() | |
| text = extract_text_from_file(file.filename, contents) | |
| add_knowledge(f"File: {file.filename}\n{text}") | |
| add_to_vectorstore(text) | |
| return {"status": "success", "filename": file.filename} | |
| except Exception as e: | |
| return {"status": "error", "error": str(e)} | |
| async def creator_upload(file: UploadFile = File(...)): | |
| return await upload_file(file) | |
| def download_knowledge(): | |
| if os.path.exists(KNOWLEDGE_FILE): | |
| return FileResponse(KNOWLEDGE_FILE, filename="knowledge.json", media_type="application/json") | |
| return {"status": "error", "error": "No knowledge file found"} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |