Alibaba Cloud Vector Search with Milvus (Milvus) と Qwen-VL 大規模言語モデル (LLM) を組み合わせて画像特徴を抽出し、テキストによる画像検索、テキストによるテキスト検索、画像による検索、画像によるテキスト検索などのマルチモーダル検索を実行します。
背景情報
マルチモーダル検索では、画像やテキストなどの非構造化データをベクトル表現に変換し、ベクトル検索技術を使用して類似コンテンツを見つけます。このトピックでは、次のツールを使用します。
-
Milvus:ベクトルの保存と取得に使用する高効率なベクトルデータベースです。
-
Qwen-VL:画像の説明とキーワードを抽出します。詳細については、「Qwen-VL」をご参照ください。
-
DashScope Embedding API:画像とテキストをベクトルに変換します。詳細については、「Multimodal-Embedding API details」をご参照ください。
サポートされている検索モードは次のとおりです。
-
テキストによる画像検索:クエリテキストを入力して、最も類似する画像を検索します。
-
テキストによるテキスト検索:クエリテキストを入力して、最も類似する画像の説明を検索します。
-
画像による検索:クエリ画像を入力して、最も類似する画像を検索します。
-
画像によるテキスト検索:クエリ画像を入力して、最も類似する画像の説明を検索します。
システムアーキテクチャ
次の図は、マルチモーダル検索システムの全体アーキテクチャを示しています。
前提条件
-
Milvus インスタンスを作成済みであること。詳細については、「Create a Milvus instance」をご参照ください。
-
Alibaba Cloud Model Studio を有効化し、API キーを取得済みであること。詳細については、「Obtain an API key」をご参照ください。
-
必要な依存関係パッケージをインストール済みであること。
pip3 install dashscope pymilvus==2.5.0このトピックの例は、
Python 3.9環境で実行されます。 -
サンプルデータセットをダウンロードして解凍済みであること。
wget https://github.com/milvus-io/pymilvus-assets/releases/download/imagedata/reverse_image_search.zip unzip -q -o reverse_image_search.zipサンプルデータセットには、
reverse_image_search.csvという名前の CSV ファイルと複数の画像ファイルが含まれています。説明このトピックで使用するサンプルデータセットとその画像は、オープンソースの Milvus プロジェクトのものです。
コアコードの紹介
この例では、Qwen-VL モデルは画像の説明を抽出し、image_description フィールドに格納します。次に、マルチモーダル埋め込みモデルは、クロスモーダル検索のデータを準備するために、画像とその説明を image_embedding や text_embedding などのベクトル表現に変換します。
デモを簡略化するため、先頭 200 枚の画像のみを使用します。
import base64
import csv
import dashscope
import os
import pandas as pd
import sys
import time
from tqdm import tqdm
from pymilvus import (
connections,
FieldSchema,
CollectionSchema,
DataType,
Collection,
MilvusException,
utility,
)
from http import HTTPStatus
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class FeatureExtractor:
def __init__(self, DASHSCOPE_API_KEY):
self._api_key = DASHSCOPE_API_KEY # API キーは環境変数に格納します
def __call__(self, input_data, input_type):
if input_type not in ("image", "text"):
raise ValueError("Invalid input type. Must be 'image' or 'text'.")
try:
if input_type == "image":
_, ext = os.path.splitext(input_data)
image_format = ext.lstrip(".").lower()
with open(input_data, "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
input_data = f"data:image/{image_format};base64,{base64_image}"
payload = [{"image": input_data}]
else:
payload = [{"text": input_data}]
resp = dashscope.MultiModalEmbedding.call(
model="multimodal-embedding-v1",
input=payload,
api_key=self._api_key,
)
if resp.status_code == HTTPStatus.OK:
return resp.output["embeddings"][0]["embedding"]
else:
raise RuntimeError(
f"API call failed. Status code: {resp.status_code}, Error message: {resp.message}"
)
except Exception as e:
logger.error(f"Processing failed: {str(e)}")
raise
class FeatureExtractorVL:
def __init__(self, DASHSCOPE_API_KEY):
self._api_key = DASHSCOPE_API_KEY # API キーは環境変数に格納します
def __call__(self, input_data, input_type):
if input_type not in ("image"):
raise ValueError("Invalid input type. Must be 'image'.")
try:
if input_type == "image":
payload=[
{
"role": "system",
"content": [{"type":"text","text": "You are a helpful assistant."}]
},
{
"role": "user",
"content": [
# {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"image": input_data},
{"text": "First, describe this image in under 50 words, and then provide 5 keywords"}
],
}
]
resp = dashscope.MultiModalConversation.call(
model="qwen-vl-plus",
messages=payload,
api_key=self._api_key,
)
if resp.status_code == HTTPStatus.OK:
return resp.output["choices"][0]["message"].content[0]["text"]
else:
raise RuntimeError(
f"API call failed. Status code: {resp.status_code}, Error message: {resp.message}"
)
except Exception as e:
logger.error(f"Processing failed: {str(e)}")
raise
class MilvusClient:
def __init__(self, MILVUS_TOKEN, MILVUS_HOST, MILVUS_PORT, INDEX, COLLECTION_NAME):
self._token = MILVUS_TOKEN
self._host = MILVUS_HOST
self._port = MILVUS_PORT
self._index = INDEX
self._collection_name = COLLECTION_NAME
self._connect()
self._create_collection_if_not_exists()
def _connect(self):
try:
connections.connect(alias="default", host=self._host, port=self._port, token=self._token)
logger.info("Connected to Milvus successfully.")
except Exception as e:
logger.error(f"Failed to connect to Milvus: {str(e)}")
sys.exit(1)
def _collection_exists(self):
return self._collection_name in utility.list_collections()
def _create_collection_if_not_exists(self):
try:
if not self._collection_exists():
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
FieldSchema(name="origin", dtype=DataType.VARCHAR, max_length=512),
FieldSchema(name="image_description", dtype=DataType.VARCHAR, max_length=1024),
FieldSchema(name="image_embedding", dtype=DataType.FLOAT_VECTOR, dim=1024),
FieldSchema(name="text_embedding", dtype=DataType.FLOAT_VECTOR, dim=1024)
]
schema = CollectionSchema(fields)
self._collection = Collection(self._collection_name, schema)
if self._index == 'IVF_FLAT':
self._create_ivf_index()
else:
self._create_hnsw_index()
logger.info("Collection created successfully.")
else:
self._collection = Collection(self._collection_name)
logger.info("Collection already exists.")
except Exception as e:
logger.error(f"Failed to create or load the collection: {str(e)}")
sys.exit(1)
def _create_ivf_index(self):
index_params = {
"index_type": "IVF_FLAT",
"params": {
"nlist": 1024, # インデックスのクラスター数
},
"metric_type": "L2",
}
self._collection.create_index("image_embedding", index_params)
self._collection.create_index("text_embedding", index_params)
logger.info("Index created successfully.")
def _create_hnsw_index(self):
index_params = {
"index_type": "HNSW",
"params": {
"M": 64, # グラフ内で各ノードが接続できる近傍の最大数
"efConstruction": 100, # インデックス構築時に接続候補として考慮する近傍数
},
"metric_type": "L2",
}
self._collection.create_index("image_embedding", index_params)
self._collection.create_index("text_embedding", index_params)
logger.info("Index created successfully.")
def insert(self, data):
try:
self._collection.insert(data)
self._collection.load()
logger.info("Data inserted and loaded successfully.")
except MilvusException as e:
logger.error(f"Failed to insert data: {str(e)}")
raise
def search(self, query_embedding, field, limit=3):
try:
if self._index == 'IVF_FLAT':
param={"metric_type": "L2", "params": {"nprobe": 10}}
else:
param={"metric_type": "L2", "params": {"ef": 10}}
result = self._collection.search(
data=[query_embedding],
anns_field=field,
param=param,
limit=limit,
output_fields=["origin", "image_description"],
)
return [{"id": hit.id, "distance": hit.distance, "origin": hit.origin, "image_description": hit.image_description} for hit in result[0]]
except Exception as e:
logger.error(f"Search failed: {str(e)}")
return None
# データを読み込み、埋め込みを生成します
def load_image_embeddings(extractor, extractorVL, csv_path):
df = pd.read_csv(csv_path)
image_embeddings = {}
for image_path in tqdm(df["path"].tolist()[:200], desc="Generating image embeddings"): # デモでは先頭 200 枚の画像のみを使用します
try:
desc = extractorVL(image_path, "image")
image_embeddings[image_path] = [desc, extractor(image_path, "image"), extractor(desc, "text")]
time.sleep(1) # API 呼び出し頻度を制御します
except Exception as e:
logger.warning(f"Failed to process {image_path}, skipping: {str(e)}")
return [{"origin": k, 'image_description':v[0], "image_embedding": v[1], 'text_embedding': v[2]} for k, v in image_embeddings.items()]
各要素の説明:
-
FeatureExtractor:DashScope Embedding APIを呼び出して、画像またはテキストをベクトル表現に変換します。 -
FeatureExtractorVL:Qwen-VL モデルを呼び出して、画像からテキスト記述とキーワードを抽出します。 -
MilvusClient: 接続、コレクションの作成、インデックスの構築、データの挿入、検索などの Milvus 操作をカプセル化します。
操作手順
手順1:データセットの読み込み
if __name__ == "__main__":
# Milvus と DashScope API を設定します
MILVUS_TOKEN = "root:****"
MILVUS_HOST = "c-0aa16b1****.milvus.aliyuncs.com"
MILVUS_PORT = "19530"
COLLECTION_NAME = "multimodal_search"
INDEX = "IVF_FLAT" # IVF_FLAT または HNSW
script_dir = os.path.dirname(os.path.abspath(__file__))
csv_path = os.path.join(script_dir, "reverse_image_search.csv")
# 手順 1: Milvus クライアントを初期化します
milvus_client = MilvusClient(MILVUS_TOKEN, MILVUS_HOST, MILVUS_PORT, INDEX, COLLECTION_NAME)
# 手順 2: Qwen-VL LLM とマルチモーダル埋め込みモデルを初期化します
extractor = FeatureExtractor(DASHSCOPE_API_KEY)
extractorVL = FeatureExtractorVL(DASHSCOPE_API_KEY)
# 手順 3: 画像データセットの埋め込みを生成し、Milvus に挿入します
embeddings = load_image_embeddings(extractor, extractorVL, csv_path)
milvus_client.insert(embeddings)
この手順では、次のパラメータを使用します。実際の値に置き換えてください。
|
パラメータ名 |
説明 |
|
|
DashScope の API キーです。Qwen-VL およびマルチモーダル埋め込みモデルの呼び出しに使用します。 |
|
|
Milvus インスタンスのアクセス資格情報は、 |
|
|
Milvus インスタンスの内部またはパブリックエンドポイント ( |
|
|
Milvus インスタンスのポート番号。デフォルト値は |
|
|
画像とテキストのベクトルデータを格納する Milvus コレクションの名前です。 |
Python ファイルを実行します。出力に次の情報が含まれていれば、データの読み込みは成功です。
Generating image embeddings: 100%
INFO:__main__:Data inserted and loaded successfully.
また、Attu ページにアクセスし、[データ] タブに移動してロードされたデータセット情報を確認することもできます。
例えば、画像が Qwen-VL LLM によって分析されると、抽出されたテキストは次のようにシーンを説明します:"A person in jeans and green boots stands on a beach. The sand is covered with water marks. Keywords: beach, footprints, sand, shoes, pants"
この説明は簡潔な言葉で画像の主要な特徴を捉え、シーンを明確にイメージできるようにします。

手順2:マルチモーダルベクトル検索の実行
例1:テキストによる画像検索とテキストによるテキスト検索
この例のクエリテキスト「a brown dog」は、マルチモーダル埋め込みモデルによってベクトル表現 (埋め込み) に変換されます。生成されたベクトルに基づき、image_embedding ではテキストから画像への検索が、text_embedding ではテキストからテキストへの検索が実行されます。
Python ファイルの main セクションを次のコードに置き換え、ファイルを実行します。
if __name__ == "__main__":
MILVUS_HOST = "c-xxxxxxxxxxxx.milvus.aliyuncs.com"
MILVUS_PORT = "19530"
MILVUS_TOKEN = "root:****"
COLLECTION_NAME = "multimodal_search"
INDEX = "IVF_FLAT" # IVF_FLAT または HNSW
DASHSCOPE_API_KEY = "<YOUR_DASHSCOPE_API_KEY >"
# 手順 1: Milvus クライアントを初期化します
milvus_client = MilvusClient(MILVUS_TOKEN, MILVUS_HOST, MILVUS_PORT, INDEX, COLLECTION_NAME)
# 手順 2: マルチモーダル埋め込みモデルを初期化します
extractor = FeatureExtractor(DASHSCOPE_API_KEY)
# 手順 4: テキストによる画像検索とテキストによるテキスト検索のマルチモーダル検索例
text_query = "a brown dog"
text_embedding = extractor(text_query, "text")
text_results_1 = milvus_client.search(text_embedding, field = 'image_embedding')
logger.info(f"Text-to-image search results: {text_results_1}")
text_results_2 = milvus_client.search(text_embedding, field = 'text_embedding')
logger.info(f"Text-to-text search results: {text_results_2}")
次の情報が返されます。
LLM の出力には一定のランダム性があるため、この例の結果は完全には再現できない場合があります。
INFO:__main__:Text-to-image search results: [
{'id': 456882250782308942, 'distance': 1.338853359222412, 'origin': './train/Rhodesian_ridgeback/n02087394_9675.JPEG', 'image_description': 'A photo of a small dog standing on a carpet. It has brown fur and blue eyes.\nKeywords: puppy, carpet, eyes, fur color, standing'},
{'id': 456882250782308933, 'distance': 1.3568601608276367, 'origin': './train/Rhodesian_ridgeback/n02087394_6382.JPEG', 'image_description': 'This is a brown hound with drooping ears and a collar around its neck. It is looking straight ahead.\n\nKeywords: dog, brown, hound, ears, collar'},
{'id': 456882250782308940, 'distance': 1.3838427066802979, 'origin': './train/Rhodesian_ridgeback/n02087394_5846.JPEG', 'image_description': 'Two puppies are playing on a blanket. One dog is lying on top of the other, with a teddy bear in the background.\n\nKeywords: puppies, playing, blanket, teddy bear, interaction'}]
INFO:__main__:Text-to-text search results: [
{'id': 456882250782309025, 'distance': 0.6969608068466187, 'origin': './train/mongoose/n02137549_7552.JPEG', 'image_description': 'This is a close-up photo of a small brown animal. It has a round face and large eyes.\n\nKeywords: small animal, brown fur, round face, large eyes, natural background'},
{'id': 456882250782308933, 'distance': 0.7110348343849182, 'origin': './train/Rhodesian_ridgeback/n02087394_6382.JPEG', 'image_description': 'This is a brown hound with drooping ears and a collar around its neck. It is looking straight ahead.\n\nKeywords: dog, brown, hound, ears, collar'},
{'id': 456882250782308992, 'distance': 0.7725887298583984, 'origin': './train/lion/n02129165_19310.JPEG', 'image_description': 'This is a close-up photo of a lion. It has a thick mane and sharp eyes.\n\nKeywords: lion, eyes, mane, natural environment, wild animal'}]
例2:画像による検索と画像によるテキスト検索
この例では、test ディレクトリ内のライオン画像 (パス:test/lion/n02129165_13728.JPEG) を使用して類似性検索を実行します。

画像による検索と画像によるテキスト検索の両方を使用すると、画像とテキストの両方のモダリティから対象画像に関連するコンテンツを見つけられます。これにより、多次元の類似性マッチングを実現できます。
if __name__ == "__main__":
# Milvus と DashScope API を設定します
MILVUS_TOKEN = "root:****"
MILVUS_HOST = "c-0aa16b1****.milvus.aliyuncs.com"
MILVUS_PORT = "19530"
COLLECTION_NAME = "multimodal_search"
INDEX = "IVF_FLAT" # IVF_FLAT または HNSW
DASHSCOPE_API_KEY = "<YOUR_DASHSCOPE_API_KEY >"
# 手順 1: Milvus クライアントを初期化します
milvus_client = MilvusClient(MILVUS_TOKEN, MILVUS_HOST, MILVUS_PORT, INDEX, COLLECTION_NAME)
# 手順 2: マルチモーダル埋め込みモデルを初期化します
extractor = FeatureExtractor(DASHSCOPE_API_KEY)
# 手順 5: 画像による検索と画像によるテキスト検索のマルチモーダル検索例
image_query_path = "./test/lion/n02129165_13728.JPEG"
image_embedding = extractor(image_query_path, "image")
image_results_1 = milvus_client.search(image_embedding, field = 'image_embedding')
logger.info(f"Search by image results: {image_results_1}")
image_results_2 = milvus_client.search(image_embedding, field = 'text_embedding')
logger.info(f"Image-to-text search results: {image_results_2}")
次の情報が返されます。
LLM の出力には一定のランダム性があるため、この例の結果は完全には再現できない場合があります。
INFO:__main__:Search by image results: [
{'id': 456882250782308987, 'distance': 0.23892249166965485, 'origin': './train/lion/n02129165_19953.JPEG', 'image_description': 'A majestic lion stands by a rock, with trees and bushes in the background. Sunlight shines on its body.\n\nKeywords: lion, rock, forest, sunlight, wildness'},
{'id': 456882250782308989, 'distance': 0.4113130569458008, 'origin': './train/lion/n02129165_1142.JPEG', 'image_description': 'A lion rests among dense green plants. The background consists of bamboo and trees.\n\nKeywords: lion, grass, green plants, tree trunk, natural environment'},
{'id': 456882250782308984, 'distance': 0.5206397175788879, 'origin': './train/lion/n02129165_16.JPEG', 'image_description': 'The image shows a pair of lions standing on the grass. The male lion has a thick mane, while the female lion appears leaner.\n\nKeywords: lion, grass, male, female, natural environment'}]
INFO:__main__:Image-to-text search results:
[{'id': 456882250782308989, 'distance': 1.0935896635055542, 'origin': './train/lion/n02129165_1142.JPEG', 'image_description': 'A lion rests among dense green plants. The background consists of bamboo and trees.\n\nKeywords: lion, grass, green plants, tree trunk, natural environment'},
{'id': 456882250782308987, 'distance': 1.2102885246276855, 'origin': './train/lion/n02129165_19953.JPEG', 'image_description': 'A majestic lion stands by a rock, with trees and bushes in the background. Sunlight shines on its body.\n\nKeywords: lion, rock, forest, sunlight, wildness'},
{'id': 456882250782308992, 'distance': 1.2725986242294312, 'origin': './train/lion/n02129165_19310.JPEG', 'image_description': 'This is a close-up photo of a lion. It has a thick mane and sharp eyes.\n\nKeywords: lion, eyes, mane, natural environment, wild animal'}]