bhavibhatt commited on
Commit
3ab979a
·
verified ·
1 Parent(s): e0763ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -30
app.py CHANGED
@@ -1,34 +1,35 @@
1
  import os
 
 
2
  import tensorflow as tf
3
- from flask import Flask, request, render_template, redirect, url_for
4
- from werkzeug.utils import secure_filename
5
 
6
  # Initialize the Flask application
7
  app = Flask(__name__)
8
 
9
- # --- Load the Clean, Compatible .h5 Model ---
10
- # This model was saved with save_format='h5' for maximum compatibility.
11
- MODEL_PATH = 'waste_classifier_final_5.h5'
12
  try:
13
  model = tf.keras.models.load_model(MODEL_PATH)
14
- print("Image classification model loaded successfully!")
15
  except Exception as e:
16
- print(f"Error loading image model: {e}")
17
  exit()
18
 
19
- # Define the class names in the correct order for the model's output
 
20
  CLASS_NAMES = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
21
 
 
22
  def preprocess_image(image_path):
23
- """
24
- Loads an image from a file path and preprocesses it for the model.
25
- This function ensures the input image matches the format used during training.
26
- """
27
  img = tf.keras.preprocessing.image.load_img(image_path, target_size=(224, 224))
28
  img_array = tf.keras.preprocessing.image.img_to_array(img)
29
- img_array = tf.expand_dims(img_array, 0) # Create a batch of one
30
- # Apply the MobileNetV2-specific preprocessing
31
- return tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
32
 
33
  @app.route('/', methods=['GET'])
34
  def index():
@@ -37,8 +38,7 @@ def index():
37
 
38
  @app.route('/predict', methods=['POST'])
39
  def predict():
40
- """Handles the image upload, prediction, and renders the result."""
41
- # Check if a file was uploaded
42
  if 'file' not in request.files:
43
  return redirect(request.url)
44
  file = request.files['file']
@@ -46,30 +46,31 @@ def predict():
46
  return redirect(request.url)
47
 
48
  if file:
49
- # Save the file securely
50
- filename = secure_filename(file.filename)
51
- filepath = os.path.join('static/uploads', filename)
52
- file.save(filepath)
 
 
 
 
 
53
 
54
- # Preprocess the image and get a prediction
55
  preprocessed_image = preprocess_image(filepath)
56
  prediction = model.predict(preprocessed_image)
57
 
58
- # Decode the prediction
59
  predicted_class_index = tf.argmax(prediction[0]).numpy()
60
  predicted_class = CLASS_NAMES[predicted_class_index]
61
  confidence = tf.reduce_max(prediction[0]).numpy() * 100
62
 
63
- # Pass the results to the HTML template
 
64
  return render_template('index.html',
65
  prediction=f'Prediction: {predicted_class}',
66
  confidence=f'Confidence: {confidence:.2f}%',
67
- uploaded_image=filepath)
 
68
  return redirect(request.url)
69
 
70
  if __name__ == '__main__':
71
- # Ensure the upload folder exists
72
- os.makedirs('static/uploads', exist_ok=True)
73
- # This host and port configuration is important for deployment services like Hugging Face
74
- app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
75
-
 
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 the Flask application
9
  app = Flask(__name__)
10
 
11
+ # --- Load the Model ---
12
+ # This now points to the directory created by model.export()
13
+ MODEL_PATH = 'waste_classifier_final_5.h5' # IMPORTANT: Ensure this matches your uploaded model's filename
14
  try:
15
  model = tf.keras.models.load_model(MODEL_PATH)
16
+ print("Image classification model loaded successfully!")
17
  except Exception as e:
18
+ print(f"Error loading image model: {e}")
19
  exit()
20
 
21
+ # --- CRITICAL: Ensure this list EXACTLY matches the output from your training script ---
22
+ # Example: ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
23
  CLASS_NAMES = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
24
 
25
+
26
  def preprocess_image(image_path):
27
+ """Loads and preprocesses an image for the model."""
 
 
 
28
  img = tf.keras.preprocessing.image.load_img(image_path, target_size=(224, 224))
29
  img_array = tf.keras.preprocessing.image.img_to_array(img)
30
+ img_array = tf.expand_dims(img_array, 0)
31
+ # --- UPDATED: Switched to the correct preprocessing for EfficientNet ---
32
+ return tf.keras.applications.efficientnet.preprocess_input(img_array)
33
 
34
  @app.route('/', methods=['GET'])
35
  def index():
 
38
 
39
  @app.route('/predict', methods=['POST'])
40
  def predict():
41
+ """Handles image upload, prediction, and renders the result."""
 
42
  if 'file' not in request.files:
43
  return redirect(request.url)
44
  file = request.files['file']
 
46
  return redirect(request.url)
47
 
48
  if file:
49
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp_file:
50
+ filepath = tmp_file.name
51
+ file.save(filepath)
52
+
53
+ with open(filepath, "rb") as f:
54
+ image_data = f.read()
55
+
56
+ encoded_image = base64.b64encode(image_data).decode('utf-8')
57
+ image_to_display = f"data:image/jpeg;base64,{encoded_image}"
58
 
 
59
  preprocessed_image = preprocess_image(filepath)
60
  prediction = model.predict(preprocessed_image)
61
 
 
62
  predicted_class_index = tf.argmax(prediction[0]).numpy()
63
  predicted_class = CLASS_NAMES[predicted_class_index]
64
  confidence = tf.reduce_max(prediction[0]).numpy() * 100
65
 
66
+ os.remove(filepath)
67
+
68
  return render_template('index.html',
69
  prediction=f'Prediction: {predicted_class}',
70
  confidence=f'Confidence: {confidence:.2f}%',
71
+ uploaded_image=image_to_display)
72
+
73
  return redirect(request.url)
74
 
75
  if __name__ == '__main__':
76
+ app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))