
import os
import csv
from moviepy.video.io.VideoFileClip import VideoFileClip

# Specify the root directory to search for video files
root_directory = r"E:\GDRIVE\.shortcut-targets-by-id\1AR1hyOICrGfRxwgV-gPaPXgTR2IWm7iI\Collections"

# Specify the output directory for converted MP4 videos
converted_videos_directory = r"C:\Users\User\Downloads\PDF\video"
# Specify the output CSV file path
output_csv = r"C:\Users\User\Downloads\PDF\csv\output.csv"


# Define a function to check if the file is a video but not MP4
def is_video_not_mp4(file_path):
    video_extensions = ['avi', 'mkv', 'mov', 'flv', 'wmv', 'webm', 'mpeg', 'mpg']
    return file_path.split('.')[-1].lower() not in ['mp4'] and file_path.split('.')[-1].lower() in video_extensions

# Define a function to convert a video to MP4 format
def convert_to_mp4(file_path):
    try:
        # Define the output path for the converted video
        base_name = os.path.basename(file_path)
        output_path = os.path.join(converted_videos_directory, os.path.splitext(base_name)[0] + '.mp4')
        
        with VideoFileClip(file_path) as video:
            video.write_videofile(output_path, codec='libx264', audio_codec='aac')
        
        print(f"Converted: {file_path} -> {output_path}")
        return output_path
    except Exception as e:
        print(f"Error converting {file_path}: {e}")
        return None

# Open the CSV file for writing
with open(output_csv, mode='w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['FileName', 'Directory']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
    # Write the header to the CSV file
    writer.writeheader()
    
    # Walk through the directory and its subdirectories
    for root, dirs, files in os.walk(root_directory):
        for file in files:
            file_path = os.path.join(root, file)
            if is_video_not_mp4(file_path):
                # Write the filename and directory to the CSV
                writer.writerow({'FileName': file, 'Directory': root})
                # Convert the non-MP4 video to MP4
                convert_to_mp4(file_path)

print(f"Process completed. Non-MP4 video files are converted and details saved to {output_csv}.")
