Spaces:
Sleeping
Sleeping
File size: 10,253 Bytes
e8e6d44 bbb7f45 e8e6d44 bbb7f45 e8e6d44 bbb7f45 e8e6d44 bbb7f45 e8e6d44 |
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
import os
import sqlite3
import hashlib
import streamlit as st
import google.generativeai as genai
from langchain.chains import conversational_retrieval
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.vectorstores import FAISS
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
import sqlite3
from datetime import datetime
from PyPDF2 import PdfReader
import pytz
import streamlit as st
from dotenv import load_dotenv
from streamlit_lottie import st_lottie
import requests
import random
# Load environemnt variables from .env files
load_dotenv()
from embed import add_user, create_table, peek, verify_user
# Create the User table
create_table()
st.set_page_config(page_title="Chat with PDF", layout="centered")
# Initialize Gemini API
goggle_api_key = os.getenv("GOGGLE_API_KEY")
genai.configure(api_key= goggle_api_key)
print(goggle_api_key)
# Initialize session state
if 'chat_history' not in st.session_state:
st.session_state.chat_history = {}
if 'flow_messages' not in st.session_state:
st.session_state.flow_messages = {}
def get_greeting_message():
ist = pytz.timezone('Asia/Kolkata')
current_datetime_ist = datetime.now(ist)
current_hour = current_datetime_ist.hour
if 5 <= current_hour < 12:
return "Good morning!"
elif 12 <= current_hour < 18:
return "Good afternoon!"
else:
return "Good evening!"
# Initialize Gemini API
google_api_key = os.getenv("GOOGLE_API_KEY")
if not google_api_key:
google_api_key = 'AIzaSyBaxMCjBV5fBlsKUmFb-8SGgkiirv1ZKck'
genai.configure(api_key=google_api_key)
# Global variable for embeddings
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=google_api_key)
def get_pdf_text(pdf_docs):
text = ""
for pdf in pdf_docs:
pdf_reader = PdfReader(pdf)
for page in pdf_reader.pages:
text += page.extract_text()
return text
def get_text_chunks(text):
text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
chunks = text_splitter.split_text(text)
return chunks
def get_vector_store(text_chunks):
vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
vector_store.save_local("faiss_index")
def load_faiss_index():
return FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
def get_conversational_chain():
prompt_template = """
Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
provided context just say, "answer is not available in the context", don't provide the wrong answer\n\n
Context:\n {context}?\n
Question: \n{question}\n
Answer:
"""
model = ChatGoogleGenerativeAI(model="gemini-1.5-flash-latest", temperature=0.3)
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
return chain
def process_user_input(user_question):
new_db = load_faiss_index()
docs = new_db.similarity_search(user_question)
chain = get_conversational_chain()
response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
print(response)
return response["output_text"]
def load_lottie_url(url: str):
r = requests.get(url)
if r.status_code != 200:
return None
return r.json()
def login():
st.subheader("Login")
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Login"):
user = verify_user(username, password)
if user:
st.success(f"Logged In as {username}")
st.session_state.logged_in = True
st.session_state.username = username
st.rerun()
return True
else:
st.error("Username or password is incorrect.")
return False
def signup():
st.subheader("Create New Account")
new_username = st.text_input("Enter Username")
new_password = st.text_input("Enter Password", type="password")
confirm_password = st.text_input("Confirm Password", type="password")
if st.button("Sign Up"):
if new_password == confirm_password:
try:
add_user(new_username, new_password)
peek()
st.success("You have successfully created an account!")
st.info("Go to Login Menu to login")
except sqlite3.IntegrityError:
st.error("Username already taken, please choose a different one.")
else:
st.warning("Passwords do not match.")
def logout():
for key in list(st.session_state.keys()):
del st.session_state[key]
st.session_state.logged_out = True
st.rerun()
def marketplace(username):
# Custom CSS for better aesthetics
st.markdown("""
<style>
.stApp {
background-color: #f0f2f6;
}
.stButton>button {
background-color: #4CAF50;
color: white;
border-radius: 10px;
}
.stTextInput>div>div>input {
border-radius: 10px;
}
</style>
""", unsafe_allow_html=True)
# Create two columns for layout
col1, col2 = st.columns([1, 2])
with col1:
st.subheader(f"Welcome, {username}!")
# Display current date and time
ist = pytz.timezone('Asia/Kolkata')
current_datetime_ist = datetime.now(ist)
st.write(f"Current Date (IST): {current_datetime_ist.strftime('%Y-%m-%d')}")
st.write(f"Current Time (IST): {current_datetime_ist.strftime('%H:%M:%S')}")
# Add a Lottie animation
lottie_url = "https://assets5.lottiefiles.com/packages/lf20_ktwnwv5m.json"
lottie_json = load_lottie_url(lottie_url)
if lottie_json:
st_lottie(lottie_json, speed=1, height=200, key="initial")
# Category selection
sections = ["Astrology", "Biology", "Business", "Chemistry", "Medicine",
"Physics", "Sports", "Life Science", "Spirituality", "Others"]
selected_section = st.selectbox("Select a category", sections)
# File uploader
uploaded_file = st.file_uploader(f"Upload a PDF for {selected_section}", type="pdf")
if uploaded_file:
with st.spinner(f"Processing {uploaded_file.name}..."):
pdf_text = get_pdf_text([uploaded_file])
text_chunks = get_text_chunks(pdf_text)
get_vector_store(text_chunks)
st.success("Document processed successfully!")
# Add a fun fact or quote
facts = [
"Did you know? The first computer programmer was a woman named Ada Lovelace.",
"Fun fact: The term 'bug' in computer science originated from an actual moth found in a computer.",
"Quote: 'The science of today is the technology of tomorrow.' - Edward Teller"
]
st.info(random.choice(facts))
with col2:
st.header(f"Chat about {selected_section}")
if uploaded_file:
# Initialize chat history for the selected section if it doesn't exist
if selected_section not in st.session_state.chat_history:
st.session_state.chat_history[selected_section] = {"messages": []}
# Display chat history
for message in st.session_state.chat_history[selected_section]["messages"]:
with st.chat_message("user" if message["is_user"] else "assistant"):
st.write(message["text"])
# User input
user_question = st.chat_input("Ask a question about the document:")
if user_question:
st.session_state.chat_history[selected_section]["messages"].append({"is_user": True, "text": user_question})
with st.chat_message("user"):
st.write(user_question)
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = process_user_input(user_question)
st.write(response)
st.session_state.chat_history[selected_section]["messages"].append({"is_user": False, "text": response})
# Clear chat button
if st.button("Clear Chat"):
st.session_state.chat_history[selected_section]["messages"] = []
st.rerun()
# Add a feature to download chat history
if st.button("Download Chat History"):
chat_history = "\n".join([f"{'User' if msg['is_user'] else 'AI'}: {msg['text']}" for msg in st.session_state.chat_history[selected_section]["messages"]])
st.download_button(
label="Download",
data=chat_history,
file_name=f"{selected_section}_chat_history.txt",
mime="text/plain"
)
else:
st.info("Please upload a PDF document to start chatting.")
# Add a feedback section
st.subheader("Feedback")
feedback = st.text_area("We'd love to hear your thoughts! Please leave your feedback here:")
if st.button("Submit Feedback"):
# Here you would typically save this feedback to a database
st.success("Thank you for your feedback!")
# Footer
st.markdown("---")
st.markdown("Created with ❤️ by Harshit S | © 2024 PDF Reader App")
def main():
if 'logged_in' not in st.session_state:
st.session_state.logged_in = False
if st.session_state.logged_in:
marketplace(st.session_state.username)
else:
st.title("Welcome to AI Chat")
choice = st.selectbox("Login/Signup", ["Login", "Sign Up"])
if choice == "Login":
login()
else:
signup()
if st.session_state.get('logged_out', False):
st.info("You have been logged out successfully.")
st.session_state.logged_out = False
if __name__ == "__main__":
print(peek())
main()
|