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