MIF_E31230820/python_ai/app.py

73 lines
2.3 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_blast.h5')
# 2. Sesuaikan dengan urutan class di Colab kamu (4 class)
CLASS_NAMES = ['Healthy', 'Blast', 'Blight', 'Tungro']
model = None
try:
model = load_model(MODEL_PATH)
print('Model berhasil dimuat dari', MODEL_PATH)
except Exception as e:
print('Gagal memuat model:', e)
def preprocess_image(path):
image = Image.open(path).convert('RGB')
image = image.resize((150, 150))
image_array = np.array(image).astype('float32') / 255.0
return np.expand_dims(image_array, axis=0)
@app.route('/prediksi', methods=['POST'])
def prediksi():
# 3. Menerima request dengan key 'gambar'
if 'gambar' not in request.files:
return jsonify({'error': 'Tidak ada file gambar'}), 400
file = request.files['gambar']
if file.filename == '':
return jsonify({'error': 'Nama file kosong'}), 400
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:
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}'
return jsonify({
'penyakit': label,
'confidence': round(confidence, 2)
})
except Exception as e:
print('Gagal prediksi:', e)
return jsonify({'error': 'Terjadi kesalahan saat memprediksi gambar.'}), 500
if __name__ == '__main__':
print('=' * 50)
print('Klasifikasi Penyakit Daun Padi')
print('=' * 50)
app.run(host='127.0.0.1', port=5000, debug=False)