# app.py # Import required libraries from flask import Flask, render_template, request, jsonify from werkzeug.utils import secure_filename import os from backend.Face_Detect import detect_faces # Custom face detection function from backend.DCT_func import process_dct # Custom DCT feature extraction function from backend.predict_deepfake import predict_deepfake # Custom deepfake prediction function from PIL import Image import base64 import pandas as pd import time app = Flask(__name__) # define flask app # Define file upload and processing directories UPLOAD_FOLDER = 'static/uploads' PROCESSED_FOLDER = 'static/processed' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['PROCESSED_FOLDER'] = PROCESSED_FOLDER # Allowed image file types ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'} # Ensure the folders exist (create if missing) os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(PROCESSED_FOLDER, exist_ok=True) # Helper function: check if uploaded file has an allowed extension def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS # Route: Home page @app.route('/') def index(): return render_template('index.html') # Route: Handle image preview uploads @app.route('/preview', methods=['POST']) def preview_image(): file = request.files['file'] if file and allowed_file(file.filename): filename = "uploaded_image." + file.filename.rsplit('.', 1)[1].lower() file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) return jsonify({'filename': filename}), 200 return jsonify({'error': 'Invalid file'}), 400 # Route: Detect faces and run DCT processing @app.route('/detect_faces', methods=['GET']) def detect_faces_route(): filename = request.args.get('filename') file_path = os.path.abspath(os.path.join(app.config['UPLOAD_FOLDER'], filename)) processed_image_path = os.path.abspath(os.path.join(app.config['PROCESSED_FOLDER'], f"processed_{filename}")) # Measure image size image_size_mb = os.path.getsize(file_path) / (1024 * 1024) # --- Face Detection --- start_fd = time.time() result, num_faces, face_coordinates, face_crops = detect_faces(file_path, processed_image_path) end_fd = time.time() fd_time = end_fd - start_fd # --- DCT Feature Extraction --- start_dct = time.time() dct_output_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{filename.split('.')[0]}_dct_features.csv") dct_result = process_dct(file_path, 'faces_detected.csv', dct_output_path) end_dct = time.time() dct_time = end_dct - start_dct # Encode processed image to Base64 for sending back to frontend with open(processed_image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') # Collect first 10 DCT features for preview first_ten = [] if dct_result and os.path.exists(dct_result): dct_df = pd.read_csv(dct_result) for index, row in dct_df.iterrows(): first_ten.append(row.iloc[:10].tolist()) # Return results as JSON return jsonify({ 'image_data': encoded_string, 'faces_detected': num_faces, 'face_coordinates': face_coordinates, 'face_crops': face_crops, 'first_ten_features': first_ten, 'image_size_mb': round(image_size_mb, 3), 'fd_time': round(fd_time, 3), 'dct_time': round(dct_time, 3) }), 200 # Route: Predict deepfake from extracted DCT features @app.route('/predict', methods=['GET']) def predict_route(): filename = request.args.get('filename') dct_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{filename.split('.')[0]}_dct_features.csv") # Ensure DCT file exists before predicting if not os.path.exists(dct_path): return jsonify({'error': 'DCT features not found'}), 404 # Run deepfake prediction start_rf = time.time() predictions = predict_deepfake(dct_path) end_rf = time.time() rf_time = end_rf - start_rf # Return predictions and runtime info return jsonify({ 'predictions': predictions['web_predictions'], 'console_output': predictions['console_output'], 'rf_time': round(rf_time, 3) }), 200 # Run Flask app if __name__ == '__main__': app.run(debug=True)