File size: 2,796 Bytes
5ee02d3
2246113
5ee02d3
 
2246113
 
3f4431f
 
 
001ce80
3f4431f
57e9c82
3f4431f
 
c7de3fd
c90ae07
5ee02d3
 
 
 
 
 
 
 
001ce80
c90ae07
5ee02d3
001ce80
c90ae07
 
 
b28a72f
c90ae07
b28a72f
 
5ee02d3
 
001ce80
5ee02d3
 
 
96ce81f
001ce80
 
b28a72f
c90ae07
5ee02d3
96ce81f
 
5ee02d3
 
 
cdce109
3f4431f
cdce109
3f4431f
 
5ee02d3
 
 
3f4431f
 
c90ae07
5ee02d3
c90ae07
 
 
5ee02d3
c90ae07
 
3f4431f
c90ae07
 
 
 
3f4431f
c90ae07
3f4431f
c90ae07
3f4431f
 
 
 
 
5ee02d3
 
 
cdce109
57e9c82
3f4431f
5ee02d3
 
 
 
 
 
 
c90ae07
5ee02d3
 
 
 
c90ae07
 
5ee02d3
 
 
3f4431f
c90ae07
3f4431f
5ee02d3
 
 
 
3f4431f
5ee02d3
3f4431f
c90ae07
 
5ee02d3
 
 
3f4431f
 
5ee02d3
 
 
 
3f4431f
5ee02d3
 
cf5b215
c90ae07
5ee02d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

import os

# Force TensorFlow Keras compatibility
os.environ["TF_USE_LEGACY_KERAS"] = "1"

import numpy as np
import tensorflow as tf
from flask import Flask, request, jsonify
from model import build_model

pneumonia_detector_api = Flask(__name__)

IMG_SIZE = 224
MODEL_PATH = "pneumonia_resnet.weights.h5"

print("TensorFlow Version:", tf.__version__)

# -----------------------------
# SAFE MODEL LOADING
# -----------------------------
def load_trained_model():

    try:

        print("Building model architecture...")

        model = build_model()

        print("Loading weights...")

        model.load_weights(
            MODEL_PATH,
            skip_mismatch=True
        )

        print("Model loaded successfully")

        return model

    except Exception as e:

        print("Model loading failed:", e)
        raise RuntimeError("Failed to load model")


model = load_trained_model()


# -----------------------------
# HOME ROUTE
# -----------------------------
@pneumonia_detector_api.route("/")
def home():
    return "Pneumonia Detection API Running"


# -----------------------------
# IMAGE PREPROCESSING
# -----------------------------
def preprocess_image(img_array):

    img = np.array(img_array)

    # Ensure image has channel dimension
    if len(img.shape) == 2:
        img = np.expand_dims(img, axis=-1)

    # Resize image
    img = tf.image.resize(img, (IMG_SIZE, IMG_SIZE)).numpy()

    # Normalize
    img = img.astype("float32") / 255.0

    # Convert grayscale → RGB
    if img.shape[-1] == 1:
        img = np.repeat(img, 3, axis=-1)

    # Add batch dimension
    img = np.expand_dims(img, axis=0)

    return img


# -----------------------------
# PREDICTION API
# -----------------------------
@pneumonia_detector_api.route("/v1/predict", methods=["POST"])
def predict():

    try:

        if "file" not in request.files:
            return jsonify({"error": "No file uploaded"}), 400

        file = request.files["file"]

        # Load .npy file
        img_array = np.load(file)

        processed_img = preprocess_image(img_array)

        print("Input shape to model:", processed_img.shape)

        prediction = model.predict(processed_img)

        probability = float(prediction[0][0])

        label = "Pneumonia" if probability >= 0.5 else "Normal"

        return jsonify({
            "Predicted_Class": label,
            "Probability_Pneumonia": round(probability, 4)
        })

    except Exception as e:

        print("Prediction error:", str(e))

        return jsonify({
            "error": str(e)
        }), 500


# -----------------------------
# RUN SERVER
# -----------------------------
if __name__ == "__main__":

    pneumonia_detector_api.run(
        host="0.0.0.0",
        port=7860,
        debug=False
    )