Yash goyal commited on
Commit
6daeb4b
·
verified ·
1 Parent(s): 6de2172

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -134
app.py CHANGED
@@ -1,134 +1,126 @@
1
- from flask import Flask, render_template, request, jsonify
2
- import tensorflow as tf
3
- import numpy as np
4
- from PIL import Image
5
- import pickle
6
- import io
7
- import os
8
- import matplotlib.pyplot as plt
9
- import logging
10
- import socket
11
-
12
- # Configure logging
13
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
14
- logger = logging.getLogger(__name__)
15
-
16
- app = Flask(__name__)
17
-
18
- MODEL_PATH = "D:\\CODEVERSE\\DNACreator\\skin_lesion_model.h5"
19
- HISTORY_PATH = "D:\\CODEVERSE\\DNACreator\\training_history.pkl"
20
-
21
- # Load model
22
- try:
23
- logger.info("Loading model from %s", MODEL_PATH)
24
- model = tf.keras.models.load_model(MODEL_PATH)
25
- except Exception as e:
26
- logger.error("Failed to load model: %s", str(e))
27
- raise
28
-
29
- # Load training history for plotting
30
- if os.path.exists(HISTORY_PATH):
31
- try:
32
- with open(HISTORY_PATH, "rb") as f:
33
- history_dict = pickle.load(f)
34
- logger.info("Loaded training history from %s", HISTORY_PATH)
35
- except Exception as e:
36
- logger.error("Failed to load training history: %s", str(e))
37
- history_dict = {}
38
- else:
39
- logger.warning("Training history file %s not found", HISTORY_PATH)
40
- history_dict = {}
41
-
42
- # Plot accuracy history
43
- if "accuracy" in history_dict and "val_accuracy" in history_dict:
44
- try:
45
- plt.plot(history_dict['accuracy'], label='Train Accuracy')
46
- plt.plot(history_dict['val_accuracy'], label='Val Accuracy')
47
- plt.xlabel('Epochs')
48
- plt.ylabel('Accuracy')
49
- plt.title('Training History')
50
- plt.legend()
51
- plt.grid(True)
52
- plt.savefig("static/training_plot.png")
53
- plt.close()
54
- logger.info("Generated training history plot at static/training_plot.png")
55
- except Exception as e:
56
- logger.error("Failed to generate training plot: %s", str(e))
57
-
58
- IMG_SIZE = (224, 224)
59
- CONFIDENCE_THRESHOLD = 0.30
60
-
61
- label_map = {
62
- 0: "Melanoma",
63
- 1: "Melanocytic nevus",
64
- 2: "Basal cell carcinoma",
65
- 3: "Actinic keratosis",
66
- 4: "Benign keratosis",
67
- 5: "Dermatofibroma",
68
- 6: "Vascular lesion",
69
- 7: "Squamous cell carcinoma"
70
- }
71
-
72
- def preprocess_image(image_bytes):
73
- try:
74
- image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
75
- image = image.resize(IMG_SIZE)
76
- image_array = tf.keras.utils.img_to_array(image)
77
- image_array = np.expand_dims(image_array, axis=0)
78
- return image_array / 255.0
79
- except Exception as e:
80
- logger.error("Failed to preprocess image: %s", str(e))
81
- raise
82
-
83
- @app.route("/form", methods=["GET"])
84
- def form():
85
- logger.info("Serving form page at /form")
86
- return render_template("form.html", history_plot="/static/training_plot.png")
87
-
88
- @app.route("/predict", methods=["POST"])
89
- def predict():
90
- logger.info("Received prediction request")
91
- if "image" not in request.files:
92
- logger.warning("No image uploaded in request")
93
- return jsonify({"error": "No image uploaded"}), 400
94
-
95
- try:
96
- image = request.files["image"].read()
97
- img_array = preprocess_image(image)
98
-
99
- logger.info("Running model prediction")
100
- prediction = model.predict(img_array)[0]
101
- predicted_index = int(np.argmax(prediction))
102
- confidence = float(prediction[predicted_index])
103
-
104
- if confidence < CONFIDENCE_THRESHOLD:
105
- result = {
106
- "prediction": "Low confidence",
107
- "confidence": f"{confidence * 100:.2f}%",
108
- "message": " This image is not confidently recognized. Please upload a clearer image."
109
- }
110
- logger.info("Prediction: Low confidence (%.2f%%)", confidence * 100)
111
- else:
112
- result = {
113
- "prediction": label_map.get(predicted_index, "Unknown"),
114
- "confidence": f"{confidence * 100:.2f}%"
115
- }
116
- logger.info("Prediction: %s (Confidence: %.2f%%)", result["prediction"], confidence * 100)
117
-
118
- return jsonify(result), 200
119
- except Exception as e:
120
- logger.error("Error processing image: %s", str(e))
121
- return jsonify({"error": f"Error processing image: {str(e)}"}), 500
122
-
123
- if __name__ == "__main__":
124
- ports = [3000, 3001, 3002] # Try these ports
125
- for port in ports:
126
- try:
127
- logger.info("Attempting to start Flask application on port %d", port)
128
- app.run(host='0.0.0.0', debug=True, port=port)
129
- break
130
- except socket.error as e:
131
- logger.error("Port %d failed: %s", port, str(e))
132
- if port == ports[-1]:
133
- logger.error("All ports failed. Please free a port or check permissions.")
134
- raise
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+ import pickle
6
+ import io
7
+ import os
8
+ import matplotlib.pyplot as plt
9
+ import logging
10
+
11
+ # Configure logging
12
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
+ logger = logging.getLogger(__name__)
14
+
15
+ app = Flask(__name__)
16
+
17
+ # Use relative paths for deployment
18
+ MODEL_PATH = "skin_lesion_model.h5"
19
+ HISTORY_PATH = "training_history.pkl"
20
+
21
+ # Load model
22
+ try:
23
+ logger.info("Loading model from %s", MODEL_PATH)
24
+ model = tf.keras.models.load_model(MODEL_PATH)
25
+ except Exception as e:
26
+ logger.error("Failed to load model: %s", str(e))
27
+ raise
28
+
29
+ # Load training history for plotting
30
+ if os.path.exists(HISTORY_PATH):
31
+ try:
32
+ with open(HISTORY_PATH, "rb") as f:
33
+ history_dict = pickle.load(f)
34
+ logger.info("Loaded training history from %s", HISTORY_PATH)
35
+ except Exception as e:
36
+ logger.error("Failed to load training history: %s", str(e))
37
+ history_dict = {}
38
+ else:
39
+ logger.warning("Training history file %s not found", HISTORY_PATH)
40
+ history_dict = {}
41
+
42
+ # Plot accuracy history
43
+ if "accuracy" in history_dict and "val_accuracy" in history_dict:
44
+ try:
45
+ plt.plot(history_dict['accuracy'], label='Train Accuracy')
46
+ plt.plot(history_dict['val_accuracy'], label='Val Accuracy')
47
+ plt.xlabel('Epochs')
48
+ plt.ylabel('Accuracy')
49
+ plt.title('Training History')
50
+ plt.legend()
51
+ plt.grid(True)
52
+ os.makedirs("static", exist_ok=True)
53
+ plt.savefig("static/training_plot.png")
54
+ plt.close()
55
+ logger.info("Generated training history plot at static/training_plot.png")
56
+ except Exception as e:
57
+ logger.error("Failed to generate training plot: %s", str(e))
58
+
59
+ IMG_SIZE = (224, 224)
60
+ CONFIDENCE_THRESHOLD = 0.30
61
+
62
+ label_map = {
63
+ 0: "Melanoma",
64
+ 1: "Melanocytic nevus",
65
+ 2: "Basal cell carcinoma",
66
+ 3: "Actinic keratosis",
67
+ 4: "Benign keratosis",
68
+ 5: "Dermatofibroma",
69
+ 6: "Vascular lesion",
70
+ 7: "Squamous cell carcinoma"
71
+ }
72
+
73
+ def preprocess_image(image_bytes):
74
+ try:
75
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
76
+ image = image.resize(IMG_SIZE)
77
+ image_array = tf.keras.utils.img_to_array(image)
78
+ image_array = np.expand_dims(image_array, axis=0)
79
+ return image_array / 255.0
80
+ except Exception as e:
81
+ logger.error("Failed to preprocess image: %s", str(e))
82
+ raise
83
+
84
+ @app.route("/form", methods=["GET"])
85
+ def form():
86
+ logger.info("Serving form page at /form")
87
+ return render_template("form.html", history_plot="/static/training_plot.png")
88
+
89
+ @app.route("/predict", methods=["POST"])
90
+ def predict():
91
+ logger.info("Received prediction request")
92
+ if "image" not in request.files:
93
+ logger.warning("No image uploaded in request")
94
+ return jsonify({"error": "No image uploaded"}), 400
95
+
96
+ try:
97
+ image = request.files["image"].read()
98
+ img_array = preprocess_image(image)
99
+
100
+ logger.info("Running model prediction")
101
+ prediction = model.predict(img_array)[0]
102
+ predicted_index = int(np.argmax(prediction))
103
+ confidence = float(prediction[predicted_index])
104
+
105
+ if confidence < CONFIDENCE_THRESHOLD:
106
+ result = {
107
+ "prediction": "Low confidence",
108
+ "confidence": f"{confidence * 100:.2f}%",
109
+ "message": "⚠ This image is not confidently recognized. Please upload a clearer image."
110
+ }
111
+ logger.info("Prediction: Low confidence (%.2f%%)", confidence * 100)
112
+ else:
113
+ result = {
114
+ "prediction": label_map.get(predicted_index, "Unknown"),
115
+ "confidence": f"{confidence * 100:.2f}%"
116
+ }
117
+ logger.info("Prediction: %s (Confidence: %.2f%%)", result["prediction"], confidence * 100)
118
+
119
+ return jsonify(result), 200
120
+ except Exception as e:
121
+ logger.error("Error processing image: %s", str(e))
122
+ return jsonify({"error": f"Error processing image: {str(e)}"}), 500
123
+
124
+ # Required port setup for Hugging Face Spaces
125
+ if __name__ == "__main__":
126
+ app.run(host="0.0.0.0", port=7860)