- Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathsample_image_embeddings.py
58 lines (46 loc) · 2.14 KB
/
sample_image_embeddings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
DESCRIPTION:
This sample demonstrates how to get image embeddings vectors for
two input images, using a synchronous client.
USAGE:
python sample_image_embeddings.py
Set these two environment variables before running the sample:
1) AZURE_AI_IMAGE_EMBEDDINGS_ENDPOINT - Your endpoint URL, in the form
https://<your-deployment-name>.<your-azure-region>.inference.ai.azure.com
where `your-deployment-name` is your unique AI Model deployment name, and
`your-azure-region` is the Azure region where your model is deployed.
2) AZURE_AI_IMAGE_EMBEDDINGS_KEY - Your model key (a 32-character string). Keep it secret.
"""
defsample_image_embeddings():
importos
importbase64
try:
endpoint=os.environ["AZURE_AI_IMAGE_EMBEDDINGS_ENDPOINT"]
key=os.environ["AZURE_AI_IMAGE_EMBEDDINGS_KEY"]
exceptKeyError:
print("Missing environment variable 'AZURE_AI_IMAGE_EMBEDDINGS_ENDPOINT' or 'AZURE_AI_IMAGE_EMBEDDINGS_KEY'")
print("Set them before running this sample.")
exit()
# [START image_embeddings]
fromazure.ai.inferenceimportImageEmbeddingsClient
fromazure.ai.inference.modelsimportEmbeddingInput
fromazure.core.credentialsimportAzureKeyCredential
withopen("sample1.png", "rb") asf:
image1: str=base64.b64encode(f.read()).decode("utf-8")
withopen("sample2.png", "rb") asf:
image2: str=base64.b64encode(f.read()).decode("utf-8")
client=ImageEmbeddingsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
response=client.embed(input=[EmbeddingInput(image=image1), EmbeddingInput(image=image2)])
foriteminresponse.data:
length=len(item.embedding)
print(
f"data[{item.index}]: length={length}, [{item.embedding[0]}, {item.embedding[1]}, "
f"..., {item.embedding[length-2]}, {item.embedding[length-1]}]"
)
# [END image_embeddings]
if__name__=="__main__":
sample_image_embeddings()