|
import torch |
|
from transformers import LlamaForCausalLM, AutoTokenizer, AutoProcessor |
|
from PIL import Image |
|
import base64 |
|
import io |
|
|
|
|
|
model_id = "kiddobellamy/Llama_Vision" |
|
|
|
|
|
model = LlamaForCausalLM.from_pretrained( |
|
model_id, |
|
torch_dtype=torch.float16, |
|
device_map="auto", |
|
) |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(model_id) |
|
|
|
|
|
processor = AutoProcessor.from_pretrained(model_id) |
|
|
|
def handler(event, context): |
|
try: |
|
|
|
inputs = event.get('inputs', {}) |
|
image_base64 = inputs.get('image') |
|
prompt = inputs.get('prompt', '') |
|
|
|
if not image_base64 or not prompt: |
|
return {'error': 'Both "image" and "prompt" are required in inputs.'} |
|
|
|
|
|
image_bytes = base64.b64decode(image_base64) |
|
image = Image.open(io.BytesIO(image_bytes)).convert('RGB') |
|
|
|
|
|
|
|
image_inputs = processor(images=image, return_tensors="pt").to(model.device) |
|
|
|
|
|
text_inputs = tokenizer(prompt, return_tensors="pt").to(model.device) |
|
|
|
|
|
|
|
inputs = { |
|
'input_ids': text_inputs['input_ids'], |
|
'attention_mask': text_inputs['attention_mask'], |
|
|
|
|
|
} |
|
|
|
|
|
output_ids = model.generate(**inputs, max_new_tokens=50) |
|
generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True) |
|
|
|
|
|
return {'generated_text': generated_text} |
|
|
|
except Exception as e: |
|
return {'error': str(e)} |
|
|