ArsanForEver commited on
Commit
f6a49ad
·
verified ·
1 Parent(s): 75d42e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -26
app.py CHANGED
@@ -1,40 +1,89 @@
1
  from fastapi import FastAPI, UploadFile, File
2
- import tensorflow as tf
3
  import numpy as np
 
 
4
  from PIL import Image
5
  import io
6
- import uvicorn
7
 
8
  app = FastAPI()
9
 
10
- # Load model Keras
11
- model = tf.keras.models.load_model("lontara_model_finetuning.keras")
12
-
13
- # Label kelas sesuai model
14
- labels = [
15
- "Tu", "He", "We", "No", "Mu", "Bu", "Ji", "Jo", "I", "Nro", "Cu", "Na", "Bo", "Yi", "Se", "Nyi",
16
- "So", "Wa", "Ko", "Ge", "E", "Yo", "Ngu", "Ra", "Wo", "Ta", "Pe", "Nra", "Da", "Ci", "Lo", "Nci",
17
- "U", "Ro", "Mo", "Nre", "Du", "Be", "Mpu", "Hu", "Ne", "Nyo", "Ncu", "Su", "Ju", "Gu", "Nu", "Di",
18
- "Nri", "Gi", "Co", "Nca", "Ri", "Si", "Ja", "Bi", "Ke", "Wu", "Nki", "Te", "Go", "Ya", "Nku", "Pu",
19
- "Nka", "Ba", "Mpe", "A", "Nya", "Me", "Nge", "Mpa", "Ma", "Mpi", "O", "Mi", "Re", "Po", "Ti", "Je",
20
- "Nco", "Pa", "Ho", "Nko", "Ce", "Li", "Nke", "Ru", "Ca", "Ke_", "Do", "Ga", "Mpo", "Nye", "Nru", "Nga",
21
- "Lu", "Pi", "Ku", "Ni", "Nce", "Le", "Ngo", "De", "Ki", "Wi", "Hi", "Ye", "Ngi", "Ka", "Nyu", "La",
22
- "Ha", "Sa"
23
- ]
24
-
25
- @app.get("/")
26
  def home():
27
  return {"message": "Aksara Lontara API is running"}
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.post("/predict")
30
  async def predict(file: UploadFile = File(...)):
31
- # Baca gambar
32
- image = Image.open(io.BytesIO(await file.read())).convert("L").resize((128, 128))
33
- image = np.array(image) / 255.0
34
- image = image.reshape(1, 128, 128, 1)
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # Prediksi
37
- prediction = model.predict(image)
38
- label = labels[np.argmax(prediction)]
39
 
40
- return {"prediction": label}
 
1
  from fastapi import FastAPI, UploadFile, File
2
+
3
  import numpy as np
4
+ import cv2
5
+ import tensorflow as tf
6
  from PIL import Image
7
  import io
8
+
9
 
10
  app = FastAPI()
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def home():
13
  return {"message": "Aksara Lontara API is running"}
14
 
15
+ def preprocess_image(image: np.ndarray):
16
+ """ Melakukan segmentasi karakter menggunakan OpenCV """
17
+
18
+ # **1️⃣ Edge Detection (Canny)**
19
+ edges = cv2.Canny(image, 50, 150)
20
+
21
+ # **2️⃣ Morphological Cleaning**
22
+ kernel = np.ones((3, 3), np.uint8)
23
+ edges_cleaned = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel, iterations=2)
24
+
25
+ # **3️⃣ Connected Component Analysis (CCA)**
26
+ num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(edges_cleaned, connectivity=8)
27
+
28
+ # **4️⃣ Filter huruf berdasarkan area**
29
+ min_area = 500
30
+ bounding_boxes = []
31
+
32
+ for i in range(1, num_labels): # Skip background
33
+ x, y, w, h, area = stats[i]
34
+ if area > min_area:
35
+ bounding_boxes.append((x, y, w, h))
36
+
37
+ # **5️⃣ Urutkan huruf berdasarkan posisi X**
38
+ bounding_boxes.sort(key=lambda b: b[0])
39
+
40
+ # **6️⃣ Gabungkan Bounding Box yang Berdekatan**
41
+ merged_boxes = []
42
+ merge_threshold = 20
43
+
44
+ for i in range(len(bounding_boxes)):
45
+ x, y, w, h = bounding_boxes[i]
46
+
47
+ if merged_boxes and (x - (merged_boxes[-1][0] + merged_boxes[-1][2])) < merge_threshold:
48
+ x_prev, y_prev, w_prev, h_prev = merged_boxes.pop()
49
+ x_new = min(x_prev, x)
50
+ y_new = min(y_prev, y)
51
+ w_new = max(x_prev + w_prev, x + w) - x_new
52
+ h_new = max(y_prev + h_prev, y + h) - y_new
53
+ merged_boxes.append((x_new, y_new, w_new, h_new))
54
+ else:
55
+ merged_boxes.append((x, y, w, h))
56
+
57
+ # **7️⃣ Potong dan proses karakter**
58
+ segmented_chars = []
59
+ for (x, y, w, h) in merged_boxes:
60
+ char_segment = image[y:y+h, x:x+w]
61
+ char_segment = cv2.resize(char_segment, (128, 128), interpolation=cv2.INTER_AREA)
62
+ segmented_chars.append(char_segment)
63
+
64
+ return segmented_chars
65
+
66
  @app.post("/predict")
67
  async def predict(file: UploadFile = File(...)):
68
+ # Baca gambar dari file upload
69
+ image = Image.open(io.BytesIO(await file.read())).convert("L")
70
+ image = np.array(image)
71
+
72
+ # **Segmentasi huruf**
73
+ segmented_chars = preprocess_image(image)
74
+
75
+ # Jika tidak ada huruf terdeteksi
76
+ if not segmented_chars:
77
+ return {"prediction": "No characters detected"}
78
+
79
+ # **Prediksi untuk setiap karakter**
80
+ predictions = []
81
+ for char in segmented_chars:
82
+ char_norm = np.array(char) / 255.0 # Normalisasi
83
+ char_norm = char_norm.reshape(1, 128, 128, 1) # Reshape untuk model
84
 
85
+ prediction = model.predict(char_norm)
86
+ predicted_label = labels[np.argmax(prediction)]
87
+ predictions.append(predicted_label)
88
 
89
+ return {"predictions": predictions}