SoulMind01 commited on
Commit
9163080
·
1 Parent(s): 7205e49

Updated `app.py`. Made it accessible from external machines.

Browse files
Files changed (1) hide show
  1. app.py +20 -49
app.py CHANGED
@@ -1,43 +1,42 @@
1
- from flask import Flask, render_template, request
2
  import numpy as np
3
  from tensorflow.keras.models import load_model
4
  from PIL import Image
5
- import os
6
-
7
- app = Flask(__name__)
8
 
9
  # Load the trained model
10
  MODEL_PATH = "vgg19_fine_tuned_block5_91.keras"
11
  model = load_model(MODEL_PATH)
12
 
13
  # Define class labels and confidence threshold
14
- CLASS_LABELS = ['NORMAL', 'PNEUMONIA']
15
  CONFIDENCE_THRESHOLD = 0.7
16
 
17
- def preprocess_image(file_path):
 
18
  """
19
  Preprocesses the input image for the model.
20
  Args:
21
- file_path (str): Path to the input image.
22
  Returns:
23
  numpy.ndarray: Preprocessed image ready for prediction.
24
  """
25
- img = Image.open(file_path).convert('RGB') # Ensure the image is RGB
26
  img = img.resize((128, 128)) # Resize to model's input size
27
  img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]
28
  img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
29
  return img_array
30
 
31
- def predict_image(file_path):
 
32
  """
33
  Predicts the class of the input image with confidence-based filtering.
34
  Args:
35
- file_path (str): Path to the input image.
36
  Returns:
37
  str: Predicted class label or uncertainty message.
38
  float: Confidence score (if applicable).
39
  """
40
- img_array = preprocess_image(file_path)
41
  prediction = model.predict(img_array)
42
  confidence = np.max(prediction)
43
 
@@ -48,44 +47,16 @@ def predict_image(file_path):
48
  predicted_class = CLASS_LABELS[np.argmax(prediction)]
49
  return predicted_class, confidence
50
 
51
- @app.route("/", methods=["GET"])
52
- def home():
53
- return render_template("index.html")
54
-
55
- @app.route("/predict", methods=["POST"])
56
- def predict():
57
- if "file" not in request.files:
58
- return "No file uploaded", 400
59
-
60
- file = request.files["file"]
61
- if file.filename == "":
62
- return "No file selected", 400
63
-
64
- if file:
65
- # Save the uploaded file temporarily
66
- upload_path = os.path.join("static/uploads", file.filename)
67
- os.makedirs("static/uploads", exist_ok=True)
68
- file.save(upload_path)
69
-
70
- # Make prediction
71
- predicted_class, confidence = predict_image(upload_path)
72
 
73
- # Format the result based on prediction type
74
- if "Uncertain" in predicted_class:
75
- message = "The model is uncertain about the prediction. Please try another image."
76
- return render_template(
77
- "result.html",
78
- prediction=message,
79
- confidence=f"{confidence*100:.2f}%",
80
- image_path=upload_path,
81
- )
82
- else:
83
- return render_template(
84
- "result.html",
85
- prediction=predicted_class,
86
- confidence=f"{confidence*100:.2f}%",
87
- image_path=upload_path,
88
- )
89
 
 
90
  if __name__ == "__main__":
91
- app.run(debug=True)
 
1
+ import gradio as gr
2
  import numpy as np
3
  from tensorflow.keras.models import load_model
4
  from PIL import Image
 
 
 
5
 
6
  # Load the trained model
7
  MODEL_PATH = "vgg19_fine_tuned_block5_91.keras"
8
  model = load_model(MODEL_PATH)
9
 
10
  # Define class labels and confidence threshold
11
+ CLASS_LABELS = ["NORMAL", "PNEUMONIA"]
12
  CONFIDENCE_THRESHOLD = 0.7
13
 
14
+
15
+ def preprocess_image(image):
16
  """
17
  Preprocesses the input image for the model.
18
  Args:
19
+ image (PIL.Image): Input image.
20
  Returns:
21
  numpy.ndarray: Preprocessed image ready for prediction.
22
  """
23
+ img = image.convert("RGB") # Ensure the image is RGB
24
  img = img.resize((128, 128)) # Resize to model's input size
25
  img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]
26
  img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
27
  return img_array
28
 
29
+
30
+ def predict_image(image):
31
  """
32
  Predicts the class of the input image with confidence-based filtering.
33
  Args:
34
+ image (PIL.Image): Input image.
35
  Returns:
36
  str: Predicted class label or uncertainty message.
37
  float: Confidence score (if applicable).
38
  """
39
+ img_array = preprocess_image(image)
40
  prediction = model.predict(img_array)
41
  confidence = np.max(prediction)
42
 
 
47
  predicted_class = CLASS_LABELS[np.argmax(prediction)]
48
  return predicted_class, confidence
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Create a Gradio interface
52
+ interface = gr.Interface(
53
+ fn=predict_image,
54
+ inputs=gr.Image(type="pil"),
55
+ outputs=[gr.Textbox(label="Predicted Class"), gr.Textbox(label="Confidence")],
56
+ title="Pneumonia Detection CNN",
57
+ description="Upload an image to classify it as NORMAL or PNEUMONIA.",
58
+ )
 
 
 
 
 
 
 
 
59
 
60
+ # Launch the interface
61
  if __name__ == "__main__":
62
+ interface.launch(server_name="0.0.0.0", server_port=7860)