ahmed-masry commited on
Commit
0201468
·
verified ·
1 Parent(s): 220c1ae

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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).
107
+
108
+ ColPali is model implemented from the [ColPali paper](https://arxiv.org/abs/2407.01449).
109
+
110
+ This demo allows you to upload PDF files and search for the most relevant pages based on your query.
111
+ Refresh the page if you change documents !
112
+
113
+ ⚠️ This demo uses a model trained exclusively on A4 PDFs in portrait mode, containing english text. Performance is expected to drop for other page formats and languages.
114
+ Other models will be released with better robustness towards different languages and document formats !
115
+ """)
116
+ with gr.Row():
117
+ with gr.Column(scale=2):
118
+ gr.Markdown("## 1️⃣ Upload PDFs")
119
+ file = gr.File(file_types=["pdf"], file_count="multiple", label="Upload PDFs")
120
+
121
+ convert_button = gr.Button("🔄 Index documents")
122
+ message = gr.Textbox("Files not yet uploaded", label="Status")
123
+ embeds = gr.State(value=[])
124
+ imgs = gr.State(value=[])
125
+
126
+ with gr.Column(scale=3):
127
+ gr.Markdown("## 2️⃣ Search")
128
+ query = gr.Textbox(placeholder="Enter your query here", label="Query")
129
+ k = gr.Slider(minimum=1, maximum=10, step=1, label="Number of results", value=5)
130
+
131
+ # with gr.Row():
132
+ # gr.Examples(
133
+ # examples=get_example(),
134
+ # inputs=[file, query],
135
+ # )
136
+
137
+ # Define the actions
138
+ search_button = gr.Button("🔍 Search", variant="primary")
139
+ output_gallery = gr.Gallery(label="Retrieved Documents", height=600, show_label=True)
140
+
141
+ convert_button.click(index, inputs=[file, embeds], outputs=[message, embeds, imgs])
142
+ search_button.click(search, inputs=[query, embeds, imgs, k], outputs=[output_gallery])
143
+
144
+ if __name__ == "__main__":
145
+ demo.queue(max_size=10).launch(debug=True)