import cv2
import os
import json

def analyze_videos(directory):
    video_infos = []

    # 遍历文件夹
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".mp4"):
                path = os.path.join(root, file)
                cap = cv2.VideoCapture(path)
                
                # 获取视频的属性
                if cap.isOpened():
                    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
                    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
                    fps = cap.get(cv2.CAP_PROP_FPS)
                    frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
                    duration = frames / fps if fps > 0 else 0

                    video_infos.append({
                        "path": path,
                        "cap": [],
                        "resolution": {
                            "height": height,
                            "width": width
                        },
                        "fps": fps,
                        "duration": duration
                    })
                cap.release()

    return video_infos

# 将结果写入JSON文件
def write_to_json(directory):
    videos_info = analyze_videos(directory)
    json_path = os.path.join(directory, 'videos_info.json')
    with open(json_path, 'w') as f:
        json.dump(videos_info, f, indent=4)

# 替换下面的路径为你的视频文件夹路径
directory_path = '/afs/crc.nd.edu/user/z/zyuan2/code/Open-Sora-Plan/sample_93x480p_cfg7.5_step100_eulera'
write_to_json(directory_path)
