from transformers import Qwen2VLForConditionalGeneration, AutoProcessor from qwen_vl_utils import process_vision_info import torch import os class VisionAgent: def __init__(self): print("👁️ [Vision] Initializing Qwen2-VL-2B...") self.model_id = "Qwen/Qwen2-VL-2B-Instruct" self.device = "cuda" if torch.cuda.is_available() else "cpu" try: dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 self.model = Qwen2VLForConditionalGeneration.from_pretrained( self.model_id, torch_dtype=dtype, device_map="auto" ) self.processor = AutoProcessor.from_pretrained(self.model_id) except: self.model = None def analyze_media(self, file_path, task_hint="describe"): if not self.model: return "Vision model not loaded." media_content = {"type": "image", "image": file_path} prompt_text = "Describe this image in detail." if "ocr" in task_hint.lower(): prompt_text = "Read all text visible." messages = [{"role": "user", "content": [media_content, {"type": "text", "text": prompt_text}]}] text = 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], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt").to(self.device) gen_ids = self.model.generate(**inputs, max_new_tokens=1024) gen_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, gen_ids)] return self.processor.batch_decode(gen_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]