import os
import sys
from moviepy.editor import VideoFileClip
def format_filesize(size):
return f"{size:,.0f}"
def format_duration(duration, use_hms=False):
if use_hms:
hours, remainder = divmod(duration, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{int(hours):02d}時間 {int(minutes):02d}分 {int(seconds):02d}秒"
else:
return f"{int(duration)}秒"
def calculate_total_duration(directory_path, use_hms=False):
video_files = [f for f in os.listdir(directory_path) if f.endswith(('.mp4', '.avi', '.mkv'))]
total_duration = 0
if use_hms:
html_output = "<html><body><h1>動画ファイル一覧</h1><table><tr><th width='160'>再生時間</th><th width='160'>ファイルサイズ</th><th>ファイル名</th></tr>"
else:
html_output = "<html><body><h1>動画ファイル一覧</h1><table><tr><th width='130'>再生時間</th><th width='160'>ファイルサイズ</th><th>ファイル名</th></tr>"
for video_file in video_files:
video_path = os.path.join(directory_path, video_file)
try:
video_clip = VideoFileClip(video_path)
duration = video_clip.duration
size = os.path.getsize(video_path)
if len(video_file) > 70:
video_file = "<br>".join([video_file[i:i+70] for i in range(0, len(video_file), 70)])
formatted_duration = format_duration(duration, use_hms)
formatted_size = format_filesize(size)
if use_hms:
html_output += f"<tr><td style='text-align:right;' width='160'>{formatted_duration}</td><td style='text-align:right;' width='160'>{formatted_size}バイト</td><td>{video_file}</td></tr>"
else:
html_output += f"<tr><td style='text-align:right;' width='130'>{formatted_duration}</td><td style='text-align:right;' width='160'>{formatted_size}バイト</td><td>{video_file}</td></tr>"
total_duration += duration
video_clip.close()
except Exception as e:
print(f"エラー: {video_file} を処理中にエラーが発生しました。")
print(e)
total_hours = int(total_duration) // 3600
total_minutes = (int(total_duration) % 3600) // 60
total_seconds = int(total_duration) % 60
html_output += f"</table><h2>合計再生時間: {total_hours:02d} 時間, {total_minutes:02d} 分, {total_seconds:02d} 秒</h2></body></html>"
base_directory_name = os.path.basename(directory_path)
output_filename = f"video_info_{base_directory_name}.html"
with open(output_filename, "w") as html_file:
html_file.write(html_output)
if __name__ == "__main__":
if len(sys.argv) >= 2:
directory_path = sys.argv[1]
use_hms = "-hms" in sys.argv
else:
print("使用法: python script.py ディレクトリパス [-hms]")
sys.exit(1)
calculate_total_duration(directory_path, use_hms)