Spaces:
Paused
Paused
Yash goyal commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from flask import Flask, render_template, request, send_file
|
| 2 |
import tensorflow as tf
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
|
@@ -6,17 +6,35 @@ 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 |
MODEL_PATH = "skin_lesion_model.h5"
|
| 18 |
HISTORY_PATH = "training_history.pkl"
|
| 19 |
PLOT_PATH = "/tmp/static/training_plot.png"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# Load model
|
| 22 |
try:
|
|
@@ -26,50 +44,28 @@ except Exception as e:
|
|
| 26 |
logger.error("Failed to load model: %s", str(e))
|
| 27 |
raise
|
| 28 |
|
| 29 |
-
# Load training history
|
|
|
|
| 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 |
-
history_dict = {}
|
| 40 |
-
logger.warning("Training history file %s not found", HISTORY_PATH)
|
| 41 |
-
|
| 42 |
-
# Generate plot
|
| 43 |
-
if "accuracy" in history_dict and "val_accuracy" in history_dict:
|
| 44 |
-
try:
|
| 45 |
os.makedirs("/tmp/static", exist_ok=True)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
-
logger.error("Failed to
|
| 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")
|
|
@@ -78,56 +74,87 @@ def preprocess_image(image_bytes):
|
|
| 78 |
image_array = np.expand_dims(image_array, axis=0)
|
| 79 |
return image_array / 255.0
|
| 80 |
except Exception as e:
|
| 81 |
-
logger.error("
|
| 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="/training_plot.png")
|
| 88 |
|
| 89 |
@app.route("/training_plot.png")
|
| 90 |
def training_plot():
|
| 91 |
-
return send_file(PLOT_PATH, mimetype=
|
| 92 |
|
| 93 |
@app.route("/predict", methods=["POST"])
|
| 94 |
def predict():
|
| 95 |
-
logger.info("Received prediction request")
|
| 96 |
-
|
| 97 |
-
result = {}
|
| 98 |
try:
|
| 99 |
if "image" not in request.files:
|
| 100 |
raise ValueError("⚠ No image uploaded.")
|
| 101 |
-
|
| 102 |
image = request.files["image"].read()
|
| 103 |
img_array = preprocess_image(image)
|
| 104 |
prediction = model.predict(img_array)[0]
|
| 105 |
predicted_index = int(np.argmax(prediction))
|
| 106 |
confidence = float(prediction[predicted_index])
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
if confidence < CONFIDENCE_THRESHOLD:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
"confidence": f"{confidence * 100:.2f}%",
|
| 112 |
-
"message": "⚠ This image is not confidently recognized. Please upload a clearer image."
|
| 113 |
-
}
|
| 114 |
else:
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
|
|
|
| 123 |
except Exception as e:
|
| 124 |
logger.error("Prediction error: %s", str(e))
|
| 125 |
-
|
| 126 |
"prediction": "Error",
|
| 127 |
"confidence": "N/A",
|
| 128 |
"message": f"An error occurred: {str(e)}"
|
| 129 |
-
}
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
if __name__ == "__main__":
|
| 133 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, redirect, url_for, session, send_file
|
| 2 |
import tensorflow as tf
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
|
|
|
| 6 |
import io
|
| 7 |
import os
|
| 8 |
import matplotlib.pyplot as plt
|
| 9 |
+
from reportlab.pdfgen import canvas
|
| 10 |
+
from datetime import datetime
|
| 11 |
import logging
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
app = Flask(__name__)
|
| 14 |
+
app.secret_key = "your-secret-key" # Required for session handling
|
| 15 |
|
| 16 |
+
# Logging setup
|
| 17 |
+
logging.basicConfig(level=logging.INFO)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
# Paths
|
| 21 |
MODEL_PATH = "skin_lesion_model.h5"
|
| 22 |
HISTORY_PATH = "training_history.pkl"
|
| 23 |
PLOT_PATH = "/tmp/static/training_plot.png"
|
| 24 |
+
IMG_SIZE = (224, 224)
|
| 25 |
+
CONFIDENCE_THRESHOLD = 0.30
|
| 26 |
+
|
| 27 |
+
# Label map
|
| 28 |
+
label_map = {
|
| 29 |
+
0: "Melanoma",
|
| 30 |
+
1: "Melanocytic nevus",
|
| 31 |
+
2: "Basal cell carcinoma",
|
| 32 |
+
3: "Actinic keratosis",
|
| 33 |
+
4: "Benign keratosis",
|
| 34 |
+
5: "Dermatofibroma",
|
| 35 |
+
6: "Vascular lesion",
|
| 36 |
+
7: "Squamous cell carcinoma"
|
| 37 |
+
}
|
| 38 |
|
| 39 |
# Load model
|
| 40 |
try:
|
|
|
|
| 44 |
logger.error("Failed to load model: %s", str(e))
|
| 45 |
raise
|
| 46 |
|
| 47 |
+
# Load and plot training history
|
| 48 |
+
history_dict = {}
|
| 49 |
if os.path.exists(HISTORY_PATH):
|
| 50 |
try:
|
| 51 |
with open(HISTORY_PATH, "rb") as f:
|
| 52 |
history_dict = pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
os.makedirs("/tmp/static", exist_ok=True)
|
| 54 |
+
if "accuracy" in history_dict and "val_accuracy" in history_dict:
|
| 55 |
+
plt.plot(history_dict['accuracy'], label='Train Accuracy')
|
| 56 |
+
plt.plot(history_dict['val_accuracy'], label='Val Accuracy')
|
| 57 |
+
plt.xlabel('Epochs')
|
| 58 |
+
plt.ylabel('Accuracy')
|
| 59 |
+
plt.title('Training History')
|
| 60 |
+
plt.legend()
|
| 61 |
+
plt.grid(True)
|
| 62 |
+
plt.savefig(PLOT_PATH)
|
| 63 |
+
plt.close()
|
| 64 |
+
logger.info("Training plot saved at %s", PLOT_PATH)
|
| 65 |
except Exception as e:
|
| 66 |
+
logger.error("Failed to load training history or plot: %s", str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# Preprocess uploaded image
|
| 69 |
def preprocess_image(image_bytes):
|
| 70 |
try:
|
| 71 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
|
|
|
| 74 |
image_array = np.expand_dims(image_array, axis=0)
|
| 75 |
return image_array / 255.0
|
| 76 |
except Exception as e:
|
| 77 |
+
logger.error("Image preprocessing failed: %s", str(e))
|
| 78 |
raise
|
| 79 |
|
| 80 |
+
# Generate PDF report
|
| 81 |
+
def generate_pdf(report_data, filepath):
|
| 82 |
+
c = canvas.Canvas(filepath)
|
| 83 |
+
c.setFont("Helvetica", 14)
|
| 84 |
+
c.drawString(50, 800, "Skin Lesion Diagnosis Report")
|
| 85 |
+
c.setFont("Helvetica", 12)
|
| 86 |
+
y = 770
|
| 87 |
+
for key, value in report_data.items():
|
| 88 |
+
c.drawString(50, y, f"{key.capitalize()}: {value}")
|
| 89 |
+
y -= 20
|
| 90 |
+
c.drawString(50, y - 20, f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 91 |
+
c.save()
|
| 92 |
+
|
| 93 |
@app.route("/form", methods=["GET"])
|
| 94 |
def form():
|
|
|
|
| 95 |
return render_template("form.html", history_plot="/training_plot.png")
|
| 96 |
|
| 97 |
@app.route("/training_plot.png")
|
| 98 |
def training_plot():
|
| 99 |
+
return send_file(PLOT_PATH, mimetype="image/png")
|
| 100 |
|
| 101 |
@app.route("/predict", methods=["POST"])
|
| 102 |
def predict():
|
|
|
|
|
|
|
|
|
|
| 103 |
try:
|
| 104 |
if "image" not in request.files:
|
| 105 |
raise ValueError("⚠ No image uploaded.")
|
| 106 |
+
|
| 107 |
image = request.files["image"].read()
|
| 108 |
img_array = preprocess_image(image)
|
| 109 |
prediction = model.predict(img_array)[0]
|
| 110 |
predicted_index = int(np.argmax(prediction))
|
| 111 |
confidence = float(prediction[predicted_index])
|
| 112 |
|
| 113 |
+
name = request.form.get("name")
|
| 114 |
+
email = request.form.get("email")
|
| 115 |
+
gender = request.form.get("gender")
|
| 116 |
+
age = request.form.get("age")
|
| 117 |
+
|
| 118 |
if confidence < CONFIDENCE_THRESHOLD:
|
| 119 |
+
pred_label = "Low confidence"
|
| 120 |
+
msg = "⚠ This image is not confidently recognized. Please upload a clearer image."
|
|
|
|
|
|
|
|
|
|
| 121 |
else:
|
| 122 |
+
pred_label = label_map.get(predicted_index, "Unknown")
|
| 123 |
+
msg = ""
|
| 124 |
+
|
| 125 |
+
session["report"] = {
|
| 126 |
+
"name": name,
|
| 127 |
+
"email": email,
|
| 128 |
+
"gender": gender,
|
| 129 |
+
"age": age,
|
| 130 |
+
"prediction": pred_label,
|
| 131 |
+
"confidence": f"{confidence * 100:.2f}%",
|
| 132 |
+
"message": msg
|
| 133 |
+
}
|
| 134 |
|
| 135 |
+
return redirect(url_for("result"))
|
| 136 |
except Exception as e:
|
| 137 |
logger.error("Prediction error: %s", str(e))
|
| 138 |
+
return render_template("form.html", history_plot="/training_plot.png", result={
|
| 139 |
"prediction": "Error",
|
| 140 |
"confidence": "N/A",
|
| 141 |
"message": f"An error occurred: {str(e)}"
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
+
@app.route("/result")
|
| 145 |
+
def result():
|
| 146 |
+
report = session.get("report", {})
|
| 147 |
+
return render_template("result.html", **report)
|
| 148 |
+
|
| 149 |
+
@app.route("/download-report")
|
| 150 |
+
def download_report():
|
| 151 |
+
report = session.get("report", {})
|
| 152 |
+
if not report:
|
| 153 |
+
return redirect(url_for("form"))
|
| 154 |
+
os.makedirs("/tmp/reports", exist_ok=True)
|
| 155 |
+
filepath = "/tmp/reports/report.pdf"
|
| 156 |
+
generate_pdf(report, filepath)
|
| 157 |
+
return send_file(filepath, as_attachment=True)
|
| 158 |
|
| 159 |
if __name__ == "__main__":
|
| 160 |
app.run(host="0.0.0.0", port=7860)
|