|
import gradio as gr |
|
import torch |
|
from PIL import Image |
|
from transformers import AutoModelForImageTextToText, MllamaForConditionalGeneration, AutoProcessor |
|
from transformers import TextStreamer |
|
from torchvision.transforms import Resize |
|
from unsloth import FastVisionModel |
|
|
|
|
|
model_id = "0llheaven/Llama-3.2-11B-Vision-Radiology-mini" |
|
|
|
|
|
model = AutoModelForImageTextToText.from_pretrained( |
|
model_id, |
|
|
|
torch_dtype=torch.bfloat16, |
|
device_map="auto", |
|
) |
|
|
|
model.gradient_checkpointing_enable() |
|
|
|
processor = AutoProcessor.from_pretrained(model_id) |
|
|
|
FastVisionModel.for_inference(model) |
|
print("กำลังโหลด tokenizer...") |
|
base_model, tokenizer = FastVisionModel.from_pretrained( |
|
"unsloth/Llama-3.2-11B-Vision-Instruct", |
|
|
|
use_gradient_checkpointing = "unsloth", |
|
) |
|
|
|
|
|
def generate_description(image: Image.Image, instruction: str): |
|
image = image.convert("RGB") |
|
|
|
|
|
|
|
instruction = "You are an expert radiographer. Describe accurately what you see in this image." |
|
messages = [ |
|
{"role": "user", "content": [ |
|
{"type": "image"}, |
|
{"type": "text", "text": instruction} |
|
]} |
|
] |
|
|
|
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt=True) |
|
|
|
inputs = tokenizer( |
|
image, |
|
input_text, |
|
add_special_tokens=False, |
|
return_tensors="pt" |
|
).to(model.device) |
|
|
|
|
|
|
|
text_streamer = TextStreamer(tokenizer, skip_prompt=True) |
|
outputs = model.generate( |
|
**inputs, |
|
streamer=text_streamer, |
|
max_new_tokens=256, |
|
use_cache=True, |
|
temperature=1.5, |
|
min_p=0.1 |
|
) |
|
return tokenizer.decode(outputs[0], skip_special_tokens=True).strip() |
|
|
|
|
|
interface = gr.Interface( |
|
fn=generate_description, |
|
inputs=gr.Image(type="pil", label="Upload an Image"), |
|
outputs=gr.Textbox(label="Generated Description"), |
|
|
|
title="Radiology Image Description Generator", |
|
description="Upload an image and provide an instruction to generate a description using a vision-language model." |
|
) |
|
|
|
|
|
interface.launch() |
|
|