133 lines
3.6 KiB
Python
133 lines
3.6 KiB
Python
from flask import Flask, request, jsonify
|
|
from flask_cors import CORS
|
|
import os
|
|
from datetime import datetime
|
|
import numpy as np
|
|
from PIL import Image
|
|
from tensorflow.keras.models import load_model
|
|
|
|
app = Flask(__name__)
|
|
CORS(app)
|
|
|
|
UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'uploads')
|
|
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
|
|
|
# 1. Sesuaikan nama file model!
|
|
MODEL_PATH = os.path.join(os.path.dirname(__file__), 'model_padi.h5')
|
|
|
|
# 2. Sesuaikan dengan urutan class di Colab kamu (4 class)
|
|
CLASS_NAMES = [
|
|
'Healthy',
|
|
'Blast',
|
|
'Blight',
|
|
'Tungro'
|
|
]
|
|
|
|
DESCRIPTIONS = {
|
|
'Healthy': {
|
|
'deskripsi': 'Kondisi tanaman sehat.',
|
|
'solusi': 'Lanjutkan perawatan normal dan pemantauan rutin.'
|
|
},
|
|
'Blast': {
|
|
'deskripsi': 'Blast adalah penyakit daun padi akibat jamur Pyricularia oryzae.',
|
|
'solusi': 'Lakukan pengendalian jamur dan semprot fungisida sesuai anjuran.'
|
|
},
|
|
'Blight': {
|
|
'deskripsi': 'Blight merupakan hawar daun bakteri.',
|
|
'solusi': 'Gunakan varietas tahan dan sanitasi lahan yang baik.'
|
|
},
|
|
'Tungro': {
|
|
'deskripsi': 'Tungro adalah penyakit virus yang ditularkan oleh wereng.',
|
|
'solusi': 'Lakukan pengendalian hama wereng dan gunakan benih sehat.'
|
|
}
|
|
}
|
|
|
|
# Load model
|
|
model = None
|
|
|
|
try:
|
|
model = load_model(MODEL_PATH)
|
|
print('Model berhasil dimuat dari', MODEL_PATH)
|
|
except Exception as e:
|
|
print("Gagal load model:", e)
|
|
|
|
def preprocess_image(path):
|
|
|
|
image = Image.open(path).convert('RGB')
|
|
|
|
image = image.resize((224, 224))
|
|
|
|
image_array = np.array(image).astype('float32') / 255.0
|
|
|
|
image_array = np.expand_dims(image_array, axis=0)
|
|
|
|
return image_array
|
|
|
|
@app.route('/prediksi', methods=['POST'])
|
|
def prediksi():
|
|
# 3. Menerima request dengan key 'gambar'
|
|
if 'gambar' not in request.files:
|
|
return jsonify({
|
|
'error': 'Tidak ada gambar'
|
|
}), 400
|
|
|
|
file = request.files['gambar']
|
|
|
|
if file.filename == '':
|
|
return jsonify({
|
|
'error': 'File kosong'
|
|
}), 400
|
|
|
|
# Simpan gambar
|
|
filename = datetime.now().strftime('%Y%m%d%H%M%S_') + file.filename
|
|
|
|
filepath = os.path.join(UPLOAD_FOLDER, filename)
|
|
|
|
file.save(filepath)
|
|
|
|
print("Gambar diterima:", filename)
|
|
|
|
if model is None:
|
|
return jsonify({'error': 'Model tidak tersedia. Pastikan file .h5 ada.'}), 500
|
|
|
|
try:
|
|
|
|
# Preprocessing
|
|
image_array = preprocess_image(filepath)
|
|
predictions = model.predict(image_array, verbose=0)
|
|
predicted_index = int(np.argmax(predictions, axis=1)[0])
|
|
confidence = float(np.max(predictions, axis=1)[0]) * 100.0
|
|
label = CLASS_NAMES[predicted_index] if predicted_index < len(CLASS_NAMES) else f'Kelas {predicted_index + 1}'
|
|
|
|
confidence_display = f'{confidence:.2f}%'
|
|
all_predictions = {
|
|
CLASS_NAMES[i]: float(predictions[0][i] * 100.0)
|
|
for i in range(len(CLASS_NAMES))
|
|
}
|
|
description_data = DESCRIPTIONS.get(label, {
|
|
'deskripsi': 'Tidak ada deskripsi tersedia.',
|
|
'solusi': 'Tidak ada solusi tersedia.'
|
|
})
|
|
|
|
return jsonify({
|
|
'penyakit': label,
|
|
'confidence': confidence_display,
|
|
'all_predictions': all_predictions,
|
|
'deskripsi': description_data['deskripsi'],
|
|
'solusi': description_data['solusi']
|
|
})
|
|
|
|
except Exception as e:
|
|
|
|
print("ERROR:", e)
|
|
|
|
return jsonify({
|
|
'error': str(e)
|
|
}), 500
|
|
|
|
|
|
if __name__ == '__main__':
|
|
print('=' * 50)
|
|
print('Klasifikasi Penyakit Daun Padi')
|
|
print('=' * 50)
|
|
app.run(host='127.0.0.1', port=5000, debug=False) |