|
|
|
import sys |
|
print("Python Version:", sys.version) |
|
from dora import DoraStatus |
|
import pyarrow as pa |
|
from transformers import AutoProcessor, AutoModelForCausalLM,AutoTokenizer |
|
from PIL import Image |
|
import torch |
|
import gc |
|
|
|
|
|
CAMERA_WIDTH = 1280 |
|
CAMERA_HEIGHT = 720 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained( |
|
'/mnt/c/Bunny-v1_0-2B-zh/', |
|
trust_remote_code=True) |
|
BAD_WORDS_IDS =tokenizer( |
|
["<image>", "<fake_token_around_image>"], add_special_tokens=False |
|
).input_ids |
|
EOS_WORDS_IDS = tokenizer( |
|
"<end_of_utterance>", add_special_tokens=False |
|
).input_ids + [tokenizer.eos_token_id] |
|
|
|
|
|
device = 'cuda' |
|
torch.set_default_device(device) |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
'/mnt/c/Bunny-v1_0-2B-zh/', |
|
torch_dtype=torch.float16, |
|
device_map='auto', |
|
trust_remote_code=True |
|
) |
|
|
|
print("load bunny model finish") |
|
|
|
|
|
def ask_vlm(image, instruction): |
|
global model |
|
prompts = [ |
|
"User:", |
|
image, |
|
f"{instruction}.<end_of_utterance>\n", |
|
"Assistant:", |
|
] |
|
inputs = {k: torch.tensor(v).to("cuda") for k, v in PROCESSOR(prompts).items()} |
|
|
|
generated_ids = model.generate( |
|
**inputs, |
|
bad_words_ids=BAD_WORDS_IDS, |
|
max_new_tokens=25, |
|
repetition_penalty=1.2, |
|
) |
|
generated_texts = PROCESSOR.batch_decode(generated_ids, skip_special_tokens=True) |
|
|
|
gc.collect() |
|
torch.cuda.empty_cache() |
|
return generated_texts[0].split("\nAssistant: ")[1] |
|
|
|
|
|
import time |
|
|
|
|
|
class Operator: |
|
def __init__(self): |
|
self.image = None |
|
self.text = None |
|
|
|
def on_event( |
|
self, |
|
dora_event, |
|
send_output, |
|
) -> DoraStatus: |
|
if dora_event["type"] == "INPUT": |
|
if dora_event["id"] == "image": |
|
self.image = ( |
|
dora_event["value"] |
|
.to_numpy() |
|
.reshape((CAMERA_HEIGHT, CAMERA_WIDTH, 3)) |
|
) |
|
elif dora_event["id"] == "text": |
|
self.text = dora_event["value"][0].as_py() |
|
output = ask_vlm(self.image, self.text).lower() |
|
send_output( |
|
"speak", |
|
pa.array([output]), |
|
) |
|
if "yes" in output: |
|
send_output( |
|
"control", |
|
pa.array([0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 0.0]), |
|
) |
|
time.sleep(2) |
|
send_output( |
|
"control", |
|
pa.array([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]), |
|
) |
|
elif "no" in output: |
|
send_output( |
|
"control", |
|
pa.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0]), |
|
) |
|
time.sleep(2) |
|
send_output( |
|
"control", |
|
pa.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), |
|
) |
|
|
|
return DoraStatus.CONTINUE |
|
|