Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
#
|
20 |
-
|
21 |
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
|
27 |
-
|
|
|
|
|
|
|
|
|
28 |
|
29 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
prompt_template = """
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
Context
|
36 |
-
|
|
|
|
|
|
|
|
|
37 |
Answer:
|
38 |
"""
|
39 |
|
40 |
-
|
41 |
-
|
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 |
-
#
|
51 |
-
|
52 |
-
|
53 |
-
st.text("File Uploaded Successfully!")
|
54 |
|
55 |
-
#
|
56 |
-
|
57 |
-
|
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 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
|
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
-
|
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 |
|