from funcs import get_files
from PIL import Image
import imagehash
import cv2

def is_static_video_phash_optimized(video_path, frame_sample_rate=30, hash_size=16, hamming_threshold=1):
    """
    Determines if a video is static using perceptual hashing (pHash) by comparing consecutive frames.

    Parameters:
    - video_path: Path to the video file.
    - frame_sample_rate: Number of frames to skip between comparisons.
    - hash_size: Size of the hash; larger values increase sensitivity.
    - hamming_threshold: Maximum Hamming distance between consecutive frames to consider the video static.

    Returns:
    - True if the video is static, False otherwise.
    """
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print("Error: Cannot open video file.")
        return False

    ret, frame = cap.read()
    if not ret:
        print("Error: Cannot read video frames.")
        cap.release()
        return False

    # Convert first frame to PIL Image and compute hash
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    pil_image = Image.fromarray(frame_rgb)
    previous_hash = imagehash.phash(pil_image, hash_size=hash_size)

    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    is_static = True

    current_frame_number = 1

    while True:
        # Skip frames according to the sample rate
        cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame_number)
        ret, frame = cap.read()
        if not ret:
            break

        # Convert frame to PIL Image and compute hash
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        pil_image = Image.fromarray(frame_rgb)
        current_hash = imagehash.phash(pil_image, hash_size=hash_size)

        # Compute Hamming distance between hashes
        hamming_distance = previous_hash - current_hash

        if hamming_distance > hamming_threshold:
            is_static = False
            break

        # Update the previous hash
        previous_hash = current_hash

        # Move to the next frame according to the sample rate
        current_frame_number += frame_sample_rate

    cap.release()
    return is_static


directory = 'videos'

files = get_files(directory)

for video_file in files:
    if video_file.endswith('.mp4'):
        if is_static_video_phash_optimized(video_file):
            print("The video is static: " + video_file)