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(""" """, 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()