HugSib commited on
Commit
fc4a494
β€’
1 Parent(s): 3f50791

feat : add retrieve top-k + improve app style

Browse files

-Top-k can be displayed as a gallery in the app
- Model cache is saved in data/ folder to allow quicker startup
- Diverse style improvement without changing the logic

Files changed (1) hide show
  1. app.py +51 -32
app.py CHANGED
@@ -2,18 +2,20 @@ 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
 
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,19 +23,27 @@ def search(query: str, ds, images):
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,41 +58,50 @@ def index(file, ds):
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)
 
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, k):
19
  qs = []
20
  with torch.no_grad():
21
  batch_query = process_queries(processor, [query], mock_image)
 
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
+ results = []
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 files:
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
  ds.extend(list(torch.unbind(embeddings_doc.to("cpu"))))
59
  return f"Uploaded and converted {len(images)} pages", ds, images
60
 
61
+ cache_dir = os.path.join(os.getcwd(), "data/", "model_cache/")
 
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 = token, cache_dir=cache_dir
67
  ).eval()
68
+
69
  model.load_adapter(model_name)
70
+ processor = AutoProcessor.from_pretrained(model_name, cache_dir=cache_dir, token = token)
71
+
72
  device = model.device
73
+
74
  mock_image = Image.new("RGB", (448, 448), (255, 255, 255))
75
 
76
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
77
+ gr.Markdown("# ColPali: Efficient Document Retrieval with Vision Language Models πŸ“š")
78
+ 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).
 
79
 
80
+ ColPali is model implemented from the [ColPali paper](https://arxiv.org/abs/2407.01449).
 
 
 
 
81
 
82
+ This demo allows you to upload PDF files and search for the most relevant pages based on your query.
83
+ """)
84
+ with gr.Row():
85
+ with gr.Column(scale=2):
86
+ gr.Markdown("## 1️⃣ Upload PDFs")
87
+ file = gr.File(file_types=["pdf"], file_count="multiple", label="Upload PDFs")
88
+
89
+ convert_button = gr.Button("πŸ”„ Convert and upload")
90
+ message = gr.Textbox("Files not yet uploaded", label="Status")
91
+ embeds = gr.State(value=[])
92
+ imgs = gr.State(value=[])
93
 
94
+ with gr.Column(scale=3):
95
+ gr.Markdown("## 2️⃣ Search")
96
+ query = gr.Textbox(placeholder="Enter your query here", label="Query")
97
+ k = gr.Slider(minimum=1, maximum=10, step=1, label="Number of results", value=3)
 
98
 
99
+ # Define the actions
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, server_name="0.0.0.0", server_port=7861)