Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
# --- CONFIGURATION ---
|
| 8 |
+
# Load environment variables from .env file for local development
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
# Configure the Gemini API key
|
| 12 |
+
try:
|
| 13 |
+
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 14 |
+
except AttributeError:
|
| 15 |
+
st.error("⚠️ Gemini API key not found. Please set it in your secrets.")
|
| 16 |
+
st.stop() # Halts execution if no key is found
|
| 17 |
+
|
| 18 |
+
# --- 1. CONTEXT PROVIDER (Simulated Notion) ---
|
| 19 |
+
# Use st.cache_data to load the database only once
|
| 20 |
+
@st.cache_data
|
| 21 |
+
def load_mock_db():
|
| 22 |
+
"""Loads the mock database from the JSON file."""
|
| 23 |
+
with open('mock-notion-db.json', 'r') as f:
|
| 24 |
+
return json.load(f)
|
| 25 |
+
|
| 26 |
+
notion_data = load_mock_db()
|
| 27 |
+
|
| 28 |
+
def get_context(query: str) -> str | None:
|
| 29 |
+
"""Finds the most relevant context using keyword matching."""
|
| 30 |
+
query_words = set(query.lower().split())
|
| 31 |
+
best_match = None
|
| 32 |
+
max_score = 0
|
| 33 |
+
|
| 34 |
+
for item in notion_data:
|
| 35 |
+
keywords = set(item.get("keywords", []))
|
| 36 |
+
score = len(query_words.intersection(keywords))
|
| 37 |
+
if score > max_score:
|
| 38 |
+
max_score = score
|
| 39 |
+
best_match = item
|
| 40 |
+
return best_match["content"] if best_match else None
|
| 41 |
+
|
| 42 |
+
# --- 2. LLM PROVIDER (Gemini) ---
|
| 43 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 44 |
+
|
| 45 |
+
def generate_response(query: str, context: str) -> str:
|
| 46 |
+
"""Generates a response using the Gemini model with provided context."""
|
| 47 |
+
prompt = f"""
|
| 48 |
+
You are a helpful and friendly campus assistant chatbot named Campus Helper Bot.
|
| 49 |
+
Use the following piece of context to answer the user's question.
|
| 50 |
+
If the context doesn't contain the answer, state that you don't have information on that topic. Do not make up information.
|
| 51 |
+
Keep your answer concise and clear.
|
| 52 |
+
|
| 53 |
+
Context: "{context or 'No context available.'}"
|
| 54 |
+
Question: "{query}"
|
| 55 |
+
Answer:
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
response = model.generate_content(prompt)
|
| 59 |
+
return response.text
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"Error generating response: {e}")
|
| 62 |
+
return "Sorry, I'm having trouble connecting right now. Please try again later."
|
| 63 |
+
|
| 64 |
+
# --- 3. STREAMLIT UI AND CHAT LOGIC ---
|
| 65 |
+
|
| 66 |
+
# Set page title and icon
|
| 67 |
+
st.set_page_config(page_title="Campus Helper Bot", page_icon="🤖")
|
| 68 |
+
|
| 69 |
+
# Display header
|
| 70 |
+
st.title("🤖 Campus Helper Bot")
|
| 71 |
+
st.caption("Your AI-powered guide to campus information")
|
| 72 |
+
|
| 73 |
+
# Initialize chat history in session state if it doesn't exist
|
| 74 |
+
if "messages" not in st.session_state:
|
| 75 |
+
st.session_state.messages = [
|
| 76 |
+
{"role": "assistant", "content": "Hello! How can I help you with campus information today?"}
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
# Display past messages from session state
|
| 80 |
+
for message in st.session_state.messages:
|
| 81 |
+
with st.chat_message(message["role"]):
|
| 82 |
+
st.markdown(message["content"])
|
| 83 |
+
|
| 84 |
+
# Main chat input logic
|
| 85 |
+
if prompt := st.chat_input("Ask about fee deadlines, scholarships, etc."):
|
| 86 |
+
# Add user message to session state and display it
|
| 87 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 88 |
+
with st.chat_message("user"):
|
| 89 |
+
st.markdown(prompt)
|
| 90 |
+
|
| 91 |
+
# Get and display bot response
|
| 92 |
+
with st.chat_message("assistant"):
|
| 93 |
+
with st.spinner("Thinking..."):
|
| 94 |
+
# 1. Retrieve context
|
| 95 |
+
context = get_context(prompt)
|
| 96 |
+
# 2. Generate response
|
| 97 |
+
response = generate_response(prompt, context)
|
| 98 |
+
# 3. Display response and add to session state
|
| 99 |
+
st.markdown(response)
|
| 100 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|