Spaces:
Sleeping
Sleeping
File size: 11,286 Bytes
a1016ff |
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 |
# import streamlit as st
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# import os
# from langchain_google_genai import GoogleGenerativeAIEmbeddings # we will use googe embiddings
# import google.generativeai as genai
# from langchain_community.vectorstores import FAISS # vectorstore
# from langchain_google_genai import ChatGoogleGenerativeAI
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# from dotenv import load_dotenv
# load_dotenv()
# os.getenv("GOOGLE_API_KEY")
# genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# #read pdf
# def get_pdf_text(pdf_doc):
# text=""
# for pdf in pdf_doc:
# pdf_reader = PdfReader(pdf)
# for page in pdf_reader.pages:
# text+=page.extract_text()
# return text
# # convert pdf into chunks
# def get_text_chunks(text):
# text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
# chunks = text_splitter.split_text(text)
# return chunks
# #convert into vectors
# def get_vector_store(text_chunks):
# embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") # embedding model from huggingface and its free
# vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
# vector_store.save_local("faiss_index") #im storing it in loca
# def get_conversational_chain():
# prompt_template = """
# Answer the question as detailed as possible from the provided context, make sure to provide all details, if the answer is not
# availabe in the provided context" , don't provide the wrong answer and say sorry there is no such information about that\n\n
# context:\n{context}?\n
# Question:\n{question}\n
# Answer:
# """
# model=ChatGoogleGenerativeAI(model="gemini-pro" , 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 user_input(user_query):
# embeddings = GoogleGenerativeAIEmbeddings(model = "models/embedding-001")
# new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
# docs = new_db.similarity_search(user_query)
# chain = get_conversational_chain()
# response = chain(
# {"input_documents":docs, "question": user_query},
# return_only_outputs=True
# )
# print(response)
# st.write("reply: ", response["output_text"])
# def main():
# st.set_page_config("Ask your PDFs")
# st.header("Chat with your PDFs")
# user_question = st.text_input("Ask any question from your PDFs")
# if user_question:
# user_input(user_question)
# with st.sidebar:
# st.title("Menu")
# pdf_docs = st.file_uploader("Upload your PDF files" , type=['pdf'], accept_multiple_files=True)
# if st.button("Submit & Process"):
# if pdf_docs:
# with st.spinner("Processing..."):
# raw_text = get_pdf_text(pdf_docs)
# text_chunks = get_text_chunks(raw_text)
# get_vector_store(text_chunks)
# st.success("Done")
# else:
# st.warning("Please upload PDF files before processing.")
# if __name__ == "__main__":
# main()
#------------------------- 1 ----------------------------
import streamlit as st
from PyPDF2 import PdfReader
from langchain.text_splitter import RecursiveCharacterTextSplitter
import os
from langchain_google_genai import GoogleGenerativeAIEmbeddings
import google.generativeai as genai
from langchain_community.vectorstores import FAISS
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Define a conversational chain for answering questions
def get_conversational_chain():
prompt_template = """
Answer the question as detailed as possible from the provided context. If the answer is not available, say
"Sorry, no information is available on this topic in the context".\n\n
Context:\n{context}?\n
Question:\n{question}\n
Answer:
"""
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
return chain
# Convert pdf text into chunks
def get_text_chunks(text):
text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
chunks = text_splitter.split_text(text)
return chunks
# Convert chunks into vector embeddings
def get_vector_store(text_chunks):
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
vector_store.save_local("faiss_index")
# Read pdf function
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() or "" # Handle None returns
return text
# Function to process user input and return bot response
def user_input(user_query):
try:
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
docs = new_db.similarity_search(user_query)
if not docs:
return {"output_text": "Sorry, no relevant documents found."} # Handle case with no results
chain = get_conversational_chain()
response = chain({"input_documents": docs, "question": user_query}, return_only_outputs=True)
return response
except Exception as e:
return {"output_text": f"Error processing your request: {str(e)}"}
# UI layout and styles for the chat interface
st.set_page_config(page_title="Ask your PDFs", layout="centered")
st.markdown("""
<style>
.chat-container {
max-width: 600px;
margin: 0 auto;
}
.user-message {
background-color: #DCF8C6;
padding: 10px;
border-radius: 10px;
margin-bottom: 5px;
text-align: left;
}
.bot-message {
background-color: #E5E5EA;
padding: 10px;
border-radius: 10px;
margin-bottom: 5px;
text-align: left;
white-space: pre-wrap;
}
.role {
font-weight: bold;
margin-top: 10px;
}
.timestamp {
font-size: 12px;
color: gray;
margin-bottom: 10px;
}
.fixed-bottom {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background-color: white;
padding: 10px;
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.2);
}
.chat-history {
max-height: 80vh; /* Limit height of chat history */
overflow-y: auto; /* Enable scrolling */
margin-bottom: 60px; /* Space for the input field */
}
.header {
text-align: center;
margin: 20px 0; /* Add margin for spacing */
}
</style>
""", unsafe_allow_html=True)
# Initialize session state for chat history
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
# Centered header
st.markdown('<h1 class="header">📄 Chat with your PDFs</h1>', unsafe_allow_html=True)
# Sidebar for PDF uploads
with st.sidebar:
st.title("Upload PDFs")
pdf_docs = st.file_uploader("Upload your PDF files", type=['pdf'], accept_multiple_files=True)
if st.button("Submit & Process"):
if pdf_docs:
with st.spinner("Processing..."):
try:
raw_text = get_pdf_text(pdf_docs)
text_chunks = get_text_chunks(raw_text)
get_vector_store(text_chunks)
st.success("Processing complete! You can start asking questions.")
except Exception as e:
st.error(f"Error processing PDF files: {e}")
else:
st.warning("Please upload PDF files before processing.")
# Display chat history
chat_history_container = st.container()
with chat_history_container:
st.markdown('<div class="chat-history">', unsafe_allow_html=True) # Add scrollable container for chat history
for role, text, timestamp in st.session_state['chat_history']:
if role == "You":
st.markdown(f'<div class="chat-container"><div class="role">You</div><div class="user-message">{text}</div><div class="timestamp">{timestamp}</div></div>', unsafe_allow_html=True)
else:
st.markdown(f'<div class="chat-container"><div class="role">Bot</div><div class="bot-message">{text}</div><div class="timestamp">{timestamp}</div></div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True) # Close scrollable container
# Input field at the bottom for user question
input_container = st.container()
with input_container:
st.markdown('<div class="fixed-bottom">', unsafe_allow_html=True)
input_text = st.text_input("Ask your PDF a question:", value="", key="input_text")
submit = st.button("Send")
st.markdown('</div>', unsafe_allow_html=True)
# Handle user input and bot response
if submit and input_text:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
st.session_state['chat_history'].append(("You", input_text, now))
# Display placeholder
st.session_state['chat_history'].append(("Bot", "Analyzing Input...", now))
# Get response from user_input function
response = user_input(input_text)
# Get the bot's response
bot_response = response.get("output_text", "Sorry, something went wrong.")
# Remove the placeholder and add bot response
st.session_state['chat_history'][-1] = ("Bot", bot_response, now) # Replace the last placeholder with the actual response
# Display the updated chat history again
with chat_history_container:
st.markdown('<div class="chat-history">', unsafe_allow_html=True) # Add scrollable container for chat history
for role, text, timestamp in st.session_state['chat_history']:
if role == "You":
st.markdown(f'<div class="chat-container"><div class="role">You</div><div class="user-message">{text}</div><div class="timestamp">{timestamp}</div></div>', unsafe_allow_html=True)
else:
st.markdown(f'<div class="chat-container"><div class="role">Bot</div><div class="bot-message">{text}</div><div class="timestamp">{timestamp}</div></div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True) # Close scrollable container
|