Mahdewa/grape-leaf-disease-classify
0
1from flask import Flask, request, jsonify
2from flask_cors import CORS
3import tensorflow as tf
4import numpy as np
5from PIL import Image, ImageOps
6import io
7import os
8
9app = Flask(__name__)
10CORS(app)
11
12try:
13 model = tf.keras.models.load_model('model_terbaik_klasifikasi_anggur.h5')
14 print("✅ Model berhasil dimuat!")
15except:
16 print("❌ Model tidak ditemukan.")
17 model = None
18
19# Definisi Kelas
20CLASS_NAMES = [
21 'Grape___Black_rot',
22 'Grape___Esca_(Black_Measles)',
23 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',
24 'Grape___healthy'
25]
26
27@app.route('/predict', methods=['POST'])
28def predict():
29 if 'file' not in request.files:
30 return jsonify({'error': 'Tidak ada file diupload'}), 400
31
32 file = request.files['file']
33
34 try:
35 # 2. PREPROCESSING IMAGE
36 # Baca gambar langsung dari memori (tanpa save ke disk dulu)
37 image = Image.open(file.stream)
38
39 # Resize ke 128x128 (Sesuai training di Kaggle)
40 image = ImageOps.fit(image, (128, 128), Image.Resampling.LANCZOS)
41
42 # Convert ke Array & Normalisasi (Sesuai training 1./255)
43 img_array = np.asarray(image)
44 img_array = img_array / 255.0
45
46 # Tambah dimensi batch (Jadi (1, 128, 128, 3))
47 img_array = np.expand_dims(img_array, axis=0)
48
49 # 3. PREDIKSI
50 if model is None:
51 return jsonify({'error': 'Model belum siap'}), 500
52
53 prediction = model.predict(img_array)
54 class_index = np.argmax(prediction)
55 confidence = float(np.max(prediction) * 100)
56
57 result_class = CLASS_NAMES[class_index]
58
59 # Kirim respons JSON ke React
60 return jsonify({
61 'class': result_class,
62 'confidence': f"{confidence:.2f}",
63 'status': 'success'
64 })
65
66 except Exception as e:
67 print(e)
68 return jsonify({'error': str(e)}), 500
69
70if __name__ == '__main__':
71 app.run(host='0.0.0.0', port=7860)