Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,26 +1,59 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
|
|
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, redirect, url_for
|
| 2 |
+
from tensorflow.keras.models import load_model
|
| 3 |
+
from tensorflow.keras.preprocessing import image
|
| 4 |
import numpy as np
|
| 5 |
+
import os
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
+
# Initialize the Flask app
|
| 9 |
+
app = Flask(__name__)
|
| 10 |
+
|
| 11 |
+
# Load trained model
|
| 12 |
+
MODEL_PATH = 'my_model.h5'
|
| 13 |
+
model = load_model(MODEL_PATH)
|
| 14 |
+
|
| 15 |
+
# List of class names (from LabelEncoder's `classes_`)
|
| 16 |
+
class_names = ['Acacia', 'Acer', 'Alnus', 'Anadenanthera', 'Betula', 'Celtis', 'Chamaerops',
|
| 17 |
+
'Corylus', 'Eucalyptus', 'Fagus', 'Fraxinus', 'Juglans', 'Laurus', 'Morus',
|
| 18 |
+
'Pinus', 'Platanus', 'Populus', 'Quercus', 'Salix', 'Tamarix', 'Tilia',
|
| 19 |
+
'Ulmus', 'Zea']
|
| 20 |
+
|
| 21 |
+
# Home route
|
| 22 |
+
@app.route('/')
|
| 23 |
+
def index():
|
| 24 |
+
return render_template('index.html')
|
| 25 |
+
|
| 26 |
+
# Predict route
|
| 27 |
+
@app.route('/predict', methods=['POST'])
|
| 28 |
+
def predict():
|
| 29 |
+
if 'file' not in request.files:
|
| 30 |
+
return redirect(request.url)
|
| 31 |
+
|
| 32 |
+
file = request.files['file']
|
| 33 |
+
if file.filename == '':
|
| 34 |
+
return redirect(request.url)
|
| 35 |
+
|
| 36 |
+
if file:
|
| 37 |
+
# Save the uploaded file
|
| 38 |
+
filepath = os.path.join('static', file.filename)
|
| 39 |
+
file.save(filepath)
|
| 40 |
+
|
| 41 |
+
# Load image
|
| 42 |
+
img = Image.open(filepath).convert("RGB")
|
| 43 |
+
img = img.resize((128, 128))
|
| 44 |
+
img_array = np.array(img) / 255.0
|
| 45 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 46 |
+
|
| 47 |
+
# Predict
|
| 48 |
+
predictions = model.predict(img_array)
|
| 49 |
+
class_index = np.argmax(predictions)
|
| 50 |
+
predicted_label = class_names[class_index]
|
| 51 |
+
confidence = round(100 * np.max(predictions), 2)
|
| 52 |
+
|
| 53 |
+
return render_template('result.html', label=predicted_label, confidence=confidence, image_path=filepath)
|
| 54 |
+
|
| 55 |
+
return redirect(url_for('index'))
|
| 56 |
+
|
| 57 |
+
# Run the app
|
| 58 |
+
if __name__ == '__main__':
|
| 59 |
+
app.run(debug=True)
|