|
from typing import Dict, Any, List |
|
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor |
|
from qwen_vl_utils import process_vision_info |
|
|
|
class EndpointHandler: |
|
def __init__(self, path: str = "") -> None: |
|
|
|
|
|
self.model = Qwen2VLForConditionalGeneration.from_pretrained( |
|
path, |
|
torch_dtype="auto", |
|
device_map="auto" |
|
) |
|
|
|
|
|
self.processor = AutoProcessor.from_pretrained(path) |
|
|
|
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]: |
|
|
|
messages = data.get("messages") |
|
if messages is None: |
|
raise ValueError("Input data must contain a 'messages' key with conversation data.") |
|
|
|
|
|
|
|
text_prompt = self.processor.apply_chat_template( |
|
messages, |
|
tokenize=False, |
|
add_generation_prompt=True |
|
) |
|
|
|
|
|
|
|
image_inputs, video_inputs = process_vision_info(messages) |
|
|
|
|
|
inputs = self.processor( |
|
text=[text_prompt], |
|
images=image_inputs, |
|
videos=video_inputs, |
|
padding=True, |
|
return_tensors="pt" |
|
) |
|
|
|
inputs = inputs.to(self.model.device) |
|
|
|
|
|
|
|
max_new_tokens = data.get("max_new_tokens", 128) |
|
generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens) |
|
|
|
|
|
generated_ids_trimmed = [ |
|
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) |
|
] |
|
|
|
|
|
output_text = self.processor.batch_decode( |
|
generated_ids_trimmed, |
|
skip_special_tokens=True, |
|
clean_up_tokenization_spaces=False |
|
) |
|
|
|
return {"output": output_text} |
|
|