Spaces:
Runtime error

File size: 6,952 Bytes
5aca483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, json, shutil
from typing import List, Dict, Optional
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.
"""

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 = "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=["*"],  # TODO: restrict later
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Serve static files (creator page)
app.mount("/static", StaticFiles(directory="static"), name="static")

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.")

# -----------------------------
# 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):
    blocked = blocked_by_guardrails(req.message)
    if blocked:
        return ChatResponse(reply=blocked, provider=provider)

    # Creator activation
    if 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
        )

    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": 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(f"File: {file.filename}\n{text}")
        return {"status": "success", "filename": file.filename}
    except Exception as e:
        return {"status": "error", "error": str(e)}

@app.get("/creator")
def get_creator_page():
    return FileResponse("static/creator.html")

# -----------------------------
# Run (local only)
# -----------------------------
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)