Spaces:
Sleeping
Sleeping
viboognesh-doaz
commited on
Commit
·
5e32aa7
1
Parent(s):
5a02e62
fixed aws errors
Browse files- app.py +5 -268
- awsfunctions.py +3 -3
- retrieve_and_display.py +9 -8
app.py
CHANGED
@@ -1,261 +1,4 @@
|
|
1 |
-
# import streamlit as st
|
2 |
-
# import os
|
3 |
-
# from PyPDF2 import PdfReader
|
4 |
-
# import pymupdf
|
5 |
-
# import numpy as np
|
6 |
-
# import cv2
|
7 |
-
# import shutil
|
8 |
-
# import imageio
|
9 |
-
# from PIL import Image
|
10 |
-
# import imagehash
|
11 |
-
# import matplotlib.pyplot as plt
|
12 |
-
# from llama_index.core.indices import MultiModalVectorStoreIndex
|
13 |
-
# from llama_index.vector_stores.qdrant import QdrantVectorStore
|
14 |
-
# from llama_index.core import SimpleDirectoryReader, StorageContext
|
15 |
-
# import qdrant_client
|
16 |
-
# from llama_index.core import PromptTemplate
|
17 |
-
# from llama_index.core.query_engine import SimpleMultiModalQueryEngine
|
18 |
-
# from llama_index.llms.openai import OpenAI
|
19 |
-
# from llama_index.core import load_index_from_storage, get_response_synthesizer
|
20 |
-
# import tempfile
|
21 |
-
# from qdrant_client import QdrantClient, models
|
22 |
-
# import getpass
|
23 |
-
|
24 |
-
# curr_user = getpass.getuser()
|
25 |
-
# # from langchain.vectorstores import Chroma
|
26 |
-
# # To connect to the same event-loop,
|
27 |
-
# # allows async events to run on notebook
|
28 |
-
|
29 |
-
# # import nest_asyncio
|
30 |
-
|
31 |
-
# # nest_asyncio.apply()
|
32 |
-
|
33 |
-
# from dotenv import load_dotenv
|
34 |
-
# load_dotenv()
|
35 |
-
|
36 |
-
|
37 |
-
# def extract_text_from_pdf(pdf_path):
|
38 |
-
# reader = PdfReader(pdf_path)
|
39 |
-
# full_text = ''
|
40 |
-
# for page in reader.pages:
|
41 |
-
# text = page.extract_text()
|
42 |
-
# full_text += text
|
43 |
-
# return full_text
|
44 |
-
|
45 |
-
# def extract_images_from_pdf(pdf_path, img_save_path):
|
46 |
-
# doc = pymupdf.open(pdf_path)
|
47 |
-
# for page in doc:
|
48 |
-
# img_number = 0
|
49 |
-
# for block in page.get_text("dict")["blocks"]:
|
50 |
-
# if block['type'] == 1:
|
51 |
-
# name = os.path.join(img_save_path, f"img{page.number}-{img_number}.{block['ext']}")
|
52 |
-
# out = open(name, "wb")
|
53 |
-
# out.write(block["image"])
|
54 |
-
# out.close()
|
55 |
-
# img_number += 1
|
56 |
-
|
57 |
-
# def is_empty(img_path):
|
58 |
-
# image = cv2.imread(img_path, 0)
|
59 |
-
# std_dev = np.std(image)
|
60 |
-
# return std_dev < 1
|
61 |
-
|
62 |
-
# def move_images(source_folder, dest_folder):
|
63 |
-
# image_files = [f for f in os.listdir(source_folder)
|
64 |
-
# if f.lower().endswith(('.jpg', '.jpeg', '.png', '.gif'))]
|
65 |
-
# os.makedirs(dest_folder, exist_ok=True)
|
66 |
-
# moved_count = 0
|
67 |
-
# for file in image_files:
|
68 |
-
# src_path = os.path.join(source_folder, file)
|
69 |
-
# if not is_empty(src_path):
|
70 |
-
# shutil.move(src_path, os.path.join(dest_folder, file))
|
71 |
-
# moved_count += 1
|
72 |
-
# return moved_count
|
73 |
-
|
74 |
-
# def remove_low_size_images(data_path):
|
75 |
-
# images_list = os.listdir(data_path)
|
76 |
-
# low_size_photo_list = []
|
77 |
-
# for one_image in images_list:
|
78 |
-
# image_path = os.path.join(data_path, one_image)
|
79 |
-
# try:
|
80 |
-
# pic = imageio.imread(image_path)
|
81 |
-
# size = pic.size
|
82 |
-
# if size < 100:
|
83 |
-
# low_size_photo_list.append(one_image)
|
84 |
-
# except:
|
85 |
-
# pass
|
86 |
-
# for one_image in low_size_photo_list[1:]:
|
87 |
-
# os.remove(os.path.join(data_path, one_image))
|
88 |
-
|
89 |
-
# def calc_diff(img1 , img2) :
|
90 |
-
# i1 = Image.open(img1)
|
91 |
-
# i2 = Image.open(img2)
|
92 |
-
# h1 = imagehash.phash(i1)
|
93 |
-
# h2 = imagehash.phash(i2)
|
94 |
-
# return h1 - h2
|
95 |
-
|
96 |
-
# def remove_duplicate_images(data_path) :
|
97 |
-
# image_files = os.listdir(data_path)
|
98 |
-
# only_images = []
|
99 |
-
# for one_image in image_files :
|
100 |
-
# if one_image.endswith('jpeg') or one_image.endswith('png') or one_image.endswith('jpg') :
|
101 |
-
# only_images.append(one_image)
|
102 |
-
# only_images1 = sorted(only_images)
|
103 |
-
# for one_image in only_images1 :
|
104 |
-
# for another_image in only_images1 :
|
105 |
-
# try :
|
106 |
-
# if one_image == another_image :
|
107 |
-
# continue
|
108 |
-
# else :
|
109 |
-
# diff = calc_diff(os.path.join(data_path ,one_image) , os.path.join(data_path ,another_image))
|
110 |
-
# if diff ==0 :
|
111 |
-
# os.remove(os.path.join(data_path , another_image))
|
112 |
-
# except Exception as e:
|
113 |
-
# print(e)
|
114 |
-
# pass
|
115 |
-
# # from langchain_chroma import Chroma
|
116 |
-
# # import chromadb
|
117 |
-
# def initialize_qdrant(temp_dir , file_name , user):
|
118 |
-
# client = qdrant_client.QdrantClient(path=f"qdrant_mm_db_pipeline_{user}_{file_name}")
|
119 |
-
# # client = qdrant_client.QdrantClient(url = "http://localhost:2452")
|
120 |
-
# # client = qdrant_client.QdrantClient(url="4b0af7be-d5b3-47ac-b215-128ebd6aa495.europe-west3-0.gcp.cloud.qdrant.io:6333", api_key="CO1sNGLmC6R_Q45qSIUxBSX8sxwHud4MCm4as_GTI-vzQqdUs-bXqw",)
|
121 |
-
# # client = qdrant_client.AsyncQdrantClient(location = ":memory:")
|
122 |
-
|
123 |
-
# if "vectordatabase" not in st.session_state or not st.session_state.vectordatabase:
|
124 |
-
|
125 |
-
# # text_store = client.create_collection(f"text_collection_pipeline_{user}_{file_name}" )
|
126 |
-
# # image_store = client.create_collection(f"image_collection_pipeline_{user}_{file_name}" )
|
127 |
-
|
128 |
-
|
129 |
-
# text_store = QdrantVectorStore( client = client , collection_name=f"text_collection_pipeline_{user}_{file_name}" )
|
130 |
-
# image_store = QdrantVectorStore(client = client , collection_name=f"image_collection_pipeline_{user}_{file_name}")
|
131 |
-
# storage_context = StorageContext.from_defaults(vector_store=text_store, image_store=image_store)
|
132 |
-
# documents = SimpleDirectoryReader(os.path.join(temp_dir, f"my_own_data_{user}_{file_name}")).load_data()
|
133 |
-
# index = MultiModalVectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
134 |
-
|
135 |
-
# st.session_state.vectordatabase = index
|
136 |
-
# else :
|
137 |
-
# index = st.session_state.vectordatabase
|
138 |
-
# retriever_engine = index.as_retriever(similarity_top_k=1, image_similarity_top_k=1)
|
139 |
-
# return retriever_engine
|
140 |
-
|
141 |
-
# def plot_images(image_paths):
|
142 |
-
# images_shown = 0
|
143 |
-
# plt.figure(figsize=(16, 9))
|
144 |
-
# for img_path in image_paths:
|
145 |
-
# if os.path.isfile(img_path):
|
146 |
-
# image = Image.open(img_path)
|
147 |
-
# plt.subplot(2, 3, images_shown + 1)
|
148 |
-
# plt.imshow(image)
|
149 |
-
# plt.xticks([])
|
150 |
-
# plt.yticks([])
|
151 |
-
# images_shown += 1
|
152 |
-
# if images_shown >= 6:
|
153 |
-
# break
|
154 |
-
|
155 |
-
# def retrieve_and_query(query, retriever_engine):
|
156 |
-
# retrieval_results = retriever_engine.retrieve(query)
|
157 |
-
|
158 |
-
# qa_tmpl_str = (
|
159 |
-
# "Context information is below.\n"
|
160 |
-
# "---------------------\n"
|
161 |
-
# "{context_str}\n"
|
162 |
-
# "---------------------\n"
|
163 |
-
# "Given the context information , "
|
164 |
-
# "answer the query in detail.\n"
|
165 |
-
# "Query: {query_str}\n"
|
166 |
-
# "Answer: "
|
167 |
-
# )
|
168 |
-
# qa_tmpl = PromptTemplate(qa_tmpl_str)
|
169 |
-
|
170 |
-
# llm = OpenAI(model="gpt-4o", temperature=0)
|
171 |
-
# response_synthesizer = get_response_synthesizer(response_mode="refine", text_qa_template=qa_tmpl, llm=llm)
|
172 |
-
|
173 |
-
# response = response_synthesizer.synthesize(query, nodes=retrieval_results)
|
174 |
-
|
175 |
-
# retrieved_image_path_list = []
|
176 |
-
# for node in retrieval_results:
|
177 |
-
# if (node.metadata['file_type'] == 'image/jpeg') or (node.metadata['file_type'] == 'image/png'):
|
178 |
-
# if node.score > 0.25:
|
179 |
-
# retrieved_image_path_list.append(node.metadata['file_path'])
|
180 |
-
|
181 |
-
# return response, retrieved_image_path_list
|
182 |
-
# #tmpnimvp35m , tmpnimvp35m , tmpydpissmv
|
183 |
-
# def process_pdf(pdf_file):
|
184 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
185 |
-
# unique_folder_name = temp_dir.name.split('/')[-1]
|
186 |
-
# temp_pdf_path = os.path.join(temp_dir.name, pdf_file.name)
|
187 |
-
# with open(temp_pdf_path, "wb") as f:
|
188 |
-
# f.write(pdf_file.getvalue())
|
189 |
-
|
190 |
-
# data_path = os.path.join(temp_dir.name, f"my_own_data_{unique_folder_name}_{os.path.splitext(pdf_file.name)[0]}")
|
191 |
-
# os.makedirs(data_path , exist_ok=True)
|
192 |
-
# img_save_path = os.path.join(temp_dir.name, f"extracted_images_{unique_folder_name}_{os.path.splitext(pdf_file.name)[0]}")
|
193 |
-
# os.makedirs(img_save_path , exist_ok=True)
|
194 |
-
|
195 |
-
# extracted_text = extract_text_from_pdf(temp_pdf_path)
|
196 |
-
# with open(os.path.join(data_path, "content.txt"), "w") as file:
|
197 |
-
# file.write(extracted_text)
|
198 |
-
|
199 |
-
# extract_images_from_pdf(temp_pdf_path, img_save_path)
|
200 |
-
# moved_count = move_images(img_save_path, data_path)
|
201 |
-
# remove_low_size_images(data_path)
|
202 |
-
# remove_duplicate_images(data_path)
|
203 |
-
# retriever_engine = initialize_qdrant(temp_dir.name , os.path.splitext(pdf_file.name)[0] , unique_folder_name)
|
204 |
-
|
205 |
-
# return temp_dir, retriever_engine
|
206 |
-
|
207 |
-
# def main():
|
208 |
-
# st.title("PDF Vector Database Query Tool")
|
209 |
-
# st.markdown("This tool creates a vector database from a PDF and allows you to query it.")
|
210 |
-
|
211 |
-
# if "retriever_engine" not in st.session_state:
|
212 |
-
# st.session_state.retriever_engine = None
|
213 |
-
# if "vectordatabase" not in st.session_state:
|
214 |
-
# st.session_state.vectordatabase = None
|
215 |
-
|
216 |
-
# uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
217 |
-
# if uploaded_file is None:
|
218 |
-
# st.info("Please upload a PDF file.")
|
219 |
-
# else:
|
220 |
-
# st.info(f"Uploaded PDF: {uploaded_file.name}")
|
221 |
-
# if st.button("Process PDF"):
|
222 |
-
# with st.spinner("Processing PDF..."):
|
223 |
-
# temp_dir, st.session_state.retriever_engine = process_pdf(uploaded_file)
|
224 |
-
|
225 |
-
# st.success("PDF processed successfully!")
|
226 |
-
|
227 |
-
# if st.session_state.retriever_engine :
|
228 |
-
# query = st.text_input("Enter your question:")
|
229 |
-
|
230 |
-
|
231 |
-
# if st.button("Ask Question"):
|
232 |
-
# print("running")
|
233 |
-
# try:
|
234 |
-
|
235 |
-
# with st.spinner("Retrieving information..."):
|
236 |
-
# response, retrieved_image_path_list = retrieve_and_query(query, st.session_state.retriever_engine)
|
237 |
-
# print(retrieved_image_path_list)
|
238 |
-
# st.write("Retrieved Context:")
|
239 |
-
# for node in response.source_nodes:
|
240 |
-
# st.code(node.node.get_text())
|
241 |
-
|
242 |
-
# st.write("\nRetrieved Images:")
|
243 |
-
# plot_images(retrieved_image_path_list)
|
244 |
-
# st.pyplot()
|
245 |
-
|
246 |
-
# st.write("\nFinal Answer:")
|
247 |
-
# st.code(response.response)
|
248 |
-
|
249 |
-
# except Exception as e:
|
250 |
-
# st.error(f"An error occurred: {e}")
|
251 |
-
|
252 |
-
# if __name__ == "__main__":
|
253 |
-
# main()
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
import streamlit as st
|
258 |
-
from PIL import Image
|
259 |
|
260 |
from pdf_processing import process_pdf
|
261 |
from retrieve_and_display import retrieve_and_query, plot_images
|
@@ -281,13 +24,7 @@ def upload_file():
|
|
281 |
st.session_state.filename_and_retriever_engine = uploaded_file.name, process_pdf(uploaded_file)
|
282 |
st.success("PDF processed successfully!")
|
283 |
st.success("Click on Chat in sidebar")
|
284 |
-
|
285 |
-
def img_display(img_path_list) :
|
286 |
-
##################### new image display function ###################################
|
287 |
-
for one_img in img_path_list :
|
288 |
-
image = Image.open(one_img)
|
289 |
-
st.image(image)
|
290 |
-
|
291 |
|
292 |
def ask_question():
|
293 |
if st.session_state.filename_and_retriever_engine :
|
@@ -295,16 +32,15 @@ def ask_question():
|
|
295 |
if user_question := st.chat_input("Ask a question"):
|
296 |
with st.spinner("Retrieving information..."):
|
297 |
response, retrieved_image_path_list = retrieve_and_query(user_question, st.session_state.filename_and_retriever_engine[1])
|
298 |
-
# st.session_state.filename_and_retriever_engine[1].count('image_collection')
|
299 |
print(retrieved_image_path_list)
|
300 |
st.write("Retrieved Context:")
|
301 |
for node in response.source_nodes:
|
302 |
st.code(node.node.get_text())
|
303 |
|
304 |
st.write("\nRetrieved Images:")
|
305 |
-
#
|
306 |
-
|
307 |
-
|
308 |
|
309 |
st.write("\nFinal Answer:")
|
310 |
st.code(response.response)
|
@@ -327,3 +63,4 @@ def main():
|
|
327 |
if __name__ == "__main__":
|
328 |
# login_page()
|
329 |
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
|
|
2 |
|
3 |
from pdf_processing import process_pdf
|
4 |
from retrieve_and_display import retrieve_and_query, plot_images
|
|
|
24 |
st.session_state.filename_and_retriever_engine = uploaded_file.name, process_pdf(uploaded_file)
|
25 |
st.success("PDF processed successfully!")
|
26 |
st.success("Click on Chat in sidebar")
|
27 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
def ask_question():
|
30 |
if st.session_state.filename_and_retriever_engine :
|
|
|
32 |
if user_question := st.chat_input("Ask a question"):
|
33 |
with st.spinner("Retrieving information..."):
|
34 |
response, retrieved_image_path_list = retrieve_and_query(user_question, st.session_state.filename_and_retriever_engine[1])
|
|
|
35 |
print(retrieved_image_path_list)
|
36 |
st.write("Retrieved Context:")
|
37 |
for node in response.source_nodes:
|
38 |
st.code(node.node.get_text())
|
39 |
|
40 |
st.write("\nRetrieved Images:")
|
41 |
+
# if len(retrieved_image_path_list) > 0:
|
42 |
+
plot_images(retrieved_image_path_list)
|
43 |
+
# st.pyplot()
|
44 |
|
45 |
st.write("\nFinal Answer:")
|
46 |
st.code(response.response)
|
|
|
63 |
if __name__ == "__main__":
|
64 |
# login_page()
|
65 |
main()
|
66 |
+
|
awsfunctions.py
CHANGED
@@ -14,7 +14,7 @@ def upload_folder_to_s3(local_dir, prefix=''):
|
|
14 |
|
15 |
# Create the directory in S3 if it doesn't exist
|
16 |
try:
|
17 |
-
s3_client.put_object(Bucket=s3_bucket, Key=
|
18 |
except ClientError as e:
|
19 |
if e.response['Error']['Code'] == '404':
|
20 |
continue # Directory already exists
|
@@ -26,8 +26,8 @@ def upload_folder_to_s3(local_dir, prefix=''):
|
|
26 |
relative_path = os.path.relpath(file_path, local_dir)
|
27 |
|
28 |
try:
|
29 |
-
s3_client.upload_file(file_path, s3_bucket,
|
30 |
-
print(f"Uploaded: {file_path} -> s3://{s3_bucket}/{prefix
|
31 |
except Exception as e:
|
32 |
raise e
|
33 |
# print(f"Error uploading {file_path}: {e}")
|
|
|
14 |
|
15 |
# Create the directory in S3 if it doesn't exist
|
16 |
try:
|
17 |
+
s3_client.put_object(Bucket=s3_bucket, Key=os.path.join(prefix, relative_path))
|
18 |
except ClientError as e:
|
19 |
if e.response['Error']['Code'] == '404':
|
20 |
continue # Directory already exists
|
|
|
26 |
relative_path = os.path.relpath(file_path, local_dir)
|
27 |
|
28 |
try:
|
29 |
+
s3_client.upload_file(file_path, s3_bucket, os.path.join(prefix, relative_path))
|
30 |
+
print(f"Uploaded: {file_path} -> s3://{s3_bucket}/{os.path.join(prefix, relative_path)}")
|
31 |
except Exception as e:
|
32 |
raise e
|
33 |
# print(f"Error uploading {file_path}: {e}")
|
retrieve_and_display.py
CHANGED
@@ -22,13 +22,14 @@ def plot_images(image_paths):
|
|
22 |
for img_path in image_paths:
|
23 |
if check_file_exists_in_s3(img_path):
|
24 |
image = get_image_from_s3(img_path)
|
25 |
-
|
26 |
-
plt.
|
27 |
-
plt.
|
28 |
-
plt.
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
32 |
|
33 |
def retrieve_and_query(query, retriever_engine):
|
34 |
retrieval_results = retriever_engine.retrieve(query)
|
@@ -45,7 +46,7 @@ def retrieve_and_query(query, retriever_engine):
|
|
45 |
)
|
46 |
qa_tmpl = PromptTemplate(qa_tmpl_str)
|
47 |
|
48 |
-
llm = OpenAI(model="gpt-4o", temperature=0)
|
49 |
response_synthesizer = get_response_synthesizer(response_mode="refine", text_qa_template=qa_tmpl, llm=llm)
|
50 |
|
51 |
response = response_synthesizer.synthesize(query, nodes=retrieval_results)
|
|
|
22 |
for img_path in image_paths:
|
23 |
if check_file_exists_in_s3(img_path):
|
24 |
image = get_image_from_s3(img_path)
|
25 |
+
st.image(image)
|
26 |
+
# plt.subplot(2, 3, images_shown + 1)
|
27 |
+
# plt.imshow(image)
|
28 |
+
# plt.xticks([])
|
29 |
+
# plt.yticks([])
|
30 |
+
# images_shown += 1
|
31 |
+
# if images_shown >= 6:
|
32 |
+
# break
|
33 |
|
34 |
def retrieve_and_query(query, retriever_engine):
|
35 |
retrieval_results = retriever_engine.retrieve(query)
|
|
|
46 |
)
|
47 |
qa_tmpl = PromptTemplate(qa_tmpl_str)
|
48 |
|
49 |
+
llm = OpenAI(model="gpt-4o-mini", temperature=0)
|
50 |
response_synthesizer = get_response_synthesizer(response_mode="refine", text_qa_template=qa_tmpl, llm=llm)
|
51 |
|
52 |
response = response_synthesizer.synthesize(query, nodes=retrieval_results)
|