Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,45 @@
|
|
| 1 |
-
import
|
| 2 |
-
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
# โหลดโมเดล
|
| 6 |
-
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
def
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
return
|
| 22 |
|
| 23 |
-
# สร้าง Gradio
|
| 24 |
iface = gr.Interface(
|
| 25 |
-
fn=
|
| 26 |
-
inputs=gr.Image(type="pil", label="
|
| 27 |
-
outputs=gr.Textbox(lines=
|
| 28 |
-
title="
|
| 29 |
-
description="
|
| 30 |
)
|
| 31 |
|
| 32 |
-
# เปิดแอป
|
| 33 |
if __name__ == "__main__":
|
| 34 |
iface.launch()
|
|
|
|
| 1 |
+
import pytesseract
|
|
|
|
| 2 |
from PIL import Image
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 5 |
+
import torch
|
| 6 |
|
| 7 |
+
# โหลดโมเดล transformers ภาษาไทย สำหรับ text classification (ตัวอย่างใช้ WangchanBERT)
|
| 8 |
+
model_name = "airesearch/wangchanberta-base-att-spm-uncased"
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 10 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
| 11 |
|
| 12 |
+
# ฟังก์ชัน OCR + วิเคราะห์ข้อความ
|
| 13 |
+
def ocr_and_classify(image):
|
| 14 |
+
# OCR อ่านข้อความจากภาพ (ตั้งภาษาไทย + อังกฤษ)
|
| 15 |
+
text = pytesseract.image_to_string(image, lang="tha+eng")
|
| 16 |
+
|
| 17 |
+
if not text.strip():
|
| 18 |
+
return "❌ ไม่พบข้อความในภาพ"
|
| 19 |
|
| 20 |
+
# เตรียม input สำหรับ transformers
|
| 21 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 22 |
+
outputs = model(**inputs)
|
| 23 |
+
|
| 24 |
+
# แปลง logits เป็น probabilities และเลือกคลาสที่มีคะแนนสูงสุด
|
| 25 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 26 |
+
pred_class_idx = torch.argmax(probs).item()
|
| 27 |
+
confidence = probs[0][pred_class_idx].item()
|
| 28 |
+
|
| 29 |
+
# สำหรับ WangchanBERT ไม่มี label mapping โดยตรง ต้องมี mapping label เอง (สมมติมี 3 คลาส)
|
| 30 |
+
labels = ["คลาส 0", "คลาส 1", "คลาส 2"] # แก้ตามโมเดลที่ใช้จริง
|
| 31 |
|
| 32 |
+
result = f"ข้อความที่อ่านได้:\n{text}\n\nการจำแนกข้อความ:\n{labels[pred_class_idx]} (ความมั่นใจ {confidence:.2%})"
|
| 33 |
+
return result
|
| 34 |
|
| 35 |
+
# สร้าง Gradio UI
|
| 36 |
iface = gr.Interface(
|
| 37 |
+
fn=ocr_and_classify,
|
| 38 |
+
inputs=gr.Image(type="pil", label="อัปโหลดภาพสลิปหรือใบเสร็จ"),
|
| 39 |
+
outputs=gr.Textbox(lines=15, label="ผลลัพธ์"),
|
| 40 |
+
title="OCR + วิเคราะห์ข้อความสลิป ด้วย pytesseract + Transformers",
|
| 41 |
+
description="อ่านข้อความด้วย pytesseract แล้วใช้โมเดล transformers วิเคราะห์ข้อความ"
|
| 42 |
)
|
| 43 |
|
|
|
|
| 44 |
if __name__ == "__main__":
|
| 45 |
iface.launch()
|