import streamlit as st
import requests
from PIL import Image
from transformers import pipeline
from urllib.parse import urlparse, parse_qs

st.set_page_config(page_title="Deepfake Video Detector", layout="centered")

st.title("🎥 Deepfake Video Detector")
st.write("Enter a YouTube video URL (supports Shorts & standard videos) to check for deepfakes.")

@st.cache_data
def extract_video_id(url):
    parsed_url = urlparse(url)
    if "youtube" in parsed_url.netloc:
        if parsed_url.path.startswith("/watch"):
            return parse_qs(parsed_url.query).get("v", [None])[0]
        elif parsed_url.path.startswith("/shorts/"):
            return parsed_url.path.split("/")[-1]
    return None

@st.cache_data
def get_thumbnail(video_id):
    return f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"

@st.cache_resource
def load_model():
    return pipeline("image-classification", model="facebook/deit-base-distilled-patch16-224")

model = load_model()

video_url = st.text_input("🔗 Paste YouTube video URL:")
if st.button("Detect Deepfake") and video_url:
    video_id = extract_video_id(video_url)
    
    if video_id:
        thumbnail_url = get_thumbnail(video_id)
        try:
            response = requests.get(thumbnail_url)
            response.raise_for_status()
            thumbnail = Image.open(requests.get(thumbnail_url, stream=True).raw)
            st.image(thumbnail, caption="Video Thumbnail", use_container_width=True)

            st.write("🔎 Analyzing thumbnail...")
            results = model(thumbnail)
            
            deepfake_score = sum(result['score'] for result in results if 'fake' in result['label'].lower())
            if deepfake_score > 0.5:
                st.error(f"⚠️ High probability of deepfake detected! (Confidence: {deepfake_score:.2%})")
            else:
                st.success(f"✅ No strong evidence of deepfake detected. (Confidence: {1 - deepfake_score:.2%})")

        except requests.exceptions.RequestException:
            st.error("❌ Failed to fetch thumbnail. Please check the video URL.")
    else:
        st.error("❌ Invalid YouTube URL. Please enter a valid video or Shorts link.")