Spaces:
Runtime error
Runtime error
rev app
Browse files
app.py
CHANGED
@@ -1,53 +1,52 @@
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import warnings
|
3 |
import torch
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
8 |
import gradio as gr
|
9 |
from huggingface_hub import login
|
10 |
-
import spaces
|
|
|
11 |
|
12 |
-
# Basic settings
|
13 |
warnings.filterwarnings('ignore')
|
14 |
|
15 |
-
# Global variables
|
16 |
model = None
|
17 |
-
|
18 |
|
19 |
-
# Login to Hugging Face Hub
|
20 |
if 'HUGGING_FACE_HUB_TOKEN' in os.environ:
|
21 |
print("กำลังเข้าสู่ระบบ Hugging Face Hub...")
|
22 |
login(token=os.environ['HUGGING_FACE_HUB_TOKEN'])
|
23 |
else:
|
24 |
print("คำเตือน: ไม่พบ HUGGING_FACE_HUB_TOKEN")
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
global model,
|
29 |
-
print("
|
30 |
try:
|
31 |
-
|
32 |
-
from unsloth import FastVisionModel
|
33 |
-
from transformers import AutoModelForVision2Seq, TextStreamer
|
34 |
-
###
|
35 |
-
# Model paths
|
36 |
-
### base_model_path = "meta-llama/Llama-3.2-11B-Vision-Instruct"
|
37 |
-
### adapter_path = "Aekanun/Llama-3.2-11B-Vision-Instruct-XRay"
|
38 |
-
|
39 |
-
# Load processor from base model
|
40 |
-
print("กำลังโหลด processor...")
|
41 |
-
###processor = AutoProcessor.from_pretrained(
|
42 |
-
### base_model_path,
|
43 |
-
### use_auth_token=True
|
44 |
-
###)
|
45 |
-
|
46 |
base_model, tokenizer = FastVisionModel.from_pretrained(
|
47 |
"unsloth/Llama-3.2-11B-Vision-Instruct",
|
48 |
use_gradient_checkpointing = "unsloth"
|
49 |
)
|
50 |
-
|
51 |
print("โหลด base model และ tokenizer สำเร็จ กำลังโหลดโมเดลที่ fine-tune...")
|
52 |
|
53 |
# ปิด FastVisionModel และโหลด model โดยตรง
|
@@ -66,68 +65,58 @@ def load_model_and_processor():
|
|
66 |
print(f"เกิดข้อผิดพลาดในการโหลดโมเดล: {str(e)}")
|
67 |
return False
|
68 |
|
69 |
-
@spaces.GPU(duration=30)
|
70 |
-
def
|
71 |
-
|
72 |
-
global model, processor
|
73 |
|
74 |
if image is None:
|
75 |
return "กรุณาอัพโหลดรูปภาพ"
|
76 |
|
77 |
try:
|
78 |
-
# Ensure image is in PIL format
|
79 |
if not isinstance(image, Image.Image):
|
80 |
image = Image.fromarray(image)
|
81 |
-
|
82 |
-
|
83 |
-
prompt = """Transcribe the Thai handwritten text from the provided image.
|
84 |
-
Only return the transcription in Thai language."""
|
85 |
-
|
86 |
-
# Create model inputs
|
87 |
messages = [
|
88 |
-
{
|
89 |
-
"
|
90 |
-
"
|
91 |
-
|
92 |
-
{"type": "image", "image": image}
|
93 |
-
],
|
94 |
-
}
|
95 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
-
|
98 |
-
text = processor.apply_chat_template(messages, tokenize=False)
|
99 |
-
inputs = processor(text=text, images=image, return_tensors="pt")
|
100 |
-
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
101 |
-
|
102 |
-
# Generate
|
103 |
-
with torch.no_grad():
|
104 |
-
outputs = model.generate(
|
105 |
-
**inputs,
|
106 |
-
max_new_tokens=512, ##256
|
107 |
-
do_sample=False,
|
108 |
-
pad_token_id=processor.tokenizer.pad_token_id
|
109 |
-
)
|
110 |
|
111 |
-
# Decode output
|
112 |
-
transcription = processor.decode(outputs[0], skip_special_tokens=True)
|
113 |
-
return transcription.strip()
|
114 |
except Exception as e:
|
115 |
return f"เกิดข้อผิดพลาด: {str(e)}"
|
116 |
|
117 |
-
# Initialize application
|
118 |
print("กำลังเริ่มต้นแอปพลิเคชัน...")
|
119 |
-
if
|
120 |
-
# Create Gradio interface
|
121 |
demo = gr.Interface(
|
122 |
-
fn=
|
123 |
-
inputs=gr.Image(type="pil"
|
124 |
-
outputs=gr.Textbox(
|
125 |
-
title="
|
126 |
-
description="อัพโหลดรูปภาพลายมือเขียนภาษาไทยเพื่อแปลงเป็นข้อความ",
|
127 |
-
examples=[["example1.jpg"], ["example2.jpg"]]
|
128 |
)
|
129 |
|
130 |
if __name__ == "__main__":
|
131 |
-
demo.launch(
|
132 |
else:
|
133 |
print("ไม่สามารถเริ่มต้นแอปพลิเคชันได้")
|
|
|
1 |
import os
|
2 |
+
import sys
|
3 |
+
import subprocess
|
4 |
+
|
5 |
+
def install_packages():
|
6 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "unsloth-zoo"])
|
7 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-deps", "git+https://github.com/unslothai/unsloth.git"])
|
8 |
+
|
9 |
+
try:
|
10 |
+
install_packages()
|
11 |
+
except Exception as e:
|
12 |
+
print(f"Failed to install packages: {e}")
|
13 |
+
|
14 |
import warnings
|
15 |
import torch
|
16 |
+
|
17 |
+
# เปลี่ยนแปลงที่ 1: เพิ่มการตั้งค่า dynamo ก่อน import unsloth
|
18 |
+
torch._dynamo.config.suppress_errors = True
|
19 |
+
torch._dynamo.config.verbose = False
|
20 |
+
|
21 |
+
from unsloth import FastVisionModel
|
22 |
+
from transformers import TextStreamer
|
23 |
import gradio as gr
|
24 |
from huggingface_hub import login
|
25 |
+
import spaces
|
26 |
+
from PIL import Image
|
27 |
|
|
|
28 |
warnings.filterwarnings('ignore')
|
29 |
|
|
|
30 |
model = None
|
31 |
+
tokenizer = None
|
32 |
|
|
|
33 |
if 'HUGGING_FACE_HUB_TOKEN' in os.environ:
|
34 |
print("กำลังเข้าสู่ระบบ Hugging Face Hub...")
|
35 |
login(token=os.environ['HUGGING_FACE_HUB_TOKEN'])
|
36 |
else:
|
37 |
print("คำเตือน: ไม่พบ HUGGING_FACE_HUB_TOKEN")
|
38 |
|
39 |
+
# เปลี่ยนแปลงที่ 2: ลบ use_auth_token ออกจากการโหลดโมเดล
|
40 |
+
def load_model():
|
41 |
+
global model, tokenizer
|
42 |
+
print("กำลังโหลดโมเดล...")
|
43 |
try:
|
44 |
+
# โหลด base model และ tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
base_model, tokenizer = FastVisionModel.from_pretrained(
|
46 |
"unsloth/Llama-3.2-11B-Vision-Instruct",
|
47 |
use_gradient_checkpointing = "unsloth"
|
48 |
)
|
49 |
+
|
50 |
print("โหลด base model และ tokenizer สำเร็จ กำลังโหลดโมเดลที่ fine-tune...")
|
51 |
|
52 |
# ปิด FastVisionModel และโหลด model โดยตรง
|
|
|
65 |
print(f"เกิดข้อผิดพลาดในการโหลดโมเดล: {str(e)}")
|
66 |
return False
|
67 |
|
68 |
+
@spaces.GPU(duration=30)
|
69 |
+
def process_image(image):
|
70 |
+
global model, tokenizer
|
|
|
71 |
|
72 |
if image is None:
|
73 |
return "กรุณาอัพโหลดรูปภาพ"
|
74 |
|
75 |
try:
|
|
|
76 |
if not isinstance(image, Image.Image):
|
77 |
image = Image.fromarray(image)
|
78 |
+
|
79 |
+
instruction = "You are an expert radiographer. Describe accurately what you see in this image."
|
|
|
|
|
|
|
|
|
80 |
messages = [
|
81 |
+
{"role": "user", "content": [
|
82 |
+
{"type": "image"},
|
83 |
+
{"type": "text", "text": instruction}
|
84 |
+
]}
|
|
|
|
|
|
|
85 |
]
|
86 |
+
|
87 |
+
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
|
88 |
+
inputs = tokenizer(
|
89 |
+
image,
|
90 |
+
input_text,
|
91 |
+
add_special_tokens=False,
|
92 |
+
return_tensors="pt",
|
93 |
+
).to("cuda")
|
94 |
+
|
95 |
+
text_streamer = TextStreamer(tokenizer, skip_prompt=True)
|
96 |
+
outputs = model.generate(
|
97 |
+
**inputs,
|
98 |
+
streamer=text_streamer,
|
99 |
+
max_new_tokens=128,
|
100 |
+
use_cache=True,
|
101 |
+
temperature=1.5,
|
102 |
+
min_p=0.1
|
103 |
+
)
|
104 |
|
105 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
|
|
|
|
|
|
107 |
except Exception as e:
|
108 |
return f"เกิดข้อผิดพลาด: {str(e)}"
|
109 |
|
|
|
110 |
print("กำลังเริ่มต้นแอปพลิเคชัน...")
|
111 |
+
if load_model():
|
|
|
112 |
demo = gr.Interface(
|
113 |
+
fn=process_image,
|
114 |
+
inputs=gr.Image(type="pil"),
|
115 |
+
outputs=gr.Textbox(),
|
116 |
+
title="Medical Vision Analysis"
|
|
|
|
|
117 |
)
|
118 |
|
119 |
if __name__ == "__main__":
|
120 |
+
demo.launch()
|
121 |
else:
|
122 |
print("ไม่สามารถเริ่มต้นแอปพลิเคชันได้")
|