Spaces:
Running
on
Zero
Running
on
Zero
revert
Browse files
app.py
CHANGED
@@ -2,20 +2,18 @@ import os
|
|
2 |
|
3 |
import gradio as gr
|
4 |
import torch
|
5 |
-
from colpali_engine.models.paligemma_colbert_architecture import ColPali
|
6 |
-
from colpali_engine.trainer.retrieval_evaluator import CustomEvaluator
|
7 |
-
from colpali_engine.utils.colpali_processing_utils import (
|
8 |
-
process_images,
|
9 |
-
process_queries,
|
10 |
-
)
|
11 |
from pdf2image import convert_from_path
|
12 |
from PIL import Image
|
13 |
from torch.utils.data import DataLoader
|
14 |
from tqdm import tqdm
|
15 |
from transformers import AutoProcessor
|
16 |
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
def search(query: str, ds, images
|
19 |
qs = []
|
20 |
with torch.no_grad():
|
21 |
batch_query = process_queries(processor, [query], mock_image)
|
@@ -23,27 +21,19 @@ def search(query: str, ds, images, k):
|
|
23 |
embeddings_query = model(**batch_query)
|
24 |
qs.extend(list(torch.unbind(embeddings_query.to("cpu"))))
|
25 |
|
|
|
26 |
retriever_evaluator = CustomEvaluator(is_multi_vector=True)
|
27 |
scores = retriever_evaluator.evaluate(qs, ds)
|
|
|
|
|
28 |
|
29 |
-
top_k_indices = scores.argsort(axis=1)[0][-k:][::-1]
|
30 |
|
31 |
-
|
32 |
-
for idx in top_k_indices:
|
33 |
-
results.append((images[idx], f"Page {idx}"))
|
34 |
-
|
35 |
-
return results
|
36 |
-
|
37 |
-
|
38 |
-
def index(files, ds):
|
39 |
"""Example script to run inference with ColPali"""
|
40 |
images = []
|
41 |
-
for f in
|
42 |
images.extend(convert_from_path(f))
|
43 |
|
44 |
-
if len(images) >= 150:
|
45 |
-
raise gr.Error("The number of images in the dataset should be less than 150.")
|
46 |
-
|
47 |
# run inference - docs
|
48 |
dataloader = DataLoader(
|
49 |
images,
|
@@ -58,50 +48,41 @@ def index(files, ds):
|
|
58 |
ds.extend(list(torch.unbind(embeddings_doc.to("cpu"))))
|
59 |
return f"Uploaded and converted {len(images)} pages", ds, images
|
60 |
|
61 |
-
|
|
|
62 |
# Load model
|
63 |
model_name = "vidore/colpali"
|
64 |
token = os.environ.get("HF_TOKEN")
|
65 |
model = ColPali.from_pretrained(
|
66 |
-
"google/paligemma-3b-mix-448", torch_dtype=torch.bfloat16, device_map="cuda", token
|
67 |
).eval()
|
68 |
-
|
69 |
model.load_adapter(model_name)
|
70 |
-
processor = AutoProcessor.from_pretrained(model_name,
|
71 |
-
|
72 |
device = model.device
|
73 |
-
|
74 |
mock_image = Image.new("RGB", (448, 448), (255, 255, 255))
|
75 |
|
76 |
-
with gr.Blocks(
|
77 |
-
gr.Markdown("# ColPali: Efficient Document Retrieval with Vision Language Models
|
78 |
-
gr.Markdown("
|
79 |
-
|
80 |
-
ColPali is model implemented from the [ColPali paper](https://arxiv.org/abs/2407.01449).
|
81 |
|
82 |
-
|
83 |
-
""
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
file = gr.File(file_types=["pdf"], file_count="multiple", label="Upload PDFs")
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
embeds = gr.State(value=[])
|
92 |
-
imgs = gr.State(value=[])
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
98 |
|
99 |
-
|
100 |
-
search_button = gr.Button("π Search", variant="primary")
|
101 |
-
output_gallery = gr.Gallery(label="Retrieved Documents", height=600, show_label=True)
|
102 |
|
103 |
-
convert_button.click(index, inputs=[file, embeds], outputs=[message, embeds, imgs])
|
104 |
-
search_button.click(search, inputs=[query, embeds, imgs, k], outputs=[output_gallery])
|
105 |
|
106 |
if __name__ == "__main__":
|
107 |
-
demo.queue(max_size=10).launch(debug=True
|
|
|
2 |
|
3 |
import gradio as gr
|
4 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
from pdf2image import convert_from_path
|
6 |
from PIL import Image
|
7 |
from torch.utils.data import DataLoader
|
8 |
from tqdm import tqdm
|
9 |
from transformers import AutoProcessor
|
10 |
|
11 |
+
from colpali_engine.models.paligemma_colbert_architecture import ColPali
|
12 |
+
from colpali_engine.trainer.retrieval_evaluator import CustomEvaluator
|
13 |
+
from colpali_engine.utils.colpali_processing_utils import process_images, process_queries
|
14 |
+
|
15 |
|
16 |
+
def search(query: str, ds, images):
|
17 |
qs = []
|
18 |
with torch.no_grad():
|
19 |
batch_query = process_queries(processor, [query], mock_image)
|
|
|
21 |
embeddings_query = model(**batch_query)
|
22 |
qs.extend(list(torch.unbind(embeddings_query.to("cpu"))))
|
23 |
|
24 |
+
# run evaluation
|
25 |
retriever_evaluator = CustomEvaluator(is_multi_vector=True)
|
26 |
scores = retriever_evaluator.evaluate(qs, ds)
|
27 |
+
best_page = int(scores.argmax(axis=1).item())
|
28 |
+
return f"The most relevant page is {best_page}", images[best_page]
|
29 |
|
|
|
30 |
|
31 |
+
def index(file, ds):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
"""Example script to run inference with ColPali"""
|
33 |
images = []
|
34 |
+
for f in file:
|
35 |
images.extend(convert_from_path(f))
|
36 |
|
|
|
|
|
|
|
37 |
# run inference - docs
|
38 |
dataloader = DataLoader(
|
39 |
images,
|
|
|
48 |
ds.extend(list(torch.unbind(embeddings_doc.to("cpu"))))
|
49 |
return f"Uploaded and converted {len(images)} pages", ds, images
|
50 |
|
51 |
+
|
52 |
+
COLORS = ["#4285f4", "#db4437", "#f4b400", "#0f9d58", "#e48ef1"]
|
53 |
# Load model
|
54 |
model_name = "vidore/colpali"
|
55 |
token = os.environ.get("HF_TOKEN")
|
56 |
model = ColPali.from_pretrained(
|
57 |
+
"google/paligemma-3b-mix-448", torch_dtype=torch.bfloat16, device_map="cuda", token=token
|
58 |
).eval()
|
|
|
59 |
model.load_adapter(model_name)
|
60 |
+
processor = AutoProcessor.from_pretrained(model_name, token=token)
|
|
|
61 |
device = model.device
|
|
|
62 |
mock_image = Image.new("RGB", (448, 448), (255, 255, 255))
|
63 |
|
64 |
+
with gr.Blocks() as demo:
|
65 |
+
gr.Markdown("# ColPali: Efficient Document Retrieval with Vision Language Models ππ")
|
66 |
+
gr.Markdown("## 1οΈβ£ Upload PDFs")
|
67 |
+
file = gr.File(file_types=["pdf"], file_count="multiple")
|
|
|
68 |
|
69 |
+
gr.Markdown("## 2οΈβ£ Convert the PDFs and upload")
|
70 |
+
convert_button = gr.Button("π Convert and upload")
|
71 |
+
message = gr.Textbox("Files not yet uploaded")
|
72 |
+
embeds = gr.State(value=[])
|
73 |
+
imgs = gr.State(value=[])
|
|
|
74 |
|
75 |
+
# Define the actions
|
76 |
+
convert_button.click(index, inputs=[file, embeds], outputs=[message, embeds, imgs])
|
|
|
|
|
77 |
|
78 |
+
gr.Markdown("## 3οΈβ£ Search")
|
79 |
+
query = gr.Textbox(placeholder="Enter your query here")
|
80 |
+
search_button = gr.Button("π Search")
|
81 |
+
message2 = gr.Textbox("Query not yet set")
|
82 |
+
output_img = gr.Image()
|
83 |
|
84 |
+
search_button.click(search, inputs=[query, embeds, imgs], outputs=[message2, output_img])
|
|
|
|
|
85 |
|
|
|
|
|
86 |
|
87 |
if __name__ == "__main__":
|
88 |
+
demo.queue(max_size=10).launch(debug=True)
|