prastya commited on
Commit
23514ec
·
verified ·
1 Parent(s): 956aeaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -54
app.py CHANGED
@@ -1,18 +1,25 @@
1
- import gradio as gr
2
- import numpy as np
3
- import tensorflow as tf
4
  from tensorflow.keras.models import load_model
5
- from tensorflow.keras.preprocessing import image # Perhatikan, ini mungkin tidak diperlukan jika menggunakan PIL Image langsung
6
  from PIL import Image
7
- from io import BytesIO
8
- import os # Tambahkan ini untuk manajemen path file
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # 1. Konstanta dan Pemuatan Model (di luar fungsi)
11
- # Pemuatan model harus dilakukan sekali saat aplikasi dimulai
12
  MODEL_PATH = 'model_cnn.h5'
13
  IMG_HEIGHT = 224
14
  IMG_WIDTH = 224
15
-
16
  class_names = [
17
  'freshapples', 'freshbanana', 'freshbittergroud', 'freshcapsicum', 'freshcucumber',
18
  'freshokra', 'freshoranges', 'freshpotato', 'freshtomato',
@@ -20,63 +27,33 @@ class_names = [
20
  'rottenokra', 'rottenoranges', 'rottenpotato', 'rottentomato'
21
  ]
22
 
23
- # Pastikan path model benar, gunakan os.path.join untuk robustness
24
  try:
25
- # os.getcwd() akan mengembalikan direktori kerja saat ini di lingkungan Space
26
  full_model_path = os.path.join(os.getcwd(), MODEL_PATH)
27
  model = load_model(full_model_path)
28
  print(f"Model loaded successfully from: {full_model_path}")
29
  except Exception as e:
30
- print(f"Error loading model from {full_model_path}: {e}")
31
- # Jika model gagal dimuat, aplikasi tidak bisa berjalan.
32
- # Disarankan untuk mengeluarkan error agar build gagal jika ini terjadi
33
  raise RuntimeError(f"Failed to load model: {e}")
34
 
35
-
36
- # 2. Fungsi Prediksi untuk Gradio
37
- # Gradio akan melewatkan input gambar dalam format numpy array jika Anda menggunakan gr.Image(type="numpy")
38
- # atau sebagai path string jika Anda menggunakan gr.Image(type="filepath").
39
- # Saya sarankan type="numpy" karena lebih mudah diproses langsung.
40
- def predict_image_gradio(input_image_numpy_array):
41
- if input_image_numpy_array is None:
42
- return "Mohon unggah gambar."
43
-
44
  try:
45
- # Konversi numpy array yang diberikan Gradio ke PIL Image
46
- img = Image.fromarray(input_image_numpy_array.astype('uint8'), 'RGB')
47
-
48
- # Lakukan pre-processing seperti yang Anda lakukan di FastAPI
49
- img = img.resize((IMG_WIDTH, IMG_HEIGHT))
50
- img_array = np.array(img) # Konversi kembali ke numpy array
51
- img_array = np.expand_dims(img_array, axis=0) # Tambahkan batch dimension
52
 
53
- # Lakukan prediksi
54
  prediction = model.predict(img_array)
55
-
56
- # Post-processing hasil
57
  predicted_class_index = np.argmax(prediction[0])
58
  confidence = float(prediction[0][predicted_class_index]) * 100
59
  pred_class_name = class_names[predicted_class_index]
60
 
61
- # Format output untuk Gradio (string teks)
62
- return f"Hasil Klasifikasi: {pred_class_name}\nTingkat Kepercayaan: {confidence:.2f}%"
63
-
 
 
 
64
  except Exception as e:
65
- return f"Terjadi kesalahan saat memproses gambar: {str(e)}"
66
-
67
- # 3. Definisikan Antarmuka Gradio
68
- # Pastikan 'inputs' dan 'outputs' sesuai dengan fungsi 'predict_image_gradio'
69
- iface = gr.Interface(
70
- fn=predict_image_gradio,
71
- inputs=gr.Image(type="numpy", label="Unggah Gambar Makanan"), # Gradio akan memberikan numpy array dari gambar
72
- outputs=gr.Textbox(label="Prediksi"), # Output berupa teks
73
- title="Demo Deteksi Kesegaran Makanan dengan CNN",
74
- description="Unggah gambar apel, pisang, pare, paprika, timun, bendi, jeruk, kentang, atau tomat untuk memprediksi kesegarannya (segar atau busuk)."
75
- )
76
-
77
- # 4. Luncurkan Aplikasi Gradio (tanpa if __name__ == "__main__":)
78
- iface.launch()
79
-
80
- # Komentar atau hapus semua kode FastAPI sebelumnya (dari `app = FastAPI()` hingga bawah)
81
- # Hapus juga import FastAPI, File, UploadFile, JSONResponse, CORSMiddleware
82
- # karena sudah tidak relevan untuk Gradio.
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
 
3
  from tensorflow.keras.models import load_model
4
+ import numpy as np
5
  from PIL import Image
6
+ import io
7
+ import os
8
+
9
+ app = FastAPI()
10
+
11
+ # Untuk mengizinkan akses dari frontend kamu (misal domain lain)
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"], # Ganti dengan domain frontend-mu kalau sudah pasti
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
 
 
 
20
  MODEL_PATH = 'model_cnn.h5'
21
  IMG_HEIGHT = 224
22
  IMG_WIDTH = 224
 
23
  class_names = [
24
  'freshapples', 'freshbanana', 'freshbittergroud', 'freshcapsicum', 'freshcucumber',
25
  'freshokra', 'freshoranges', 'freshpotato', 'freshtomato',
 
27
  'rottenokra', 'rottenoranges', 'rottenpotato', 'rottentomato'
28
  ]
29
 
 
30
  try:
 
31
  full_model_path = os.path.join(os.getcwd(), MODEL_PATH)
32
  model = load_model(full_model_path)
33
  print(f"Model loaded successfully from: {full_model_path}")
34
  except Exception as e:
35
+ print(f"Error loading model: {e}")
 
 
36
  raise RuntimeError(f"Failed to load model: {e}")
37
 
38
+ @app.post("/predict")
39
+ async def predict_image(file: UploadFile = File(...)):
 
 
 
 
 
 
 
40
  try:
41
+ contents = await file.read()
42
+ image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
43
+ image_pil = image_pil.resize((IMG_WIDTH, IMG_HEIGHT))
44
+ img_array = np.array(image_pil)
45
+ img_array = np.expand_dims(img_array, axis=0)
 
 
46
 
 
47
  prediction = model.predict(img_array)
 
 
48
  predicted_class_index = np.argmax(prediction[0])
49
  confidence = float(prediction[0][predicted_class_index]) * 100
50
  pred_class_name = class_names[predicted_class_index]
51
 
52
+ return {
53
+ "title": pred_class_name,
54
+ "confidence": f"{confidence:.2f}",
55
+ "message": f"Prediksi: {pred_class_name} dengan kepercayaan {confidence:.2f}%",
56
+ "details": []
57
+ }
58
  except Exception as e:
59
+ raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")