Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334import gradio as grfrom transformers import TrOCRProcessor, VisionEncoderDecoderModelfrom PIL import Image# โหลดโมเดล TrOCR และ Processor จาก Hugging Faceprocessor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")# ฟังก์ชันหลักสำหรับแสดงข้อความที่ตรวจจับได้จากภาพdef ocr_text(image):# ตรวจสอบว่าเป็น RGBif image.mode != "RGB":image = image.convert("RGB")# ทำ OCR ด้วย TrOCRpixel_values = processor(images=image, return_tensors="pt").pixel_valuesgenerated_ids = model.generate(pixel_values)text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]# แสดงข้อความที่ตรวจจับได้return f"📄 ข้อความที่พบในภาพ:\n{text}"# สร้าง Gradio Interfaceiface = gr.Interface(fn=ocr_text,inputs=gr.Image(type="pil", label="อัปโหลดภาพที่มีข้อความ"),outputs=gr.Textbox(lines=10, label="ข้อความที่ตรวจจับได้"),title="🧾 อ่านข้อความจากภาพ (OCR)",description="ระบบจะอ่านข้อความจากภาพและแสดงผลลัพธ์ทั้งหมดโดยไม่กรอง")# เปิดแอปif __name__ == "__main__":iface.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445import pytesseractfrom PIL import Imageimport gradio as grfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport torch# โหลดโมเดล transformers ภาษาไทย สำหรับ text classification (ตัวอย่างใช้ WangchanBERT)model_name = "airesearch/wangchanberta-base-att-spm-uncased"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForSequenceClassification.from_pretrained(model_name)# ฟังก์ชัน OCR + วิเคราะห์ข้อความdef ocr_and_classify(image):# OCR อ่านข้อความจากภาพ (ตั้งภาษาไทย + อังกฤษ)text = pytesseract.image_to_string(image, lang="tha+eng")if not text.strip():return "❌ ไม่พบข้อความในภาพ"# เตรียม input สำหรับ transformersinputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)outputs = model(**inputs)# แปลง logits เป็น probabilities และเลือกคลาสที่มีคะแนนสูงสุดprobs = torch.nn.functional.softmax(outputs.logits, dim=-1)pred_class_idx = torch.argmax(probs).item()confidence = probs[0][pred_class_idx].item()# สำหรับ WangchanBERT ไม่มี label mapping โดยตรง ต้องมี mapping label เอง (สมมติมี 3 คลาส)labels = ["คลาส 0", "คลาส 1", "คลาส 2"] # แก้ตามโมเดลที่ใช้จริงresult = f"ข้อความที่อ่านได้:\n{text}\n\nการจำแนกข้อความ:\n{labels[pred_class_idx]} (ความมั่นใจ {confidence:.2%})"return result# สร้าง Gradio UIiface = gr.Interface(fn=ocr_and_classify,inputs=gr.Image(type="pil", label="อัปโหลดภาพสลิปหรือใบเสร็จ"),outputs=gr.Textbox(lines=15, label="ผลลัพธ์"),title="OCR + วิเคราะห์ข้อความสลิป ด้วย pytesseract + Transformers",description="อ่านข้อความด้วย pytesseract แล้วใช้โมเดล transformers วิเคราะห์ข้อความ")if __name__ == "__main__":iface.launch()
app.py+34-23