Spaces:
Paused
Paused
Yash goyal commited on
Update app.py
Browse files
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 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
MODEL_PATH = "
|
| 19 |
-
HISTORY_PATH = "
|
| 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 |
-
|
| 53 |
-
plt.
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
image =
|
| 76 |
-
|
| 77 |
-
image_array =
|
| 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 |
-
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|