import tensorflow as tf from tensorflow.keras.models import load_model import numpy as np import cv2 import os from flask import Flask, request, jsonify from werkzeug.utils import secure_filename # Initialize Flask app app = Flask(_name_) # Load the trained Keras model MODEL_PATH = "model.weights.h5" model = load_model(MODEL_PATH) # Define allowed extensions for image upload ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def preprocess_image(image_path): """ Preprocess the uploaded image to match the model's input shape """ img = cv2.imread(image_path) img = cv2.resize(img, (224, 224)) # Resize to model's expected input size img = img / 255.0 # Normalize pixel values img = np.expand_dims(img, axis=0) # Add batch dimension return img @app.route('/predict', methods=['POST']) def predict(): """ API endpoint to predict melanoma from an uploaded image """ if 'file' not in request.files: return jsonify({"error": "No file uploaded"}), 400 file = request.files['file'] if file.filename == '': return jsonify({"error": "No selected file"}), 400 if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_path = os.path.join("uploads", filename) file.save(file_path) # Preprocess and predict image = preprocess_image(file_path) prediction = model.predict(image) os.remove(file_path) # Remove the file after prediction # Assuming model outputs a probability (0 = not melanoma, 1 = melanoma) result = "Melanoma" if prediction[0][0] > 0.5 else "Not Melanoma" return jsonify({"prediction": result, "confidence": float(prediction[0][0])}) return jsonify({"error": "Invalid file format"}), 400 if _name_ == '_main_': os.makedirs("uploads", exist_ok=True) # Ensure upload directory exists app.run(host='0.0.0.0', port=5000, debug=True)