{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":9431759,"sourceType":"datasetVersion","datasetId":5730244},{"sourceId":9431810,"sourceType":"datasetVersion","datasetId":5730285},{"sourceId":116557,"sourceType":"modelInstanceVersion","modelInstanceId":97957,"modelId":122142}],"dockerImageVersionId":30762,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"pip install opencv-python tensorflow mtcnn imageio","metadata":{"execution":{"iopub.status.busy":"2025-01-26T10:08:13.661696Z","iopub.execute_input":"2025-01-26T10:08:13.662056Z","iopub.status.idle":"2025-01-26T10:08:24.104901Z","shell.execute_reply.started":"2025-01-26T10:08:13.662024Z","shell.execute_reply":"2025-01-26T10:08:24.103792Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport tensorflow as tf\nfrom mtcnn import MTCNN\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\n\n# Load the pre-trained Xception model\nmodel = tf.keras.models.load_model('/kaggle/input/xception5o/tensorflow2/default/1/xception_deepfake_image_5o.h5')\n\n# Constants\nIMAGE_SIZE = (224, 224)\nMAX_SEQ_LENGTH = 20  # Adjust to match your model's input length\nNUM_FEATURES = 2048  # Based on Xception output\nBATCH_SIZE = 32  # Batch size for prediction\nFRAME_SAMPLE_RATE = 10  # Process every 10th frame\nfeature_extractor = tf.keras.applications.Xception(weights=\"imagenet\", include_top=False, pooling=\"avg\")\n\n# Initialize face detector\ndetector = MTCNN()\n\n# Function to extract frames from video/GIF, sampling every Nth frame\ndef extract_frames_from_video(video_path, sample_rate=FRAME_SAMPLE_RATE):\n    frames = []\n    vidcap = cv2.VideoCapture(video_path)\n    success, image = vidcap.read()\n    count = 0\n    while success:\n        if count % sample_rate == 0:\n            frames.append(image)\n        success, image = vidcap.read()\n        count += 1\n    return frames\n\n# Function to detect and crop faces from a single frame\ndef detect_and_crop_faces(frame):\n    faces = []\n    detections = detector.detect_faces(frame)\n    for detection in detections:\n        x, y, width, height = detection['box']\n        face = frame[y:y+height, x:x+width]\n        face = cv2.resize(face, IMAGE_SIZE)\n        faces.append(face)\n    return faces\n\n# Function to preprocess and extract features from faces\ndef preprocess_faces(faces):\n    face_features = np.zeros((len(faces), *IMAGE_SIZE, 3))\n    for i, face in enumerate(faces):\n        face_features[i] = tf.keras.applications.xception.preprocess_input(face)\n    return face_features\n\n# Function to parallelize face detection using ThreadPoolExecutor\ndef detect_faces_parallel(frames):\n    with ThreadPoolExecutor() as executor:\n        results = executor.map(detect_and_crop_faces, frames)\n    all_faces = []\n    for faces in results:\n        all_faces.extend(faces)\n    return all_faces\n\n# Function to predict whether a video is FAKE or REAL\ndef predict_fake_real(video_path):\n    # Extract and sample frames from video\n    frames = extract_frames_from_video(video_path)\n\n    # Detect faces in parallel\n    all_faces = detect_faces_parallel(frames)\n    \n    if not all_faces:\n        print(\"No faces detected!\")\n        return None\n\n    # Limit the number of frames for consistency\n    all_faces = all_faces[:MAX_SEQ_LENGTH]\n\n    # Preprocess faces in batches\n    preprocessed_faces = preprocess_faces(all_faces)\n    \n    # Predict using the model in batches\n    predictions = []\n    for i in range(0, len(preprocessed_faces), BATCH_SIZE):\n        batch_faces = preprocessed_faces[i:i+BATCH_SIZE]\n        batch_predictions = model.predict(np.array(batch_faces))\n        predictions.extend(batch_predictions)\n    \n    # Compute average prediction\n    avg_prediction = np.mean(predictions)\n\n    return 'FAKE' if avg_prediction >= 0.5 else 'REAL'\n\n# Example usage:\nvideo_path = '/kaggle/input/videotest/WIN_20240919_10_19_21_Pro.mp4'   # this is my friend testing the model\nresult = predict_fake_real(video_path)\nprint(f'The video is {result}')\n","metadata":{"execution":{"iopub.status.busy":"2024-09-19T10:04:18.939809Z","iopub.execute_input":"2024-09-19T10:04:18.940148Z","iopub.status.idle":"2024-09-19T10:04:59.452766Z","shell.execute_reply.started":"2024-09-19T10:04:18.940111Z","shell.execute_reply":"2024-09-19T10:04:59.451811Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport tensorflow as tf\nfrom mtcnn import MTCNN\n\n# Load the pre-trained Xception model\nmodel = tf.keras.models.load_model('/kaggle/input/xception5o/tensorflow2/default/1/xception_deepfake_image_5o.h5')\n\n# Constants\nIMAGE_SIZE = (224, 224)\n\n# Initialize face detector\ndetector = MTCNN()\n\n# Function to detect and crop faces from a jpg image\ndef detect_and_crop_faces(image):\n    faces = []\n    detections = detector.detect_faces(image)\n    for detection in detections:\n        x, y, width, height = detection['box']\n        face = image[y:y+height, x:x+width]\n        face = cv2.resize(face, IMAGE_SIZE)\n        faces.append(face)\n    return faces\n\n# Function to preprocess and extract features from faces\ndef preprocess_faces(faces):\n    face_features = np.zeros((len(faces), *IMAGE_SIZE, 3))\n    for i, face in enumerate(faces):\n        face_features[i] = tf.keras.applications.xception.preprocess_input(face)\n    return face_features\n\n# Function to predict from a single jpg image\ndef predict_from_image(image_path):\n    image = cv2.imread(image_path)\n    faces = detect_and_crop_faces(image)\n    \n    if not faces:\n        print(\"No faces detected!\")\n        return None\n\n    # Preprocess the detected faces\n    preprocessed_faces = preprocess_faces(faces)\n\n    # Predict using the model\n    predictions = model.predict(np.array(preprocessed_faces))\n    avg_prediction = np.mean(predictions)\n\n    return 'FAKE' if avg_prediction >= 0.5 else 'REAL'\n\n# Example usage:\nimage_path = '/kaggle/input/imgofme2/IMG_20231210_2204042142.jpg'\nresult = predict_from_image(image_path)\nprint(f'The image is {result}')\n","metadata":{"execution":{"iopub.status.busy":"2025-01-26T10:08:24.107141Z","iopub.execute_input":"2025-01-26T10:08:24.107871Z","iopub.status.idle":"2025-01-26T10:08:36.297180Z","shell.execute_reply.started":"2025-01-26T10:08:24.107823Z","shell.execute_reply":"2025-01-26T10:08:36.296243Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{},"outputs":[],"execution_count":null}]}