import pytesseract
from PIL import Image
import os

# Tentukan path ke executable Tesseract 
# pytesseract.pytesseract.tesseract_cmd = r'D:\Tesseract-OCR\tesseract.exe'  

# Fungsi untuk menghitung akurasi karakter
def calculate_accuracy(ground_truth, ocr_text):
    correct_chars = sum(1 for gt, ocr in zip(ground_truth, ocr_text) if gt == ocr)
    total_chars = len(ground_truth)
    accuracy = (correct_chars / total_chars) * 100
    return accuracy

# Path folder yang berisi gambar-gambar yang akan diuji
image_folder = 'gambar'

# Daftar nama gambar dan teks ground truth yang sesuai
image_files = [
    'G1.jpg', 'G2.jpg', 'G3.jpg',
    'G4.jpg', 'G5.jpg', 'G6.jpg',
    'G7.jpg', 'G8.jpg', 'G9.jpg', 'G10.jpg'
]

# Teks ground truth yang diberikan
ground_truths = [
    'BN 5572 XB', 'BN 4717 DF', 'BN 4250 TR', 'BN 3227 VH',
    'BN 6277 XF', 'BN 2201 PB', 'BN 3146 PW', 'BN 3464 TD',
    'H 3141 NB', 'H 3982 DP'
]

# Loop untuk membaca setiap gambar dan menjalankan OCR
for image_file, ground_truth in zip(image_files, ground_truths):
    # Membaca gambar
    image_path = os.path.join(image_folder, image_file)
    img = Image.open(image_path)

    # Melakukan OCR pada gambar
    ocr_text = pytesseract.image_to_string(img)
    print(ocr_text)

    # Menghitung akurasi berdasarkan karakter
    accuracy = calculate_accuracy(ground_truth, ocr_text.strip())
  
    # Status apakah OCR berhasil atau tidak
    if accuracy >= 100:  # Atur threshold akurasi sesuai kebutuhanmu
        status = "True"
    else:
        status = "False"

    # Menampilkan hasil OCR dan status
    print(f"File: {image_file}")
    print(f"Hasil OCR: {ocr_text.strip()}")
    print(f"Akurasi: {accuracy:.2f}%")
    print(f"Status: {status}")
    print("-" * 40)