from fastapi import FastAPI, UploadFile, File import tensorflow as tf import numpy as np import cv2 import io import tempfile app = FastAPI() # Load model Keras model = tf.keras.models.load_model("lontara_model_finetuning.keras") # Label kelas sesuai model labels = [ "Tu", "He", "We", "No", "Mu", "Bu", "Ji", "Jo", "I", "Nro", "Cu", "Na", "Bo", "Yi", "Se", "Nyi", "So", "Wa", "Ko", "Ge", "E", "Yo", "Ngu", "Ra", "Wo", "Ta", "Pe", "Nra", "Da", "Ci", "Lo", "Nci", "U", "Ro", "Mo", "Nre", "Du", "Be", "Mpu", "Hu", "Ne", "Nyo", "Ncu", "Su", "Ju", "Gu", "Nu", "Di", "Nri", "Gi", "Co", "Nca", "Ri", "Si", "Ja", "Bi", "Ke", "Wu", "Nki", "Te", "Go", "Ya", "Nku", "Pu", "Nka", "Ba", "Mpe", "A", "Nya", "Me", "Nge", "Mpa", "Ma", "Mpi", "O", "Mi", "Re", "Po", "Ti", "Je", "Nco", "Pa", "Ho", "Nko", "Ce", "Li", "Nke", "Ru", "Ca", "Ke_", "Do", "Ga", "Mpo", "Nye", "Nru", "Nga", "Lu", "Pi", "Ku", "Ni", "Nce", "Le", "Ngo", "De", "Ki", "Wi", "Hi", "Ye", "Ngi", "Ka", "Nyu", "La", "Ha", "Sa" ] @app.get("/") def home(): return {"message": "Aksara Lontara API is running"} @app.post("/predict") async def predict(file: UploadFile = File(...)): # Simpan file gambar sementara temp = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") temp.write(await file.read()) temp.close() # Baca gambar menggunakan OpenCV image = cv2.imread(temp.name) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Thresholding untuk mempermudah deteksi huruf _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) # Temukan kontur huruf contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Urutkan kontur dari kiri ke kanan contours = sorted(contours, key=lambda c: cv2.boundingRect(c)[0]) # Loop untuk memotong dan klasifikasi tiap huruf hasil_klasifikasi = [] for contour in contours: x, y, w, h = cv2.boundingRect(contour) huruf = gray[y:y+h, x:x+w] # Resize ke ukuran model huruf = cv2.resize(huruf, (128, 128)) huruf = np.array(huruf) / 255.0 huruf = huruf.reshape(1, 128, 128, 1) # Prediksi prediction = model.predict(huruf) label = labels[np.argmax(prediction)] hasil_klasifikasi.append(label) # Gabungkan hasil klasifikasi menjadi teks akhir hasil_teks = "".join(hasil_klasifikasi) return {"prediction": hasil_teks}