Spaces:
Running
on
Zero
Running
on
Zero
fixed app.py
Browse files
app.py
CHANGED
@@ -18,131 +18,130 @@ 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 |
-
|
53 |
-
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
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 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
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 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
)
|
147 |
else:
|
148 |
-
|
|
|
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 |
+
low_memory=True # เพิ่ม low memory option
|
41 |
+
)
|
42 |
|
43 |
+
# Load base model with CPU configurations
|
44 |
+
print("กำลังโหลด base model...")
|
45 |
+
base_model = AutoModelForVision2Seq.from_pretrained(
|
46 |
+
base_model_path,
|
47 |
+
device_map={"": "cpu"},
|
48 |
+
torch_dtype=torch.float32,
|
49 |
+
trust_remote_code=True,
|
50 |
+
use_auth_token=True,
|
51 |
+
low_cpu_mem_usage=True, # เพิ่ม low memory usage
|
52 |
+
offload_folder="offload" # เพิ่ม offload folder
|
53 |
+
)
|
54 |
|
55 |
+
# Load adapter with CPU configurations
|
56 |
+
print("กำลังโหลด adapter...")
|
57 |
+
model = PeftModel.from_pretrained(
|
58 |
+
base_model,
|
59 |
+
adapter_path,
|
60 |
+
torch_dtype=torch.float32,
|
61 |
+
device_map={"": "cpu"},
|
62 |
+
use_auth_token=True,
|
63 |
+
low_cpu_mem_usage=True # เพิ่ม low memory usage
|
64 |
+
)
|
65 |
|
66 |
+
# Clear memory
|
67 |
+
gc.collect()
|
68 |
+
torch.cuda.empty_cache() if torch.cuda.is_available() else None
|
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 |
+
"""ฟังก์ชันสำหรับ Gradio interface"""
|
78 |
+
global model, processor
|
79 |
+
|
80 |
+
if image is None:
|
81 |
+
return "กรุณาอัพโหลดรูปภาพ"
|
82 |
+
|
83 |
+
try:
|
84 |
+
# Ensure image is in PIL format
|
85 |
+
if not isinstance(image, Image.Image):
|
86 |
+
image = Image.fromarray(image)
|
87 |
+
|
88 |
+
# Create prompt
|
89 |
+
prompt = """Transcribe the Thai handwritten text from the provided image.
|
90 |
Only return the transcription in Thai language."""
|
91 |
+
|
92 |
+
# Create model inputs
|
93 |
+
messages = [
|
94 |
+
{
|
95 |
+
"role": "user",
|
96 |
+
"content": [
|
97 |
+
{"type": "text", "text": prompt},
|
98 |
+
{"type": "image", "image": image}
|
99 |
+
],
|
100 |
+
}
|
101 |
+
]
|
102 |
+
|
103 |
+
# Process with model
|
104 |
+
text = processor.apply_chat_template(messages, tokenize=False)
|
105 |
+
inputs = processor(text=text, images=image, return_tensors="pt")
|
106 |
+
inputs = {k: v.to('cpu') for k, v in inputs.items()}
|
107 |
+
|
108 |
+
# Generate with memory optimization
|
109 |
+
with torch.no_grad():
|
110 |
+
outputs = model.generate(
|
111 |
+
**inputs,
|
112 |
+
max_new_tokens=256,
|
113 |
+
do_sample=False,
|
114 |
+
pad_token_id=processor.tokenizer.pad_token_id,
|
115 |
+
use_cache=True # ใช้ cache เพื่อประหยัด memory
|
116 |
+
)
|
117 |
+
|
118 |
+
# Clear memory after generation
|
119 |
+
gc.collect()
|
120 |
+
|
121 |
+
# Decode output
|
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 |
+
# Create Gradio interface with lower memory usage
|
131 |
+
demo = gr.Interface(
|
132 |
+
fn=process_handwriting,
|
133 |
+
inputs=gr.Image(type="pil", label="อัพโหลดรูปลายมือเขียนภาษาไทย"),
|
134 |
+
outputs=gr.Textbox(label="ข้อความที่แปลงได้"),
|
135 |
+
title="Thai Handwriting Recognition",
|
136 |
+
description="อัพโหลดรูปภาพลายมือเขียนภาษาไทยเพื่อแปลงเป็นข้อความ",
|
137 |
+
examples=[["example1.jpg"], ["example2.jpg"]],
|
138 |
+
cache_examples=False # ไม่ cache examples เพื่อประหยัด memory
|
139 |
+
)
|
140 |
+
|
141 |
+
if __name__ == "__main__":
|
142 |
+
demo.launch(
|
143 |
+
share=False, # ไม่แชร์ public URL
|
144 |
+
show_error=True # แสดง error messages
|
145 |
+
)
|
|
|
146 |
else:
|
147 |
+
print("ไม่สามารถเริ่มต้นแอปพลิเคชันได้")
|