ujan2003 commited on
Commit
89c08b7
Β·
verified Β·
1 Parent(s): 420366f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -13
app.py CHANGED
@@ -7,40 +7,68 @@ from werkzeug.utils import secure_filename
7
 
8
  app = Flask(__name__)
9
 
10
- # Load trained model
11
- model = tf.keras.models.load_model("trained.h5")
 
 
12
 
13
- # Define allowed extensions
14
  ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}
15
 
16
  def allowed_file(filename):
17
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
 
 
 
 
 
 
 
18
 
19
  def preprocess_image(img_path):
20
- img = image.load_img(img_path, target_size=(150, 150)) # Resize to model input size
21
- img_array = image.img_to_array(img) / 255.0 # Normalize
22
- img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
23
- return img_array
 
 
 
 
 
24
 
25
  @app.route("/predict", methods=["POST"])
26
  def predict():
 
 
 
 
27
  if "file" not in request.files:
28
  return jsonify({"error": "No file uploaded"}), 400
29
 
30
  file = request.files["file"]
31
-
32
  if file.filename == "":
33
  return jsonify({"error": "No selected file"}), 400
34
 
35
  if file and allowed_file(file.filename):
36
  filename = secure_filename(file.filename)
37
- file_path = os.path.join("uploads", filename)
38
  file.save(file_path)
39
 
40
  img_array = preprocess_image(file_path)
41
- prediction = model.predict(img_array)[0][0]
 
 
 
 
 
 
 
 
 
42
 
43
- os.remove(file_path) # Clean up
44
 
45
  result = "Pneumonia Detected" if prediction > 0.5 else "No Pneumonia"
46
  confidence = float(prediction) if prediction > 0.5 else 1 - float(prediction)
@@ -50,4 +78,4 @@ def predict():
50
  return jsonify({"error": "Invalid file format"}), 400
51
 
52
  if __name__ == "__main__":
53
- app.run(host="0.0.0.0", port=7860)
 
7
 
8
  app = Flask(__name__)
9
 
10
+ # Ensure the uploads directory exists
11
+ UPLOAD_FOLDER = "uploads"
12
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
13
+ app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
14
 
15
+ # Allowed file types
16
  ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}
17
 
18
  def allowed_file(filename):
19
+ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
20
+
21
+ # Load trained model
22
+ try:
23
+ model = tf.keras.models.load_model("trained.h5")
24
+ print("βœ… Model loaded successfully")
25
+ except Exception as e:
26
+ print(f"❌ Error loading model: {str(e)}")
27
+ model = None
28
 
29
  def preprocess_image(img_path):
30
+ """ Preprocesses image for model prediction. """
31
+ try:
32
+ img = image.load_img(img_path, target_size=(150, 150)) # Resize
33
+ img_array = image.img_to_array(img) / 255.0 # Normalize
34
+ img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
35
+ return img_array
36
+ except Exception as e:
37
+ print(f"❌ Error in image preprocessing: {str(e)}")
38
+ return None
39
 
40
  @app.route("/predict", methods=["POST"])
41
  def predict():
42
+ """ Handles image upload and model prediction. """
43
+ if model is None:
44
+ return jsonify({"error": "Model not loaded. Check logs for details."}), 500
45
+
46
  if "file" not in request.files:
47
  return jsonify({"error": "No file uploaded"}), 400
48
 
49
  file = request.files["file"]
50
+
51
  if file.filename == "":
52
  return jsonify({"error": "No selected file"}), 400
53
 
54
  if file and allowed_file(file.filename):
55
  filename = secure_filename(file.filename)
56
+ file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
57
  file.save(file_path)
58
 
59
  img_array = preprocess_image(file_path)
60
+ if img_array is None:
61
+ os.remove(file_path)
62
+ return jsonify({"error": "Invalid image format"}), 400
63
+
64
+ try:
65
+ prediction = model.predict(img_array)[0][0]
66
+ except Exception as e:
67
+ os.remove(file_path)
68
+ print(f"❌ Prediction Error: {str(e)}")
69
+ return jsonify({"error": "Error making prediction"}), 500
70
 
71
+ os.remove(file_path) # Cleanup
72
 
73
  result = "Pneumonia Detected" if prediction > 0.5 else "No Pneumonia"
74
  confidence = float(prediction) if prediction > 0.5 else 1 - float(prediction)
 
78
  return jsonify({"error": "Invalid file format"}), 400
79
 
80
  if __name__ == "__main__":
81
+ app.run(host="0.0.0.0", port=7860, debug=True, threaded=True)