File size: 2,593 Bytes
8085865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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/<path:filename>')
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)