Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines45678915 unmodified lines2526272829303130 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101 unmodified line11211311411511611711811912012112212312412512612712812937 unmodified lines1671681691701711721731741751761773 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412423 unmodified linesfrom fastapi import FastAPI, File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel, Field# -----------------------------15 unmodified lineselse:provider = "openai" if HAS_OPENAI else ("gemini" if HAS_GEMINI else "none")# Lazy initopenai_client = Nonegemini_model = None30 unmodified lines]# -----------------------------# File storage# -----------------------------KNOWLEDGE_FILE = "knowledge.json"STATE_FILE = "state.json"def load_state() -> Dict:if os.path.exists(STATE_FILE):try:with open(STATE_FILE, "r", encoding="utf-8") as f:return json.load(f)except Exception:return {"creator_mode": False}return {"creator_mode": False}def save_state(state: Dict):with open(STATE_FILE, "w", encoding="utf-8") as f:json.dump(state, f, indent=2)# load state on startupstate = load_state()def load_knowledge() -> str:if os.path.exists(KNOWLEDGE_FILE):try:with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:data = json.load(f)return "\n".join(data.get("knowledge", []))except Exception:return ""return ""def add_knowledge(text: str):data = {"knowledge": []}if os.path.exists(KNOWLEDGE_FILE):with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:try:data = json.load(f)except Exception:data = {"knowledge": []}data["knowledge"].append(text)with open(KNOWLEDGE_FILE, "w", encoding="utf-8") as f:json.dump(data, f, indent=2)# -----------------------------# FastAPI app# -----------------------------1 unmodified lineapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_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")else:print(f"⚠️ Warning: Static folder not found at {STATIC_DIR}")class ChatRequest(BaseModel):message: str = Field(..., min_length=1, max_length=4000)37 unmodified lines# -----------------------------@app.get("/")def root():return {"ok": True, "message": "Portfolio Chatbot running.", "provider": provider, "creator_mode": state["creator_mode"]}@app.get("/health")def health():return {"status": "healthy", "provider": provider, "creator_mode": state["creator_mode"]}@app.post("/api/chat", response_model=ChatResponse)def chat(req: ChatRequest):3 unmodified linesuser_msg = req.message.strip().lower()# ✅ Creator activationif user_msg == "hi i am creator i want to make you learn":state["creator_mode"] = Truesave_state(state)return ChatResponse(reply="🔑 Creator mode activated. Upload files here: /api/upload\n(To exit, type: exit creator mode)",provider=provider)# ✅ Creator deactivationif user_msg == "exit creator mode":state["creator_mode"] = Falsesave_state(state)return ChatResponse(reply="🔒 Creator mode deactivated. You are back to normal chat.",provider=provider)# ✅ Behavior if in creator modeif state["creator_mode"]:return ChatResponse(reply="⚡ You are in Creator Mode. You can upload files at /api/upload to teach me more.\n(To exit, type: exit creator mode)",provider=provider)# Normal chatbot flowextra_knowledge = load_knowledge()system_prompt = ("You are a helpful assistant for a developer portfolio website. ""Answer concisely, be friendly, and help users navigate ONLY if they ask. "2 unmodified lines+ "\n\nAdditional Knowledge:\n"+ extra_knowledge)messages = [{"role": "system", "content": system_prompt},{"role": "system", "content": ABOUT_ME},{"role": "user", "content": req.message},]reply = call_llm(messages)return ChatResponse(reply=reply, provider=provider)@app.post("/api/upload")async def upload_file(file: UploadFile = File(...)):"""Upload files to extend bot knowledge."""if not state["creator_mode"]:return {"status": "error", "error": "❌ Uploads only allowed in Creator Mode. Say: hi i am creator i want to make you learn"}try:contents = await file.read()text = contents.decode("utf-8", errors="ignore")add_knowledge(f"File: {file.filename}\n{text}")return {"status": "success", "filename": file.filename}except Exception as e:return {"status": "error", "error": str(e)}# -----------------------------# Run (local only, HF handles automatically)# -----------------------------3 unmodified lines4567891015 unmodified lines2627282930313230 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021 unmodified line10410510610710810911011111211311411511611711811912037 unmodified lines1581591601611621631641651661671683 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362373 unmodified linesfrom fastapi import FastAPI, File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponsefrom pydantic import BaseModel, Field# -----------------------------15 unmodified lineselse:provider = "openai" if HAS_OPENAI else ("gemini" if HAS_GEMINI else "none")# Lazy init to avoid importing unused SDKsopenai_client = Nonegemini_model = None30 unmodified lines]# -----------------------------# Knowledge Handling# -----------------------------KNOWLEDGE_FILE = "knowledge.json"def load_knowledge() -> 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": []}return {"knowledge": []}def save_knowledge(data: Dict):with open(KNOWLEDGE_FILE, "w", encoding="utf-8") as f:json.dump(data, f, indent=2)def add_knowledge(text: str, filename: str):data = load_knowledge()data["knowledge"].append({"file": filename, "content": text})save_knowledge(data)def delete_knowledge(filename: str) -> bool:data = load_knowledge()before = len(data["knowledge"])data["knowledge"] = [item for item in data["knowledge"] if item["file"] != filename]after = len(data["knowledge"])save_knowledge(data)return before != afterdef list_files() -> List[str]:data = load_knowledge()return [item["file"] for item in data["knowledge"]]# -----------------------------# FastAPI app# -----------------------------1 unmodified lineapp.add_middleware(CORSMiddleware,allow_origins=["*"], # TODO: replace with your domain laterallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# ✅ Static folder mount (optional UI)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")class ChatRequest(BaseModel):message: str = Field(..., min_length=1, max_length=4000)37 unmodified lines# -----------------------------@app.get("/")def root():return {"ok": True, "message": "Portfolio Chatbot running.", "provider": provider}@app.get("/health")def health():return {"status": "healthy", "provider": provider}@app.post("/api/chat", response_model=ChatResponse)def chat(req: ChatRequest):3 unmodified linesuser_msg = req.message.strip().lower()# File management commandsif user_msg == "what did i upload":files = list_files()if files:return ChatResponse(reply=f"📂 You uploaded: {', '.join(files)}", provider=provider)return ChatResponse(reply="⚠️ You haven’t uploaded any files yet.", provider=provider)if user_msg.startswith("delete file "):filename = user_msg.replace("delete file ", "").strip()if delete_knowledge(filename):return ChatResponse(reply=f"🗑️ Deleted file: {filename}", provider=provider)return ChatResponse(reply=f"⚠️ File not found: {filename}", provider=provider)if user_msg == "download all my knowledge":if os.path.exists(KNOWLEDGE_FILE):return ChatResponse(reply=f"⬇️ Download your knowledge here: /api/download",provider=provider)return ChatResponse(reply="⚠️ No knowledge stored yet.", provider=provider)# Normal chatbot modeextra_knowledge = "\n".join([f"{item['file']}: {item['content'][:200]}..." for item in load_knowledge().get("knowledge", [])])system_prompt = ("You are a helpful assistant for a developer portfolio website. ""Answer concisely, be friendly, and help users navigate ONLY if they ask. "2 unmodified lines+ "\n\nAdditional Knowledge:\n"+ extra_knowledge)messages = [{"role": "system", "content": system_prompt},{"role": "system", "content": ABOUT_ME},{"role": "user", "content": req.message},]reply = call_llm(messages)return ChatResponse(reply=reply, provider=provider)@app.post("/api/upload")async def upload_file(file: UploadFile = File(...)):try:contents = await file.read()text = contents.decode("utf-8", errors="ignore")add_knowledge(text, file.filename)return {"status": "success", "filename": file.filename}except Exception as e:return {"status": "error", "error": str(e)}@app.get("/api/download")def download_knowledge():if os.path.exists(KNOWLEDGE_FILE):return FileResponse(KNOWLEDGE_FILE, filename="knowledge.json")return {"status": "error", "error": "No knowledge stored yet."}# -----------------------------# Run (local only, HF handles automatically)# -----------------------------
app.py+63-68