File size: 4,021 Bytes
034b730 |
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
from dora import DoraStatus
import os
import pyarrow as pa
import requests
import os
import base64
import requests
from io import BytesIO
import numpy as np
import cv2
def encode_numpy_image(np_image):
# Convert the NumPy array to a PIL Image
cv2.resize(np_image, (512, 512))
_, buffer = cv2.imencode(
".png", np_image
) # You can change '.png' to another format if needed
# Convert the buffer to a byte stream
byte_stream = BytesIO(buffer)
# Encode the byte stream to base64
base64_encoded_image = base64.b64encode(byte_stream.getvalue()).decode("utf-8")
return base64_encoded_image
CAMERA_WIDTH = 640
CAMERA_HEIGHT = 480
API_KEY = os.getenv("OPENAI_API_KEY")
MESSAGE_SENDER_TEMPLATE = """
You control a robot. Don't get too close to objects.
{user_message}
Respond with only one of the following actions:
- FORWARD
- BACKWARD
- TURN_RIGHT
- TURN_LEFT
- NOD_YES
- NOD_NO
- STOP
You're last 5 actions where:
{actions}
"""
import time
def understand_image(image, user_message, actions):
# Getting the base64 string
base64_image = encode_numpy_image(image)
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}"}
now = time.time()
payload = {
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": MESSAGE_SENDER_TEMPLATE.format(
user_message="\n".join(user_message),
actions="\n".join(actions[:-5]),
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
"detail": "low",
},
},
],
}
],
"max_tokens": 50,
}
response = requests.post(
"https://api.openai.com/v1/chat/completions", headers=headers, json=payload
)
print("resp:", time.time() - now)
return response.json()["choices"][0]["message"]["content"]
class Operator:
def __init__(self):
self.actions = []
self.instruction = []
def on_event(
self,
dora_event,
send_output,
) -> DoraStatus:
if dora_event["type"] == "INPUT":
if dora_event["id"] == "image":
image = (
dora_event["value"]
.to_numpy()
.reshape((CAMERA_HEIGHT, CAMERA_WIDTH, 3))
.copy()
)
output = understand_image(image, self.instruction, self.actions)
self.actions.append(output)
print("response: ", output, flush=True)
send_output(
"assistant_message",
pa.array([f"{output}"]),
dora_event["metadata"],
)
elif dora_event["id"] == "instruction":
self.instruction.append(dora_event["value"][0].as_py())
print("instructions: ", self.instruction, flush=True)
return DoraStatus.CONTINUE
if __name__ == "__main__":
op = Operator()
# Path to the current file
current_file_path = __file__
# Directory of the current file
current_directory = os.path.dirname(current_file_path)
path = current_directory + "/test_image.jpg"
op.on_event(
{
"type": "INPUT",
"id": "code_modifier",
"value": pa.array(
[
{
"path": path,
"user_message": "change planning to make gimbal follow bounding box ",
},
]
),
"metadata": [],
},
print,
)
|