-
Notifications
You must be signed in to change notification settings - Fork 0
/
clip_timestamps.py
71 lines (47 loc) · 2.54 KB
/
clip_timestamps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import re
from datetime import datetime, timedelta
from tkinter.filedialog import askopenfilename, askdirectory
from moviepy.editor import *
VIDEO_CLIP_TIME_S = 10
if __name__ == "__main__":
video_path = askopenfilename(title="Select Video")
video_dir = os.path.dirname(video_path)
if not video_path or video_path == "":
raise Exception("Invalid video path")
timestamps_path = askopenfilename(title="Select Timestamps")
if not timestamps_path or timestamps_path == "":
raise Exception("Invalid timestamps path")
save_dir = askdirectory(title="Select Save Folder")
if not save_dir or save_dir == "":
raise Exception("Invalid save folder")
clip = VideoFileClip(video_path, verbose=False)
video_filename = os.path.basename(video_path)
clip_start_time = datetime.strptime(video_filename, "%Y-%m-%d %H-%M-%S.mkv")
clip_end_time = clip_start_time + timedelta(seconds=clip.duration)
with open(timestamps_path, "r") as f:
timestamps_text = f.read()
timestamps_data = timestamps_text.split("\n")
for timestamp_data in timestamps_data:
if timestamp_data.strip() == "":
continue
find_timestamp = re.match(r"^\d{4}\\\d{2}\\\d{2} \d{2}:\d{2}:\d{2}",string=timestamp_data)
if find_timestamp is None:
print(f"Could not find this time stamp {timestamp_data}")
continue
timestamp_start, timestamp_end = find_timestamp.span()
event_time = datetime.strptime(timestamp_data[timestamp_start, timestamp_end], "%Y\\%m\\%d %H:%M:%S")
event_time_str = event_time.strftime("%Y-%m-%d_%H-%M_%S")
if event_time < clip_start_time or event_time > clip_end_time:
print(f"!!! Timestamp Not Within This Clip: {timestamp_data} | {event_time_str} !!!")
continue
event_time_start = event_time - timedelta(seconds = int(VIDEO_CLIP_TIME_S/2))
event_time_end = event_time + timedelta(seconds = int(VIDEO_CLIP_TIME_S/2))
if event_time_start < clip_start_time:
event_time_start = clip_start_time
if event_time_end > clip_end_time:
event_time_end = clip_end_time
time_elapsed_start = int((event_time_start-clip_start_time).total_seconds())
time_elapsed_end =int((event_time_end-clip_start_time).total_seconds())
sub_clip: VideoFileClip = clip.subclip(time_elapsed_start, time_elapsed_end)
sub_clip.write_videofile(os.path.join(save_dir, f"{event_time_str}.mp4"), logger=None)