1from unsloth import FastVisionModel
2from PIL import Image
3import requests
4from transformers import TextStreamer
5
6# Load the model and tokenizer
7model, tokenizer = FastVisionModel.from_pretrained(
8 model_name="saishshinde15/VisionAI", # YOUR MODEL YOU USED FOR TRAINING
9 load_in_4bit=False # Set to False for 16bit LoRA
10)
11
12# Enable the model for inference
13FastVisionModel.for_inference(model)
14
15# Load the image from URL
16url = 'your image url'
17image = Image.open(requests.get(url, stream=True).raw)
18
19# Define the instruction and user query
20instruction = (
21 "You are an expert in answering questions related to the image provided: "
22 "Answer to the questions given by the user accurately by referring to the image."
23)
24query = "What is this image about?"
25
26# Create the chat message structure
27messages = [
28 {"role": "user", "content": [
29 {"type": "image"},
30 {"type": "text", "text": instruction},
31 {"type": "text", "text": query}
32 ]}
33]
34
35# Generate input text using the tokenizer's chat template
36input_text = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
37
38# Tokenize the inputs
39inputs = tokenizer(
40 image,
41 input_text,
42 add_special_tokens=False,
43 return_tensors="pt",
44).to("cuda")
45
46# Initialize the text streamer
47text_streamer = TextStreamer(tokenizer, skip_prompt=True)
48
49# Generate the response
50_ = model.generate(
51 **inputs,
52 streamer=text_streamer,
53 max_new_tokens=128,
54 use_cache=True,
55 temperature=1.5,
56 min_p=0.1
57)