Views
No views yet
1from unsloth import FastVisionModel
2from PIL import Image
3import numpy as np
4import torch
5
6device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
8# Load model and tokenizer
9model, tokenizer = FastVisionModel.from_pretrained(
10 "0llheaven/Llama-3.2-CXR-Instruct-V1",
11 load_in_4bit=True,
12 use_gradient_checkpointing="unsloth",
13)
14FastVisionModel.for_inference(model)
15
16model.to(device)
17
18def predict_radiology_description(image, instruction):
19 try:
20 messages = [{"role": "user", "content": [
21 {"type": "image"},
22 {"type": "text", "text": instruction}
23 ]}]
24 input_text = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
25
26 inputs = tokenizer(
27 image,
28 input_text,
29 add_special_tokens=False,
30 return_tensors="pt",
31 ).to(device)
32
33 output_ids = model.generate(
34 **inputs,
35 max_new_tokens=256,
36 temperature=1.5,
37 min_p=0.1
38 )
39
40 generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
41 return generated_text.replace("assistant", "\n\nassistant").strip()
42 except Exception as e:
43 return f"Error: {str(e)}"
44
45# Example of usage!
46image_path = 'example_image.jpeg'
47instruction = 'You are an expert radiographer. Describe accurately what you see in this image.'
48
49image = Image.open(image_path).convert("RGB")
50output = predict_radiology_description(image, instruction)
51print(output)