bdtraining / app.py
lrmaneedeep's picture
Update app.py
10348d3 verified
from flask import Flask, request, jsonify, render_template
import tensorflow as tf
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
import os
from werkzeug.utils import secure_filename
app = Flask(__name__)
# Configuration
UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Create upload folder if it doesn't exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Load model once at startup
model = None
def get_model():
global model
if model is None:
model = load_model('brain_tumor_model.h5')
return model
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def preprocess_image(img_path, target_size=(150, 150)): # ← Update this!
"""Preprocess image for model prediction"""
img = image.load_img(img_path, target_size=target_size)
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = img_array / 255.0 # Normalize
return img_array
@app.route("/")
def index():
return render_template('index.html')
@app.route("/predict", methods=["POST"])
def predict():
if 'file' not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No file selected"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
try:
# Preprocess and predict
model = get_model()
processed_image = preprocess_image(filepath)
prediction = model.predict(processed_image)
# Adjust this based on your model's output
# For binary classification:
if prediction[0][0] > 0.5:
result = "Tumor Detected"
confidence = float(prediction[0][0]) * 100
else:
result = "No Tumor Detected"
confidence = (1 - float(prediction[0][0])) * 100
return jsonify({
"success": True,
"prediction": result,
"confidence": f"{confidence:.2f}%",
"image_path": filepath
})
except Exception as e:
return jsonify({"error": str(e)}), 500
return jsonify({"error": "Invalid file type. Use PNG, JPG, or JPEG"}), 400
if __name__ == '__main__':
print("Loading model...")
get_model()
print("Model loaded successfully!")
app.run(host="0.0.0.0",port=7860,debug=False)