AliXaidi commited on
Commit
89483ba
1 Parent(s): bb5d60d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain.prompts import PromptTemplate
3
+ from langchain.chains.question_answering import load_qa_chain
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.vectorstores import Chroma
6
+ from langchain_community.vectorstores.faiss import FAISS
7
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
8
+ from dotenv import load_dotenv
9
+ import PyPDF2
10
+ import os
11
+ import io
12
+
13
+ # st.title("Chat Your PDFs") # Updated title
14
+ st.set_page_config(layout="centered")
15
+ st.markdown("<h1 style='font-size:24px;'>PDF ChatBot by Arooj & Ali</h1>", unsafe_allow_html=True)
16
+
17
+ # Load environment variables from .env file
18
+ load_dotenv()
19
+
20
+ # Retrieve API key from environment variable
21
+ google_api_key = os.getenv("GOOGLE_API_KEY")
22
+
23
+ # Check if the API key is available
24
+ if google_api_key is None:
25
+ st.warning("API key not found. Please set the google_api_key environment variable.")
26
+ st.stop()
27
+
28
+ # File Upload with user-defined name
29
+ uploaded_file = st.file_uploader("Your PDF file here", type=["pdf"])
30
+
31
+ prompt_template = """
32
+ Answer the question as detailed as possible from the provided context,
33
+ make sure to provide all the details, if the answer is not in
34
+ provided context just say, "answer is not available in the context",
35
+ don't provide the wrong answer\n\n
36
+ Context:\n {context}?\n
37
+ Question: \n{question}\n
38
+ Answer:
39
+ """
40
+
41
+ # Additional prompts to enhance the template
42
+ prompt_template = prompt_template + """
43
+ --------------------------------------------------
44
+ Prompt Suggestions:
45
+ 1. Summarize the primary theme of the context.
46
+ 2. Elaborate on the crucial concepts highlighted in the context.
47
+ 3. Pinpoint any supporting details or examples pertinent to the question.
48
+ 4. Examine any recurring themes or patterns relevant to the question within the context.
49
+ 5. Contrast differing viewpoints or elements mentioned in the context.
50
+ 6. Explore the potential implications or outcomes of the information provided.
51
+ 7. Assess the trustworthiness and validity of the information given.
52
+ 8. Propose recommendations or advice based on the presented information.
53
+ 9. Forecast likely future events or results stemming from the context.
54
+ 10. Expand on the context or background information pertinent to the question.
55
+ 11. Define any specialized terms or technical language used within the context.
56
+ 12. Analyze any visual representations like charts or graphs in the context.
57
+ 13. Highlight any restrictions or important considerations when responding to the question.
58
+ 14. Examine any presuppositions or biases evident within the context.
59
+ 15. Present alternate interpretations or viewpoints regarding the information provided.
60
+ 16. Reflect on any moral or ethical issues raised by the context.
61
+ 17. Investigate any cause-and-effect relationships identified in the context.
62
+ 18. Uncover any questions or areas requiring further exploration.
63
+ 19. Resolve any vague or conflicting information in the context.
64
+ 20. Cite case studies or examples that demonstrate the concepts discussed in the context.
65
+ """
66
+
67
+ # Return the enhanced prompt template
68
+ prompt_template = prompt_template + """
69
+ --------------------------------------------------
70
+ Context:\n{context}\n
71
+ Question:\n{question}\n
72
+ Answer:
73
+ """
74
+
75
+ if uploaded_file is not None:
76
+ st.text("File Uploaded Successfully!")
77
+
78
+ # PDF Processing (using PyPDF2 directly)
79
+ pdf_data = uploaded_file.read()
80
+ pdf_reader = PyPDF2.PdfReader(io.BytesIO(pdf_data))
81
+ pdf_pages = pdf_reader.pages
82
+
83
+ context = "\n\n".join(page.extract_text() for page in pdf_pages)
84
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=200)
85
+ texts = text_splitter.split_text(context)
86
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
87
+ # vector_index = Chroma.from_texts(texts, embeddings).as_retriever()
88
+ vector_index = FAISS.from_texts(texts, embeddings).as_retriever()
89
+
90
+ user_question = st.text_input("Ask Anything from PDF:", "")
91
+
92
+
93
+
94
+ if st.button("Get Answer"):
95
+ if user_question:
96
+ with st.spinner("Processing..."):
97
+ # Get Relevant Documents
98
+ docs = vector_index.get_relevant_documents(user_question)
99
+ prompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question'])
100
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3, api_key=google_api_key)
101
+ chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
102
+ response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
103
+ st.subheader("Answer:")
104
+ st.write(response['output_text'])
105
+
106
+ else:
107
+ st.warning("Please Ask.")