Spaces:
Running
on
Zero
Running
on
Zero
AdrienB134
commited on
Commit
•
8001e7f
1
Parent(s):
3083423
ff
Browse files- app.py +131 -58
- requirements.txt +6 -1
app.py
CHANGED
@@ -1,63 +1,136 @@
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
def respond(
|
11 |
-
message,
|
12 |
-
history: list[tuple[str, str]],
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
"""
|
43 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
44 |
-
"""
|
45 |
-
demo = gr.ChatInterface(
|
46 |
-
respond,
|
47 |
-
additional_inputs=[
|
48 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
49 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
50 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
51 |
-
gr.Slider(
|
52 |
-
minimum=0.1,
|
53 |
-
maximum=1.0,
|
54 |
-
value=0.95,
|
55 |
-
step=0.05,
|
56 |
-
label="Top-p (nucleus sampling)",
|
57 |
-
),
|
58 |
-
],
|
59 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
|
|
|
|
61 |
|
62 |
if __name__ == "__main__":
|
63 |
-
demo.launch()
|
|
|
1 |
+
import os
|
2 |
+
import spaces
|
3 |
+
|
4 |
import gradio as gr
|
5 |
+
import torch
|
6 |
+
from colpali_engine.models.paligemma_colbert_architecture import ColPali
|
7 |
+
from colpali_engine.trainer.retrieval_evaluator import CustomEvaluator
|
8 |
+
from colpali_engine.utils.colpali_processing_utils import (
|
9 |
+
process_images,
|
10 |
+
process_queries,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
)
|
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 |
+
# Load model
|
19 |
+
model_name = "vidore/colpali-v1.2"
|
20 |
+
token = os.environ.get("HF_TOKEN")
|
21 |
+
model = ColPali.from_pretrained(
|
22 |
+
"vidore/colpaligemma-3b-pt-448-base", torch_dtype=torch.bfloat16, device_map="cuda", token = token).eval()
|
23 |
+
|
24 |
+
model.load_adapter(model_name)
|
25 |
+
model = model.eval()
|
26 |
+
processor = AutoProcessor.from_pretrained(model_name, token = token)
|
27 |
+
|
28 |
+
mock_image = Image.new("RGB", (448, 448), (255, 255, 255))
|
29 |
+
|
30 |
+
|
31 |
+
@spaces.GPU
|
32 |
+
def search(query: str, ds, images, k):
|
33 |
+
|
34 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
35 |
+
if device != model.device:
|
36 |
+
model.to(device)
|
37 |
+
|
38 |
+
qs = []
|
39 |
+
with torch.no_grad():
|
40 |
+
batch_query = process_queries(processor, [query], mock_image)
|
41 |
+
batch_query = {k: v.to(device) for k, v in batch_query.items()}
|
42 |
+
embeddings_query = model(**batch_query)
|
43 |
+
qs.extend(list(torch.unbind(embeddings_query.to("cpu"))))
|
44 |
+
|
45 |
+
retriever_evaluator = CustomEvaluator(is_multi_vector=True)
|
46 |
+
scores = retriever_evaluator.evaluate(qs, ds)
|
47 |
+
|
48 |
+
top_k_indices = scores.argsort(axis=1)[0][-k:][::-1]
|
49 |
+
|
50 |
+
results = []
|
51 |
+
for idx in top_k_indices:
|
52 |
+
results.append((images[idx], f"Page {idx}"))
|
53 |
+
|
54 |
+
return results
|
55 |
+
|
56 |
+
|
57 |
+
def index(files, ds):
|
58 |
+
print("Converting files")
|
59 |
+
images = convert_files(files)
|
60 |
+
print(f"Files converted with {len(images)} images.")
|
61 |
+
return index_gpu(images, ds)
|
62 |
+
|
63 |
+
|
64 |
+
|
65 |
+
def convert_files(files):
|
66 |
+
images = []
|
67 |
+
for f in files:
|
68 |
+
images.extend(convert_from_path(f, thread_count=4))
|
69 |
+
|
70 |
+
if len(images) >= 150:
|
71 |
+
raise gr.Error("The number of images in the dataset should be less than 150.")
|
72 |
+
return images
|
73 |
+
|
74 |
+
|
75 |
+
@spaces.GPU
|
76 |
+
def index_gpu(images, ds):
|
77 |
+
"""Example script to run inference with ColPali"""
|
78 |
+
|
79 |
+
# run inference - docs
|
80 |
+
dataloader = DataLoader(
|
81 |
+
images,
|
82 |
+
batch_size=4,
|
83 |
+
shuffle=False,
|
84 |
+
collate_fn=lambda x: process_images(processor, x),
|
85 |
+
)
|
86 |
+
|
87 |
+
|
88 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
89 |
+
if device != model.device:
|
90 |
+
model.to(device)
|
91 |
+
|
92 |
+
|
93 |
+
for batch_doc in tqdm(dataloader):
|
94 |
+
with torch.no_grad():
|
95 |
+
batch_doc = {k: v.to(device) for k, v in batch_doc.items()}
|
96 |
+
embeddings_doc = model(**batch_doc)
|
97 |
+
ds.extend(list(torch.unbind(embeddings_doc.to("cpu"))))
|
98 |
+
return f"Uploaded and converted {len(images)} pages", ds, images
|
99 |
+
|
100 |
+
|
101 |
+
def get_example():
|
102 |
+
return [[["climate_youth_magazine.pdf"], "How much tropical forest is cut annually ?"]]
|
103 |
+
|
104 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
105 |
+
gr.Markdown("# ColPali: Efficient Document Retrieval with Vision Language Models 📚")
|
106 |
+
|
107 |
+
with gr.Row():
|
108 |
+
with gr.Column(scale=2):
|
109 |
+
gr.Markdown("## 1️⃣ Upload PDFs")
|
110 |
+
file = gr.File(file_types=["pdf"], file_count="multiple", label="Upload PDFs")
|
111 |
+
|
112 |
+
convert_button = gr.Button("🔄 Index documents")
|
113 |
+
message = gr.Textbox("Files not yet uploaded", label="Status")
|
114 |
+
embeds = gr.State(value=[])
|
115 |
+
imgs = gr.State(value=[])
|
116 |
+
|
117 |
+
with gr.Column(scale=3):
|
118 |
+
gr.Markdown("## 2️⃣ Search")
|
119 |
+
query = gr.Textbox(placeholder="Enter your query here", label="Query")
|
120 |
+
k = gr.Slider(minimum=1, maximum=10, step=1, label="Number of results", value=5)
|
121 |
+
|
122 |
+
# with gr.Row():
|
123 |
+
# gr.Examples(
|
124 |
+
# examples=get_example(),
|
125 |
+
# inputs=[file, query],
|
126 |
+
# )
|
127 |
+
|
128 |
+
# Define the actions
|
129 |
+
search_button = gr.Button("🔍 Search", variant="primary")
|
130 |
+
output_gallery = gr.Gallery(label="Retrieved Documents", height=600, show_label=True)
|
131 |
|
132 |
+
convert_button.click(index, inputs=[file, embeds], outputs=[message, embeds, imgs])
|
133 |
+
search_button.click(search, inputs=[query, embeds, imgs, k], outputs=[output_gallery])
|
134 |
|
135 |
if __name__ == "__main__":
|
136 |
+
demo.queue(max_size=10).launch(debug=True)
|
requirements.txt
CHANGED
@@ -1 +1,6 @@
|
|
1 |
-
huggingface_hub==0.22.2
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub==0.22.2
|
2 |
+
colpali-engine==0.2.0
|
3 |
+
pdf2image
|
4 |
+
GPUtil
|
5 |
+
accelerate==0.30.1
|
6 |
+
mteb>=1.12.22
|