Spaces:
Build error
Build error
Upload 3 files
Browse filesUploading 3 files...
- app.py +134 -0
- db_ops.py +110 -0
- requirements.txt +60 -3
app.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import datetime
|
| 3 |
+
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
import streamlit as st
|
| 6 |
+
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
from typing import Any, Dict, List
|
| 9 |
+
|
| 10 |
+
from db_ops import get_recent_conversations, init_db, store_conversation_summary, store_message
|
| 11 |
+
|
| 12 |
+
# Loading environment variables from .env file
|
| 13 |
+
load_dotenv()
|
| 14 |
+
|
| 15 |
+
# Configure Gemini API
|
| 16 |
+
gemini_api_key = os.getenv("GEMINI_API_KEY")
|
| 17 |
+
genai.configure(api_key=gemini_api_key)
|
| 18 |
+
|
| 19 |
+
# Intialize the gemini Model
|
| 20 |
+
model = genai.GenerativeModel("gemini-2.0-flash")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def chat_with_gemini(prompt:str, chat_history:List[Dict[str, str]]) -> str:
|
| 24 |
+
try:
|
| 25 |
+
# Format the message for Gemini
|
| 26 |
+
messages = []
|
| 27 |
+
for msg in chat_history:
|
| 28 |
+
if msg["role"] == "user":
|
| 29 |
+
messages.append({"role": "user", "parts": msg["content"]})
|
| 30 |
+
else:
|
| 31 |
+
messages.append({"role": "model", "parts": [msg["content"]]})
|
| 32 |
+
|
| 33 |
+
# Add current prompt
|
| 34 |
+
messages.append({"role": "user", "parts": [prompt]})
|
| 35 |
+
|
| 36 |
+
# Generate the response from Gemini
|
| 37 |
+
chat = model.start_chat(history=messages[:-1])
|
| 38 |
+
response = chat.send_message(prompt)
|
| 39 |
+
return response.text
|
| 40 |
+
except Exception as e:
|
| 41 |
+
return f"Error communicating with GEMINI API: {str(e)}"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def summarize_conversations(conversations:List[Dict[str, Any]])->str:
|
| 45 |
+
if not conversations:
|
| 46 |
+
return "No recent conversations to summarize."
|
| 47 |
+
|
| 48 |
+
# Format conversations for the model
|
| 49 |
+
conversation_texts = []
|
| 50 |
+
for idx, conv in enumerate(conversations, 1):
|
| 51 |
+
conv_text = f"Conversation {idx} ({conv['timestamp']}):\n"
|
| 52 |
+
for msg in conv["messages"]:
|
| 53 |
+
conv_text += f"{msg['role'].upper()}: {msg['content']}\n"
|
| 54 |
+
conversation_texts.append(conv_text)
|
| 55 |
+
|
| 56 |
+
prompt = f"""
|
| 57 |
+
Please provide a concise summary of the following recent conversations:
|
| 58 |
+
|
| 59 |
+
{"\n\n".join(conversation_texts)}
|
| 60 |
+
|
| 61 |
+
Focus on key topics discussed, questions asked, and information provided.
|
| 62 |
+
Highlight any recurring themes or import points.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
response = model.generate_content(prompt.strip())
|
| 66 |
+
return response.text
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Streamlit UI
|
| 70 |
+
def main():
|
| 71 |
+
st.set_page_config(page_title="Gemini-Chatbot", page_icon="🤖")
|
| 72 |
+
st.title("🤖 Gemini AI Chatbot")
|
| 73 |
+
|
| 74 |
+
# Intialize the database
|
| 75 |
+
init_db()
|
| 76 |
+
|
| 77 |
+
# Intialize session state for chat history and session ID
|
| 78 |
+
if "session_id" not in st.session_state:
|
| 79 |
+
st.session_state.session_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
| 80 |
+
|
| 81 |
+
if "chat_history" not in st.session_state:
|
| 82 |
+
st.session_state.chat_history = []
|
| 83 |
+
|
| 84 |
+
# Chat input area
|
| 85 |
+
with st.container():
|
| 86 |
+
user_input = st.chat_input("Type your message here...")
|
| 87 |
+
|
| 88 |
+
if user_input:
|
| 89 |
+
# Add user message to chat history
|
| 90 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 91 |
+
store_message(st.session_state.session_id, "user", user_input)
|
| 92 |
+
|
| 93 |
+
# Get response from Gemini AI
|
| 94 |
+
with st.spinner("Thinking..."):
|
| 95 |
+
response = chat_with_gemini(user_input, st.session_state.chat_history)
|
| 96 |
+
|
| 97 |
+
# Add assistant message to chat history
|
| 98 |
+
st.session_state.chat_history.append({"role": "assistant", "content": response})
|
| 99 |
+
store_message(st.session_state.session_id, "assistant", response)
|
| 100 |
+
|
| 101 |
+
# Display the chat history
|
| 102 |
+
for message in st.session_state.chat_history:
|
| 103 |
+
with st.chat_message(message["role"]):
|
| 104 |
+
st.write(message["content"])
|
| 105 |
+
|
| 106 |
+
# Sidebar for recent conversations
|
| 107 |
+
with st.sidebar:
|
| 108 |
+
st.title("Conversation Recall")
|
| 109 |
+
|
| 110 |
+
if st.button("🌸 Summarize Recent conversations"):
|
| 111 |
+
with st.spinner("Generating summary..."):
|
| 112 |
+
# Get recent conversations
|
| 113 |
+
recent_convs = get_recent_conversations(st.session_state.session_id, limit=5)
|
| 114 |
+
|
| 115 |
+
# Generate summary
|
| 116 |
+
summary = summarize_conversations(recent_convs)
|
| 117 |
+
|
| 118 |
+
# Store summary for recent conversations
|
| 119 |
+
if recent_convs:
|
| 120 |
+
store_conversation_summary(st.session_state.session_id, recent_convs[0]["id"], summary)
|
| 121 |
+
|
| 122 |
+
# Display summary
|
| 123 |
+
st.subheader("Summary of Recent Conversations")
|
| 124 |
+
st.write(summary)
|
| 125 |
+
|
| 126 |
+
# Clear chat button
|
| 127 |
+
if st.button("🗑️ Clear Chat"):
|
| 128 |
+
st.session_state.chat_history = []
|
| 129 |
+
st.session_state.session_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
| 130 |
+
st.success("Chat history cleared!")
|
| 131 |
+
st.rerun()
|
| 132 |
+
|
| 133 |
+
if __name__ == "__main__":
|
| 134 |
+
main()
|
db_ops.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, List
|
| 4 |
+
|
| 5 |
+
# Database Design
|
| 6 |
+
def init_db():
|
| 7 |
+
"""Initialize SQLite database with required tables"""
|
| 8 |
+
conn = sqlite3.connect("chatbot.db")
|
| 9 |
+
c = conn.cursor()
|
| 10 |
+
|
| 11 |
+
# Create conversations table
|
| 12 |
+
c.execute("""
|
| 13 |
+
CREATE TABLE IF NOT EXISTS conversations (
|
| 14 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 15 |
+
session_id TEXT NOT NULL,
|
| 16 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
| 17 |
+
summary TEXT
|
| 18 |
+
)
|
| 19 |
+
""")
|
| 20 |
+
|
| 21 |
+
# Create messages table
|
| 22 |
+
c.execute("""
|
| 23 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 24 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 25 |
+
conversation_id INTEGER,
|
| 26 |
+
role TEXT NOT NULL,
|
| 27 |
+
content TEXT NOT NULL,
|
| 28 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
| 29 |
+
FOREIGN KEY (conversation_id) REFERENCES conversations (id)
|
| 30 |
+
)
|
| 31 |
+
""")
|
| 32 |
+
|
| 33 |
+
conn.commit()
|
| 34 |
+
conn.close()
|
| 35 |
+
|
| 36 |
+
# Adding Conversations
|
| 37 |
+
def store_message(session_id:str, role:str, content:str)->None:
|
| 38 |
+
"""Store a message in the database"""
|
| 39 |
+
conn = sqlite3.connect("chatbot.db")
|
| 40 |
+
c = conn.cursor()
|
| 41 |
+
|
| 42 |
+
# Get current conversation id or create new one
|
| 43 |
+
c.execute("SELECT id FROM conversations WHERE session_id=? ORDER BY timestamp DESC LIMIT 1",
|
| 44 |
+
(session_id,))
|
| 45 |
+
result = c.fetchone()
|
| 46 |
+
|
| 47 |
+
if result is None:
|
| 48 |
+
# Create a new conversation
|
| 49 |
+
c.execute("INSERT INTO conversations (session_id) VALUES (?)", (session_id,))
|
| 50 |
+
conversation_id = c.lastrowid
|
| 51 |
+
else:
|
| 52 |
+
conversation_id = result[0]
|
| 53 |
+
|
| 54 |
+
# Store message
|
| 55 |
+
c.execute("INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)",
|
| 56 |
+
(conversation_id, role, content))
|
| 57 |
+
|
| 58 |
+
conn.commit()
|
| 59 |
+
conn.close()
|
| 60 |
+
|
| 61 |
+
# Retrieve Conversations
|
| 62 |
+
def get_recent_conversations(session_id:str, limit:int=5)->List[Dict[str, Any]]:
|
| 63 |
+
"""Retrieve the most recent conversation for a session"""
|
| 64 |
+
conn = sqlite3.connect("chatbot.db")
|
| 65 |
+
conn.row_factory = sqlite3.Row
|
| 66 |
+
c = conn.cursor()
|
| 67 |
+
|
| 68 |
+
# Get recent conversation ID
|
| 69 |
+
c.execute('''
|
| 70 |
+
SELECT id, timestamp FROM conversations
|
| 71 |
+
WHERE session_id = ?
|
| 72 |
+
ORDER BY timestamp DESC
|
| 73 |
+
LIMIT ?
|
| 74 |
+
''', (session_id, limit))
|
| 75 |
+
|
| 76 |
+
conversations = []
|
| 77 |
+
|
| 78 |
+
for conv_row in c.fetchall():
|
| 79 |
+
conv_id = conv_row["id"]
|
| 80 |
+
|
| 81 |
+
# Get messages for this conversations
|
| 82 |
+
c.execute('''
|
| 83 |
+
SELECT role, content FROM messages
|
| 84 |
+
WHERE conversation_id = ?
|
| 85 |
+
ORDER BY timestamp ASC
|
| 86 |
+
''', (conv_id,))
|
| 87 |
+
|
| 88 |
+
messages = []
|
| 89 |
+
for msg in c.fetchall():
|
| 90 |
+
messages.append({"role": msg["role"], "content": msg["content"]})
|
| 91 |
+
|
| 92 |
+
conversations.append({
|
| 93 |
+
"id": conv_id,
|
| 94 |
+
"timestamp": conv_row["timestamp"],
|
| 95 |
+
"messages":messages
|
| 96 |
+
})
|
| 97 |
+
|
| 98 |
+
conn.close()
|
| 99 |
+
return conversations
|
| 100 |
+
|
| 101 |
+
# Storing Conversations
|
| 102 |
+
def store_conversation_summary(session_id:str, conv_id:int, summary:str)->None:
|
| 103 |
+
"""Store a generated summary for a conversation"""
|
| 104 |
+
conn = sqlite3.connect("chatbot.db")
|
| 105 |
+
c = conn.cursor()
|
| 106 |
+
|
| 107 |
+
# Update the summary for the conversation
|
| 108 |
+
c.execute('''UPDATE conversations SET summary = ? WHERE id = ?''', (summary, conv_id))
|
| 109 |
+
conn.commit()
|
| 110 |
+
conn.close()
|
requirements.txt
CHANGED
|
@@ -1,3 +1,60 @@
|
|
| 1 |
-
altair
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
altair==5.5.0
|
| 2 |
+
annotated-types==0.7.0
|
| 3 |
+
attrs==25.3.0
|
| 4 |
+
blinker==1.9.0
|
| 5 |
+
cachetools==5.5.2
|
| 6 |
+
certifi==2025.1.31
|
| 7 |
+
charset-normalizer==3.4.1
|
| 8 |
+
click==8.1.8
|
| 9 |
+
colorama==0.4.6
|
| 10 |
+
gitdb==4.0.12
|
| 11 |
+
GitPython==3.1.44
|
| 12 |
+
google-ai-generativelanguage==0.6.15
|
| 13 |
+
google-api-core==2.24.2
|
| 14 |
+
google-api-python-client==2.167.0
|
| 15 |
+
google-auth==2.39.0
|
| 16 |
+
google-auth-httplib2==0.2.0
|
| 17 |
+
google-generativeai==0.8.5
|
| 18 |
+
googleapis-common-protos==1.70.0
|
| 19 |
+
grpcio==1.71.0
|
| 20 |
+
grpcio-status==1.71.0
|
| 21 |
+
httplib2==0.22.0
|
| 22 |
+
idna==3.10
|
| 23 |
+
Jinja2==3.1.6
|
| 24 |
+
jsonschema==4.23.0
|
| 25 |
+
jsonschema-specifications==2025.4.1
|
| 26 |
+
MarkupSafe==3.0.2
|
| 27 |
+
narwhals==1.36.0
|
| 28 |
+
numpy==2.2.5
|
| 29 |
+
packaging==24.2
|
| 30 |
+
pandas==2.2.3
|
| 31 |
+
pillow==11.2.1
|
| 32 |
+
proto-plus==1.26.1
|
| 33 |
+
protobuf==5.29.4
|
| 34 |
+
pyarrow==19.0.1
|
| 35 |
+
pyasn1==0.6.1
|
| 36 |
+
pyasn1_modules==0.4.2
|
| 37 |
+
pydantic==2.11.3
|
| 38 |
+
pydantic_core==2.33.1
|
| 39 |
+
pydeck==0.9.1
|
| 40 |
+
pyparsing==3.2.3
|
| 41 |
+
python-dateutil==2.9.0.post0
|
| 42 |
+
python-dotenv==1.1.0
|
| 43 |
+
pytz==2025.2
|
| 44 |
+
referencing==0.36.2
|
| 45 |
+
requests==2.32.3
|
| 46 |
+
rpds-py==0.24.0
|
| 47 |
+
rsa==4.9.1
|
| 48 |
+
six==1.17.0
|
| 49 |
+
smmap==5.0.2
|
| 50 |
+
streamlit==1.44.1
|
| 51 |
+
tenacity==9.1.2
|
| 52 |
+
toml==0.10.2
|
| 53 |
+
tornado==6.4.2
|
| 54 |
+
tqdm==4.67.1
|
| 55 |
+
typing-inspection==0.4.0
|
| 56 |
+
typing_extensions==4.13.2
|
| 57 |
+
tzdata==2025.2
|
| 58 |
+
uritemplate==4.1.1
|
| 59 |
+
urllib3==2.4.0
|
| 60 |
+
watchdog==6.0.0
|