d-e-e-k-11's picture
Upload folder using huggingface_hub
ca72ed3 verified
from flask import Flask, render_template, request, jsonify
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np
import os
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Load model
MODEL_PATH = 'bird_vs_drone_model.h5'
model = None
def get_model():
global model
if model is None:
if os.path.exists(MODEL_PATH):
model = tf.keras.models.load_model(MODEL_PATH)
elif os.path.exists('final_model.h5'):
model = tf.keras.models.load_model('final_model.h5')
return model
@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'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'})
if file:
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Preprocess
img = image.load_img(filepath, target_size=(224, 224))
img_array = image.img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
# Predict
m = get_model()
if m is None:
return jsonify({'error': 'Model not found. Please train the model first.'})
prediction = m.predict(img_array)[0][0]
# Result
# Class index 0 is Bird, 1 is Drone (based on our generator)
# Binary generator usually sorts class names alphabetically: ['Bird', 'Drone']
# So Bird = 0, Drone = 1.
# prediction > 0.5 means Drone
label = 'Drone' if prediction > 0.5 else 'Bird'
confidence = float(prediction) if label == 'Drone' else float(1 - prediction)
return jsonify({
'label': label,
'confidence': f"{confidence*100:.2f}%",
'image_url': f"/static/uploads/{filename}"
})
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)