from flask import Flask, request, jsonify, render_template, send_from_directory from tensorflow.keras.models import load_model from PIL import Image import numpy as np import os app = Flask(__name__) # Loading the trained model try: model = load_model('model.h5') # Replacing with the path to your saved model except Exception as e: print("Error loading the model:", e) def detect_image(image_path): try: # Function to detect image img = Image.open(image_path).resize((256, 256)) # Resizing image img_array = np.array(img) / 255.0 # Normalizing pixel values img_array = np.expand_dims(img_array, axis=0) # Adding batch dimension prediction = model.predict(img_array)[0][0] probability_real = prediction * 100 # Converting prediction to percentage probability_ai = (1 - prediction) * 100 # Determine the final output if probability_real > probability_ai: result = 'Input Image is Real' confidence = probability_real else: result = 'Input Image is AI Generated' confidence = probability_ai return result, confidence except Exception as e: print("Error detecting image:", e) return "Error detecting image", 0 @app.route('/') def index(): return render_template('home.html') @app.route('/detect', methods=['POST']) def detect(): try: if 'file' not in request.files: return jsonify({'error': 'No file provided'}) file = request.files['file'] if file.filename.split('.')[-1].lower() not in ['jpg', 'jpeg', 'png']: return jsonify({'error': 'Unsupported file type. Please provide an image in JPG, JPEG, or PNG format.'}) file_path = 'DetectionImage/' + file.filename # Specifying the directory where images will be saved file.save(file_path) result, confidence = detect_image(file_path) response = { 'result': result, 'confidence': confidence, 'image_path': file_path } return jsonify(response) except Exception as e: print("Error processing request:", e) return jsonify({'error': 'Error processing request'}) @app.route('/DetectionImage/') def serve_image(filename): return send_from_directory('DetectionImage', filename) if __name__ == '__main__': if not os.path.exists('DetectionImage'): os.makedirs('DetectionImage') app.run(debug=True)