NaimaAqeel commited on
Commit
90bf4dc
·
verified ·
1 Parent(s): dcb9703

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -77
app.py CHANGED
@@ -1,98 +1,188 @@
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
33
- provided context just say, "answer is not available in the context",
34
- don't provide the wrong answer\n\n
35
- Context:\n {context}?\n
36
- Question: \n{question}\n
 
 
 
 
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
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import fitz
3
+ from docx import Document
4
+ from sentence_transformers import SentenceTransformer
5
+ import faiss
6
+ import numpy as np
7
+ import pickle
8
+ import gradio as gr
9
+ from langchain_community.llms import HuggingFaceEndpoint
10
+ from langchain_community.vectorstores import FAISS
11
+ from langchain_community.embeddings import HuggingFaceEmbeddings
12
 
13
+ # Function to extract text from a PDF file
14
+ def extract_text_from_pdf(pdf_path):
15
+ text = ""
16
+ try:
17
+ doc = fitz.open(pdf_path)
18
+ for page_num in range(len(doc)):
19
+ page = doc.load_page(page_num)
20
+ text += page.get_text()
21
+ except Exception as e:
22
+ print(f"Error extracting text from PDF: {e}")
23
+ return text
24
 
25
+ # Function to extract text from a Word document
26
+ def extract_text_from_docx(docx_path):
27
+ text = ""
28
+ try:
29
+ doc = Document(docx_path)
30
+ text = "\n".join([para.text for para in doc.paragraphs])
31
+ except Exception as e:
32
+ print(f"Error extracting text from DOCX: {e}")
33
+ return text
34
 
35
+ # Initialize the embedding model
36
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
37
 
38
+ # Hugging Face API token
39
+ api_token = os.getenv('HUGGINGFACEHUB_API_TOKEN')
40
+ if not api_token:
41
+ raise ValueError("HUGGINGFACEHUB_API_TOKEN environment variable is not set or invalid")
42
 
43
+ # Initialize the HuggingFace LLM
44
+ llm = HuggingFaceEndpoint(
45
+ endpoint_url="https://api-inference.huggingface.co/models/gpt2", # Using gpt2 model
46
+ model_kwargs={"api_key": api_token}
47
+ )
48
 
49
+ # Initialize the HuggingFace embeddings
50
+ embedding = HuggingFaceEmbeddings()
51
+
52
+ # Load or create FAISS index
53
+ index_path = "faiss_index.pkl"
54
+ document_texts_path = "document_texts.pkl"
55
+
56
+ document_texts = []
57
+
58
+ if os.path.exists(index_path) and os.path.exists(document_texts_path):
59
+ try:
60
+ with open(index_path, "rb") as f:
61
+ index = pickle.load(f)
62
+ print("Loaded FAISS index from faiss_index.pkl")
63
+ with open(document_texts_path, "rb") as f:
64
+ document_texts = pickle.load(f)
65
+ print("Loaded document texts from document_texts.pkl")
66
+ except Exception as e:
67
+ print(f"Error loading FAISS index or document texts: {e}")
68
+ else:
69
+ # Create a new FAISS index if it doesn't exist
70
+ index = faiss.IndexFlatL2(embedding_model.get_sentence_embedding_dimension())
71
+ with open(index_path, "wb") as f:
72
+ pickle.dump(index, f)
73
+ print("Created new FAISS index and saved to faiss_index.pkl")
74
+
75
+ def preprocess_text(text):
76
+ # Add more preprocessing steps if necessary
77
+ return text.strip()
78
+
79
+ def upload_files(files):
80
+ global index, document_texts
81
+ try:
82
+ for file in files:
83
+ file_path = file.name # Get the file path from the NamedString object
84
+ if file_path.endswith('.pdf'):
85
+ text = extract_text_from_pdf(file_path)
86
+ elif file_path.endswith('.docx'):
87
+ text = extract_text_from_docx(file_path)
88
+ else:
89
+ return "Unsupported file format"
90
+
91
+ print(f"Extracted text: {text[:100]}...") # Debug: Show the first 100 characters of the extracted text
92
+
93
+ # Process the text and update FAISS index
94
+ sentences = text.split("\n")
95
+ sentences = [preprocess_text(sentence) for sentence in sentences if sentence.strip()]
96
+ embeddings = embedding_model.encode(sentences)
97
+ print(f"Embeddings shape: {embeddings.shape}") # Debug: Show the shape of the embeddings
98
+ index.add(np.array(embeddings))
99
+ document_texts.extend(sentences) # Store sentences for retrieval
100
+
101
+ # Save the updated index and documents
102
+ with open(index_path, "wb") as f:
103
+ pickle.dump(index, f)
104
+ print("Saved updated FAISS index to faiss_index.pkl")
105
+ with open(document_texts_path, "wb") as f:
106
+ pickle.dump(document_texts, f)
107
+ print("Saved updated document texts to document_texts.pkl")
108
+
109
+ return "Files processed successfully"
110
+ except Exception as e:
111
+ print(f"Error processing files: {e}")
112
+ return f"Error processing files: {e}"
113
+
114
+ # Improved prompt template
115
  prompt_template = """
116
+ You are a helpful assistant. Use the provided context to answer the question accurately.
117
+ If the answer is not in the context, say "answer is not available in the context".
118
+ Do not provide false information.
119
+
120
+ Context:
121
+ {context}
122
+
123
+ Question:
124
+ {question}
125
+
126
  Answer:
127
  """
128
 
129
+ def query_text(text):
130
+ try:
131
+ print(f"Query text: {text}") # Debug: Show the query text
 
 
 
 
 
 
132
 
133
+ # Encode the query text
134
+ query_embedding = embedding_model.encode([text])
135
+ print(f"Query embedding shape: {query_embedding.shape}") # Debug: Show the shape of the query embedding
 
136
 
137
+ # Search the FAISS index
138
+ D, I = index.search(np.array(query_embedding), k=5)
139
+ print(f"Distances: {D}, Indices: {I}") # Debug: Show the distances and indices of the search results
 
 
 
 
 
 
 
 
 
140
 
141
+ top_documents = []
142
+ for idx in I[0]:
143
+ if idx != -1 and idx < len(document_texts):
144
+ # Get a passage around the retrieved sentence (e.g., paragraph)
145
+ passage_start = max(0, idx - 5) # Adjust window size as needed
146
+ passage_end = min(len(document_texts), idx + 5)
147
+ passage = "\n".join(document_texts[passage_start:passage_end])
148
+ top_documents.append(passage)
149
+ else:
150
+ print(f"Invalid index found: {idx}")
151
 
152
+ # Remove duplicates and sort by relevance
153
+ top_documents = list(dict.fromkeys(top_documents))
154
 
155
+ # Join the top documents for the context
156
+ context = "\n".join(top_documents)
157
+
158
+ # Prepare the prompt
159
+ prompt = prompt_template.format(context=context, question=text)
160
+
161
+ # Query the LLM
162
+ response = llm(prompt)
163
+ return response
164
+ except Exception as e:
165
+ print(f"Error querying text: {e}")
166
+ return f"Error querying text: {e}"
167
+
168
+ # Create Gradio interface
169
+ with gr.Blocks() as demo:
170
+ gr.Markdown("## Document Upload and Query System")
171
+
172
+ with gr.Tab("Upload Files"):
173
+ upload = gr.File(file_count="multiple", label="Upload PDF or DOCX files")
174
+ upload_button = gr.Button("Upload")
175
+ upload_output = gr.Textbox()
176
+ upload_button.click(fn=upload_files, inputs=upload, outputs=upload_output)
177
+
178
+ with gr.Tab("Query"):
179
+ query = gr.Textbox(label="Enter your query")
180
+ query_button = gr.Button("Search")
181
+ query_output = gr.Textbox()
182
+ query_button.click(fn=query_text, inputs=query, outputs=query_output)
183
 
184
+ demo.launch()
 
 
185
 
 
 
186
 
187
 
188