amulmm's picture
Update main.py
33e10cf verified
import numpy as np
from tensorflow.keras.preprocessing import image
from flask import Flask, request, jsonify
import numpy as np
import os
# Available backend options are: "jax", "torch", "tensorflow".
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras
app = Flask(__name__)
# Define the Hugging Face model repository ID and the specific file to download
# HF_MODEL_REPO_ID = "amulmm/brain_tumor_training"
# HF_MODEL_FILE = "saved_model.keras"
# Download the model file (if needed, otherwise load locally)
# For Hugging Face Spaces, the model can be directly in the repo
# model_path = hf_hub_download(repo_id=HF_MODEL_REPO_ID, filename=HF_MODEL_FILE)
# Load the model directly from the .keras file
model = keras.models.load_model("brain_tumor_model.keras")
# Define image dimensions
IMG_HEIGHT = 150
IMG_WIDTH = 150
# Define class names (assuming 4 classes as per cobacoba.py)
CLASS_NAMES = ['glioma', 'meningioma', 'notumor', 'pituitary', 'non_brain']
@app.route('/predict', methods=['POST'])
def predict():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file:
# Read the image file directly from the request
import io
img_bytes = io.BytesIO(file.read())
img = image.load_img(img_bytes, target_size=(IMG_HEIGHT, IMG_WIDTH))
try:
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) # Create a batch
img_array /= 255.0 # Normalize pixel values
# Make prediction using the loaded model
predictions = model.predict(img_array)
except Exception as e:
return jsonify({'error': f'Error processing image or making prediction: {str(e)}'}), 500
# Proses hasil prediksi
predicted_class_index = np.argmax(predictions[0])
confidence = float(predictions[0][predicted_class_index] * 100)
# Set a confidence threshold
CONFIDENCE_THRESHOLD = 80.0 # Adjust as needed
if confidence < CONFIDENCE_THRESHOLD:
predicted_class_name = "Unknown (Not a brain tumor image or low confidence)"
else:
predicted_class_name = CLASS_NAMES[predicted_class_index]
return jsonify({
'prediction': predicted_class_name,
'confidence': f'{confidence:.2f}%'
})
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(debug=True, host='0.0.0.0', port=port)