Source: Phi 3 Vision Nividia Nim · GitHub · microsoft/generative-ai-for-beginners Authors: Microsoft (microsoft) Licence: MIT — https://spdx.org/licenses/MIT.html
import requests, base64
invoke_url = "https://ai.api.nvidia.com/v1/vlm/microsoft/phi-3-vision-128k-instruct"
with open("./img/demo.png", "rb") as f:
image_b64 = base64.b64encode(f.read()).decode()
len(image_b64)
assert len(image_b64) < 180_000, \
"To upload larger images, use the assets API (see docs)"
stream = False
headers = {
"Authorization": "Bearer Your Nvidia NIM API Key",
"Accept": "text/event-stream" if stream else "application/json"
}
# payload = {
# "messages": [
# {
# "role": "user",
# "content": f'Tell me what is in the picture <img src="data:image/png;base64,{image_b64}" />'
# }
# ],
# "max_tokens": 1024,
# "temperature": 0.6,
# "top_p": 1.0,
# "stream": stream
# }
payload = {
"messages": [
{
"role": "user",
"content": f'Please create Python code for image, and use plt to save the new picture under imgs/ and name it phi-3-vision.jpg. <img src="data:image/png;base64,{image_b64}" />'
}
],
"max_tokens": 1024,
"temperature": 0.6,
"top_p": 1.0,
"stream": stream
}
response = requests.post(invoke_url, headers=headers, json=payload)
if stream:
for line in response.iter_lines():
if line:
print(line.decode("utf-8"))
else:
print(response.json())
code = response.json()["choices"][0]["message"]["content"]
code
# Find the starting index of the Python code block within the generated code
# The index function locates the substring '```python' and adds 9 to skip past it
begin = code.index('```python') + 9
# Slice the code string from the calculated starting index to the end
# This removes the initial part of the string up to and including '```python'
code = code[begin:]
end = code.index('```')
code = code[:end]
code
Disclaimer: This document has been translated using the AI translation service Co-op Translator. While we strive for accuracy, please be aware that automated translations may contain errors or inaccuracies. The original document in its native language should be considered the authoritative source. For critical information, professional human translation is recommended. We are not liable for any misunderstandings or misinterpretations arising from the use of this translation.