Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -46,19 +46,19 @@ llama_parser = LlamaParse(
|
|
46 |
language="en",
|
47 |
)
|
48 |
|
49 |
-
def load_document(
|
50 |
"""Loads and splits the document into pages."""
|
51 |
if parser == "pypdf":
|
52 |
-
loader = PyPDFLoader(
|
53 |
return loader.load_and_split()
|
54 |
elif parser == "llamaparse":
|
55 |
try:
|
56 |
-
documents = llama_parser.load_data(
|
57 |
-
return [Document(page_content=doc.text, metadata={"source":
|
58 |
except Exception as e:
|
59 |
print(f"Error using Llama Parse: {str(e)}")
|
60 |
print("Falling back to PyPDF parser")
|
61 |
-
loader = PyPDFLoader(
|
62 |
return loader.load_and_split()
|
63 |
else:
|
64 |
raise ValueError("Invalid parser specified. Use 'pypdf' or 'llamaparse'.")
|
@@ -85,7 +85,12 @@ def update_vectors(files, parser):
|
|
85 |
for file in files:
|
86 |
logging.info(f"Processing file: {file.name}")
|
87 |
try:
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
89 |
logging.info(f"Loaded {len(data)} chunks from {file.name}")
|
90 |
all_data.extend(data)
|
91 |
total_chunks += len(data)
|
@@ -100,16 +105,10 @@ def update_vectors(files, parser):
|
|
100 |
|
101 |
logging.info(f"Total chunks processed: {total_chunks}")
|
102 |
|
103 |
-
if
|
104 |
-
logging.info("Updating existing FAISS database")
|
105 |
-
database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
|
106 |
-
database.add_documents(all_data)
|
107 |
-
else:
|
108 |
-
logging.info("Creating new FAISS database")
|
109 |
database = FAISS.from_documents(all_data, embed)
|
110 |
-
|
111 |
-
|
112 |
-
logging.info("FAISS database saved")
|
113 |
|
114 |
return f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files using {parser}.", gr.CheckboxGroup(
|
115 |
choices=[doc["name"] for doc in uploaded_documents],
|
@@ -117,6 +116,52 @@ def update_vectors(files, parser):
|
|
117 |
label="Select documents to query"
|
118 |
)
|
119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
def generate_chunked_response(prompt, model, max_tokens=10000, num_calls=3, temperature=0.2, should_stop=False):
|
121 |
print(f"Starting generate_chunked_response with {num_calls} calls")
|
122 |
full_response = ""
|
@@ -247,7 +292,6 @@ def respond(message, history, model, temperature, num_calls, use_web_search, sel
|
|
247 |
logging.info(f"User Query: {message}")
|
248 |
logging.info(f"Model Used: {model}")
|
249 |
logging.info(f"Search Type: {'Web Search' if use_web_search else 'PDF Search'}")
|
250 |
-
|
251 |
logging.info(f"Selected Documents: {selected_docs}")
|
252 |
|
253 |
try:
|
@@ -265,7 +309,7 @@ def respond(message, history, model, temperature, num_calls, use_web_search, sel
|
|
265 |
|
266 |
# Filter relevant documents based on user selection
|
267 |
all_relevant_docs = retriever.get_relevant_documents(message)
|
268 |
-
relevant_docs = [doc for doc in all_relevant_docs if doc.metadata["source"] in selected_docs]
|
269 |
|
270 |
if not relevant_docs:
|
271 |
yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
|
|
|
46 |
language="en",
|
47 |
)
|
48 |
|
49 |
+
def load_document(file_path: str, parser: str = "llamaparse") -> List[Document]:
|
50 |
"""Loads and splits the document into pages."""
|
51 |
if parser == "pypdf":
|
52 |
+
loader = PyPDFLoader(file_path)
|
53 |
return loader.load_and_split()
|
54 |
elif parser == "llamaparse":
|
55 |
try:
|
56 |
+
documents = llama_parser.load_data(file_path)
|
57 |
+
return [Document(page_content=doc.text, metadata={"source": file_path}) for doc in documents]
|
58 |
except Exception as e:
|
59 |
print(f"Error using Llama Parse: {str(e)}")
|
60 |
print("Falling back to PyPDF parser")
|
61 |
+
loader = PyPDFLoader(file_path)
|
62 |
return loader.load_and_split()
|
63 |
else:
|
64 |
raise ValueError("Invalid parser specified. Use 'pypdf' or 'llamaparse'.")
|
|
|
85 |
for file in files:
|
86 |
logging.info(f"Processing file: {file.name}")
|
87 |
try:
|
88 |
+
# Save the uploaded file
|
89 |
+
os.makedirs("uploaded_files", exist_ok=True)
|
90 |
+
file_path = os.path.join("uploaded_files", file.name)
|
91 |
+
file.save(file_path)
|
92 |
+
|
93 |
+
data = load_document(file_path, parser)
|
94 |
logging.info(f"Loaded {len(data)} chunks from {file.name}")
|
95 |
all_data.extend(data)
|
96 |
total_chunks += len(data)
|
|
|
105 |
|
106 |
logging.info(f"Total chunks processed: {total_chunks}")
|
107 |
|
108 |
+
if all_data:
|
|
|
|
|
|
|
|
|
|
|
109 |
database = FAISS.from_documents(all_data, embed)
|
110 |
+
database.save_local("faiss_database")
|
111 |
+
logging.info("FAISS database saved")
|
|
|
112 |
|
113 |
return f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files using {parser}.", gr.CheckboxGroup(
|
114 |
choices=[doc["name"] for doc in uploaded_documents],
|
|
|
116 |
label="Select documents to query"
|
117 |
)
|
118 |
|
119 |
+
def delete_selected_files(selected_files):
|
120 |
+
global uploaded_documents
|
121 |
+
if not selected_files:
|
122 |
+
return "No files selected for deletion.", document_selector
|
123 |
+
|
124 |
+
deleted_files = []
|
125 |
+
for file_name in selected_files:
|
126 |
+
# Remove the file from uploaded_documents
|
127 |
+
uploaded_documents = [doc for doc in uploaded_documents if doc["name"] != file_name]
|
128 |
+
|
129 |
+
# Delete the file from the file system if it exists
|
130 |
+
file_path = os.path.join("uploaded_files", file_name)
|
131 |
+
if os.path.exists(file_path):
|
132 |
+
os.remove(file_path)
|
133 |
+
|
134 |
+
deleted_files.append(file_name)
|
135 |
+
|
136 |
+
# Update the FAISS database
|
137 |
+
update_faiss_database()
|
138 |
+
|
139 |
+
remaining_files = [doc["name"] for doc in uploaded_documents]
|
140 |
+
return f"Deleted files: {', '.join(deleted_files)}", gr.CheckboxGroup(choices=remaining_files, value=remaining_files, label="Select documents to query")
|
141 |
+
|
142 |
+
def update_faiss_database():
|
143 |
+
global uploaded_documents
|
144 |
+
|
145 |
+
embed = get_embeddings()
|
146 |
+
all_data = []
|
147 |
+
|
148 |
+
for doc in uploaded_documents:
|
149 |
+
file_path = os.path.join("uploaded_files", doc["name"])
|
150 |
+
if os.path.exists(file_path):
|
151 |
+
data = load_document(file_path, parser="llamaparse") # or use your preferred parser
|
152 |
+
all_data.extend(data)
|
153 |
+
|
154 |
+
if all_data:
|
155 |
+
database = FAISS.from_documents(all_data, embed)
|
156 |
+
database.save_local("faiss_database")
|
157 |
+
logging.info("FAISS database updated after deletion")
|
158 |
+
else:
|
159 |
+
# If no documents left, remove the FAISS database
|
160 |
+
if os.path.exists("faiss_database"):
|
161 |
+
import shutil
|
162 |
+
shutil.rmtree("faiss_database")
|
163 |
+
logging.info("All documents deleted, FAISS database removed")
|
164 |
+
|
165 |
def generate_chunked_response(prompt, model, max_tokens=10000, num_calls=3, temperature=0.2, should_stop=False):
|
166 |
print(f"Starting generate_chunked_response with {num_calls} calls")
|
167 |
full_response = ""
|
|
|
292 |
logging.info(f"User Query: {message}")
|
293 |
logging.info(f"Model Used: {model}")
|
294 |
logging.info(f"Search Type: {'Web Search' if use_web_search else 'PDF Search'}")
|
|
|
295 |
logging.info(f"Selected Documents: {selected_docs}")
|
296 |
|
297 |
try:
|
|
|
309 |
|
310 |
# Filter relevant documents based on user selection
|
311 |
all_relevant_docs = retriever.get_relevant_documents(message)
|
312 |
+
relevant_docs = [doc for doc in all_relevant_docs if os.path.basename(doc.metadata["source"]) in selected_docs]
|
313 |
|
314 |
if not relevant_docs:
|
315 |
yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
|