arpitha9380/Cat_VS_Dog_Classification
0
1from flask import Flask, render_template, request, jsonify2import tensorflow as tf3from tensorflow.keras.preprocessing import image4import numpy as np5import os6from werkzeug.utils import secure_filename7 8app = Flask(__name__)9app.config['UPLOAD_FOLDER'] = 'static/uploads'10app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size11os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)12 13# Allowed file extensions14ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}15 16def allowed_file(filename):17 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS18 19# Load the model20model = None21try:22 model = tf.keras.models.load_model('cat_dog_model.h5')23 print("Model loaded successfully")24except Exception as e:25 print(f"Model not found or error loading model: {e}")26 27def predict_image(img_path):28 """Predict if image is a cat or dog"""29 if model is None:30 return "Model not loaded", 0.031 32 try:33 img = image.load_img(img_path, target_size=(128, 128))34 img_array = image.img_to_array(img)35 img_array = np.expand_dims(img_array, axis=0) / 255.036 37 prediction = model.predict(img_array, verbose=0)38 confidence = float(prediction[0][0])39 40 # prediction > 0.5 means Dog, else Cat41 if confidence > 0.5:42 return "Dog", confidence * 10043 else:44 return "Cat", (1 - confidence) * 10045 except Exception as e:46 print(f"Error during prediction: {e}")47 return "Error", 0.048 49@app.route('/')50def index():51 return render_template('index.html')52 53@app.route('/predict', methods=['POST'])54def predict():55 if 'file' not in request.files:56 return jsonify({'error': 'No file uploaded'})57 58 file = request.files['file']59 if file.filename == '':60 return jsonify({'error': 'No file selected'})61 62 if not allowed_file(file.filename):63 return jsonify({'error': 'Invalid file type. Please upload an image.'})64 65 if file:66 filename = secure_filename(file.filename)67 filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)68 file.save(filepath)69 70 result, confidence = predict_image(filepath)71 return jsonify({72 'result': result,73 'confidence': f"{confidence:.2f}%",74 'image_url': filepath75 })76 77if __name__ == '__main__':78 app.run(debug=False, host='0.0.0.0', port=7860)79 