bhavibhatt commited on
Commit
cf8196b
·
verified ·
1 Parent(s): 6006447

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ import tempfile
4
+ import tensorflow as tf
5
+ from flask import Flask, request, render_template, redirect
6
+ from io import BytesIO
7
+
8
+ # Initialize application
9
+ app = Flask(__name__)
10
+
11
+ # Load the Model
12
+ MODEL_PATH = 'waste_classifier_final_5.h5'
13
+ try:
14
+ model = tf.keras.models.load_model(MODEL_PATH)
15
+ print("Image classification model loaded successfully!")
16
+ except Exception as e:
17
+ print(f"Error loading image model: {e}")
18
+ exit()
19
+
20
+ CLASS_NAMES = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
21
+
22
+
23
+ def preprocess_image(image_path):
24
+ img = tf.keras.preprocessing.image.load_img(image_path, target_size=(224, 224))
25
+ img_array = tf.keras.preprocessing.image.img_to_array(img)
26
+ img_array = tf.expand_dims(img_array, 0)
27
+
28
+ return tf.keras.applications.efficientnet.preprocess_input(img_array)
29
+
30
+ @app.route('/', methods=['GET'])
31
+ def index():
32
+ return render_template('index.html')
33
+
34
+ @app.route('/predict', methods=['POST'])
35
+ def predict():
36
+ if 'file' not in request.files:
37
+ return redirect(request.url)
38
+ file = request.files['file']
39
+ if file.filename == '':
40
+ return redirect(request.url)
41
+
42
+ if file:
43
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp_file:
44
+ filepath = tmp_file.name
45
+ file.save(filepath)
46
+
47
+ with open(filepath, "rb") as f:
48
+ image_data = f.read()
49
+
50
+ encoded_image = base64.b64encode(image_data).decode('utf-8')
51
+ image_to_display = f"data:image/jpeg;base64,{encoded_image}"
52
+
53
+ preprocessed_image = preprocess_image(filepath)
54
+ prediction = model.predict(preprocessed_image)
55
+
56
+ predicted_class_index = tf.argmax(prediction[0]).numpy()
57
+ predicted_class = CLASS_NAMES[predicted_class_index]
58
+ confidence = tf.reduce_max(prediction[0]).numpy() * 100
59
+
60
+ os.remove(filepath)
61
+
62
+ return render_template('index.html',
63
+ prediction=f'Prediction: {predicted_class}',
64
+ confidence=f'Confidence: {confidence:.2f}%',
65
+ uploaded_image=image_to_display)
66
+
67
+ return redirect(request.url)
68
+
69
+ if __name__ == '__main__':
70
+ app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))