NaimaAqeel commited on
Commit
1649416
·
verified ·
1 Parent(s): a42468d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -88
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 langchain_community.embeddings import HuggingFaceEmbeddings
13
- from langchain_community.llms import HuggingFaceEndpoint
 
 
 
14
 
15
- # Initialize the embedding model
16
- embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
 
17
 
18
- # Initialize the HuggingFace LLM
19
- llm = HuggingFaceEndpoint(
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
- # Initialize the HuggingFace embeddings
25
- embedding = HuggingFaceEmbeddings()
26
 
27
- # Streamlit setup
28
- st.set_page_config(layout="centered")
29
- st.markdown("<h1 style='font-size:24px;'>PDF and DOCX ChatBot</h1>", unsafe_allow_html=True)
 
30
 
31
- # File Upload
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
- 3. Pinpoint any supporting details or examples pertinent to the question.
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
- def extract_text_from_docx(docx_file):
74
- text = ""
75
- try:
76
- doc = Document(docx_file)
77
- text = "\n".join([para.text for para in doc.paragraphs])
78
- except Exception as e:
79
- print(f"Error extracting text from DOCX: {e}")
80
- return text
81
-
82
- def extract_text_from_pdf(pdf_file):
83
- text = ""
84
- try:
85
- pdf_document = fitz.open(stream=pdf_file, filetype="pdf")
86
- for page_num in range(len(pdf_document)):
87
- page = pdf_document[page_num]
88
- text += page.get_text()
89
- except Exception as e:
90
- print(f"Error extracting text from PDF: {e}")
91
- return text
92
-
93
- if uploaded_file is not None:
94
- st.text("File Uploaded Successfully!")
95
-
96
- context = ""
97
-
98
- # Process the uploaded file
99
- if uploaded_file.name.endswith('.pdf'):
100
- context = extract_text_from_pdf(uploaded_file)
101
- elif uploaded_file.name.endswith('.docx'):
102
- context = extract_text_from_docx(uploaded_file)
 
 
 
 
 
 
 
 
 
103
 
104
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=200)
105
- texts = text_splitter.split_text(context)
106
- vector_index = FAISS.from_texts(texts, embedding).as_retriever()
107
 
108
- user_question = st.text_input("Ask Anything from the Document:", "")
 
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