Spaces:
Running
on
Zero
Running
on
Zero
fixing
Browse files
app.py
CHANGED
@@ -2,7 +2,7 @@ import os
|
|
2 |
import warnings
|
3 |
import torch
|
4 |
import gc
|
5 |
-
from transformers import
|
6 |
from PIL import Image
|
7 |
import gradio as gr
|
8 |
from huggingface_hub import login
|
@@ -11,39 +11,57 @@ warnings.filterwarnings('ignore')
|
|
11 |
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
|
12 |
|
13 |
# Global variables
|
14 |
-
|
|
|
15 |
|
16 |
if torch.cuda.is_available():
|
17 |
torch.cuda.empty_cache()
|
18 |
gc.collect()
|
19 |
print("เคลียร์ CUDA cache เรียบร้อยแล้ว")
|
20 |
|
21 |
-
def
|
22 |
-
"""
|
23 |
-
global
|
24 |
-
print("
|
25 |
|
26 |
try:
|
|
|
|
|
27 |
hub_model_path = "Aekanun/thai-handwriting-llm"
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
token=os.environ.get('HUGGING_FACE_HUB_TOKEN')
|
36 |
)
|
|
|
37 |
|
38 |
-
print("โหลด pipeline สำเร็จ!")
|
39 |
return True
|
40 |
except Exception as e:
|
41 |
-
print(f"
|
42 |
return False
|
43 |
|
44 |
def process_handwriting(image):
|
45 |
"""ฟังก์ชันสำหรับ Gradio interface"""
|
46 |
-
global
|
47 |
|
48 |
if image is None:
|
49 |
return "กรุณาอัพโหลดรูปภาพ"
|
@@ -57,33 +75,46 @@ def process_handwriting(image):
|
|
57 |
if image.mode != "RGB":
|
58 |
image = image.convert("RGB")
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
except Exception as e:
|
75 |
return f"เกิดข้อผิดพลาด: {str(e)}"
|
76 |
|
77 |
# Initialize application
|
78 |
print("กำลังเริ่มต้นแอปพลิเคชัน...")
|
79 |
-
if
|
80 |
demo = gr.Interface(
|
81 |
fn=process_handwriting,
|
82 |
inputs=gr.Image(type="pil", label="อัพโหลดรูปลายมือเขียนภาษาไทย"),
|
83 |
outputs=gr.Textbox(label="ข้อความที่แปลงได้"),
|
84 |
title="Thai Handwriting Recognition",
|
85 |
-
description="อัพโหลดรูปภาพลายมือเขียนภาษาไทยเพื่อแปลงเป็นข้อความ"
|
86 |
-
examples=[["example1.jpg"], ["example2.jpg"]]
|
87 |
)
|
88 |
|
89 |
if __name__ == "__main__":
|
|
|
2 |
import warnings
|
3 |
import torch
|
4 |
import gc
|
5 |
+
from transformers import AutoModelForVision2Seq, AutoProcessor, BitsAndBytesConfig
|
6 |
from PIL import Image
|
7 |
import gradio as gr
|
8 |
from huggingface_hub import login
|
|
|
11 |
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
|
12 |
|
13 |
# Global variables
|
14 |
+
model = None
|
15 |
+
processor = None
|
16 |
|
17 |
if torch.cuda.is_available():
|
18 |
torch.cuda.empty_cache()
|
19 |
gc.collect()
|
20 |
print("เคลียร์ CUDA cache เรียบร้อยแล้ว")
|
21 |
|
22 |
+
def load_model_and_processor():
|
23 |
+
"""โหลดโมเดลและ processor"""
|
24 |
+
global model, processor
|
25 |
+
print("กำลังโหลดโมเดลและ processor...")
|
26 |
|
27 |
try:
|
28 |
+
# กำหนด paths
|
29 |
+
base_model_path = "meta-llama/Llama-3.2-11B-Vision-Instruct"
|
30 |
hub_model_path = "Aekanun/thai-handwriting-llm"
|
31 |
|
32 |
+
# ตั้งค่า BitsAndBytes
|
33 |
+
bnb_config = BitsAndBytesConfig(
|
34 |
+
load_in_4bit=True,
|
35 |
+
bnb_4bit_use_double_quant=True,
|
36 |
+
bnb_4bit_quant_type="nf4",
|
37 |
+
bnb_4bit_compute_dtype=torch.bfloat16
|
38 |
+
)
|
39 |
+
|
40 |
+
# โหลด processor จาก base model
|
41 |
+
processor = AutoProcessor.from_pretrained(
|
42 |
+
base_model_path,
|
43 |
+
token=os.environ.get('HUGGING_FACE_HUB_TOKEN')
|
44 |
+
)
|
45 |
+
|
46 |
+
# โหลดโมเดลจาก Hub
|
47 |
+
print("กำลังโหลดโมเดลจาก Hub...")
|
48 |
+
model = AutoModelForVision2Seq.from_pretrained(
|
49 |
+
hub_model_path,
|
50 |
+
device_map="auto",
|
51 |
+
torch_dtype=torch.bfloat16,
|
52 |
+
quantization_config=bnb_config,
|
53 |
token=os.environ.get('HUGGING_FACE_HUB_TOKEN')
|
54 |
)
|
55 |
+
print("โหลดโมเดลจาก Hub สำเร็จ!")
|
56 |
|
|
|
57 |
return True
|
58 |
except Exception as e:
|
59 |
+
print(f"เกิดข้อผิดพลาดในการโหลดโมเดล: {str(e)}")
|
60 |
return False
|
61 |
|
62 |
def process_handwriting(image):
|
63 |
"""ฟังก์ชันสำหรับ Gradio interface"""
|
64 |
+
global model, processor
|
65 |
|
66 |
if image is None:
|
67 |
return "กรุณาอัพโหลดรูปภาพ"
|
|
|
75 |
if image.mode != "RGB":
|
76 |
image = image.convert("RGB")
|
77 |
|
78 |
+
prompt = """Transcribe the Thai handwritten text from the provided image.
|
79 |
+
Only return the transcription in Thai language."""
|
80 |
+
|
81 |
+
messages = [
|
82 |
+
{
|
83 |
+
"role": "user",
|
84 |
+
"content": [
|
85 |
+
{"type": "text", "text": prompt},
|
86 |
+
{"type": "image", "image": image}
|
87 |
+
],
|
88 |
+
}
|
89 |
+
]
|
90 |
+
|
91 |
+
text = processor.apply_chat_template(messages, tokenize=False)
|
92 |
+
inputs = processor(text=text, images=image, return_tensors="pt")
|
93 |
+
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
94 |
+
|
95 |
+
with torch.no_grad():
|
96 |
+
outputs = model.generate(
|
97 |
+
**inputs,
|
98 |
+
max_new_tokens=256,
|
99 |
+
do_sample=False,
|
100 |
+
pad_token_id=processor.tokenizer.pad_token_id
|
101 |
+
)
|
102 |
+
|
103 |
+
transcription = processor.decode(outputs[0], skip_special_tokens=True)
|
104 |
+
return transcription.strip()
|
105 |
|
106 |
except Exception as e:
|
107 |
return f"เกิดข้อผิดพลาด: {str(e)}"
|
108 |
|
109 |
# Initialize application
|
110 |
print("กำลังเริ่มต้นแอปพลิเคชัน...")
|
111 |
+
if load_model_and_processor():
|
112 |
demo = gr.Interface(
|
113 |
fn=process_handwriting,
|
114 |
inputs=gr.Image(type="pil", label="อัพโหลดรูปลายมือเขียนภาษาไทย"),
|
115 |
outputs=gr.Textbox(label="ข้อความที่แปลงได้"),
|
116 |
title="Thai Handwriting Recognition",
|
117 |
+
description="อัพโหลดรูปภาพลายมือเขียนภาษาไทยเพื่อแปลงเป็นข้อความ"
|
|
|
118 |
)
|
119 |
|
120 |
if __name__ == "__main__":
|