megustaSzy commited on
Commit
a19b458
·
verified ·
1 Parent(s): 17887b4

Upload 5 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/cholestify_fase3.keras filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user requirements.txt .
10
+ RUN pip install --no-cache-dir -r requirements.txt
11
+
12
+ COPY --chown=user . .
13
+
14
+ EXPOSE 7860
15
+
16
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
class_indices.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "0": "beresiko",
3
+ "1": "kolesterol",
4
+ "2": "normal"
5
+ }
main.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import json, numpy as np, cv2, tensorflow as tf
3
+ from tensorflow.keras.applications.efficientnet import preprocess_input as efficientnet_preprocess
4
+ from fastapi import FastAPI, File, UploadFile, HTTPException
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+
7
+ app = FastAPI(
8
+ title="Cholestify AI Eye Scan API",
9
+ description="""
10
+ API ini bertugas menerima gambar mata (retina/kornea) dan mendeteksi indikasi penyakit kolesterol tinggi (Arcus Senilis) menggunakan model Deep Learning **EfficientNetB0**.
11
+
12
+ **Fitur Utama:**
13
+ - 🛡️ **OOD Detection**: Secara otomatis memblokir gambar palsu yang bukan mata manusia.
14
+ - ✂️ **Auto Preprocessing**: Memotong area mata secara presisi dan meningkatkan kontras warna (CLAHE).
15
+ - ⚡ **Fast Inference**: Menghasilkan persentase probabilitas, status, dan rekomendasi dokter.
16
+ """,
17
+ version="2.1.0",
18
+ docs_url="/docs",
19
+ redoc_url="/redoc",
20
+ contact={
21
+ "name": "Tim Cholestify AI"
22
+ }
23
+ )
24
+ app.add_middleware(CORSMiddleware, allow_origins=["*"],
25
+ allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
26
+
27
+ MODEL_PATH = "models/cholestify_fase3.keras"
28
+ INDICES_PATH = "class_indices.json"
29
+ CONFIDENCE_THRESHOLD = 60.0
30
+ MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
31
+
32
+ class FocalLoss(tf.keras.losses.Loss):
33
+ def __init__(self, gamma=2.0, alpha=0.25, **kwargs):
34
+ super().__init__(**kwargs); self.gamma=gamma; self.alpha=alpha
35
+ def call(self, y_true, y_pred):
36
+ y_pred=tf.clip_by_value(y_pred,1e-7,1-1e-7)
37
+ ce=-tf.reduce_sum(y_true*tf.math.log(y_pred),axis=-1)
38
+ p_t=tf.reduce_sum(y_true*y_pred,axis=-1)
39
+ return self.alpha*tf.pow(1.0-p_t,self.gamma)*ce
40
+ def get_config(self):
41
+ cfg=super().get_config(); cfg.update({"gamma":self.gamma,"alpha":self.alpha}); return cfg
42
+
43
+ model = tf.keras.models.load_model(MODEL_PATH, custom_objects={"FocalLoss":FocalLoss})
44
+ with open(INDICES_PATH, encoding="utf-8") as f: index_to_class = json.load(f)
45
+
46
+ LABEL_INFO = {
47
+ "normal": {"status":"Normal",
48
+ "keterangan":"Tidak ada indikasi endapan lipid.",
49
+ "rekomendasi":"Pantau rutin setiap 6 bulan."},
50
+ "beresiko": {"status":"Indikasi Ringan",
51
+ "keterangan":"Indikasi awal endapan lipid di kornea perifer.",
52
+ "rekomendasi":"Tindak lanjut 3-6 bulan, monitor pola makan."},
53
+ "kolesterol": {"status":"Indikasi Kuat",
54
+ "keterangan":"Endapan lipid signifikan terdeteksi.",
55
+ "rekomendasi":"Konsultasi dokter segera, lakukan cek lipid panel."},
56
+ "tidak_pasti": {"status":"Tidak Dapat Dianalisis",
57
+ "keterangan":"Kualitas foto tidak mencukupi.",
58
+ "rekomendasi":"Ambil ulang foto sesuai panduan."}
59
+ }
60
+
61
+ # ===================================================================
62
+ # OOD DETECTION -- 3 lapis filter sebelum model inference
63
+ # ===================================================================
64
+ def validate_eye_image(img):
65
+ if img is None:
66
+ return False, "File gambar tidak dapat dibaca."
67
+ h, w = img.shape[:2]
68
+
69
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
70
+ gray_bl = cv2.GaussianBlur(gray, (5, 5), 0)
71
+ circles = cv2.HoughCircles(
72
+ gray_bl, cv2.HOUGH_GRADIENT, dp=1.2,
73
+ minDist=int(min(h, w) * 0.3),
74
+ param1=50, param2=28,
75
+ minRadius=int(min(h, w) * 0.08),
76
+ maxRadius=int(min(h, w) * 0.55)
77
+ )
78
+ if circles is None:
79
+ return False, (
80
+ "Tidak terdeteksi struktur mata (iris/pupil). "
81
+ "Pastikan foto menampilkan mata dengan jelas, "
82
+ "pencahayaan cukup, dan mata terbuka penuh."
83
+ )
84
+
85
+ x, y, r = np.round(circles[0, 0]).astype(int)
86
+ roi = img[max(0,y-r):min(h,y+r), max(0,x-r):min(w,x+r)]
87
+ if roi.size == 0:
88
+ return False, "Area mata tidak dapat dianalisis."
89
+
90
+ hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
91
+ mask_white = cv2.inRange(hsv, np.array([0, 0, 150]), np.array([180, 60, 255]))
92
+ mask_dark = cv2.inRange(hsv, np.array([0, 0, 0 ]), np.array([180, 255, 120]))
93
+ eye_ratio = (cv2.countNonZero(mask_white) + cv2.countNonZero(mask_dark)) / (roi.shape[0]*roi.shape[1])
94
+ if eye_ratio < 0.35:
95
+ return False, (
96
+ "Warna dominan tidak sesuai dengan foto mata. "
97
+ "Pastikan gambar adalah foto mata manusia, bukan objek lain."
98
+ )
99
+
100
+ ratio = r / min(h, w)
101
+ if ratio < 0.07:
102
+ return False, "Struktur mata terlalu kecil. Dekatkan kamera ke mata (10-15 cm)."
103
+ if ratio > 0.60:
104
+ return False, "Objek bundar terlalu besar, kemungkinan bukan foto mata."
105
+
106
+ return True, "OK"
107
+
108
+ # ===================================================================
109
+ # Preprocessing (crop + CLAHE) -- hanya dipanggil jika lolos OOD
110
+ # ===================================================================
111
+ def preprocess_image(img, target_size=(240,240)):
112
+ h0, w0 = img.shape[:2]
113
+ if max(h0, w0) > 800:
114
+ s = 800/max(h0,w0); img = cv2.resize(img,(int(w0*s),int(h0*s)))
115
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
116
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
117
+ h, w = gray.shape
118
+ circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100,
119
+ param1=50, param2=30,
120
+ minRadius=int(h*0.1), maxRadius=int(h*0.5))
121
+ if circles is not None:
122
+ x,y,r = np.round(circles[0,0]).astype(int); r = int(r*1.1)
123
+ crop = rgb[max(0,y-r):min(h,y+r), max(0,x-r):min(w,x+r)]
124
+ else:
125
+ ch,cw = int(h*0.8),int(w*0.8); y1,x1 = (h-ch)//2,(w-cw)//2
126
+ crop = rgb[y1:y1+ch, x1:x1+cw]
127
+ resized = cv2.resize(crop, target_size)
128
+ lab = cv2.cvtColor(resized, cv2.COLOR_RGB2LAB)
129
+ l, a, b = cv2.split(lab)
130
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
131
+ final = cv2.cvtColor(cv2.merge((clahe.apply(l),a,b)), cv2.COLOR_LAB2RGB)
132
+ return np.expand_dims(efficientnet_preprocess(final.astype(np.float32)), axis=0)
133
+
134
+ # ===================================================================
135
+ # ENDPOINTS
136
+ # ===================================================================
137
+ @app.get("/api", tags=["General"], summary="Root API", description="Mengecek identitas dan versi server API saat ini.")
138
+ def root(): return {"message": "Cholestify EfficientNetB0 API", "version": "2.1.0"}
139
+
140
+ @app.get("/api/health", tags=["General"], summary="Server Health Check", description="Mengecek status kesiapan server dan status *load* model AI di memori.")
141
+ def health(): return {"status": "ok", "model": "EfficientNetB0", "loaded": model is not None}
142
+
143
+ @app.post(
144
+ "/api/predict",
145
+ tags=["Prediction"],
146
+ summary="Menganalisis Gambar Mata (Upload Foto)",
147
+ description="""
148
+ Endpoint ini menerima **file gambar** (JPG, PNG) maksimal 10MB.
149
+ Proses yang terjadi di dalam server:
150
+ 1. **Validasi File**: Pengecekan tipe gambar dan batasan *size*.
151
+ 2. **Auto-Resize**: Mengkompres ukuran gambar super besar (>1200px) untuk mencegah *Memory Overflow*.
152
+ 3. **OOD Check**: Validasi matematis bentuk lingkaran dan rasio warna (*Computer Vision*). Jika terdeteksi bukan mata, akan otomatis ditolak (*Bad Request*).
153
+ 4. **AI Inference**: Prediksi endapan lipid menggunakan *EfficientNetB0*.
154
+ """,
155
+ response_description="Hasil prediksi berupa tingkat persentase kolesterol, status, dan saran medis."
156
+ )
157
+ def predict(file: UploadFile = File(..., description="File gambar mata (retina/kornea). Harus berformat JPG atau PNG dan terang.")):
158
+ # -- Validasi tipe & ukuran file ------------------------------------
159
+ if file.content_type not in ["image/jpeg", "image/png", "image/jpg"]:
160
+ raise HTTPException(400, f"Tipe file tidak didukung: {file.content_type}. Gunakan JPG atau PNG.")
161
+ file.file.seek(0, 2); size = file.file.tell(); file.file.seek(0)
162
+ if size > MAX_FILE_SIZE:
163
+ raise HTTPException(400, "File terlalu besar (maksimal 10MB).")
164
+
165
+ image_bytes = file.file.read()
166
+ img = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
167
+ if img is None:
168
+ raise HTTPException(400, "File tidak dapat dibaca sebagai gambar.")
169
+
170
+ # -- Mencegah RAM Lagging jika foto beresolusi terlampau raksasa --
171
+ h_init, w_init = img.shape[:2]
172
+ if max(h_init, w_init) > 1200:
173
+ scale = 1200 / max(h_init, w_init)
174
+ img = cv2.resize(img, (int(w_init * scale), int(h_init * scale)))
175
+
176
+ # -- OOD Check -------------------------------------------------------
177
+ is_valid, reason = validate_eye_image(img)
178
+ if not is_valid:
179
+ return {
180
+ "success": False,
181
+ "error_code": "INVALID_IMAGE",
182
+ "result": {
183
+ "label": "gambar_tidak_valid",
184
+ "status": "Gambar Tidak Sesuai",
185
+ "confidence": 0.0,
186
+ "keterangan": reason,
187
+ "rekomendasi": (
188
+ "Panduan foto yang benar: "
189
+ "(1) foto adalah mata manusia, "
190
+ "(2) mata terbuka penuh, "
191
+ "(3) pencahayaan cukup, "
192
+ "(4) jarak kamera 10-15 cm dari mata."
193
+ )
194
+ }
195
+ }
196
+
197
+ # -- Preprocessing & Inferensi ---------------------------------------
198
+ tensor = preprocess_image(img)
199
+ preds = model.predict(tensor, verbose=0)[0]
200
+ idx = str(np.argmax(preds))
201
+ lbl = index_to_class[idx]
202
+ conf = round(float(np.max(preds)) * 100, 2)
203
+ ok = conf >= CONFIDENCE_THRESHOLD
204
+ if not ok: lbl = "tidak_pasti"
205
+ info = LABEL_INFO[lbl]
206
+
207
+ res = {
208
+ "success": True,
209
+ "result": {
210
+ "label": lbl,
211
+ "status": info["status"],
212
+ "confidence": conf,
213
+ "is_confident": ok,
214
+ "keterangan": info["keterangan"],
215
+ "rekomendasi": info["rekomendasi"],
216
+ "probabilitas": {
217
+ index_to_class[str(i)]: round(float(p)*100, 2)
218
+ for i, p in enumerate(preds)
219
+ }
220
+ }
221
+ }
222
+ if not ok:
223
+ res["result"]["warning"] = (
224
+ f"Confidence {conf}% di bawah threshold {CONFIDENCE_THRESHOLD}%. "
225
+ "Coba foto ulang dengan kondisi lebih baik."
226
+ )
227
+ return res
models/cholestify_fase3.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e5ffd04b145ec1960fc1139988fcacf2513cc52dbd61aad4512e1626bf45d8b
3
+ size 38546445
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ python-multipart
4
+ numpy
5
+ tensorflow
6
+ opencv-python-headless