Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,36 +1,32 @@
|
|
1 |
-
import os
|
2 |
-
import io
|
3 |
-
import fitz # PyMuPDF
|
4 |
-
import PyPDF2
|
5 |
-
from docx import Document
|
6 |
import streamlit as st
|
7 |
-
from sentence_transformers import SentenceTransformer
|
8 |
from langchain.prompts import PromptTemplate
|
9 |
from langchain.chains.question_answering import load_qa_chain
|
10 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
11 |
from langchain_community.vectorstores.faiss import FAISS
|
12 |
-
from
|
13 |
-
from
|
|
|
|
|
|
|
14 |
|
15 |
-
#
|
16 |
-
|
|
|
17 |
|
18 |
-
#
|
19 |
-
|
20 |
-
endpoint_url="https://api-inference.huggingface.co/models/gpt-3.5-turbo",
|
21 |
-
model_kwargs={"api_key": "YOUR_HUGGINGFACE_API_KEY"}
|
22 |
-
)
|
23 |
|
24 |
-
#
|
25 |
-
|
26 |
|
27 |
-
#
|
28 |
-
|
29 |
-
st.
|
|
|
30 |
|
31 |
-
|
32 |
-
uploaded_file = st.file_uploader("Upload your PDF or DOCX file", type=["pdf", "docx"])
|
33 |
|
|
|
34 |
prompt_template = """
|
35 |
Answer the question as detailed as possible from the provided context,
|
36 |
make sure to provide all the details, if the answer is not in
|
@@ -41,82 +37,62 @@ Question: \n{question}\n
|
|
41 |
Answer:
|
42 |
"""
|
43 |
|
|
|
44 |
prompt_template += """
|
45 |
--------------------------------------------------
|
46 |
Prompt Suggestions:
|
47 |
1. Summarize the primary theme of the context.
|
48 |
2. Elaborate on the crucial concepts highlighted in the context.
|
49 |
-
|
50 |
-
4. Examine any recurring themes or patterns relevant to the question within the context.
|
51 |
-
5. Contrast differing viewpoints or elements mentioned in the context.
|
52 |
-
6. Explore the potential implications or outcomes of the information provided.
|
53 |
-
7. Assess the trustworthiness and validity of the information given.
|
54 |
-
8. Propose recommendations or advice based on the presented information.
|
55 |
-
9. Forecast likely future events or results stemming from the context.
|
56 |
-
10. Expand on the context or background information pertinent to the question.
|
57 |
-
11. Define any specialized terms or technical language used within the context.
|
58 |
-
12. Analyze any visual representations like charts or graphs in the context.
|
59 |
-
13. Highlight any restrictions or important considerations when responding to the question.
|
60 |
-
14. Examine any presuppositions or biases evident within the context.
|
61 |
-
15. Present alternate interpretations or viewpoints regarding the information provided.
|
62 |
-
16. Reflect on any moral or ethical issues raised by the context.
|
63 |
-
17. Investigate any cause-and-effect relationships identified in the context.
|
64 |
-
18. Uncover any questions or areas requiring further exploration.
|
65 |
-
19. Resolve any vague or conflicting information in the context.
|
66 |
20. Cite case studies or examples that demonstrate the concepts discussed in the context.
|
67 |
-
--------------------------------------------------
|
68 |
-
Context:\n{context}\n
|
69 |
-
Question:\n{question}\n
|
70 |
-
Answer:
|
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 |
-
if st.button("Get Answer"):
|
111 |
-
if user_question:
|
112 |
-
with st.spinner("Processing..."):
|
113 |
-
docs = vector_index.get_relevant_documents(user_question)
|
114 |
-
prompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question'])
|
115 |
-
chain = load_qa_chain(llm, chain_type="stuff", prompt=prompt)
|
116 |
-
response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
|
117 |
-
st.subheader("Answer:")
|
118 |
-
st.write(response['output_text'])
|
119 |
-
else:
|
120 |
-
st.warning("Please enter a question.")
|
121 |
|
122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
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_community.vectorstores.faiss import FAISS
|
6 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
import PyPDF2
|
9 |
+
import os
|
10 |
+
import io
|
11 |
|
12 |
+
# Set page configuration
|
13 |
+
st.set_page_config(layout="centered")
|
14 |
+
st.markdown("<h1 style='font-size:24px;'>PDF ChatBot by Ali & Arooj</h1>", unsafe_allow_html=True)
|
15 |
|
16 |
+
# Load environment variables from .env file
|
17 |
+
load_dotenv()
|
|
|
|
|
|
|
18 |
|
19 |
+
# Retrieve API key from environment variable
|
20 |
+
google_api_key = os.getenv("GOOGLE_API_KEY")
|
21 |
|
22 |
+
# Check if the API key is available
|
23 |
+
if google_api_key is None:
|
24 |
+
st.warning("API key not found. Please set the google_api_key environment variable.")
|
25 |
+
st.stop()
|
26 |
|
27 |
+
uploaded_file = st.file_uploader("Your PDF file here", type=["pdf", "docx"])
|
|
|
28 |
|
29 |
+
# Prompt template
|
30 |
prompt_template = """
|
31 |
Answer the question as detailed as possible from the provided context,
|
32 |
make sure to provide all the details, if the answer is not in
|
|
|
37 |
Answer:
|
38 |
"""
|
39 |
|
40 |
+
# Additional prompts
|
41 |
prompt_template += """
|
42 |
--------------------------------------------------
|
43 |
Prompt Suggestions:
|
44 |
1. Summarize the primary theme of the context.
|
45 |
2. Elaborate on the crucial concepts highlighted in the context.
|
46 |
+
...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
20. Cite case studies or examples that demonstrate the concepts discussed in the context.
|
|
|
|
|
|
|
|
|
48 |
"""
|
49 |
|
50 |
+
# Function to process PDF and DOCX files
|
51 |
+
def process_files(uploaded_file):
|
52 |
+
if uploaded_file is not None:
|
53 |
+
st.text("File Uploaded Successfully!")
|
54 |
+
|
55 |
+
# Check file type and process accordingly
|
56 |
+
if uploaded_file.type == "application/pdf":
|
57 |
+
# PDF Processing
|
58 |
+
pdf_data = uploaded_file.read()
|
59 |
+
pdf_reader = PyPDF2.PdfReader(io.BytesIO(pdf_data))
|
60 |
+
pdf_pages = pdf_reader.pages
|
61 |
+
|
62 |
+
context = "\n\n".join(page.extract_text() for page in pdf_pages)
|
63 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=200)
|
64 |
+
texts = text_splitter.split_text(context)
|
65 |
+
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
66 |
+
vector_index = FAISS.from_texts(texts, embeddings).as_retriever()
|
67 |
+
|
68 |
+
elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
|
69 |
+
# DOCX Processing (if needed)
|
70 |
+
pass
|
71 |
+
else:
|
72 |
+
st.warning("Unsupported file format. Please upload PDF or DOCX.")
|
73 |
+
st.stop()
|
74 |
+
|
75 |
+
user_question = st.text_input("Ask Anything from PDF:", "")
|
76 |
+
|
77 |
+
if st.button("Get Answer"):
|
78 |
+
if user_question:
|
79 |
+
with st.spinner("Processing..."):
|
80 |
+
docs = vector_index.get_relevant_documents(user_question)
|
81 |
+
prompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question'])
|
82 |
+
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3, api_key=google_api_key)
|
83 |
+
chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
|
84 |
+
response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
|
85 |
+
st.subheader("Answer:")
|
86 |
+
st.write(response['output_text'])
|
87 |
+
else:
|
88 |
+
st.warning("Please Ask.")
|
89 |
|
90 |
+
# Main function
|
91 |
+
def main():
|
92 |
+
process_files(uploaded_file)
|
93 |
|
94 |
+
if __name__ == "__main__":
|
95 |
+
main()
|
96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
|