tirta16 commited on
Commit
d5d8aa3
·
verified ·
1 Parent(s): 4dfaddb

update main.py dan update semua model terbaru

Browse files
.gitattributes CHANGED
@@ -36,3 +36,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  freshly_saved_model_banana/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
37
  freshly_saved_model_mango/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
38
  freshly_saved_model_orange/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
36
  freshly_saved_model_banana/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
37
  freshly_saved_model_mango/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
38
  freshly_saved_model_orange/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
39
+ banana_saved_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
40
+ chili_saved_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
41
+ mango_saved_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
42
+ orange_saved_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
43
+ paprika_saved_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
44
+ tomato_saved_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
banana_saved_model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51dfb428765635b5fce639267bdade63078b16d1cadcfb559ebcbeda6177d512
3
+ size 51029
banana_saved_model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:257ef542157172cb183e728e7dd6e022c65fd4def4690674288ee241dc800ce4
3
+ size 430850
banana_saved_model/variables/variables.data-00000-of-00001 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0cc1ef25479f9ad3520addf6007fb834fe44664dc5475a7e94e496e58b2e17a
3
+ size 2063728
banana_saved_model/variables/variables.index ADDED
Binary file (2.87 kB). View file
 
chili_saved_model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:324f9d91cb1b2e8b3970a3522dcc48a11baa6c3ece2dc69865edf24a39d51685
3
+ size 51026
chili_saved_model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9aac7fc4f671562a22824f270e5851ccba0beadecd2177b447e7b3bb1db3673
3
+ size 430399
chili_saved_model/variables/variables.data-00000-of-00001 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c792597c6fff5ade8694a297f5df493682e329c752494531cc9f5972363be780
3
+ size 2063728
chili_saved_model/variables/variables.index ADDED
Binary file (2.87 kB). View file
 
main.py CHANGED
@@ -1,112 +1,98 @@
1
- import io
2
- import numpy as np
3
- import tensorflow as tf
4
- from fastapi import FastAPI, File, UploadFile, Form, HTTPException
5
- from fastapi.middleware.cors import CORSMiddleware
6
- from PIL import Image
7
-
8
- app = FastAPI(
9
- title="Freshly Universal API",
10
- description="API deteksi kematangan buah dan sayur.",
11
- version="1.0.1"
12
- )
13
-
14
- # --- 2. TAMBAHKAN BLOK KODE CORS INI ---
15
- app.add_middleware(
16
- CORSMiddleware,
17
- allow_origins=["*"], # Mengizinkan website dari domain mana pun untuk mengakses API ini
18
- allow_credentials=True,
19
- allow_methods=["*"], # Mengizinkan semua metode (GET, POST, dll)
20
- allow_headers=["*"],
21
- )
22
-
23
- # 1. Konfigurasi Model
24
- CONFIG = {
25
- "banana": ['banana_ripe', 'banana_rotten', 'banana_unripe'],
26
- "mango": ['mango_ripe', 'mango_rotten', 'mango_unripe'],
27
- "orange": ['orange_ripe', 'orange_rotten', 'orange_unripe'],
28
- #"chili": ['chili_ripe', 'chili_rotten', 'chili_unripe'],
29
- #"paprika": ['paprika_ripe', 'paprika_rotten', 'paprika_unripe'],
30
- #"tomato": ['tomato_ripe', 'tomato_rotten', 'tomato_unripe']
31
- }
32
-
33
- IMG_SIZE = (224, 224)
34
- MEAN = np.array([0.485, 0.456, 0.406])
35
- STD = np.array([0.229, 0.224, 0.225])
36
-
37
- # 2. Memuat Semua Model ke Memori
38
- models = {}
39
- print("Memulai proses pemuatan semua model...")
40
- for fruit_type in CONFIG.keys():
41
- model_folder = f"freshly_saved_model_{fruit_type}"
42
- try:
43
- models[fruit_type] = tf.keras.models.load_model(model_folder)
44
- print(f" -> Model {fruit_type.upper()} berhasil dimuat.")
45
- except Exception as e:
46
- print(f" [X] Gagal memuat model {fruit_type}: {e}")
47
-
48
- # 3. Fungsi Preprocessing
49
- def preprocess_image(image_bytes):
50
- try:
51
- img = Image.open(io.BytesIO(image_bytes)).convert('RGB')
52
- img = img.resize(IMG_SIZE)
53
- img_array = tf.keras.utils.img_to_array(img)
54
- img_array = img_array / 255.0
55
- img_array = (img_array - MEAN) / STD
56
- img_array = np.expand_dims(img_array, axis=0)
57
- return img_array
58
- except Exception as e:
59
- raise ValueError(f"Gagal memproses gambar: {str(e)}")
60
-
61
- # ---------------------------------------------------------
62
- # ENDPOINT HEALTH CHECK (Untuk UptimeRobot)
63
- # ---------------------------------------------------------
64
- @app.get("/health")
65
- def health_check():
66
- return {"status": "active", "message": "Server is awake and ready!"}
67
-
68
- # ---------------------------------------------------------
69
- # ENDPOINT PREDIKSI (Satu URL untuk semua model)
70
- # ---------------------------------------------------------
71
- @app.post("/predict")
72
- async def predict_fruit(
73
- # Menerima teks (jenis buah) dan file (gambar) dalam satu Form yang sama
74
- fruit_type: str = Form(..., description="Tulis: banana, mango, orange, chili, paprika, atau tomato"),
75
- file: UploadFile = File(...)
76
- ):
77
- fruit_type = fruit_type.lower()
78
-
79
- # Validasi jenis buah
80
- if fruit_type not in models:
81
- raise HTTPException(
82
- status_code=404,
83
- detail=f"Model '{fruit_type}' tidak ada. Pilihan: {list(models.keys())}"
84
- )
85
-
86
- # Validasi file
87
- if not file.content_type.startswith('image/'):
88
- raise HTTPException(status_code=400, detail="File harus berupa gambar.")
89
-
90
- try:
91
- contents = await file.read()
92
- img_tensor = preprocess_image(contents)
93
-
94
- # Prediksi
95
- active_model = models[fruit_type]
96
- class_names = CONFIG[fruit_type]
97
-
98
- predictions = active_model.predict(img_tensor)
99
- pred_index = np.argmax(predictions[0])
100
- confidence = float(predictions[0][pred_index])
101
-
102
- return {
103
- "fruit_type": fruit_type,
104
- "filename": file.filename,
105
- "predicted_class": class_names[pred_index],
106
- "confidence": round(confidence * 100, 2),
107
- "all_probabilities": {
108
- class_names[i]: round(float(predictions[0][i]) * 100, 2) for i in range(len(class_names))
109
- }
110
- }
111
- except Exception as e:
112
  raise HTTPException(status_code=500, detail=str(e))
 
1
+ import io
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException
5
+ from PIL import Image
6
+
7
+ app = FastAPI(
8
+ title="Freshly API",
9
+ description="API deteksi kematangan buah dan sayur.",
10
+ version="1.0.2"
11
+ )
12
+
13
+ # 1. Konfigurasi Model
14
+ CONFIG = {
15
+ "banana": ['banana_ripe', 'banana_rotten', 'banana_unripe'],
16
+ "mango": ['mango_ripe', 'mango_rotten', 'mango_unripe'],
17
+ "orange": ['orange_ripe', 'orange_rotten', 'orange_unripe'],
18
+ "chili": ['chili_ripe', 'chili_rotten', 'chili_unripe'],
19
+ "paprika": ['paprika_ripe', 'paprika_rotten', 'paprika_unripe'],
20
+ "tomato": ['tomato_ripe', 'tomato_rotten', 'tomato_unripe']
21
+ }
22
+
23
+ IMG_SIZE = (224, 224)
24
+ MEAN = np.array([0.485, 0.456, 0.406])
25
+ STD = np.array([0.229, 0.224, 0.225])
26
+
27
+ # 2. Memuat Semua Model ke Memori
28
+ models = {}
29
+ print("Memulai proses pemuatan semua model...")
30
+ for fruit_type in CONFIG.keys():
31
+ model_folder = f"{fruit_type}_saved_model"
32
+ try:
33
+ models[fruit_type] = tf.keras.models.load_model(model_folder)
34
+ print(f" -> Model {fruit_type.upper()} berhasil dimuat.")
35
+ except Exception as e:
36
+ print(f" [X] Gagal memuat model {fruit_type}: {e}")
37
+
38
+ # 3. Fungsi Preprocessing
39
+ def preprocess_image(image_bytes):
40
+ try:
41
+ img = Image.open(io.BytesIO(image_bytes)).convert('RGB')
42
+ img = img.resize(IMG_SIZE)
43
+ img_array = tf.keras.utils.img_to_array(img)
44
+ img_array = img_array / 255.0
45
+ img_array = (img_array - MEAN) / STD
46
+ img_array = np.expand_dims(img_array, axis=0)
47
+ return img_array
48
+ except Exception as e:
49
+ raise ValueError(f"Gagal memproses gambar: {str(e)}")
50
+
51
+ # ENDPOINT HEALTH CHECK (Untuk UptimeRobot)
52
+ @app.get("/health")
53
+ def health_check():
54
+ return {"status": "active", "message": "Server is awake and ready!"}
55
+
56
+ # ENDPOINT PREDIKSI (Satu URL untuk semua model)
57
+ @app.post("/predict")
58
+ async def predict_fruit(
59
+ # Menerima teks (jenis buah) dan file (gambar) dalam satu Form yang sama
60
+ fruit_type: str = Form(..., description="Tulis: banana, mango, orange, chili, paprika, atau tomato"),
61
+ file: UploadFile = File(...)
62
+ ):
63
+ fruit_type = fruit_type.lower()
64
+
65
+ # Validasi jenis buah
66
+ if fruit_type not in models:
67
+ raise HTTPException(
68
+ status_code=404,
69
+ detail=f"Model '{fruit_type}' tidak ada. Pilihan: {list(models.keys())}"
70
+ )
71
+
72
+ # Validasi file
73
+ if not file.content_type.startswith('image/'):
74
+ raise HTTPException(status_code=400, detail="File harus berupa gambar.")
75
+
76
+ try:
77
+ contents = await file.read()
78
+ img_tensor = preprocess_image(contents)
79
+
80
+ # Prediksi
81
+ active_model = models[fruit_type]
82
+ class_names = CONFIG[fruit_type]
83
+
84
+ predictions = active_model.predict(img_tensor)
85
+ pred_index = np.argmax(predictions[0])
86
+ confidence = float(predictions[0][pred_index])
87
+
88
+ return {
89
+ "fruit_type": fruit_type,
90
+ "filename": file.filename,
91
+ "predicted_class": class_names[pred_index],
92
+ "confidence": round(confidence * 100, 2),
93
+ "all_probabilities": {
94
+ class_names[i]: round(float(predictions[0][i]) * 100, 2) for i in range(len(class_names))
95
+ }
96
+ }
97
+ except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  raise HTTPException(status_code=500, detail=str(e))
mango_saved_model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9e6e019c2a8bb4a6c22ac5bc9b34223748d0c8938a640d120920c4265936186
3
+ size 51026
mango_saved_model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7310f6fbfe95842d9d7f859229b4a45a5b79c1901f369a45d790ae2b6ac4943e
3
+ size 429659
mango_saved_model/variables/variables.data-00000-of-00001 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acb09087aa26cf4cc7f1c399742f4abcefd7a16aaea5bb74bec7ca9c22542c2e
3
+ size 2063728
mango_saved_model/variables/variables.index ADDED
Binary file (2.87 kB). View file
 
orange_saved_model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f12b8535b3ca9628e5f2b7a85aa16e07fdf2c15964785537d5b99b9ab0a33246
3
+ size 51029
orange_saved_model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b0b00a34ac5db224a428a5616765ca6c21624896f4992dab9a7b70d4513de59
3
+ size 430110
orange_saved_model/variables/variables.data-00000-of-00001 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7b18a3914f82ca6b86adfefde7ed5e30f9761b0b086eadb9698014bd07ed85f
3
+ size 2063728
orange_saved_model/variables/variables.index ADDED
Binary file (2.87 kB). View file
 
paprika_saved_model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88834b962ec018d4dba61f3f2eb48bbf56254ee3c9296b27ce14379e4452521b
3
+ size 51140
paprika_saved_model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f89acc77fb077d0256f39e9dd3a008e549012c2b016cce1ce150a6cf2f7ecdfd
3
+ size 432637
paprika_saved_model/variables/variables.data-00000-of-00001 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89686d99996c9c69dca60007451974d373ca028ef5d8432c3e933bf9da86b76c
3
+ size 2063744
paprika_saved_model/variables/variables.index ADDED
Binary file (2.87 kB). View file
 
tomato_saved_model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7835216fc070946e00e9254596ac23cb784fa9bbe819669c206e2b90f0a5ba1d
3
+ size 51029
tomato_saved_model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7249074d9b98c5efc6d99b383111be64fc7bf87f0b18990321e735edd61b1cf3
3
+ size 430110
tomato_saved_model/variables/variables.data-00000-of-00001 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:182f729158f0839b1944352e46e2c364d69c5cc50d4d6754999d213dc764a0f8
3
+ size 2063728
tomato_saved_model/variables/variables.index ADDED
Binary file (2.87 kB). View file