prastya commited on
Commit
5886919
·
verified ·
1 Parent(s): 8d023ef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -48
app.py CHANGED
@@ -2,12 +2,12 @@ from fastapi import FastAPI, File, UploadFile
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import uvicorn
5
- import numpy as np
6
- import tensorflow as tf
7
- from tensorflow.keras.models import load_model
8
- from tensorflow.keras.preprocessing import image
9
- from PIL import Image
10
- from io import BytesIO
11
 
12
  # === Inisialisasi FastAPI ===
13
  app = FastAPI()
@@ -15,66 +15,45 @@ app = FastAPI()
15
  # === Middleware CORS agar bisa diakses dari frontend (JS) ===
16
  app.add_middleware(
17
  CORSMiddleware,
18
- allow_origins=["*"], # Ganti dengan domain frontend-mu untuk keamanan
19
  allow_credentials=True,
20
  allow_methods=["*"],
21
  allow_headers=["*"],
22
  )
23
 
24
- # === Konfigurasi Model ===
25
- MODEL_PATH = 'model_cnn.h5' # Pastikan path model benar
26
- IMG_HEIGHT = 224
27
- IMG_WIDTH = 224
 
 
28
 
29
- class_names = [
30
- 'freshapples', 'freshbanana', 'freshbittergroud', 'freshcapsicum', 'freshcucumber',
31
- 'freshokra', 'freshoranges', 'freshpotato', 'freshtomato',
32
- 'rottenapples', 'rottenbanana', 'rottenbittergroud', 'rottencapsicum', 'rottencucumber',
33
- 'rottenokra', 'rottenoranges', 'rottenpotato', 'rottentomato'
34
- ]
35
-
36
- # Muat model sekali saja saat startup
37
- model = load_model(MODEL_PATH)
38
-
39
- # === Fungsi bantu ===
40
- def read_imagefile(file) -> Image.Image:
41
- image = Image.open(BytesIO(file)).convert("RGB") # Pastikan RGB
42
- return image
43
-
44
- def predict(img: Image.Image):
45
- # Resize dan ubah ke array tanpa normalisasi ulang (karena model sudah punya Rescaling)
46
- img = img.resize((IMG_WIDTH, IMG_HEIGHT))
47
- img_array = image.img_to_array(img) # [0,255]
48
- img_array = np.expand_dims(img_array, axis=0) # [1, 224, 224, 3]
49
-
50
- prediction = model.predict(img_array)
51
- predicted_class = np.argmax(prediction[0])
52
- confidence = float(prediction[0][predicted_class]) * 100
53
-
54
- return class_names[predicted_class], confidence
55
 
56
  # === Endpoint utama ===
57
  @app.post("/predict")
58
  async def predict_image(file: UploadFile = File(...)):
59
  try:
60
- img = read_imagefile(await file.read())
61
- pred_class, confidence = predict(img)
 
62
 
63
  response = {
64
  "filename": file.filename,
65
- "title": "Prediction Result",
66
- "message": f"The item is classified as: {pred_class}",
67
- "confidence": f"{confidence:.2f}",
68
- "details": [f"Class: {pred_class}", f"Confidence: {confidence:.2f}%"]
69
  }
70
 
71
  return JSONResponse(content=response)
72
  except Exception as e:
73
  return JSONResponse(content={"error": str(e)}, status_code=500)
74
 
75
- # === Untuk menjalankan secara lokal ===
76
  if __name__ == "__main__":
77
- import uvicorn
78
- uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)
79
-
80
- # uvicorn app:app --reload
 
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import uvicorn
5
+ # import numpy as np # <-- KOMENTARI ATAU HAPUS BARIS INI
6
+ # import tensorflow as tf # <-- KOMENTARI ATAU HAPUS BARIS INI
7
+ # from tensorflow.keras.models import load_model # <-- KOMENTARI ATAU HAPUS BARIS INI
8
+ # from tensorflow.keras.preprocessing import image # <-- KOMENTARI ATAU HAPUS BARIS INI
9
+ from PIL import Image # <-- TETAPKAN INI JIKA KAMU MASIH INGIN MENERIMA FILE
10
+ from io import BytesIO # <-- TETAPKAN INI JIKA KAMU MASIH INGIN MENERIMA FILE
11
 
12
  # === Inisialisasi FastAPI ===
13
  app = FastAPI()
 
15
  # === Middleware CORS agar bisa diakses dari frontend (JS) ===
16
  app.add_middleware(
17
  CORSMiddleware,
18
+ allow_origins=["*"],
19
  allow_credentials=True,
20
  allow_methods=["*"],
21
  allow_headers=["*"],
22
  )
23
 
24
+ # === Konfigurasi Model === (KOMENTARI ATAU HAPUS SELURUH BAGIAN INI)
25
+ # MODEL_PATH = 'model_cnn.h5'
26
+ # IMG_HEIGHT = 224
27
+ # IMG_WIDTH = 224
28
+ # class_names = [...]
29
+ # model = load_model(MODEL_PATH)
30
 
31
+ # === Fungsi bantu === (KOMENTARI ATAU HAPUS SELURUH BAGIAN INI)
32
+ # def read_imagefile(file) -> Image.Image:
33
+ # image = Image.open(BytesIO(file)).convert("RGB")
34
+ # return image
35
+ # def predict(img: Image.Image):
36
+ # # ... prediction logic ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # === Endpoint utama ===
39
  @app.post("/predict")
40
  async def predict_image(file: UploadFile = File(...)):
41
  try:
42
+ # Kita tidak akan memproses file, hanya menerima untuk demo
43
+ # await file.read() # <-- Bisa dikomentari juga jika tidak perlu baca filenya
44
+ # read_imagefile(await file.read()) # <-- Pastikan ini tidak dipanggil
45
 
46
  response = {
47
  "filename": file.filename,
48
+ "title": "Prediction Result (DUMMY)",
49
+ "message": "Ini adalah respons DUMMY. API berfungsi!",
50
+ "confidence": "99.99",
51
+ "details": ["Class: dummy_class", "Confidence: 99.99%"]
52
  }
53
 
54
  return JSONResponse(content=response)
55
  except Exception as e:
56
  return JSONResponse(content={"error": str(e)}, status_code=500)
57
 
 
58
  if __name__ == "__main__":
59
+ uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)