赞
踩
本教程在前述教程(DashVector + ModelScope玩转多模态检索)的基础之上,基于DashScope上新推出的ONE-PEACE通用多模态表征模型结合向量检索服务DashVector来对多模态检索进行升级,接下来我们将展示更丰富的多模态检索能力。
主要分为两个阶段:
多模态数据Embedding入库。通过ONE-PEACE模型服务Embedding接口将多种模态的数据集数据转化为高维向量。
多模态Query检索。基于ONE-PEACE模型提供的多模态Embedding能力,我们可以自由组合不同模态的输入,例如单文本、文本+音频、音频+图片等多模态输入,获取Embedding向量后通过DashVector跨模态检索相似结果。
开通灵积模型服务,并获得API-KEY:开通DashScope并创建API-KEY
开通DashVector向量检索服务,并获得API-KEY:API-KEY管理
本教程使用的多模态推理模型服务是DashScope最新的ONE-PEACE模型。ONE-PEACE是一个图文音三模态通用表征模型,在语义分割、音文检索、音频分类和视觉定位几个任务都达到了新SOTA表现,在视频分类、图像分类图文检索、以及多模态经典benchmark也都取得了比较领先的结果。模型相关的环境依赖如下:
说明
需要提前安装Python3.7 及以上版本,请确保相应的python版本。
- # 安装 dashscope 和 dashvector sdk
- pip3 install dashscope dashvector
说明
由于DashScope的ONE-PEACE模型服务当前只支持URL形式的图片、音频输入,因此需要将数据集提前上传到公共网络存储(例如 oss/s3),并获取对应图片、音频的url地址列表。
当前示例场景使用ImageNet-1k的validation数据集作为入库的图片数据集,将原始图片数据Embedding入库。检索时使用ESC-50数据集作为音频输入,文本和图片输入由用户自定义,用户也可对不同模态数据自由组合。
说明
本教程所涉及的 your-xxx-api-key 以及 your-xxx-cluster-endpoint,均需要替换为您自己的API-KAY及CLUSTER_ENDPOINT后,代码才能正常运行。
ImageNet-1k的validation数据集包含50000张标注好的图片数据,其中包含1000个类别,每个类别50张图片,这里我们基于ONE-PEACE模型提取原始图片的Embedding向量入库,另外为了方便后续的图片展示,我们也将原始图片的url一起入库。代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client, Doc, DashVectorException
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
- # 由于 ONE-PEACE 模型服务当前只支持 url 形式的图片、音频输入,因此用户需要将数据集提前上传到
- # 公共网络存储(例如 oss/s3),并获取对应图片、音频的 url 列表。
- # 该文件每行存储数据集单张图片的公共 url,与当前python脚本位于同目录下
- IMAGENET1K_URLS_FILE_PATH = "imagenet1k-urls.txt"
-
-
- def index_image():
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 创建集合:指定集合名称和向量维度, ONE-PEACE 模型产生的向量统一为 1536 维
- rsp = client.create('imagenet1k_val_embedding', 1536)
- if not rsp:
- raise DashVectorException(rsp.code, reason=rsp.message)
-
- # 调用 dashscope ONE-PEACE 模型生成图片 Embedding,并插入 dashvector
- collection = client.get('imagenet1k_val_embedding')
- with open(IMAGENET1K_URLS_FILE_PATH, 'r') as file:
- for i, line in enumerate(file):
- url = line.strip('\n')
- input = [{'image': url}]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- print(f"ONE-PEACE failed to generate embedding of {url}, result: {result}")
- continue
- embedding = result.output["embedding"]
- collection.insert(
- Doc(
- id=str(i),
- vector=embedding,
- fields={'image_url': url}
- )
- )
- if (i + 1) % 100 == 0:
- print(f"---- Succeeded to insert {i + 1} image embeddings")
-
-
- if __name__ == '__main__':
- index_image()
说明
上述代码需要访问DashScope的ONE-PEACE多模态Embedding模型,总体运行速度视用户开通该服务的qps有所不同。
因图片大小影响ONE-PEACE模型获取Embedding的成功与否,上述代码运行后最终入库数据可能小于50000条。
对于单文本模态检索,可以通过ONE-PEACE模型获取文本Embedding向量,再通过DashVector向量检索服务的检索接口,快速检索相似的底库图片。这里文本query是猫 “cat”,代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image(image_list):
- for img in image_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
-
-
- def text_search(input_text):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('imagenet1k_val_embedding')
-
- # 获取文本 query 的 Embedding 向量
- input = [{'text': input_text}]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- text_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(text_vector, topk=3)
- image_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img = Image.open(urlopen(img_url))
- image_list.append(img)
- return image_list
-
-
- if __name__ == '__main__':
- """文本检索"""
- # 猫
- text_query = "cat"
- show_image(text_search(text_query))
运行上述代码,检索结果如下:
单音频模态检索与文本检索类似,这里音频query取自ESC-50的“猫叫声”片段,代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image(image_list):
- for img in image_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
-
-
- def audio_search(input_audio):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('imagenet1k_val_embedding')
-
- # 获取音频 query 的 Embedding 向量
- input = [{'audio': input_audio}]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- audio_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(audio_vector, topk=3)
- image_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img = Image.open(urlopen(img_url))
- image_list.append(img)
- return image_list
-
-
- if __name__ == '__main__':
- """音频检索"""
- # 猫叫声
- audio_url = "http://proxima-internal.oss-cn-zhangjiakou.aliyuncs.com/audio-dataset/esc-50/1-47819-A-5.wav"
- show_image(audio_search(audio_url))
运行上述代码,检索结果如下:
接下来,我们尝试“文本+音频”联合模态检索,同上,首先通过ONE-PEACE模型获取“文本+音频”输入的Embedding向量,再通过DashVector向量检索服务检索结果。这里的文本query选取的是草地“grass”,音频query依然选择的是ESC-50的“猫叫声”片段。代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image(image_list):
- for img in image_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
-
-
- def text_audio_search(input_text, input_audio):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('imagenet1k_val_embedding')
-
- # 获取文本+音频 query 的 Embedding 向量
- input = [
- {'text': input_text},
- {'audio': input_audio},
- ]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- text_audio_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(text_audio_vector, topk=3)
- image_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img = Image.open(urlopen(img_url))
- image_list.append(img)
- return image_list
-
-
- if __name__ == '__main__':
- """文本+音频检索"""
- # 草地
- text_query = "grass"
- # 猫叫声
- audio_url = "http://proxima-internal.oss-cn-zhangjiakou.aliyuncs.com/audio-dataset/esc-50/1-47819-A-5.wav"
- show_image(text_audio_search(text_query, audio_url))
运行上述代码,检索结果如下:
我们再尝试下“图片+音频”联合模态检索,与前述“文本+音频”检索类似,这里的图片选取的是草地图像(需先上传到公共网络存储并获取 url),音频query依然选择的是ESC-50的“猫叫声”片段。代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image(image_list):
- for img in image_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
-
-
- def image_audio_search(input_image, input_audio):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('imagenet1k_val_embedding')
-
- # 获取图片+音频 query 的 Embedding 向量
- # 注意,这里音频 audio 模态输入的权重参数 factor 为 2(默认为1)
- # 目的是为了增大音频输入(猫叫声)对检索结果的影响
- input = [
- {'factor': 1, 'image': input_image},
- {'factor': 2, 'audio': input_audio},
- ]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- image_audio_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(image_audio_vector, topk=3)
- image_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img = Image.open(urlopen(img_url))
- image_list.append(img)
- return image_list
-
-
- if __name__ == '__main__':
- """图片+音频检索"""
- # 草地
- image_url = "http://proxima-internal.oss-cn-zhangjiakou.aliyuncs.com/image-dataset/grass-field.jpeg"
- # 猫叫声
- audio_url = "http://proxima-internal.oss-cn-zhangjiakou.aliyuncs.com/audio-dataset/esc-50/1-47819-A-5.wav"
- show_image(image_audio_search(image_url, audio_url))
输入示意图如下:
运行代码,检索结果如下:
上述场景里作为检索底库数据的是单模态的图片数据,这里我们也可以将多种模态的数据同时通过ONE-PEACE模型获取Embedding向量,将Embedding向量作为检索库数据入库检索,观察检索效果。
本示例场景使用微软COCO在Captioning场景下的validation数据集,将图片以及对应的图片描述caption文本两种模态数据一起Embedding入库。对于检索时输入的图片、音频与文本等多模态数据,用户可以自定义,也可以使用公共数据集的数据。
说明
本教程所涉及的 your-xxx-api-key 以及 your-xxx-cluster-endpoint,均需要替换为您自己的API-KAY及CLUSTER_ENDPOINT后,代码才能正常运行。
微软COCO的Captioning validation验证集包含5000张标注良好的图片及对应的说明文本,这里我们需要通过 DashScope的ONE-PEACE模型提取数据集的“图片+文本”的Embedding向量入库,另外为了方便后续的图片展示,我们也将原始图片url和对应caption文本一起入库。代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client, Doc, DashVectorException
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
- # 由于 ONE-PEACE 模型服务当前只支持 url 形式的图片、音频输入,因此用户需要将数据集提前上传到
- # 公共网络存储(例如 oss/s3),并获取对应图片、音频的 url 列表。
- # 该文件每行存储数据集单张图片的公共 url 和对应的 caption 文本,以`;`分割
- COCO_CAPTIONING_URLS_FILE_PATH = "cocoval5k-urls-captions.txt"
-
-
- def index_image_text():
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 创建集合:指定集合名称和向量维度, ONE-PEACE 模型产生的向量统一为 1536 维
- rsp = client.create('coco_val_embedding', 1536)
- if not rsp:
- raise DashVectorException(rsp.code, reason=rsp.message)
-
- # 调用 dashscope ONE-PEACE 模型生成图片 Embedding,并插入 dashvector
- collection = client.get('coco_val_embedding')
- with open(COCO_CAPTIONING_URLS_FILE_PATH, 'r') as file:
- for i, line in enumerate(file):
- url, caption = line.strip('\n').split(";")
- input = [
- {'text': caption},
- {'image': url},
- ]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- print(f"ONE-PEACE failed to generate embedding of {url}, result: {result}")
- continue
- embedding = result.output["embedding"]
- collection.insert(
- Doc(
- id=str(i),
- vector=embedding,
- fields={'image_url': url, 'image_caption': caption}
- )
- )
- if (i + 1) % 20 == 0:
- print(f"---- Succeeded to insert {i + 1} image embeddings")
-
-
- if __name__ == '__main__':
- index_image_text()
说明
上述代码需要访问DashScope的ONE-PEACE多模态Embedding模型,总体运行速度视用户开通该服务的qps有所不同。
首先我们尝试单文本模态检索。代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image_text(image_text_list):
- for img, cap in image_text_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
- print(cap)
-
-
- def text_search(input_text):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('coco_val_embedding')
-
- # 获取文本 query 的 Embedding 向量
- input = [{'text': input_text}]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- text_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(text_vector, topk=3)
- image_text_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img_cap = doc.fields['image_caption']
- img = Image.open(urlopen(img_url))
- image_text_list.append((img, img_cap))
- return image_text_list
-
-
- if __name__ == '__main__':
- """文本检索"""
- # 狗
- text_query = "dog"
- show_image_text(text_search(text_query))
运行上述代码,检索结果如下:
The fur on this dog is long enough to cover his eyes. | A picture of a dog on a bed. | A dog going to the bathroom in the park. |
我们再尝试单音频模态检索。我们使用ESC-50数据集的“狗叫声片段”作为音频输入,代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image_text(image_text_list):
- for img, cap in image_text_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
- print(cap)
-
-
- def audio_search(input_audio):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('coco_val_embedding')
-
- # 获取音频 query 的 Embedding 向量
- input = [{'audio': input_audio}]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- audio_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(audio_vector, topk=3)
- image_text_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img_cap = doc.fields['image_caption']
- img = Image.open(urlopen(img_url))
- image_text_list.append((img, img_cap))
- return image_text_list
-
-
- if __name__ == '__main__':
- """"音频检索"""
- # dog bark
- audio_url = "http://proxima-internal.oss-cn-zhangjiakou.aliyuncs.com/audio-dataset/esc-50/1-100032-A-0.wav"
- show_image_text(audio_search(audio_url))
运行上述代码,检索结果如下:
The fur on this dog is long enough to cover his eyes. | A dog standing on a bed in a room. | A small black and white dog with the wind blowing through it's hair. |
进一步的,我们尝试使用“文本+音频”进行双模态检索。这里使用ESC-50数据集的“狗叫声片段”作为音频输入,另外使用“beach”作为文本输入,代码示例如下:
- import dashscope
- from dashscope import MultiModalEmbedding
- from dashvector import Client
- from urllib.request import urlopen
- from PIL import Image
-
- dashscope.api_key = '{your-dashscope-api-key}'
-
-
- def show_image_text(image_text_list):
- for img, cap in image_text_list:
- # 注意:show() 函数在 Linux 服务器上可能需要安装必要的图像浏览器组件才生效
- # 建议在支持 jupyter notebook 的服务器上运行该代码
- img.show()
- print(cap)
-
-
- def text_audio_search(input_text, input_audio):
- # 初始化 dashvector client
- client = Client(
- api_key='{your-dashvector-api-key}',
- endpoint='{your-dashvector-cluster-endpoint}'
- )
-
- # 获取上述入库的集合
- collection = client.get('coco_val_embedding')
-
- # 获取文本+音频 query 的 Embedding 向量
- input = [
- {'text': input_text},
- {'audio': input_audio},
- ]
- result = MultiModalEmbedding.call(model=MultiModalEmbedding.Models.multimodal_embedding_one_peace_v1,
- input=input,
- auto_truncation=True)
- if result.status_code != 200:
- raise Exception(f"ONE-PEACE failed to generate embedding of {input}, result: {result}")
- text_audio_vector = result.output["embedding"]
-
- # DashVector 向量检索
- rsp = collection.query(text_audio_vector, topk=3)
- image_text_list = list()
- for doc in rsp:
- img_url = doc.fields['image_url']
- img_cap = doc.fields['image_caption']
- img = Image.open(urlopen(img_url))
- image_text_list.append((img, img_cap))
- return image_text_list
-
-
- if __name__ == '__main__':
- """文本+音频检索"""
- text_query = "beach"
- # 狗叫声
- audio_url = "http://proxima-internal.oss-cn-zhangjiakou.aliyuncs.com/audio-dataset/esc-50/1-100032-A-0.wav"
- show_image_text(text_audio_search(text_query, audio_url))
运行上述代码,检索结果如下:
a couple of dogs stand on a beach next to some water. | A view of a beach that has some people sitting on it. | people enjoy swimming in the waves of the ocean on a sunny day at the beach. |
观察上述检索结果,发现后两张图的重点更多的是在展示 “beach” 文本输入对应的沙滩,而 “狗叫声片段”音频输入指示的狗的图片形象则不明显,其中第二张图需要放大后才可以看到图片中站立在水中的狗,第三张图中基本没有狗的形象。
对于上述情况,我们可以通过调整不同输入的权重来设置mbedding向量中哪种模态占更大的比重,从而在检索中突出重点。例如对于上述代码,我们可以给予“狗叫声片段”更大的权重,重点突出检索结果里狗的形象。
- # 其他代码一致
-
- # 通过 `factor` 参数来调整不同模态输入的权重,默认为 1,这里设置 audio 为 2
- input = [
- {'factor': 1, 'text': input_text},
- {'factor': 2, 'audio': input_audio},
- ]
替换 input
后,运行上述代码,结果如下:
a couple of dogs stand on a beach next to some water. | A beautiful woman in a bikini surfing with her dog. | A small black and white dog with the wind blowing through it's hair. |
本文结合DashScope的ONE-PEACE模型的和DashVector向量检索服务向大家展示了丰富多样的多模态检索示例,得益于ONE-PEACE模型优秀的多模态Embedding能力和DashVector强大的向量检索能力,我们能初步看到AI多模态检索令人惊喜的效果。
本文的范例中,我们的向量检索服务,模型服务以及数据均可以公开获取,我们提供的示例也只是有限的展示了多模态检索的效果,非常欢迎大家来体验,自由发掘多模态检索的潜力。
免费体验阿里云高性能向量检索服务:https://www.aliyun.com/product/ai/dashvector
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。