Spaces:
Runtime error
Runtime error
Update app.py
Browse files123465 unmodified lines7071727374757677787980818283848586878889909111 unmodified lines1031041051061071081091101111121131141156 unmodified lines1221231241251261271285 unmodified lines13413513613713813914030 unmodified lines17117217317417517662 unmodified lines2392402412422432442451 unmodified line2472482492502512522531 unmodified line2552562572582592602612 unmodified lines26426526626726826927013 unmodified lines28428528628728828929022 unmodified lines313314315316317318319import os, json, shutilfrom typing import List, Dict, Optionalfrom pathlib import Pathfrom fastapi import FastAPI, File, UploadFile65 unmodified lines# -----------------------------# Persistent storage paths# -----------------------------# -----------------------------# Persistent storage (Hugging Face Spaces)# -----------------------------STORE_DIR = Path("/data/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# -----------------------------embedding_model = OpenAIEmbeddings(model="text-embedding-3-small")dimension = 1536 # embedding dimensionindex = Noneknowledge_chunks = []11 unmodified linesprint("β οΈ 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, indexsplitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)chunks = splitter.split_text(text)6 unmodified linessave_vectorstore()def retrieve_relevant(query: str, k=3):"""Search top-k relevant chunks."""if index.ntotal == 0:return []q_vec = embedding_model.embed_query(query)5 unmodified linesinit_vectorstore()# -----------------------------# Knowledge Handling (legacy JSON store)# -----------------------------def load_knowledge() -> str:if os.path.exists(KNOWLEDGE_FILE):30 unmodified linesallow_headers=["*"],)STATIC_DIR = BASE_DIR / "static"if STATIC_DIR.is_dir():app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")62 unmodified linesif blocked:return ChatResponse(reply=blocked, provider=provider)# β Enter creator modeif user_msg.lower() == "hi i am creator i want to make you learn":CREATOR_MODE["active"] = Truereturn ChatResponse(1 unmodified lineprovider=provider)# β Exit creator modeif user_msg.lower() == "exit creator mode":CREATOR_MODE["active"] = Falsereturn ChatResponse(1 unmodified lineprovider=provider)# β In creator mode β store as knowledgeif CREATOR_MODE["active"]:add_knowledge(f"Manual-entry: {user_msg}")add_to_vectorstore(user_msg)2 unmodified linesprovider=provider)# β List uploaded knowledgeif user_msg.lower() == "what did i upload":if os.path.exists(KNOWLEDGE_FILE):with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:13 unmodified linesreturn ChatResponse(reply="π No knowledge uploaded yet.", provider=provider)return ChatResponse(reply="π No knowledge file found.", provider=provider)# Normal chatbot flow (RAG-enabled)retrieved = retrieve_relevant(user_msg, k=3)context = "\n".join(retrieved)22 unmodified linescontents = await file.read()text = contents.decode("utf-8", errors="ignore")add_knowledge(f"File: {file.filename}\n{text}")add_to_vectorstore(text) # β NEWreturn {"status": "success", "filename": file.filename}except Exception as e:return {"status": "error", "error": str(e)}123465 unmodified lines7071727374757677787980818283848586878889909111 unmodified lines1031041051061071081091101111121136 unmodified lines1201211221231241255 unmodified lines13113213313413513613730 unmodified lines16816917017117217317462 unmodified lines2372382392402412421 unmodified line2442452462472482491 unmodified line2512522532542552562 unmodified lines25926026126226326413 unmodified lines27827928028128228322 unmodified lines306307308309310311312import os, jsonfrom typing import List, Dict, Optionalfrom pathlib import Pathfrom fastapi import FastAPI, File, UploadFile65 unmodified lines# -----------------------------# Persistent storage paths# -----------------------------try:STORE_DIR = Path("/app/store")STORE_DIR.mkdir(parents=True, exist_ok=True)except Exception:STORE_DIR = Path("/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# -----------------------------embedding_model = OpenAIEmbeddings(model="text-embedding-3-small")dimension = 1536index = Noneknowledge_chunks = []11 unmodified linesprint("β οΈ No FAISS index found, starting fresh")def save_vectorstore():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):global knowledge_chunks, indexsplitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)chunks = splitter.split_text(text)6 unmodified linessave_vectorstore()def retrieve_relevant(query: str, k=3):if index.ntotal == 0:return []q_vec = embedding_model.embed_query(query)5 unmodified linesinit_vectorstore()# -----------------------------# Knowledge Handling (JSON)# -----------------------------def load_knowledge() -> str:if os.path.exists(KNOWLEDGE_FILE):30 unmodified linesallow_headers=["*"],)BASE_DIR = Path(__file__).resolve().parentSTATIC_DIR = BASE_DIR / "static"if STATIC_DIR.is_dir():app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")62 unmodified linesif blocked:return ChatResponse(reply=blocked, provider=provider)if user_msg.lower() == "hi i am creator i want to make you learn":CREATOR_MODE["active"] = Truereturn ChatResponse(1 unmodified lineprovider=provider)if user_msg.lower() == "exit creator mode":CREATOR_MODE["active"] = Falsereturn ChatResponse(1 unmodified lineprovider=provider)if CREATOR_MODE["active"]:add_knowledge(f"Manual-entry: {user_msg}")add_to_vectorstore(user_msg)2 unmodified linesprovider=provider)if user_msg.lower() == "what did i upload":if os.path.exists(KNOWLEDGE_FILE):with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:13 unmodified linesreturn ChatResponse(reply="π No knowledge uploaded yet.", provider=provider)return ChatResponse(reply="π No knowledge file found.", provider=provider)retrieved = retrieve_relevant(user_msg, k=3)context = "\n".join(retrieved)22 unmodified linescontents = await file.read()text = contents.decode("utf-8", errors="ignore")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)}
app.py+11-18