AliZain1 commited on
Commit
5d46dac
·
verified ·
1 Parent(s): 83a661a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -42
app.py CHANGED
@@ -6,71 +6,74 @@ from langchain.chains.combine_documents import create_stuff_documents_chain
6
  from langchain_core.prompts import ChatPromptTemplate
7
  from langchain.chains import create_retrieval_chain
8
  from langchain_community.vectorstores import FAISS
9
- from langchain_community.document_loaders import PyPDFDirectoryLoader
10
  from langchain_google_genai import GoogleGenerativeAIEmbeddings
11
  from dotenv import load_dotenv
12
- import os
 
13
  load_dotenv()
14
 
15
  ## load the GROQ And OpenAI API KEY
16
- groq_api_key=os.getenv('GROQ_API_KEY')
17
- os.environ["GOOGLE_API_KEY"]=os.getenv("GOOGLE_API_KEY")
18
 
19
  st.title("Gemma Model Document Q&A")
20
 
21
- llm=ChatGroq(groq_api_key=groq_api_key,
22
- model_name="Llama3-8b-8192")
23
 
24
- prompt=ChatPromptTemplate.from_template(
25
  """
26
  Answer the questions based on the provided context only.
27
- Please provide the most accurate response based on the question
28
  <context>
29
  {context}
30
  <context>
31
- Questions:{input}
32
-
33
  """
34
  )
35
 
36
- def vector_embedding():
37
 
38
  if "vectors" not in st.session_state:
39
 
40
- st.session_state.embeddings=GoogleGenerativeAIEmbeddings(model = "models/embedding-001")
41
- st.session_state.loader=PyPDFDirectoryLoader("./us_census") ## Data Ingestion
42
- st.session_state.docs=st.session_state.loader.load() ## Document Loading
43
- st.session_state.text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200) ## Chunk Creation
44
- st.session_state.final_documents=st.session_state.text_splitter.split_documents(st.session_state.docs[:20]) #splitting
45
- st.session_state.vectors=FAISS.from_documents(st.session_state.final_documents,st.session_state.embeddings) #vector OpenAI embeddings
46
-
47
-
48
-
49
-
50
-
51
- prompt1=st.text_input("Enter Your Question From Doduments")
52
-
53
-
54
- if st.button("Documents Embedding"):
55
- vector_embedding()
56
- st.write("Vector Store DB Is Ready")
57
-
58
- import time
59
-
60
-
61
-
62
- if prompt1:
63
- document_chain=create_stuff_documents_chain(llm,prompt)
64
- retriever=st.session_state.vectors.as_retriever()
65
- retrieval_chain=create_retrieval_chain(retriever,document_chain)
66
- start=time.process_time()
67
- response=retrieval_chain.invoke({'input':prompt1})
68
- print("Response time :",time.process_time()-start)
 
 
69
  st.write(response['answer'])
70
 
71
- # With a streamlit expander
72
  with st.expander("Document Similarity Search"):
73
  # Find the relevant chunks
74
  for i, doc in enumerate(response["context"]):
75
  st.write(doc.page_content)
76
- st.write("--------------------------------")
 
 
 
6
  from langchain_core.prompts import ChatPromptTemplate
7
  from langchain.chains import create_retrieval_chain
8
  from langchain_community.vectorstores import FAISS
9
+ from langchain_community.document_loaders import PyPDFLoader
10
  from langchain_google_genai import GoogleGenerativeAIEmbeddings
11
  from dotenv import load_dotenv
12
+ import time
13
+
14
  load_dotenv()
15
 
16
  ## load the GROQ And OpenAI API KEY
17
+ groq_api_key = os.getenv('GROQ_API_KEY')
18
+ os.environ["GOOGLE_API_KEY"] = os.getenv("GOOGLE_API_KEY")
19
 
20
  st.title("Gemma Model Document Q&A")
21
 
22
+ llm = ChatGroq(groq_api_key=groq_api_key, model_name="Llama3-8b-8192")
 
23
 
24
+ prompt = ChatPromptTemplate.from_template(
25
  """
26
  Answer the questions based on the provided context only.
27
+ Please provide the most accurate response based on the question.
28
  <context>
29
  {context}
30
  <context>
31
+ Questions: {input}
 
32
  """
33
  )
34
 
35
+ def vector_embedding(uploaded_files):
36
 
37
  if "vectors" not in st.session_state:
38
 
39
+ st.session_state.embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
40
+
41
+ # Load documents from the uploaded PDF files
42
+ documents = []
43
+ for uploaded_file in uploaded_files:
44
+ loader = PyPDFLoader(uploaded_file)
45
+ documents.extend(loader.load())
46
+
47
+ st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
48
+ st.session_state.final_documents = st.session_state.text_splitter.split_documents(documents)
49
+
50
+ if st.session_state.final_documents:
51
+ st.session_state.vectors = FAISS.from_documents(st.session_state.final_documents, st.session_state.embeddings)
52
+ st.write("Vector Store DB Is Ready")
53
+ else:
54
+ st.write("No documents were loaded or processed. Please check your files.")
55
+
56
+ prompt1 = st.text_input("Enter Your Question From Documents")
57
+
58
+ uploaded_files = st.file_uploader("Upload your PDF files", accept_multiple_files=True, type=["pdf"])
59
+
60
+ if st.button("Documents Embedding") and uploaded_files:
61
+ vector_embedding(uploaded_files)
62
+
63
+ if prompt1 and "vectors" in st.session_state:
64
+ document_chain = create_stuff_documents_chain(llm, prompt)
65
+ retriever = st.session_state.vectors.as_retriever()
66
+ retrieval_chain = create_retrieval_chain(retriever, document_chain)
67
+ start = time.process_time()
68
+ response = retrieval_chain.invoke({'input': prompt1})
69
+ st.write(f"Response time: {time.process_time() - start:.2f} seconds")
70
  st.write(response['answer'])
71
 
72
+ # With a Streamlit expander
73
  with st.expander("Document Similarity Search"):
74
  # Find the relevant chunks
75
  for i, doc in enumerate(response["context"]):
76
  st.write(doc.page_content)
77
+ st.write("--------------------------------")
78
+ else:
79
+ st.write("Please upload your documents and click on 'Documents Embedding' first.")