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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from qdrant_client import models
|
| 3 |
+
from qdrant_client import QdrantClient
|
| 4 |
+
from colpali_engine.models import ColPali, ColPaliProcessor
|
| 5 |
+
from Janus.janus.models import MultiModalityCausalLM, VLChatProcessor
|
| 6 |
+
from Janus.janus.utils.io import load_pil_images
|
| 7 |
+
from transformers import AutoModelForCausalLM
|
| 8 |
+
import base64
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
def batch_iterate(lst, batch_size):
|
| 13 |
+
"""Yield successive n-sized chunks from lst."""
|
| 14 |
+
for i in range(0, len(lst), batch_size):
|
| 15 |
+
yield lst[i : i + batch_size]
|
| 16 |
+
|
| 17 |
+
def image_to_base64(image):
|
| 18 |
+
buffered = BytesIO()
|
| 19 |
+
|
| 20 |
+
image.save(buffered, format="JPEG")
|
| 21 |
+
|
| 22 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 23 |
+
|
| 24 |
+
class EmbedData:
|
| 25 |
+
|
| 26 |
+
def __init__(self, embed_model_name="vidore/colpali-v1.2", batch_size = 4):
|
| 27 |
+
self.embed_model_name = embed_model_name
|
| 28 |
+
self.embed_model, self.processor = self._load_embed_model()
|
| 29 |
+
self.batch_size = batch_size
|
| 30 |
+
self.embeddings = []
|
| 31 |
+
|
| 32 |
+
def _load_embed_model(self):
|
| 33 |
+
embed_model = ColPali.from_pretrained(
|
| 34 |
+
self.embed_model_name,
|
| 35 |
+
torch_dtype=torch.bfloat16,
|
| 36 |
+
device_map="mps",
|
| 37 |
+
trust_remote_code=True,
|
| 38 |
+
cache_dir="./Janus/hf_cache"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
processor = ColPaliProcessor.from_pretrained(self.embed_model_name)
|
| 42 |
+
return embed_model, processor
|
| 43 |
+
|
| 44 |
+
def get_query_embedding(self, query):
|
| 45 |
+
|
| 46 |
+
with torch.no_grad():
|
| 47 |
+
query = self.processor.process_queries([query]).to(self.embed_model.device)
|
| 48 |
+
|
| 49 |
+
query_embedding = self.embed_model(**query)
|
| 50 |
+
|
| 51 |
+
return query_embedding[0].cpu().float().numpy().tolist()
|
| 52 |
+
|
| 53 |
+
def generate_embedding(self, images):
|
| 54 |
+
with torch.no_grad():
|
| 55 |
+
batch_images = self.processor.process_images(images).to(self.embed_model.device)
|
| 56 |
+
image_embeddings = self.embed_model(**batch_images).cpu().float().numpy().tolist()
|
| 57 |
+
|
| 58 |
+
return image_embeddings
|
| 59 |
+
|
| 60 |
+
def embed(self, images):
|
| 61 |
+
|
| 62 |
+
self.images = images
|
| 63 |
+
self.all_embeddings = []
|
| 64 |
+
|
| 65 |
+
for batch_images in tqdm(batch_iterate(images, self.batch_size), desc="Generating embeddings"):
|
| 66 |
+
batch_embeddings = self.generate_embedding(batch_images)
|
| 67 |
+
self.embeddings.extend(batch_embeddings)
|
| 68 |
+
|
| 69 |
+
class QdrantVDB_QB:
|
| 70 |
+
|
| 71 |
+
def __init__(self, collection_name, vector_dim = 128, batch_size=4):
|
| 72 |
+
self.collection_name = collection_name
|
| 73 |
+
self.batch_size = batch_size
|
| 74 |
+
self.vector_dim = vector_dim
|
| 75 |
+
|
| 76 |
+
def define_client(self):
|
| 77 |
+
|
| 78 |
+
self.client = QdrantClient(url="http://localhost:6333", prefer_grpc=True)
|
| 79 |
+
|
| 80 |
+
def create_collection(self):
|
| 81 |
+
|
| 82 |
+
if not self.client.collection_exists(collection_name=self.collection_name):
|
| 83 |
+
|
| 84 |
+
self.client.create_collection(
|
| 85 |
+
collection_name=self.collection_name,
|
| 86 |
+
on_disk_payload=True,
|
| 87 |
+
vectors_config=models.VectorParams(
|
| 88 |
+
size=self.vector_dim,
|
| 89 |
+
distance=models.Distance.COSINE,
|
| 90 |
+
on_disk=True,
|
| 91 |
+
multivector_config=models.MultiVectorConfig(
|
| 92 |
+
comparator=models.MultiVectorComparator.MAX_SIM
|
| 93 |
+
),
|
| 94 |
+
),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def ingest_data(self, embeddata):
|
| 98 |
+
|
| 99 |
+
for i, batch_embeddings in tqdm(enumerate(batch_iterate(embeddata.embeddings, self.batch_size)), desc="Ingesting data"):
|
| 100 |
+
|
| 101 |
+
points = []
|
| 102 |
+
for j, embedding in enumerate(batch_embeddings):
|
| 103 |
+
|
| 104 |
+
image_bs64 = image_to_base64(embeddata.images[i*self.batch_size + j])
|
| 105 |
+
|
| 106 |
+
current_point = models.PointStruct(id=i*self.batch_size + j,
|
| 107 |
+
vector=embedding,
|
| 108 |
+
payload={"image": image_bs64})
|
| 109 |
+
|
| 110 |
+
points.append(current_point)
|
| 111 |
+
|
| 112 |
+
self.client.upsert(collection_name=self.collection_name, points=points, wait=True)
|
| 113 |
+
|
| 114 |
+
class Retriever:
|
| 115 |
+
|
| 116 |
+
def __init__(self, vector_db, embeddata):
|
| 117 |
+
|
| 118 |
+
self.vector_db = vector_db
|
| 119 |
+
self.embeddata = embeddata
|
| 120 |
+
|
| 121 |
+
def search(self, query):
|
| 122 |
+
query_embedding = self.embeddata.get_query_embedding(query)
|
| 123 |
+
|
| 124 |
+
query_result = self.vector_db.client.query_points(collection_name=self.vector_db.collection_name,
|
| 125 |
+
query=query_embedding,
|
| 126 |
+
limit=4,
|
| 127 |
+
search_params=models.SearchParams(
|
| 128 |
+
quantization=models.QuantizationSearchParams(
|
| 129 |
+
ignore=True,
|
| 130 |
+
rescore=True,
|
| 131 |
+
oversampling=2.0
|
| 132 |
+
)
|
| 133 |
+
)
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
return query_result
|
| 137 |
+
|
| 138 |
+
class RAG:
|
| 139 |
+
|
| 140 |
+
def __init__(self,
|
| 141 |
+
retriever,
|
| 142 |
+
llm_name = "deepseek-ai/Janus-Pro-1B"
|
| 143 |
+
):
|
| 144 |
+
|
| 145 |
+
self.llm_name = llm_name
|
| 146 |
+
self._setup_llm()
|
| 147 |
+
self.retriever = retriever
|
| 148 |
+
|
| 149 |
+
def _setup_llm(self):
|
| 150 |
+
|
| 151 |
+
self.vl_chat_processor = VLChatProcessor.from_pretrained(self.llm_name, cache_dir="./Janus/hf_cache")
|
| 152 |
+
self.tokenizer = self.vl_chat_processor.tokenizer
|
| 153 |
+
|
| 154 |
+
self.vl_gpt = AutoModelForCausalLM.from_pretrained(
|
| 155 |
+
self.llm_name, trust_remote_code=True, cache_dir="./Janus/hf_cache"
|
| 156 |
+
).to(torch.bfloat16).eval()
|
| 157 |
+
|
| 158 |
+
def generate_context(self, query):
|
| 159 |
+
|
| 160 |
+
result = self.retriever.search(query)
|
| 161 |
+
return f"./images/page{result.points[0].id}.jpg"
|
| 162 |
+
|
| 163 |
+
def query(self, query):
|
| 164 |
+
image_context = self.generate_context(query=query)
|
| 165 |
+
|
| 166 |
+
qa_prompt_tmpl_str = f"""The user has asked the following question:
|
| 167 |
+
|
| 168 |
+
---------------------
|
| 169 |
+
|
| 170 |
+
Query: {query}
|
| 171 |
+
|
| 172 |
+
---------------------
|
| 173 |
+
|
| 174 |
+
Some images are available to you
|
| 175 |
+
for this question. You have
|
| 176 |
+
to understand these images thoroughly and
|
| 177 |
+
extract all relevant information that will
|
| 178 |
+
help you answer the query.
|
| 179 |
+
|
| 180 |
+
---------------------
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
conversation = [
|
| 184 |
+
{
|
| 185 |
+
"role": "User",
|
| 186 |
+
"content": f"<image_placeholder> \n {qa_prompt_tmpl_str}",
|
| 187 |
+
"images": [image_context],
|
| 188 |
+
},
|
| 189 |
+
{"role": "Assistant", "content": ""},
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
pil_images = load_pil_images(conversation)
|
| 193 |
+
prepare_inputs = self.vl_chat_processor(
|
| 194 |
+
conversations=conversation, images=pil_images, force_batchify=True
|
| 195 |
+
).to(self.vl_gpt.device)
|
| 196 |
+
|
| 197 |
+
inputs_embeds = self.vl_gpt.prepare_inputs_embeds(**prepare_inputs)
|
| 198 |
+
|
| 199 |
+
outputs = self.vl_gpt.language_model.generate(
|
| 200 |
+
inputs_embeds=inputs_embeds,
|
| 201 |
+
attention_mask=prepare_inputs.attention_mask,
|
| 202 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 203 |
+
bos_token_id=self.tokenizer.bos_token_id,
|
| 204 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
| 205 |
+
max_new_tokens=512,
|
| 206 |
+
do_sample=False,
|
| 207 |
+
use_cache=True,
|
| 208 |
+
)
|
| 209 |
+
streaming_response = self.tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=True)
|
| 210 |
+
|
| 211 |
+
return streaming_response
|