CoolFace
Apppublic

Asmaad/DeefFakeDetection_using_XceptionNet

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
streamlit_app.py191 linesDownload Raw Back to src
1import streamlit as st2import cv23import tempfile4import numpy as np5import os6from PIL import Image7import gc8import tensorflow9import tensorflow as tf10from tensorflow.keras.applications import Xception11from tensorflow.keras.models import Model12from tensorflow.keras.layers import Dense, GlobalAveragePooling2D  # or ConvNeXtBase, depending on your model13 14 15 16# Set page config17st.set_page_config(page_title="DeepFake Detector", layout="centered", initial_sidebar_state="collapsed")18 19# Minimal dark mode style20st.markdown("""21<style>22    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');23 24    html, body, .stApp {25        background-color: #0e0e0e;26        color: #ffffff;27        font-family: 'Inter', sans-serif;28        padding-top: 1rem;29        padding-bottom: 1rem;30    }31 32    .block-container {33        padding: 2rem 2rem;34    }35 36    h1, h2, h3, .stMarkdown, .stFileUploader, .stVideo, .stImage, .stButton, .stProgress, .score-box {37        margin-top: 1.5rem !important;38        margin-bottom: 1.5rem !important;39    }40 41    h1, h2, h3 {42        color: #fefefe;43        font-weight: 600;44        border-left: 4px solid #00e5ff;45        padding-left: 10px;46    }47 48    .stButton>button {49        background-color: #00e5ff;50        color: black;51        border-radius: 10px;52        padding: 0.6em 1.2em;53        font-weight: 600;54        border: none;55        transition: 0.3s;56        margin-top: 1rem;57        margin-bottom: 1rem;58    }59 60    .stButton>button:hover {61        background-color: #00bcd4;62        transform: scale(1.05);63    }64 65    .stFileUploader {66        background-color: #1e1e1e;67        padding: 1em;68        border-radius: 12px;69        border: 1px dashed #444;70    }71 72    .stVideo, .stImage > img {73        border-radius: 8px;74        box-shadow: 0 0 10px rgba(0,0,0,0.5);75        margin-top: 1rem;76        margin-bottom: 1rem;77    }78 79    .stProgress > div > div > div > div {80        background-color: #00e5ff;81    }82 83    .score-box {84        background-color: #1e1e1e;85        padding: 1em;86        margin-top: 1.5rem;87        margin-bottom: 1.5rem;88        border-radius: 10px;89        border-left: 4px solid #00e5ff;90        font-size: 1.1rem;91    }92 93</style>94""", unsafe_allow_html=True)95 96 97 98# Logo99# st.markdown("""100# <a href="https://www.intel.com/content/www/us/en/research/fakecatcher.html" target="_blank">101#     <img src="https://cdn-icons-png.flaticon.com/512/10471/10471465.png" width="100">102# </a>103# """, unsafe_allow_html=True)104 105# App title & subtitle106st.title("๐Ÿ•ต๏ธโ€โ™‚๏ธ DeepFake Detector")107st.markdown("Upload a video and detect deepfakes using an AI-based model โ€” powered by Xception!")108 109st.markdown("""110<div class='animated-desc'>111Analyze your video content for potential deepfake alterations using cutting-edge frame-by-frame AI detection.112</div>113""", unsafe_allow_html=True)114 115# Upload file116uploaded_file = st.file_uploader("๐Ÿ“ค Upload a video (MP4, MOV, AVI)", type=["mp4", "mov", "avi"])117@st.cache_resource118def load_model():119    weights_path = "src/Xception_ft.weights.h5"120    base_model = Xception(weights=None, include_top=False, input_shape=(299, 299, 3))121    x = GlobalAveragePooling2D()(base_model.output)122    x = Dense(1, activation='sigmoid')(x)123    model = Model(inputs=base_model.input, outputs=x)124    model.load_weights(weights_path)125    return model126 127model = load_model()128 129 130# Real detector function131def real_fake_detector(frame: np.ndarray) -> float:132    resized = tf.image.resize(frame, (299, 299)) / 255.0133    resized = tf.expand_dims(resized, axis=0)134    prediction = model.predict(resized, verbose=0)[0][0]135    return float(prediction)136 137# Main logic138if uploaded_file:139    tfile = tempfile.NamedTemporaryFile(delete=False)140    tfile.write(uploaded_file.read())141    video_path = tfile.name142 143    # Show uploaded video144    st.video(uploaded_file)145 146    st.info("๐Ÿง  Extracting frames and analyzing with local model...")147    cap = cv2.VideoCapture(video_path)148    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))149    selected_frames = []150    fake_scores = []151    progress = st.progress(0)152 153    for i in range(frame_count):154        ret, frame = cap.read()155        if not ret:156            break157 158        if i % 20 == 0:159            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)160            selected_frames.append(frame_rgb)161            score = real_fake_detector(frame_rgb)162            fake_scores.append(score)163 164        progress.progress(min((i + 1) / frame_count, 1.0))165 166    cap.release()167 168    # Display a few sample frames169    st.subheader("๐Ÿ“ท Sample Extracted Frames")170    cols = st.columns(min(len(selected_frames), 5))171    for idx, img in enumerate(selected_frames[:5]):172        with cols[idx]:173            st.image(Image.fromarray(img), use_column_width=True)174 175    avg_score = np.mean(fake_scores)176    st.markdown("---")177    st.subheader("๐Ÿ“Š DeepFake Analysis Result")178 179    with st.container():180        st.markdown(f"""181            <div class='score-box'>182            <strong>Average Fake Score:</strong> {avg_score:.2f}<br>183            <strong>Confidence Level:</strong> {'โš  High' if avg_score > 0.75 else 'โœ… Moderate'}184            </div>185        """, unsafe_allow_html=True)186    187        if avg_score > 0.5:188            st.error("๐Ÿ” The video is likely **DeepFake**.")189        else:190            st.success("๐ŸŽ‰ The video appears **Authentic**.")191