Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from unsloth import FastVisionModel
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 7 |
+
|
| 8 |
+
# Load model and tokenizer
|
| 9 |
+
model, tokenizer = FastVisionModel.from_pretrained(
|
| 10 |
+
"0llheaven/Llama-3.2-11B-Vision-Radiology-mini",
|
| 11 |
+
load_in_4bit=True,
|
| 12 |
+
use_gradient_checkpointing="unsloth",
|
| 13 |
+
)
|
| 14 |
+
FastVisionModel.for_inference(model)
|
| 15 |
+
|
| 16 |
+
model.to(device)
|
| 17 |
+
|
| 18 |
+
def 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!
|
| 46 |
+
image_path = 'example_image.jpeg'
|
| 47 |
+
instruction = 'You are an expert radiographer. Describe accurately what you see in this image.'
|
| 48 |
+
|
| 49 |
+
image = Image.open(image_path).convert("RGB")
|
| 50 |
+
output = predict_radiology_description(image, instruction)
|
| 51 |
+
print(output)
|