Spaces:
Running
Running
Update app.py
Browse files123420 unmodified lines2526272829303130 unmodified lines626364656667686970717273747576777879808182838485868788894 unmodified lines94959697989912 unmodified lines11211311411511611711811912012112212312412541 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132 unmodified lines2162172182192202212222232242252262272282292302312322332348 unmodified lines243244245246247import os, jsonfrom typing import List, Dict, Optionalfrom pathlib import Pathfrom fastapi import FastAPI, File, UploadFile20 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:4 unmodified linesreturn ""def add_knowledge(text: str):data = {"knowledge": []}if os.path.exists(KNOWLEDGE_FILE):with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:12 unmodified linesapp.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:41 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):blocked = blocked_by_guardrails(req.message)if blocked:return ChatResponse(reply=blocked, provider=provider)user_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")8 unmodified linesif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)123420 unmodified lines2526272829303130 unmodified lines6263646566676869707172734 unmodified lines7879808182838412 unmodified lines97989910010110210310410510610710810911011111241 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811822 unmodified lines1851861871881891901911921931941951961971981992002012022038 unmodified lines212213214import os, json, shutilfrom typing import List, Dict, Optionalfrom pathlib import Pathfrom fastapi import FastAPI, File, UploadFile20 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() -> str:"""Return additional knowledge text if available."""if os.path.exists(KNOWLEDGE_FILE):try:with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:4 unmodified linesreturn ""def add_knowledge(text: str):"""Append new knowledge to file."""data = {"knowledge": []}if os.path.exists(KNOWLEDGE_FILE):with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:12 unmodified linesapp.add_middleware(CORSMiddleware,allow_origins=["*"], # TODO: replace with your domain laterallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# β Static folder mount (explicit path fix)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:41 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):# Guardrailsblocked = blocked_by_guardrails(req.message)if blocked:return ChatResponse(reply=blocked, provider=provider)# Check for creator activation phraseif req.message.strip().lower() == "hi i am creator i want to make you learn":return ChatResponse(reply="π Creator mode activated. Upload files here: /creator",provider=provider)# Knowledge loadextra_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."""try:contents = await file.read()text = contents.decode("utf-8", errors="ignore")8 unmodified linesif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
app.py+18-51