Spaces:
Running
Running
liubangwei
commited on
Commit
·
a72a7d4
1
Parent(s):
94a930c
init IDMR demo
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- app.py +194 -0
- image_embeddings.pkl +3 -0
- imgs/candidates/000000007574.jpg +0 -0
- imgs/candidates/000000009448.jpg +0 -0
- imgs/candidates/000000014007.jpg +0 -0
- imgs/candidates/000000021839.jpg +0 -0
- imgs/candidates/000000022892.jpg +0 -0
- imgs/candidates/000000024610.jpg +0 -0
- imgs/candidates/000000025593.jpg +0 -0
- imgs/candidates/000000044068.jpg +0 -0
- imgs/candidates/000000084362.jpg +0 -0
- imgs/candidates/000000098839.jpg +0 -0
- imgs/candidates/000000107339.jpg +0 -0
- imgs/candidates/000000144333.jpg +0 -0
- imgs/candidates/000000159791.jpg +0 -0
- imgs/candidates/000000168593.jpg +0 -0
- imgs/candidates/000000182155.jpg +0 -0
- imgs/candidates/000000186449.jpg +0 -0
- imgs/candidates/000000191845.jpg +0 -0
- imgs/candidates/000000210299.jpg +0 -0
- imgs/candidates/000000221708.jpg +0 -0
- imgs/candidates/000000223747.jpg +0 -0
- imgs/candidates/000000226111.jpg +0 -0
- imgs/candidates/000000226984.jpg +0 -0
- imgs/candidates/000000252294.jpg +0 -0
- imgs/candidates/000000256941.jpg +0 -0
- imgs/candidates/000000280710.jpg +0 -0
- imgs/candidates/000000281179.jpg +0 -0
- imgs/candidates/000000283717.jpg +0 -0
- imgs/candidates/000000284445.jpg +0 -0
- imgs/candidates/000000287649.jpg +0 -0
- imgs/candidates/000000289343.jpg +0 -0
- imgs/candidates/000000295809.jpg +0 -0
- imgs/candidates/000000334371.jpg +0 -0
- imgs/candidates/000000350054.jpg +0 -0
- imgs/candidates/000000361621.jpg +0 -0
- imgs/candidates/000000369503.jpg +0 -0
- imgs/candidates/000000384661.jpg +0 -0
- imgs/candidates/000000385997.jpg +0 -0
- imgs/candidates/000000398377.jpg +0 -0
- imgs/candidates/000000402473.jpg +0 -0
- imgs/candidates/000000426166.jpg +0 -0
- imgs/candidates/000000441247.jpg +0 -0
- imgs/candidates/000000455157.jpg +0 -0
- imgs/candidates/000000492077.jpg +0 -0
- imgs/candidates/000000496854.jpg +0 -0
- imgs/candidates/000000501523.jpg +0 -0
- imgs/candidates/000000530099.jpg +0 -0
- imgs/candidates/000000530162.jpg +0 -0
- imgs/candidates/000000530836.jpg +0 -0
app.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import pickle
|
| 7 |
+
from transformers import AutoProcessor
|
| 8 |
+
from src.model import MMEBModel
|
| 9 |
+
from src.arguments import ModelArguments
|
| 10 |
+
|
| 11 |
+
# 假设图片库存储在本地文件夹中
|
| 12 |
+
QUERY_DIR = "imgs/queries"
|
| 13 |
+
IMAGE_DIR = "imgs/candidates"
|
| 14 |
+
# IMAGE_DIR = "imgs"
|
| 15 |
+
image_paths = [os.path.join(IMAGE_DIR, f) for f in os.listdir(IMAGE_DIR) if f.endswith((".jpg", ".png"))]
|
| 16 |
+
global IMAGE_TOKEN, TOP_N
|
| 17 |
+
IMAGE_TOKEN = "<|image_1|>"
|
| 18 |
+
TOP_N = 5
|
| 19 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
print(f"device: {device}")
|
| 21 |
+
# 模型加载和初始化
|
| 22 |
+
def load_model():
|
| 23 |
+
global IMAGE_TOKEN
|
| 24 |
+
# 模型参数
|
| 25 |
+
model_args = ModelArguments(
|
| 26 |
+
# model_name="/fs-computility/ai-shen/kilab-shared/liubangwei/ckpt/IDMR/IDMR_InternVL2_5-2B", # 替换为你的模型名称
|
| 27 |
+
model_name="/fs-computility/ai-shen/kilab-shared/liubangwei/ckpt/my_hf/IDMR-2B",
|
| 28 |
+
model_backbone="internvl_2_5", # 替换为你的模型 backbone
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# 加载处理器
|
| 32 |
+
if model_args.model_backbone == "phi35v":
|
| 33 |
+
processor = AutoProcessor.from_pretrained(
|
| 34 |
+
model_args.model_name,
|
| 35 |
+
trust_remote_code=True,
|
| 36 |
+
num_crops=model_args.num_crops,
|
| 37 |
+
)
|
| 38 |
+
processor.tokenizer.padding_side = "right"
|
| 39 |
+
elif model_args.model_backbone == "internvl_2_5":
|
| 40 |
+
from src.vlm_backbone.intern_vl import InternVLProcessor
|
| 41 |
+
from transformers import AutoTokenizer, AutoImageProcessor
|
| 42 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 43 |
+
model_args.model_name,
|
| 44 |
+
trust_remote_code=True
|
| 45 |
+
)
|
| 46 |
+
image_processor = AutoImageProcessor.from_pretrained(
|
| 47 |
+
model_args.model_name,
|
| 48 |
+
trust_remote_code=True,
|
| 49 |
+
use_fast=False
|
| 50 |
+
)
|
| 51 |
+
processor = InternVLProcessor(
|
| 52 |
+
image_processor=image_processor,
|
| 53 |
+
tokenizer=tokenizer
|
| 54 |
+
)
|
| 55 |
+
IMAGE_TOKEN = "<image>"
|
| 56 |
+
|
| 57 |
+
# 加载模型
|
| 58 |
+
model = MMEBModel.load(model_args)
|
| 59 |
+
model = model.to(device, dtype=torch.bfloat16)
|
| 60 |
+
model.eval()
|
| 61 |
+
|
| 62 |
+
return model, processor
|
| 63 |
+
|
| 64 |
+
# 加载模型和处理器
|
| 65 |
+
model, processor = load_model()
|
| 66 |
+
|
| 67 |
+
def get_inputs(processor, text, image_path=None, image=None):
|
| 68 |
+
if image_path:
|
| 69 |
+
image = Image.open(image_path)
|
| 70 |
+
|
| 71 |
+
if image is None:
|
| 72 |
+
text = text.replace(IMAGE_TOKEN, "")
|
| 73 |
+
|
| 74 |
+
inputs = processor(
|
| 75 |
+
text=text,
|
| 76 |
+
images=[image] if image else None,
|
| 77 |
+
return_tensors="pt",
|
| 78 |
+
max_length=1024,
|
| 79 |
+
truncation=True
|
| 80 |
+
)
|
| 81 |
+
inputs = {key: value.to(device) for key, value in inputs.items()}
|
| 82 |
+
inputs["image_flags"] = torch.tensor([1 if image else 0], dtype=torch.long).to(device)
|
| 83 |
+
if image is None:
|
| 84 |
+
del inputs['pixel_values']
|
| 85 |
+
return inputs
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# 将图片库中的图像编码为 embedding
|
| 89 |
+
def encode_image_library(image_paths):
|
| 90 |
+
embeddings = []
|
| 91 |
+
for img_path in image_paths:
|
| 92 |
+
text = f"{IMAGE_TOKEN}\n Represent the given image."
|
| 93 |
+
print(f"text: {text}")
|
| 94 |
+
inputs = get_inputs(processor, text, image_path=img_path)
|
| 95 |
+
with torch.no_grad(), torch.autocast(device_type=device, dtype=torch.bfloat16):
|
| 96 |
+
output = model(tgt=inputs)
|
| 97 |
+
embeddings.append(output["tgt_reps"].float().cpu().numpy())
|
| 98 |
+
return np.stack(embeddings)
|
| 99 |
+
|
| 100 |
+
# 保存 embedding 到文件
|
| 101 |
+
def save_embeddings(embeddings, file_path="image_embeddings.pkl"):
|
| 102 |
+
with open(file_path, "wb") as f:
|
| 103 |
+
pickle.dump(embeddings, f)
|
| 104 |
+
|
| 105 |
+
# 加载 embedding 从文件
|
| 106 |
+
def load_embeddings(file_path="image_embeddings.pkl"):
|
| 107 |
+
with open(file_path, "rb") as f:
|
| 108 |
+
return pickle.load(f)
|
| 109 |
+
|
| 110 |
+
# 计算相似度(余弦相似度)
|
| 111 |
+
def cosine_similarity(query_embedding, embeddings):
|
| 112 |
+
similarity = np.sum(query_embedding * embeddings, axis=-1)
|
| 113 |
+
return similarity
|
| 114 |
+
|
| 115 |
+
# 检索逻辑
|
| 116 |
+
def retrieve_images(query_text, query_image, top_n=TOP_N):
|
| 117 |
+
if query_text:
|
| 118 |
+
query_text = f"{IMAGE_TOKEN}\n {query_text}"
|
| 119 |
+
else:
|
| 120 |
+
query_text = f"{IMAGE_TOKEN}\n Represent the given image."
|
| 121 |
+
|
| 122 |
+
if query_image is not None:
|
| 123 |
+
image = Image.fromarray(query_image)
|
| 124 |
+
else:
|
| 125 |
+
image = None
|
| 126 |
+
inputs = get_inputs(processor, query_text, image=image)
|
| 127 |
+
print(f"inputs: {inputs}")
|
| 128 |
+
# with torch.no_grad():
|
| 129 |
+
with torch.no_grad(), torch.autocast(device_type=device, dtype=torch.bfloat16):
|
| 130 |
+
query_embedding = model(qry=inputs)["qry_reps"].float().cpu().numpy()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# 加载图片库的 embedding
|
| 134 |
+
embeddings = load_embeddings()
|
| 135 |
+
|
| 136 |
+
# 计算相似度
|
| 137 |
+
similarity = cosine_similarity(query_embedding, embeddings)
|
| 138 |
+
similarity = similarity.T
|
| 139 |
+
print(f"cosine_similarity: {similarity}")
|
| 140 |
+
top_indices = np.argsort(-similarity).squeeze(0)[:top_n]
|
| 141 |
+
print(f"top_indices: {top_indices}")
|
| 142 |
+
|
| 143 |
+
# similarity = model.compute_similarity(np.expand_dims(query_embedding.squeeze(0), axis=1), embeddings.squeeze(1))
|
| 144 |
+
# print(f"model.compute_similarity: {similarity}")
|
| 145 |
+
|
| 146 |
+
return [image_paths[i] for i in top_indices]
|
| 147 |
+
|
| 148 |
+
# 界面逻辑
|
| 149 |
+
def demo(query_text, query_image):
|
| 150 |
+
# 执行检索
|
| 151 |
+
# print(f"query_text: {query_text}, query_image: {query_image}, type(query_image): {type(query_image)}, image shape: {query_image.shape if query_image is not None else 'None'}")
|
| 152 |
+
|
| 153 |
+
retrieved_images = retrieve_images(query_text, query_image)
|
| 154 |
+
# 返回检索结果(图片列表)
|
| 155 |
+
return [Image.open(img) for img in retrieved_images]
|
| 156 |
+
|
| 157 |
+
# 预置示例
|
| 158 |
+
def load_examples():
|
| 159 |
+
examples = []
|
| 160 |
+
# 获取QUERY_DIR中的所有图片文件
|
| 161 |
+
image_files = [f for f in os.listdir(QUERY_DIR) if f.endswith((".jpg", ".png"))]
|
| 162 |
+
|
| 163 |
+
for img_file in image_files:
|
| 164 |
+
# 构建图片完整路径
|
| 165 |
+
img_path = os.path.join(QUERY_DIR, img_file)
|
| 166 |
+
# 获取对应的txt文件名(将图片扩展名替换为.txt)
|
| 167 |
+
txt_file = os.path.splitext(img_file)[0] + ".txt"
|
| 168 |
+
txt_path = os.path.join(QUERY_DIR, txt_file)
|
| 169 |
+
|
| 170 |
+
# 如果存在对应的txt文件,读取查询文本
|
| 171 |
+
if os.path.exists(txt_path):
|
| 172 |
+
with open(txt_path, 'r', encoding='utf-8') as f:
|
| 173 |
+
query_text = f.read().strip().replace("<|image_1|>\n", "")
|
| 174 |
+
examples.append([query_text, img_path])
|
| 175 |
+
|
| 176 |
+
return examples
|
| 177 |
+
|
| 178 |
+
# 构建 Gradio 界面
|
| 179 |
+
iface = gr.Interface(
|
| 180 |
+
fn=demo,
|
| 181 |
+
inputs=["text", "image"],
|
| 182 |
+
outputs=gr.Gallery(label=f"Retrieved Images (Top {TOP_N})"),
|
| 183 |
+
examples=load_examples(), # 使用动态加载的示例
|
| 184 |
+
title="Multimodal Retrieval Demo",
|
| 185 |
+
description="Enter a query and upload an image to retrieve relevant images from the library. You can click on the example below to use it as a query"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# 在启动时编码图片库并保存 embedding
|
| 189 |
+
if not os.path.exists("image_embeddings.pkl"):
|
| 190 |
+
embeddings = encode_image_library(image_paths)
|
| 191 |
+
save_embeddings(embeddings)
|
| 192 |
+
|
| 193 |
+
# 启动 Gradio 应用
|
| 194 |
+
iface.launch()
|
image_embeddings.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b8dcedaab4e3bcc555795f56b15a7d830b74ffc707260c3b0152ba8d99a992bd
|
| 3 |
+
size 409764
|
imgs/candidates/000000007574.jpg
ADDED
|
imgs/candidates/000000009448.jpg
ADDED
|
imgs/candidates/000000014007.jpg
ADDED
|
imgs/candidates/000000021839.jpg
ADDED
|
imgs/candidates/000000022892.jpg
ADDED
|
imgs/candidates/000000024610.jpg
ADDED
|
imgs/candidates/000000025593.jpg
ADDED
|
imgs/candidates/000000044068.jpg
ADDED
|
imgs/candidates/000000084362.jpg
ADDED
|
imgs/candidates/000000098839.jpg
ADDED
|
imgs/candidates/000000107339.jpg
ADDED
|
imgs/candidates/000000144333.jpg
ADDED
|
imgs/candidates/000000159791.jpg
ADDED
|
imgs/candidates/000000168593.jpg
ADDED
|
imgs/candidates/000000182155.jpg
ADDED
|
imgs/candidates/000000186449.jpg
ADDED
|
imgs/candidates/000000191845.jpg
ADDED
|
imgs/candidates/000000210299.jpg
ADDED
|
imgs/candidates/000000221708.jpg
ADDED
|
imgs/candidates/000000223747.jpg
ADDED
|
imgs/candidates/000000226111.jpg
ADDED
|
imgs/candidates/000000226984.jpg
ADDED
|
imgs/candidates/000000252294.jpg
ADDED
|
imgs/candidates/000000256941.jpg
ADDED
|
imgs/candidates/000000280710.jpg
ADDED
|
imgs/candidates/000000281179.jpg
ADDED
|
imgs/candidates/000000283717.jpg
ADDED
|
imgs/candidates/000000284445.jpg
ADDED
|
imgs/candidates/000000287649.jpg
ADDED
|
imgs/candidates/000000289343.jpg
ADDED
|
imgs/candidates/000000295809.jpg
ADDED
|
imgs/candidates/000000334371.jpg
ADDED
|
imgs/candidates/000000350054.jpg
ADDED
|
imgs/candidates/000000361621.jpg
ADDED
|
imgs/candidates/000000369503.jpg
ADDED
|
imgs/candidates/000000384661.jpg
ADDED
|
imgs/candidates/000000385997.jpg
ADDED
|
imgs/candidates/000000398377.jpg
ADDED
|
imgs/candidates/000000402473.jpg
ADDED
|
imgs/candidates/000000426166.jpg
ADDED
|
imgs/candidates/000000441247.jpg
ADDED
|
imgs/candidates/000000455157.jpg
ADDED
|
imgs/candidates/000000492077.jpg
ADDED
|
imgs/candidates/000000496854.jpg
ADDED
|
imgs/candidates/000000501523.jpg
ADDED
|
imgs/candidates/000000530099.jpg
ADDED
|
imgs/candidates/000000530162.jpg
ADDED
|
imgs/candidates/000000530836.jpg
ADDED
|