Spaces:
Sleeping
Sleeping
Delete app.py
#2
by
yamunagovindha
- opened
app.py
DELETED
|
@@ -1,212 +0,0 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import sqlite3
|
| 3 |
-
import uuid
|
| 4 |
-
import time
|
| 5 |
-
from langchain_google_genai import GoogleGenerativeAI
|
| 6 |
-
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 7 |
-
from langchain_core.output_parsers import StrOutputParser
|
| 8 |
-
from langchain_community.chat_message_histories import SQLChatMessageHistory
|
| 9 |
-
from langchain_core.runnables.history import RunnableWithMessageHistory
|
| 10 |
-
import io
|
| 11 |
-
|
| 12 |
-
# Load API key
|
| 13 |
-
GOOGLE_API_KEY = st.secrets.get("GOOGLE_API_KEY")
|
| 14 |
-
|
| 15 |
-
# Set up the Gemini 1.5 Pro model
|
| 16 |
-
llm = GoogleGenerativeAI(api_key=GOOGLE_API_KEY, model="gemini-1.5-pro")
|
| 17 |
-
|
| 18 |
-
# Initialize SQLite database
|
| 19 |
-
conn = sqlite3.connect("chat_history.db", check_same_thread=False)
|
| 20 |
-
cursor = conn.cursor()
|
| 21 |
-
cursor.execute("""
|
| 22 |
-
CREATE TABLE IF NOT EXISTS chat (
|
| 23 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 24 |
-
session_id TEXT,
|
| 25 |
-
role TEXT,
|
| 26 |
-
content TEXT,
|
| 27 |
-
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
| 28 |
-
)
|
| 29 |
-
""")
|
| 30 |
-
conn.commit()
|
| 31 |
-
|
| 32 |
-
# Function to save messages
|
| 33 |
-
def save_message(session_id, role, content):
|
| 34 |
-
cursor.execute("INSERT INTO chat (session_id, role, content) VALUES (?, ?, ?)",
|
| 35 |
-
(session_id, role, content))
|
| 36 |
-
conn.commit()
|
| 37 |
-
|
| 38 |
-
# Function to load chat history
|
| 39 |
-
def load_chat_history(session_id):
|
| 40 |
-
cursor.execute("SELECT role, content, timestamp FROM chat WHERE session_id = ? ORDER BY timestamp",
|
| 41 |
-
(session_id,))
|
| 42 |
-
return cursor.fetchall()
|
| 43 |
-
|
| 44 |
-
# Chat history instance
|
| 45 |
-
def chat_history(session_id):
|
| 46 |
-
return SQLChatMessageHistory(
|
| 47 |
-
session_id=session_id,
|
| 48 |
-
connection="sqlite:///chat_history.db"
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
-
# Generate unique session ID
|
| 52 |
-
if "session_id" not in st.session_state:
|
| 53 |
-
st.session_state.session_id = str(uuid.uuid4())
|
| 54 |
-
|
| 55 |
-
# Custom CSS
|
| 56 |
-
st.markdown("""
|
| 57 |
-
<style>
|
| 58 |
-
.title-text {
|
| 59 |
-
text-align: center;
|
| 60 |
-
font-size: 32px;
|
| 61 |
-
font-weight: bold;
|
| 62 |
-
margin-bottom: 20px;
|
| 63 |
-
}
|
| 64 |
-
.stTextInput {
|
| 65 |
-
position: fixed;
|
| 66 |
-
bottom: 60px;
|
| 67 |
-
width: 70%;
|
| 68 |
-
left: 15%;
|
| 69 |
-
z-index: 999;
|
| 70 |
-
}
|
| 71 |
-
.code-block {
|
| 72 |
-
background-color: #f0f0f0;
|
| 73 |
-
padding: 10px;
|
| 74 |
-
border-radius: 5px;
|
| 75 |
-
font-family: monospace;
|
| 76 |
-
}
|
| 77 |
-
.timestamp {
|
| 78 |
-
font-size: 12px;
|
| 79 |
-
color: #666;
|
| 80 |
-
margin-top: 5px;
|
| 81 |
-
}
|
| 82 |
-
</style>
|
| 83 |
-
""", unsafe_allow_html=True)
|
| 84 |
-
|
| 85 |
-
# Sidebar for additional controls
|
| 86 |
-
with st.sidebar:
|
| 87 |
-
st.title("Chat Controls")
|
| 88 |
-
theme = st.selectbox("Theme", ["Light", "Dark"])
|
| 89 |
-
if theme == "Dark":
|
| 90 |
-
st.markdown("""
|
| 91 |
-
<style>
|
| 92 |
-
.stApp {
|
| 93 |
-
background-color: #1E1E1E;
|
| 94 |
-
color: #FFFFFF;
|
| 95 |
-
}
|
| 96 |
-
.code-block {
|
| 97 |
-
background-color: #2D2D2D;
|
| 98 |
-
color: #FFFFFF;
|
| 99 |
-
}
|
| 100 |
-
</style>
|
| 101 |
-
""", unsafe_allow_html=True)
|
| 102 |
-
|
| 103 |
-
if st.button("🆕 New Chat"):
|
| 104 |
-
st.session_state.session_id = str(uuid.uuid4())
|
| 105 |
-
st.session_state.messages = []
|
| 106 |
-
st.rerun()
|
| 107 |
-
|
| 108 |
-
# Export chat feature
|
| 109 |
-
if st.button("📥 Export Chat"):
|
| 110 |
-
chat_data = load_chat_history(st.session_state.session_id)
|
| 111 |
-
export_text = "\n\n".join([f"{row[0].upper()}[{row[2]}]: {row[1]}"
|
| 112 |
-
for row in chat_data])
|
| 113 |
-
st.download_button(
|
| 114 |
-
label="Download Chat",
|
| 115 |
-
data=export_text,
|
| 116 |
-
file_name=f"chat_{st.session_state.session_id}.txt",
|
| 117 |
-
mime="text/plain"
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
# Animated Title Function
|
| 121 |
-
def animated_text(text, speed=0.03):
|
| 122 |
-
placeholder = st.empty()
|
| 123 |
-
displayed_text = ""
|
| 124 |
-
for letter in text:
|
| 125 |
-
displayed_text += letter
|
| 126 |
-
placeholder.markdown(f"""
|
| 127 |
-
<h1 class="title-text" style="color: {'#00D1FF' if theme == 'Light' else '#FFD700'}">
|
| 128 |
-
{displayed_text} 🚀
|
| 129 |
-
</h1>
|
| 130 |
-
""", unsafe_allow_html=True)
|
| 131 |
-
time.sleep(speed)
|
| 132 |
-
|
| 133 |
-
# Display Animated Welcome Message
|
| 134 |
-
animated_text('Data Science Tutor AI')
|
| 135 |
-
|
| 136 |
-
# Get session ID and chat history
|
| 137 |
-
session_id = st.session_state.session_id
|
| 138 |
-
chat_history_instance = chat_history(session_id)
|
| 139 |
-
|
| 140 |
-
# Define Chat Prompt Template
|
| 141 |
-
chat_prompt = ChatPromptTemplate(
|
| 142 |
-
messages=[
|
| 143 |
-
('system', """You are an AI assistant specialized in Data Science tutoring.
|
| 144 |
-
You will only answer questions related to Data Science.
|
| 145 |
-
Provide code examples with proper syntax highlighting when relevant.
|
| 146 |
-
If asked anything outside this topic, politely decline and request a Data Science-related question.
|
| 147 |
-
"""),
|
| 148 |
-
MessagesPlaceholder(variable_name="history", optional=True),
|
| 149 |
-
('human', '{prompt}')
|
| 150 |
-
]
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
# Create chain
|
| 154 |
-
out_parser = StrOutputParser()
|
| 155 |
-
chain = chat_prompt | llm | out_parser
|
| 156 |
-
chat = RunnableWithMessageHistory(
|
| 157 |
-
chain,
|
| 158 |
-
lambda session: SQLChatMessageHistory(session, "sqlite:///chat_history.db"),
|
| 159 |
-
input_messages_key="prompt",
|
| 160 |
-
history_messages_key="history"
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
# Chat History Container
|
| 164 |
-
chat_container = st.container()
|
| 165 |
-
|
| 166 |
-
# Load and display chat history
|
| 167 |
-
if "messages" not in st.session_state:
|
| 168 |
-
st.session_state.messages = load_chat_history(session_id)
|
| 169 |
-
|
| 170 |
-
with chat_container:
|
| 171 |
-
for role, content, timestamp in st.session_state.messages:
|
| 172 |
-
with st.chat_message(role):
|
| 173 |
-
# Handle code blocks in content
|
| 174 |
-
if "```" in content:
|
| 175 |
-
parts = content.split("```")
|
| 176 |
-
for i, part in enumerate(parts):
|
| 177 |
-
if i % 2 == 0:
|
| 178 |
-
st.markdown(part)
|
| 179 |
-
else:
|
| 180 |
-
st.markdown(f'<div class="code-block">{part}</div>',
|
| 181 |
-
unsafe_allow_html=True)
|
| 182 |
-
else:
|
| 183 |
-
st.markdown(content)
|
| 184 |
-
st.markdown(f'<div class="timestamp">{timestamp}</div>',
|
| 185 |
-
unsafe_allow_html=True)
|
| 186 |
-
|
| 187 |
-
# User input with additional features
|
| 188 |
-
with st.form(key='chat_form', clear_on_submit=True):
|
| 189 |
-
col1, col2 = st.columns([5, 1])
|
| 190 |
-
with col1:
|
| 191 |
-
user_input = st.text_input("Ask a Data Science question:", key="user_message")
|
| 192 |
-
with col2:
|
| 193 |
-
submit_button = st.form_submit_button("Send")
|
| 194 |
-
|
| 195 |
-
# Process user input
|
| 196 |
-
if submit_button and user_input:
|
| 197 |
-
save_message(session_id, "user", user_input)
|
| 198 |
-
st.session_state.messages.append(("user", user_input, time.strftime('%Y-%m-%d %H:%M:%S')))
|
| 199 |
-
|
| 200 |
-
config = {'configurable': {'session_id': session_id}}
|
| 201 |
-
response = chat.invoke({'prompt': user_input}, config)
|
| 202 |
-
|
| 203 |
-
save_message(session_id, "assistant", response)
|
| 204 |
-
st.session_state.messages.append(("assistant", response, time.strftime('%Y-%m-%d %H:%M:%S')))
|
| 205 |
-
st.rerun()
|
| 206 |
-
|
| 207 |
-
# Help button in bottom right
|
| 208 |
-
st.markdown("""
|
| 209 |
-
<div style="position: fixed; bottom: 10px; right: 10px;">
|
| 210 |
-
<button onclick="alert('Ask me anything about Data Science! Examples: Python, SQL, Machine Learning, Statistics')">ℹ️ Help</button>
|
| 211 |
-
</div>
|
| 212 |
-
""", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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