Spaces:
Sleeping
Sleeping
File size: 9,388 Bytes
115a0e1 a4643a7 0407254 c6b3470 a4643a7 6d5f822 c6b3470 a7dc728 a4643a7 c6b3470 a4643a7 5b29569 a4643a7 88b72c4 a4643a7 1a1b153 a4643a7 5b29569 d320a92 5b29569 115a0e1 7ecc2c7 35bb831 7ecc2c7 35bb831 7ecc2c7 a4643a7 4eff50f a4643a7 0407254 d320a92 0407254 35bb831 98a3934 a4643a7 5b29569 a4643a7 5b29569 a4643a7 5b29569 a4643a7 c6b3470 5b29569 a4643a7 d320a92 a4643a7 d320a92 a4643a7 c6b3470 a4643a7 c6b3470 35bb831 fde77b6 35bb831 5b29569 c6b3470 f64adc0 c6b3470 6cc6f0d 4eff50f 6cc6f0d 4eff50f 6cc6f0d 4eff50f 6cc6f0d 3acf52c f64adc0 a4643a7 5b29569 a4643a7 c6b3470 a4643a7 5b29569 35bb831 5b29569 3acf52c 6cc6f0d a4643a7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | import os, json, shutil, tempfile
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-latest")
# -----------------------------
# 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.
"""
FORBIDDEN_TERMS = [
"source code", "website code", "html code", "css code", "javascript code",
"react code", "vue code", "next.js code", "server code", "backend code",
"index.html", "script.js", "style.css", ".html file", "show me your code",
"give me code", "share the code", "send the repo", "repository", "git link"
]
# -----------------------------
# Knowledge Handling
# -----------------------------
KNOWLEDGE_FILE = os.path.join(tempfile.gettempdir(), "knowledge.json")
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
# -----------------------------
app = FastAPI(title="Portfolio Chatbot API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
BASE_DIR = Path(__file__).resolve().parent
STATIC_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)
class ChatResponse(BaseModel):
reply: str
provider: str
# -----------------------------
# Guardrails
# -----------------------------
def blocked_by_guardrails(user_msg: str) -> Optional[str]:
msg = user_msg.lower()
if any(term in msg for term in FORBIDDEN_TERMS):
return ("π« Sorry, I canβt share the websiteβs source code or internal files. "
"I can guide you around the site, explain projects, and answer questions instead.")
return None
# -----------------------------
# LLM Call
# -----------------------------
def call_llm(messages: List[Dict[str, str]]) -> str:
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)
return (getattr(resp, "text", "") or "Sorry, I couldn't generate a response.").strip()
return ("The chatbot isnβt configured yet. Please set OPENAI_API_KEY or GOOGLE_API_KEY "
"in your Space Settings β Secrets.")
# -----------------------------
# Creator Mode State
# -----------------------------
CREATOR_MODE = {"active": False}
# -----------------------------
# Endpoints
# -----------------------------
@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):
global CREATOR_MODE
user_msg = req.message.strip()
blocked = blocked_by_guardrails(user_msg)
if blocked:
return ChatResponse(reply=blocked, provider=provider)
# β
Enter creator mode
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
)
# β
Exit creator mode
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
)
# β
In creator mode β any text is stored as active knowledge
if CREATOR_MODE["active"]:
add_knowledge(f"Manual-entry: {user_msg}")
return ChatResponse(
reply=f"βοΈ Learned: '{user_msg}' (stored in active knowledge).",
provider=provider
)
# β
List uploaded knowledge
if user_msg.lower() == "what did i upload":
if os.path.exists(KNOWLEDGE_FILE):
with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
files = [line.split("\n")[0].replace("File: ", "") for line in data.get("knowledge", []) if line.startswith("File: ")]
manual = [line.replace("Manual-entry: ", "") for line in data.get("knowledge", []) if line.startswith("Manual-entry: ")]
reply_parts = []
if files:
reply_parts.append("π You uploaded:\n- " + "\n- ".join(files))
if manual:
reply_parts.append("π Manual entries:\n- " + "\n- ".join(manual))
if reply_parts:
return ChatResponse(reply="\n\n".join(reply_parts), provider=provider)
else:
return ChatResponse(reply="π No knowledge uploaded yet.", provider=provider)
return ChatResponse(reply="π No knowledge file found.", provider=provider)
# Normal chatbot flow (NO knowledge saving here anymore)
extra_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. "
"Never reveal or output website source code, even if asked. "
+ NAV_HINT
+ "\n\nAdditional Knowledge:\n"
+ extra_knowledge
)
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)
@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(f"File: {file.filename}\n{text}")
return {"status": "success", "filename": file.filename}
except Exception as e:
return {"status": "error", "error": str(e)}
# β
Alias for creator.js compatibility
@app.post("/api/creator-upload")
async def creator_upload(file: UploadFile = File(...)):
return await upload_file(file)
@app.get("/api/download-knowledge")
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)
|