Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from PIL import Image
|
4 |
+
from transformers import MllamaForConditionalGeneration, AutoProcessor
|
5 |
+
|
6 |
+
# โหลดโมเดลและตัวประมวลผล
|
7 |
+
model_id = "0llheaven/Llama-3.2-11B-Vision-Radiology-mini"
|
8 |
+
|
9 |
+
model = MllamaForConditionalGeneration.from_pretrained(
|
10 |
+
model_id,
|
11 |
+
torch_dtype=torch.bfloat16,
|
12 |
+
device_map="auto",
|
13 |
+
)
|
14 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
15 |
+
|
16 |
+
# ฟังก์ชันประมวลผลภาพและสร้างคำบรรยาย
|
17 |
+
def generate_caption(image):
|
18 |
+
# แปลงภาพเป็น RGB และปรับขนาด
|
19 |
+
image = image.convert("RGB")
|
20 |
+
|
21 |
+
instruction = "You are an expert radiographer. Describe accurately what you see in this image."
|
22 |
+
messages = [
|
23 |
+
{"role": "user", "content": [
|
24 |
+
{"type": "image"},
|
25 |
+
{"type": "text", "text": instruction}
|
26 |
+
]}
|
27 |
+
]
|
28 |
+
|
29 |
+
input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
|
30 |
+
inputs = processor(
|
31 |
+
image,
|
32 |
+
input_text,
|
33 |
+
add_special_tokens=False,
|
34 |
+
return_tensors="pt"
|
35 |
+
).to(model.device)
|
36 |
+
|
37 |
+
# สร้างข้อความตอบกลับจากโมเดล
|
38 |
+
output = model.generate(**inputs, max_new_tokens=256, use_cache=True, temperature=1.5, min_p=0.1)
|
39 |
+
return processor.decode(output[0])
|
40 |
+
|
41 |
+
# สร้างอินเตอร์เฟซด้วย Gradio
|
42 |
+
with gr.Blocks() as demo:
|
43 |
+
gr.Markdown("# Radiology Image Captioning")
|
44 |
+
with gr.Row():
|
45 |
+
image_input = gr.Image(type="pil", label="Upload Image")
|
46 |
+
output_text = gr.Textbox(label="Generated Caption")
|
47 |
+
title="Medical Vision Analysis"
|
48 |
+
generate_button = gr.Button("Generate Caption")
|
49 |
+
|
50 |
+
# กำหนดการทำงานเมื่อกดปุ่ม
|
51 |
+
generate_button.click(fn=generate_caption, inputs=image_input, outputs=output_text)
|
52 |
+
|
53 |
+
# รันแอป
|
54 |
+
demo.launch()
|