Spaces:
Sleeping
Sleeping
viboognesh
commited on
Upload folder using huggingface_hub
Browse files- app.py +206 -0
- requirements.txt +15 -0
app.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
22 |
+
|
23 |
+
def extract_text_from_pdf(pdf_path):
|
24 |
+
reader = PdfReader(pdf_path)
|
25 |
+
full_text = ''
|
26 |
+
for page in reader.pages:
|
27 |
+
text = page.extract_text()
|
28 |
+
full_text += text
|
29 |
+
return full_text
|
30 |
+
|
31 |
+
def extract_images_from_pdf(pdf_path, img_save_path):
|
32 |
+
doc = pymupdf.open(pdf_path)
|
33 |
+
for page in doc:
|
34 |
+
img_number = 0
|
35 |
+
for block in page.get_text("dict")["blocks"]:
|
36 |
+
if block['type'] == 1:
|
37 |
+
name = os.path.join(img_save_path, f"img{page.number}-{img_number}.{block['ext']}")
|
38 |
+
out = open(name, "wb")
|
39 |
+
out.write(block["image"])
|
40 |
+
out.close()
|
41 |
+
img_number += 1
|
42 |
+
|
43 |
+
def is_empty(img_path):
|
44 |
+
image = cv2.imread(img_path, 0)
|
45 |
+
std_dev = np.std(image)
|
46 |
+
return std_dev < 1
|
47 |
+
|
48 |
+
def move_images(source_folder, dest_folder):
|
49 |
+
image_files = [f for f in os.listdir(source_folder)
|
50 |
+
if f.lower().endswith(('.jpg', '.jpeg', '.png', '.gif'))]
|
51 |
+
os.makedirs(dest_folder, exist_ok=True)
|
52 |
+
moved_count = 0
|
53 |
+
for file in image_files:
|
54 |
+
src_path = os.path.join(source_folder, file)
|
55 |
+
if not is_empty(src_path):
|
56 |
+
shutil.move(src_path, os.path.join(dest_folder, file))
|
57 |
+
moved_count += 1
|
58 |
+
return moved_count
|
59 |
+
|
60 |
+
def remove_low_size_images(data_path):
|
61 |
+
images_list = os.listdir(data_path)
|
62 |
+
low_size_photo_list = []
|
63 |
+
for one_image in images_list:
|
64 |
+
image_path = os.path.join(data_path, one_image)
|
65 |
+
try:
|
66 |
+
pic = imageio.imread(image_path)
|
67 |
+
size = pic.size
|
68 |
+
if size < 100:
|
69 |
+
low_size_photo_list.append(one_image)
|
70 |
+
except:
|
71 |
+
pass
|
72 |
+
for one_image in low_size_photo_list[1:]:
|
73 |
+
os.remove(os.path.join(data_path, one_image))
|
74 |
+
|
75 |
+
def initialize_qdrant(temp_dir):
|
76 |
+
try :
|
77 |
+
client = qdrant_client.QdrantClient(path="qdrant_mm_db_pipeline")
|
78 |
+
except :
|
79 |
+
pass
|
80 |
+
if "vectordatabase" not in st.session_state or not st.session_state.vectordatabase:
|
81 |
+
text_store = QdrantVectorStore(client=client, collection_name="text_collection_pipeline")
|
82 |
+
image_store = QdrantVectorStore(client=client, collection_name="image_collection_pipeline")
|
83 |
+
storage_context = StorageContext.from_defaults(vector_store=text_store, image_store=image_store)
|
84 |
+
documents = SimpleDirectoryReader(os.path.join(temp_dir, "my_own_data")).load_data()
|
85 |
+
index = MultiModalVectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
86 |
+
st.session_state.vectordatabase = index
|
87 |
+
else :
|
88 |
+
index = st.session_state.vectordatabase
|
89 |
+
retriever_engine = index.as_retriever(similarity_top_k=1, image_similarity_top_k=1)
|
90 |
+
return retriever_engine
|
91 |
+
|
92 |
+
def plot_images(image_paths):
|
93 |
+
images_shown = 0
|
94 |
+
plt.figure(figsize=(16, 9))
|
95 |
+
for img_path in image_paths:
|
96 |
+
if os.path.isfile(img_path):
|
97 |
+
image = Image.open(img_path)
|
98 |
+
plt.subplot(2, 3, images_shown + 1)
|
99 |
+
plt.imshow(image)
|
100 |
+
plt.xticks([])
|
101 |
+
plt.yticks([])
|
102 |
+
images_shown += 1
|
103 |
+
if images_shown >= 6:
|
104 |
+
break
|
105 |
+
|
106 |
+
def retrieve_and_query(query, retriever_engine):
|
107 |
+
retrieval_results = retriever_engine.retrieve(query)
|
108 |
+
|
109 |
+
qa_tmpl_str = (
|
110 |
+
"Context information is below.\n"
|
111 |
+
"---------------------\n"
|
112 |
+
"{context_str}\n"
|
113 |
+
"---------------------\n"
|
114 |
+
"Given the context information , "
|
115 |
+
"answer the query in detail.\n"
|
116 |
+
"Query: {query_str}\n"
|
117 |
+
"Answer: "
|
118 |
+
)
|
119 |
+
qa_tmpl = PromptTemplate(qa_tmpl_str)
|
120 |
+
|
121 |
+
llm = OpenAI(model="gpt-4o", temperature=0)
|
122 |
+
response_synthesizer = get_response_synthesizer(response_mode="refine", text_qa_template=qa_tmpl, llm=llm)
|
123 |
+
|
124 |
+
response = response_synthesizer.synthesize(query, nodes=retrieval_results)
|
125 |
+
|
126 |
+
retrieved_image_path_list = []
|
127 |
+
for node in retrieval_results:
|
128 |
+
if (node.metadata['file_type'] == 'image/jpeg') or (node.metadata['file_type'] == 'image/png'):
|
129 |
+
if node.score > 0.25:
|
130 |
+
retrieved_image_path_list.append(node.metadata['file_path'])
|
131 |
+
|
132 |
+
return response, retrieved_image_path_list
|
133 |
+
|
134 |
+
def process_pdf(pdf_file):
|
135 |
+
# import pdb; pdb.set_trace()
|
136 |
+
temp_dir = tempfile.TemporaryDirectory()
|
137 |
+
temp_pdf_path = os.path.join(temp_dir.name, pdf_file.name)
|
138 |
+
with open(temp_pdf_path, "wb") as f:
|
139 |
+
f.write(pdf_file.getvalue())
|
140 |
+
|
141 |
+
data_path = os.path.join(temp_dir.name, "my_own_data")
|
142 |
+
os.makedirs(data_path , exist_ok=True)
|
143 |
+
img_save_path = os.path.join(temp_dir.name, "extracted_images")
|
144 |
+
os.makedirs(img_save_path , exist_ok=True)
|
145 |
+
|
146 |
+
extracted_text = extract_text_from_pdf(temp_pdf_path)
|
147 |
+
with open(os.path.join(data_path, "content.txt"), "w") as file:
|
148 |
+
file.write(extracted_text)
|
149 |
+
|
150 |
+
extract_images_from_pdf(temp_pdf_path, img_save_path)
|
151 |
+
moved_count = move_images(img_save_path, data_path)
|
152 |
+
remove_low_size_images(data_path)
|
153 |
+
|
154 |
+
retriever_engine = initialize_qdrant(temp_dir.name)
|
155 |
+
|
156 |
+
return temp_dir, retriever_engine
|
157 |
+
|
158 |
+
def main():
|
159 |
+
st.title("PDF Vector Database Query Tool")
|
160 |
+
st.markdown("This tool creates a vector database from a PDF and allows you to query it.")
|
161 |
+
|
162 |
+
if "retriever_engine" not in st.session_state:
|
163 |
+
st.session_state.retriever_engine = None
|
164 |
+
if "vectordatabase" not in st.session_state:
|
165 |
+
st.session_state.vectordatabase = None
|
166 |
+
|
167 |
+
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
168 |
+
if uploaded_file is None:
|
169 |
+
st.info("Please upload a PDF file.")
|
170 |
+
else:
|
171 |
+
st.info(f"Uploaded PDF: {uploaded_file.name}")
|
172 |
+
if st.button("Process PDF"):
|
173 |
+
with st.spinner("Processing PDF..."):
|
174 |
+
temp_dir, st.session_state.retriever_engine = process_pdf(uploaded_file)
|
175 |
+
|
176 |
+
st.success("PDF processed successfully!")
|
177 |
+
|
178 |
+
|
179 |
+
query = st.text_input("Enter your question:")
|
180 |
+
|
181 |
+
|
182 |
+
if st.button("Ask Question"):
|
183 |
+
print("running")
|
184 |
+
try:
|
185 |
+
import pdb; pdb.set_trace()
|
186 |
+
|
187 |
+
with st.spinner("Retrieving information..."):
|
188 |
+
import pdb; pdb.set_trace()
|
189 |
+
response, retrieved_image_path_list = retrieve_and_query(query, st.session_state.retriever_engine)
|
190 |
+
|
191 |
+
st.write("Retrieved Context:")
|
192 |
+
for node in response.source_nodes:
|
193 |
+
st.code(node.node.get_text())
|
194 |
+
|
195 |
+
st.write("\nRetrieved Images:")
|
196 |
+
plot_images(retrieved_image_path_list)
|
197 |
+
st.pyplot()
|
198 |
+
|
199 |
+
st.write("\nFinal Answer:")
|
200 |
+
st.code(response.response)
|
201 |
+
|
202 |
+
except Exception as e:
|
203 |
+
st.error(f"An error occurred: {e}")
|
204 |
+
|
205 |
+
if __name__ == "__main__":
|
206 |
+
main()
|
requirements.txt
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
PyPDF2==3.0.1
|
2 |
+
PyMuPDF==1.24.9
|
3 |
+
numpy==1.26.4
|
4 |
+
opencv-python==4.10.0.84
|
5 |
+
matplotlib==3.9.2
|
6 |
+
llama-index==0.11.2
|
7 |
+
llama-index-vector-stores-qdrant==0.3.0
|
8 |
+
ipython==8.26.0
|
9 |
+
llama-index-embeddings-clip==0.2.0
|
10 |
+
imageio==2.35.1
|
11 |
+
pillow==10.4.0
|
12 |
+
imagehash
|
13 |
+
llama-index-embeddings-clip
|
14 |
+
git+https://github.com/openai/CLIP.git
|
15 |
+
dotenv
|