Spaces:
Running
on
Zero
Running
on
Zero
fixed app.py
Browse files
app.py
CHANGED
@@ -7,10 +7,10 @@ from peft import PeftModel
|
|
7 |
from PIL import Image
|
8 |
import gradio as gr
|
9 |
from huggingface_hub import login
|
|
|
10 |
|
11 |
# Basic settings
|
12 |
warnings.filterwarnings('ignore')
|
13 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
14 |
|
15 |
# Global variables
|
16 |
model = None
|
@@ -18,130 +18,115 @@ processor = None
|
|
18 |
|
19 |
# Login to Hugging Face Hub
|
20 |
if 'HUGGING_FACE_HUB_TOKEN' in os.environ:
|
21 |
-
|
22 |
-
|
23 |
else:
|
24 |
-
|
25 |
|
26 |
def load_model_and_processor():
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
)
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
offload_folder="offload" # เพิ่ม offload folder
|
53 |
-
)
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
print("โหลดโมเดลสำเร็จ!")
|
71 |
-
return True
|
72 |
-
except Exception as e:
|
73 |
-
print(f"เกิดข้อผิดพลาดในการโหลดโมเดล: {str(e)}")
|
74 |
-
return False
|
75 |
|
|
|
76 |
def process_handwriting(image):
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
Only return the transcription in Thai language."""
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
transcription = processor.decode(outputs[0], skip_special_tokens=True)
|
123 |
-
return transcription.strip()
|
124 |
-
except Exception as e:
|
125 |
-
return f"เกิดข้อผิดพลาด: {str(e)}"
|
126 |
|
127 |
# Initialize application
|
128 |
print("กำลังเริ่มต้นแอปพลิเคชัน...")
|
129 |
if load_model_and_processor():
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
demo.launch(
|
143 |
-
share=False, # ไม่แชร์ public URL
|
144 |
-
show_error=True # แสดง error messages
|
145 |
-
)
|
146 |
else:
|
147 |
-
|
|
|
7 |
from PIL import Image
|
8 |
import gradio as gr
|
9 |
from huggingface_hub import login
|
10 |
+
import spaces # เพิ่ม import spaces
|
11 |
|
12 |
# Basic settings
|
13 |
warnings.filterwarnings('ignore')
|
|
|
14 |
|
15 |
# Global variables
|
16 |
model = None
|
|
|
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 |
def load_model_and_processor():
|
27 |
+
"""โหลดโมเดลและ processor"""
|
28 |
+
global model, processor
|
29 |
+
print("กำลังโหลดโมเดลและ processor...")
|
30 |
+
try:
|
31 |
+
# Model paths
|
32 |
+
base_model_path = "meta-llama/Llama-3.2-11B-Vision-Instruct"
|
33 |
+
adapter_path = "Aekanun/thai-handwriting-llm"
|
34 |
|
35 |
+
# Load processor from base model
|
36 |
+
print("กำลังโหลด processor...")
|
37 |
+
processor = AutoProcessor.from_pretrained(
|
38 |
+
base_model_path,
|
39 |
+
use_auth_token=True
|
40 |
+
)
|
|
|
41 |
|
42 |
+
# Load base model
|
43 |
+
print("กำลังโหลด base model...")
|
44 |
+
base_model = AutoModelForVision2Seq.from_pretrained(
|
45 |
+
base_model_path,
|
46 |
+
device_map="auto",
|
47 |
+
torch_dtype=torch.float16, # เปลี่ยนกลับเป็น float16
|
48 |
+
trust_remote_code=True,
|
49 |
+
use_auth_token=True
|
50 |
+
)
|
|
|
|
|
51 |
|
52 |
+
# Load adapter
|
53 |
+
print("กำลังโหลด adapter...")
|
54 |
+
model = PeftModel.from_pretrained(
|
55 |
+
base_model,
|
56 |
+
adapter_path,
|
57 |
+
device_map="auto", # ให้จัดการ device map อัตโนมัติ
|
58 |
+
torch_dtype=torch.float16,
|
59 |
+
use_auth_token=True
|
60 |
+
)
|
61 |
+
|
62 |
+
print("โหลดโมเดลสำเร็จ!")
|
63 |
+
return True
|
64 |
+
except Exception as e:
|
65 |
+
print(f"เกิดข้อผิดพลาดในการโหลดโมเดล: {str(e)}")
|
66 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
@spaces.GPU(duration=30) # ใช้ GPU decorator กำหนดเวลาสูงสุด 30 วินาที
|
69 |
def process_handwriting(image):
|
70 |
+
"""ฟังก์ชันสำหรับ Gradio interface"""
|
71 |
+
global model, processor
|
72 |
+
|
73 |
+
if image is None:
|
74 |
+
return "กรุณาอัพโหลดรูปภ���พ"
|
75 |
+
|
76 |
+
try:
|
77 |
+
# Ensure image is in PIL format
|
78 |
+
if not isinstance(image, Image.Image):
|
79 |
+
image = Image.fromarray(image)
|
80 |
+
|
81 |
+
# Create prompt
|
82 |
+
prompt = """Transcribe the Thai handwritten text from the provided image.
|
83 |
Only return the transcription in Thai language."""
|
84 |
+
|
85 |
+
# Create model inputs
|
86 |
+
messages = [
|
87 |
+
{
|
88 |
+
"role": "user",
|
89 |
+
"content": [
|
90 |
+
{"type": "text", "text": prompt},
|
91 |
+
{"type": "image", "image": image}
|
92 |
+
],
|
93 |
+
}
|
94 |
+
]
|
95 |
+
|
96 |
+
# Process with model
|
97 |
+
text = processor.apply_chat_template(messages, tokenize=False)
|
98 |
+
inputs = processor(text=text, images=image, return_tensors="pt")
|
99 |
+
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
100 |
+
|
101 |
+
# Generate
|
102 |
+
with torch.no_grad():
|
103 |
+
outputs = model.generate(
|
104 |
+
**inputs,
|
105 |
+
max_new_tokens=256,
|
106 |
+
do_sample=False,
|
107 |
+
pad_token_id=processor.tokenizer.pad_token_id
|
108 |
+
)
|
109 |
+
|
110 |
+
# Decode output
|
111 |
+
transcription = processor.decode(outputs[0], skip_special_tokens=True)
|
112 |
+
return transcription.strip()
|
113 |
+
except Exception as e:
|
114 |
+
return f"เกิดข้อผิดพลาด: {str(e)}"
|
|
|
|
|
|
|
|
|
115 |
|
116 |
# Initialize application
|
117 |
print("กำลังเริ่มต้นแอปพลิเคชัน...")
|
118 |
if load_model_and_processor():
|
119 |
+
# Create Gradio interface
|
120 |
+
demo = gr.Interface(
|
121 |
+
fn=process_handwriting,
|
122 |
+
inputs=gr.Image(type="pil", label="อัพโหลดรูปลายมือเขียนภาษาไทย"),
|
123 |
+
outputs=gr.Textbox(label="ข้อความที่แปลงได้"),
|
124 |
+
title="Thai Handwriting Recognition",
|
125 |
+
description="อัพโหลดรูปภาพลายมือเขียนภาษาไทยเพื่อแปลงเป็นข้อความ",
|
126 |
+
examples=[["example1.jpg"], ["example2.jpg"]]
|
127 |
+
)
|
128 |
+
|
129 |
+
if __name__ == "__main__":
|
130 |
+
demo.launch(show_error=True)
|
|
|
|
|
|
|
|
|
131 |
else:
|
132 |
+
print("ไม่สามารถเริ่มต้นแอปพลิเคชันได้")
|